1 //
2 // Copyright (C) 2014-2016 LunarG, Inc.
3 // Copyright (C) 2018-2020 Google, Inc.
4 //
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 // Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //
14 // Redistributions in binary form must reproduce the above
15 // copyright notice, this list of conditions and the following
16 // disclaimer in the documentation and/or other materials provided
17 // with the distribution.
18 //
19 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20 // contributors may be used to endorse or promote products derived
21 // from this software without specific prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 // POSSIBILITY OF SUCH DAMAGE.
35
36 //
37 // Call into SPIRV-Tools to disassemble, validate, and optimize.
38 //
39
40 #if ENABLE_OPT
41
42 #include <cstdio>
43 #include <iostream>
44
45 #include "SpvTools.h"
46 #include "spirv-tools/optimizer.hpp"
47
48 namespace glslang {
49
50 // Translate glslang's view of target versioning to what SPIRV-Tools uses.
MapToSpirvToolsEnv(const SpvVersion & spvVersion,spv::SpvBuildLogger * logger)51 spv_target_env MapToSpirvToolsEnv(const SpvVersion& spvVersion, spv::SpvBuildLogger* logger)
52 {
53 switch (spvVersion.vulkan) {
54 case glslang::EShTargetVulkan_1_0:
55 return spv_target_env::SPV_ENV_VULKAN_1_0;
56 case glslang::EShTargetVulkan_1_1:
57 switch (spvVersion.spv) {
58 case EShTargetSpv_1_0:
59 case EShTargetSpv_1_1:
60 case EShTargetSpv_1_2:
61 case EShTargetSpv_1_3:
62 return spv_target_env::SPV_ENV_VULKAN_1_1;
63 case EShTargetSpv_1_4:
64 return spv_target_env::SPV_ENV_VULKAN_1_1_SPIRV_1_4;
65 default:
66 logger->missingFunctionality("Target version for SPIRV-Tools validator");
67 return spv_target_env::SPV_ENV_VULKAN_1_1;
68 }
69 case glslang::EShTargetVulkan_1_2:
70 return spv_target_env::SPV_ENV_VULKAN_1_2;
71 default:
72 break;
73 }
74
75 if (spvVersion.openGl > 0)
76 return spv_target_env::SPV_ENV_OPENGL_4_5;
77
78 logger->missingFunctionality("Target version for SPIRV-Tools validator");
79 return spv_target_env::SPV_ENV_UNIVERSAL_1_0;
80 }
81
82 // Callback passed to spvtools::Optimizer::SetMessageConsumer
OptimizerMesssageConsumer(spv_message_level_t level,const char * source,const spv_position_t & position,const char * message)83 void OptimizerMesssageConsumer(spv_message_level_t level, const char *source,
84 const spv_position_t &position, const char *message)
85 {
86 auto &out = std::cerr;
87 switch (level)
88 {
89 case SPV_MSG_FATAL:
90 case SPV_MSG_INTERNAL_ERROR:
91 case SPV_MSG_ERROR:
92 out << "error: ";
93 break;
94 case SPV_MSG_WARNING:
95 out << "warning: ";
96 break;
97 case SPV_MSG_INFO:
98 case SPV_MSG_DEBUG:
99 out << "info: ";
100 break;
101 default:
102 break;
103 }
104 if (source)
105 {
106 out << source << ":";
107 }
108 out << position.line << ":" << position.column << ":" << position.index << ":";
109 if (message)
110 {
111 out << " " << message;
112 }
113 out << std::endl;
114 }
115
116 // Use the SPIRV-Tools disassembler to print SPIR-V using a SPV_ENV_UNIVERSAL_1_3 environment.
SpirvToolsDisassemble(std::ostream & out,const std::vector<unsigned int> & spirv)117 void SpirvToolsDisassemble(std::ostream& out, const std::vector<unsigned int>& spirv)
118 {
119 SpirvToolsDisassemble(out, spirv, spv_target_env::SPV_ENV_UNIVERSAL_1_3);
120 }
121
122 // Use the SPIRV-Tools disassembler to print SPIR-V with a provided SPIR-V environment.
SpirvToolsDisassemble(std::ostream & out,const std::vector<unsigned int> & spirv,spv_target_env requested_context)123 void SpirvToolsDisassemble(std::ostream& out, const std::vector<unsigned int>& spirv,
124 spv_target_env requested_context)
125 {
126 // disassemble
127 spv_context context = spvContextCreate(requested_context);
128 spv_text text;
129 spv_diagnostic diagnostic = nullptr;
130 spvBinaryToText(context, spirv.data(), spirv.size(),
131 SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES | SPV_BINARY_TO_TEXT_OPTION_INDENT,
132 &text, &diagnostic);
133
134 // dump
135 if (diagnostic == nullptr)
136 out << text->str;
137 else
138 spvDiagnosticPrint(diagnostic);
139
140 // teardown
141 spvDiagnosticDestroy(diagnostic);
142 spvContextDestroy(context);
143 }
144
145 // Apply the SPIRV-Tools validator to generated SPIR-V.
SpirvToolsValidate(const glslang::TIntermediate & intermediate,std::vector<unsigned int> & spirv,spv::SpvBuildLogger * logger,bool prelegalization)146 void SpirvToolsValidate(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
147 spv::SpvBuildLogger* logger, bool prelegalization)
148 {
149 // validate
150 spv_context context = spvContextCreate(MapToSpirvToolsEnv(intermediate.getSpv(), logger));
151 spv_const_binary_t binary = { spirv.data(), spirv.size() };
152 spv_diagnostic diagnostic = nullptr;
153 spv_validator_options options = spvValidatorOptionsCreate();
154 spvValidatorOptionsSetRelaxBlockLayout(options, intermediate.usingHlslOffsets());
155 spvValidatorOptionsSetBeforeHlslLegalization(options, prelegalization);
156 spvValidatorOptionsSetScalarBlockLayout(options, intermediate.usingScalarBlockLayout());
157 spvValidatorOptionsSetWorkgroupScalarBlockLayout(options, intermediate.usingScalarBlockLayout());
158 spvValidateWithOptions(context, options, &binary, &diagnostic);
159
160 // report
161 if (diagnostic != nullptr) {
162 logger->error("SPIRV-Tools Validation Errors");
163 logger->error(diagnostic->error);
164 }
165
166 // tear down
167 spvValidatorOptionsDestroy(options);
168 spvDiagnosticDestroy(diagnostic);
169 spvContextDestroy(context);
170 }
171
172 // Apply the SPIRV-Tools optimizer to generated SPIR-V. HLSL SPIR-V is legalized in the process.
SpirvToolsTransform(const glslang::TIntermediate & intermediate,std::vector<unsigned int> & spirv,spv::SpvBuildLogger * logger,const SpvOptions * options)173 void SpirvToolsTransform(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
174 spv::SpvBuildLogger* logger, const SpvOptions* options)
175 {
176 spv_target_env target_env = MapToSpirvToolsEnv(intermediate.getSpv(), logger);
177
178 spvtools::Optimizer optimizer(target_env);
179 optimizer.SetMessageConsumer(OptimizerMesssageConsumer);
180
181 // If debug (specifically source line info) is being generated, propagate
182 // line information into all SPIR-V instructions. This avoids loss of
183 // information when instructions are deleted or moved. Later, remove
184 // redundant information to minimize final SPRIR-V size.
185 if (options->stripDebugInfo) {
186 optimizer.RegisterPass(spvtools::CreateStripDebugInfoPass());
187 }
188 optimizer.RegisterPass(spvtools::CreateWrapOpKillPass());
189 optimizer.RegisterPass(spvtools::CreateDeadBranchElimPass());
190 optimizer.RegisterPass(spvtools::CreateMergeReturnPass());
191 optimizer.RegisterPass(spvtools::CreateInlineExhaustivePass());
192 optimizer.RegisterPass(spvtools::CreateEliminateDeadFunctionsPass());
193 optimizer.RegisterPass(spvtools::CreateScalarReplacementPass());
194 optimizer.RegisterPass(spvtools::CreateLocalAccessChainConvertPass());
195 optimizer.RegisterPass(spvtools::CreateLocalSingleBlockLoadStoreElimPass());
196 optimizer.RegisterPass(spvtools::CreateLocalSingleStoreElimPass());
197 optimizer.RegisterPass(spvtools::CreateSimplificationPass());
198 optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
199 optimizer.RegisterPass(spvtools::CreateVectorDCEPass());
200 optimizer.RegisterPass(spvtools::CreateDeadInsertElimPass());
201 optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
202 optimizer.RegisterPass(spvtools::CreateDeadBranchElimPass());
203 optimizer.RegisterPass(spvtools::CreateBlockMergePass());
204 optimizer.RegisterPass(spvtools::CreateLocalMultiStoreElimPass());
205 optimizer.RegisterPass(spvtools::CreateIfConversionPass());
206 optimizer.RegisterPass(spvtools::CreateSimplificationPass());
207 optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
208 optimizer.RegisterPass(spvtools::CreateVectorDCEPass());
209 optimizer.RegisterPass(spvtools::CreateDeadInsertElimPass());
210 if (options->optimizeSize) {
211 optimizer.RegisterPass(spvtools::CreateRedundancyEliminationPass());
212 }
213 optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
214 optimizer.RegisterPass(spvtools::CreateCFGCleanupPass());
215
216 spvtools::OptimizerOptions spvOptOptions;
217 optimizer.SetTargetEnv(MapToSpirvToolsEnv(intermediate.getSpv(), logger));
218 spvOptOptions.set_run_validator(false); // The validator may run as a separate step later on
219 optimizer.Run(spirv.data(), spirv.size(), &spirv, spvOptOptions);
220 }
221
222 // Apply the SPIRV-Tools optimizer to strip debug info from SPIR-V. This is implicitly done by
223 // SpirvToolsTransform if spvOptions->stripDebugInfo is set, but can be called separately if
224 // optimization is disabled.
SpirvToolsStripDebugInfo(const glslang::TIntermediate & intermediate,std::vector<unsigned int> & spirv,spv::SpvBuildLogger * logger)225 void SpirvToolsStripDebugInfo(const glslang::TIntermediate& intermediate,
226 std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
227 {
228 spv_target_env target_env = MapToSpirvToolsEnv(intermediate.getSpv(), logger);
229
230 spvtools::Optimizer optimizer(target_env);
231 optimizer.SetMessageConsumer(OptimizerMesssageConsumer);
232
233 optimizer.RegisterPass(spvtools::CreateStripDebugInfoPass());
234
235 spvtools::OptimizerOptions spvOptOptions;
236 optimizer.SetTargetEnv(MapToSpirvToolsEnv(intermediate.getSpv(), logger));
237 spvOptOptions.set_run_validator(false); // The validator may run as a separate step later on
238 optimizer.Run(spirv.data(), spirv.size(), &spirv, spvOptOptions);
239 }
240
241 }; // end namespace glslang
242
243 #endif
244