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     spvValidateWithOptions(context, options, &binary, &diagnostic);
157 
158     // report
159     if (diagnostic != nullptr) {
160         logger->error("SPIRV-Tools Validation Errors");
161         logger->error(diagnostic->error);
162     }
163 
164     // tear down
165     spvValidatorOptionsDestroy(options);
166     spvDiagnosticDestroy(diagnostic);
167     spvContextDestroy(context);
168 }
169 
170 // 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)171 void SpirvToolsTransform(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
172                          spv::SpvBuildLogger* logger, const SpvOptions* options)
173 {
174     spv_target_env target_env = MapToSpirvToolsEnv(intermediate.getSpv(), logger);
175 
176     spvtools::Optimizer optimizer(target_env);
177     optimizer.SetMessageConsumer(OptimizerMesssageConsumer);
178 
179     // If debug (specifically source line info) is being generated, propagate
180     // line information into all SPIR-V instructions. This avoids loss of
181     // information when instructions are deleted or moved. Later, remove
182     // redundant information to minimize final SPRIR-V size.
183     if (options->stripDebugInfo) {
184         optimizer.RegisterPass(spvtools::CreateStripDebugInfoPass());
185     }
186     optimizer.RegisterPass(spvtools::CreateWrapOpKillPass());
187     optimizer.RegisterPass(spvtools::CreateDeadBranchElimPass());
188     optimizer.RegisterPass(spvtools::CreateMergeReturnPass());
189     optimizer.RegisterPass(spvtools::CreateInlineExhaustivePass());
190     optimizer.RegisterPass(spvtools::CreateEliminateDeadFunctionsPass());
191     optimizer.RegisterPass(spvtools::CreateScalarReplacementPass());
192     optimizer.RegisterPass(spvtools::CreateLocalAccessChainConvertPass());
193     optimizer.RegisterPass(spvtools::CreateLocalSingleBlockLoadStoreElimPass());
194     optimizer.RegisterPass(spvtools::CreateLocalSingleStoreElimPass());
195     optimizer.RegisterPass(spvtools::CreateSimplificationPass());
196     optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
197     optimizer.RegisterPass(spvtools::CreateVectorDCEPass());
198     optimizer.RegisterPass(spvtools::CreateDeadInsertElimPass());
199     optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
200     optimizer.RegisterPass(spvtools::CreateDeadBranchElimPass());
201     optimizer.RegisterPass(spvtools::CreateBlockMergePass());
202     optimizer.RegisterPass(spvtools::CreateLocalMultiStoreElimPass());
203     optimizer.RegisterPass(spvtools::CreateIfConversionPass());
204     optimizer.RegisterPass(spvtools::CreateSimplificationPass());
205     optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
206     optimizer.RegisterPass(spvtools::CreateVectorDCEPass());
207     optimizer.RegisterPass(spvtools::CreateDeadInsertElimPass());
208     if (options->optimizeSize) {
209         optimizer.RegisterPass(spvtools::CreateRedundancyEliminationPass());
210     }
211     optimizer.RegisterPass(spvtools::CreateAggressiveDCEPass());
212     optimizer.RegisterPass(spvtools::CreateCFGCleanupPass());
213 
214     spvtools::OptimizerOptions spvOptOptions;
215     optimizer.SetTargetEnv(MapToSpirvToolsEnv(intermediate.getSpv(), logger));
216     spvOptOptions.set_run_validator(false); // The validator may run as a separate step later on
217     optimizer.Run(spirv.data(), spirv.size(), &spirv, spvOptOptions);
218 }
219 
220 // Apply the SPIRV-Tools optimizer to strip debug info from SPIR-V.  This is implicitly done by
221 // SpirvToolsTransform if spvOptions->stripDebugInfo is set, but can be called separately if
222 // optimization is disabled.
SpirvToolsStripDebugInfo(const glslang::TIntermediate & intermediate,std::vector<unsigned int> & spirv,spv::SpvBuildLogger * logger)223 void SpirvToolsStripDebugInfo(const glslang::TIntermediate& intermediate,
224         std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
225 {
226     spv_target_env target_env = MapToSpirvToolsEnv(intermediate.getSpv(), logger);
227 
228     spvtools::Optimizer optimizer(target_env);
229     optimizer.SetMessageConsumer(OptimizerMesssageConsumer);
230 
231     optimizer.RegisterPass(spvtools::CreateStripDebugInfoPass());
232 
233     spvtools::OptimizerOptions spvOptOptions;
234     optimizer.SetTargetEnv(MapToSpirvToolsEnv(intermediate.getSpv(), logger));
235     spvOptOptions.set_run_validator(false); // The validator may run as a separate step later on
236     optimizer.Run(spirv.data(), spirv.size(), &spirv, spvOptOptions);
237 }
238 
239 }; // end namespace glslang
240 
241 #endif
242