1 // Copyright (c) 2016 Google Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ 16 #define INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ 17 18 #include <memory> 19 #include <ostream> 20 #include <string> 21 #include <unordered_map> 22 #include <unordered_set> 23 #include <utility> 24 #include <vector> 25 26 #include "libspirv.hpp" 27 28 namespace spvtools { 29 30 namespace opt { 31 class Pass; 32 struct DescriptorSetAndBinding; 33 } // namespace opt 34 35 // C++ interface for SPIR-V optimization functionalities. It wraps the context 36 // (including target environment and the corresponding SPIR-V grammar) and 37 // provides methods for registering optimization passes and optimizing. 38 // 39 // Instances of this class provides basic thread-safety guarantee. 40 class SPIRV_TOOLS_EXPORT Optimizer { 41 public: 42 // The token for an optimization pass. It is returned via one of the 43 // Create*Pass() standalone functions at the end of this header file and 44 // consumed by the RegisterPass() method. Tokens are one-time objects that 45 // only support move; copying is not allowed. 46 struct PassToken { 47 struct SPIRV_TOOLS_LOCAL Impl; // Opaque struct for holding internal data. 48 49 PassToken(std::unique_ptr<Impl>); 50 51 // Tokens for built-in passes should be created using Create*Pass functions 52 // below; for out-of-tree passes, use this constructor instead. 53 // Note that this API isn't guaranteed to be stable and may change without 54 // preserving source or binary compatibility in the future. 55 PassToken(std::unique_ptr<opt::Pass>&& pass); 56 57 // Tokens can only be moved. Copying is disabled. 58 PassToken(const PassToken&) = delete; 59 PassToken(PassToken&&); 60 PassToken& operator=(const PassToken&) = delete; 61 PassToken& operator=(PassToken&&); 62 63 ~PassToken(); 64 65 std::unique_ptr<Impl> impl_; // Unique pointer to internal data. 66 }; 67 68 // Constructs an instance with the given target |env|, which is used to decode 69 // the binaries to be optimized later. 70 // 71 // The instance will have an empty message consumer, which ignores all 72 // messages from the library. Use SetMessageConsumer() to supply a consumer 73 // if messages are of concern. 74 explicit Optimizer(spv_target_env env); 75 76 // Disables copy/move constructor/assignment operations. 77 Optimizer(const Optimizer&) = delete; 78 Optimizer(Optimizer&&) = delete; 79 Optimizer& operator=(const Optimizer&) = delete; 80 Optimizer& operator=(Optimizer&&) = delete; 81 82 // Destructs this instance. 83 ~Optimizer(); 84 85 // Sets the message consumer to the given |consumer|. The |consumer| will be 86 // invoked once for each message communicated from the library. 87 void SetMessageConsumer(MessageConsumer consumer); 88 89 // Returns a reference to the registered message consumer. 90 const MessageConsumer& consumer() const; 91 92 // Registers the given |pass| to this optimizer. Passes will be run in the 93 // exact order of registration. The token passed in will be consumed by this 94 // method. 95 Optimizer& RegisterPass(PassToken&& pass); 96 97 // Registers passes that attempt to improve performance of generated code. 98 // This sequence of passes is subject to constant review and will change 99 // from time to time. 100 // 101 // If |preserve_interface| is true, all non-io variables in the entry point 102 // interface are considered live and are not eliminated. 103 Optimizer& RegisterPerformancePasses(); 104 Optimizer& RegisterPerformancePasses(bool preserve_interface); 105 106 // Registers passes that attempt to improve the size of generated code. 107 // This sequence of passes is subject to constant review and will change 108 // from time to time. 109 // 110 // If |preserve_interface| is true, all non-io variables in the entry point 111 // interface are considered live and are not eliminated. 112 Optimizer& RegisterSizePasses(); 113 Optimizer& RegisterSizePasses(bool preserve_interface); 114 115 // Registers passes that attempt to legalize the generated code. 116 // 117 // Note: this recipe is specially designed for legalizing SPIR-V. It should be 118 // used by compilers after translating HLSL source code literally. It should 119 // *not* be used by general workloads for performance or size improvement. 120 // 121 // This sequence of passes is subject to constant review and will change 122 // from time to time. 123 // 124 // If |preserve_interface| is true, all non-io variables in the entry point 125 // interface are considered live and are not eliminated. 126 Optimizer& RegisterLegalizationPasses(); 127 Optimizer& RegisterLegalizationPasses(bool preserve_interface); 128 129 // Register passes specified in the list of |flags|. Each flag must be a 130 // string of a form accepted by Optimizer::FlagHasValidForm(). 131 // 132 // If the list of flags contains an invalid entry, it returns false and an 133 // error message is emitted to the MessageConsumer object (use 134 // Optimizer::SetMessageConsumer to define a message consumer, if needed). 135 // 136 // If |preserve_interface| is true, all non-io variables in the entry point 137 // interface are considered live and are not eliminated. 138 // 139 // If all the passes are registered successfully, it returns true. 140 bool RegisterPassesFromFlags(const std::vector<std::string>& flags); 141 bool RegisterPassesFromFlags(const std::vector<std::string>& flags, 142 bool preserve_interface); 143 144 // Registers the optimization pass associated with |flag|. This only accepts 145 // |flag| values of the form "--pass_name[=pass_args]". If no such pass 146 // exists, it returns false. Otherwise, the pass is registered and it returns 147 // true. 148 // 149 // The following flags have special meaning: 150 // 151 // -O: Registers all performance optimization passes 152 // (Optimizer::RegisterPerformancePasses) 153 // 154 // -Os: Registers all size optimization passes 155 // (Optimizer::RegisterSizePasses). 156 // 157 // --legalize-hlsl: Registers all passes that legalize SPIR-V generated by an 158 // HLSL front-end. 159 // 160 // If |preserve_interface| is true, all non-io variables in the entry point 161 // interface are considered live and are not eliminated. 162 bool RegisterPassFromFlag(const std::string& flag); 163 bool RegisterPassFromFlag(const std::string& flag, bool preserve_interface); 164 165 // Validates that |flag| has a valid format. Strings accepted: 166 // 167 // --pass_name[=pass_args] 168 // -O 169 // -Os 170 // 171 // If |flag| takes one of the forms above, it returns true. Otherwise, it 172 // returns false. 173 bool FlagHasValidForm(const std::string& flag) const; 174 175 // Allows changing, after creation time, the target environment to be 176 // optimized for and validated. Should be called before calling Run(). 177 void SetTargetEnv(const spv_target_env env); 178 179 // Optimizes the given SPIR-V module |original_binary| and writes the 180 // optimized binary into |optimized_binary|. The optimized binary uses 181 // the same SPIR-V version as the original binary. 182 // 183 // Returns true on successful optimization, whether or not the module is 184 // modified. Returns false if |original_binary| fails to validate or if errors 185 // occur when processing |original_binary| using any of the registered passes. 186 // In that case, no further passes are executed and the contents in 187 // |optimized_binary| may be invalid. 188 // 189 // By default, the binary is validated before any transforms are performed, 190 // and optionally after each transform. Validation uses SPIR-V spec rules 191 // for the SPIR-V version named in the binary's header (at word offset 1). 192 // Additionally, if the target environment is a client API (such as 193 // Vulkan 1.1), then validate for that client API version, to the extent 194 // that it is verifiable from data in the binary itself. 195 // 196 // It's allowed to alias |original_binary| to the start of |optimized_binary|. 197 bool Run(const uint32_t* original_binary, size_t original_binary_size, 198 std::vector<uint32_t>* optimized_binary) const; 199 200 // DEPRECATED: Same as above, except passes |options| to the validator when 201 // trying to validate the binary. If |skip_validation| is true, then the 202 // caller is guaranteeing that |original_binary| is valid, and the validator 203 // will not be run. The |max_id_bound| is the limit on the max id in the 204 // module. 205 bool Run(const uint32_t* original_binary, const size_t original_binary_size, 206 std::vector<uint32_t>* optimized_binary, 207 const ValidatorOptions& options, bool skip_validation) const; 208 209 // Same as above, except it takes an options object. See the documentation 210 // for |OptimizerOptions| to see which options can be set. 211 // 212 // By default, the binary is validated before any transforms are performed, 213 // and optionally after each transform. Validation uses SPIR-V spec rules 214 // for the SPIR-V version named in the binary's header (at word offset 1). 215 // Additionally, if the target environment is a client API (such as 216 // Vulkan 1.1), then validate for that client API version, to the extent 217 // that it is verifiable from data in the binary itself, or from the 218 // validator options set on the optimizer options. 219 bool Run(const uint32_t* original_binary, const size_t original_binary_size, 220 std::vector<uint32_t>* optimized_binary, 221 const spv_optimizer_options opt_options) const; 222 223 // Returns a vector of strings with all the pass names added to this 224 // optimizer's pass manager. These strings are valid until the associated 225 // pass manager is destroyed. 226 std::vector<const char*> GetPassNames() const; 227 228 // Sets the option to print the disassembly before each pass and after the 229 // last pass. If |out| is null, then no output is generated. Otherwise, 230 // output is sent to the |out| output stream. 231 Optimizer& SetPrintAll(std::ostream* out); 232 233 // Sets the option to print the resource utilization of each pass. If |out| 234 // is null, then no output is generated. Otherwise, output is sent to the 235 // |out| output stream. 236 Optimizer& SetTimeReport(std::ostream* out); 237 238 // Sets the option to validate the module after each pass. 239 Optimizer& SetValidateAfterAll(bool validate); 240 241 private: 242 struct SPIRV_TOOLS_LOCAL Impl; // Opaque struct for holding internal data. 243 std::unique_ptr<Impl> impl_; // Unique pointer to internal data. 244 }; 245 246 // Creates a null pass. 247 // A null pass does nothing to the SPIR-V module to be optimized. 248 Optimizer::PassToken CreateNullPass(); 249 250 // Creates a strip-debug-info pass. 251 // A strip-debug-info pass removes all debug instructions (as documented in 252 // Section 3.42.2 of the SPIR-V spec) of the SPIR-V module to be optimized. 253 Optimizer::PassToken CreateStripDebugInfoPass(); 254 255 // [Deprecated] This will create a strip-nonsemantic-info pass. See below. 256 Optimizer::PassToken CreateStripReflectInfoPass(); 257 258 // Creates a strip-nonsemantic-info pass. 259 // A strip-nonsemantic-info pass removes all reflections and explicitly 260 // non-semantic instructions. 261 Optimizer::PassToken CreateStripNonSemanticInfoPass(); 262 263 // Creates an eliminate-dead-functions pass. 264 // An eliminate-dead-functions pass will remove all functions that are not in 265 // the call trees rooted at entry points and exported functions. These 266 // functions are not needed because they will never be called. 267 Optimizer::PassToken CreateEliminateDeadFunctionsPass(); 268 269 // Creates an eliminate-dead-members pass. 270 // An eliminate-dead-members pass will remove all unused members of structures. 271 // This will not affect the data layout of the remaining members. 272 Optimizer::PassToken CreateEliminateDeadMembersPass(); 273 274 // Creates a set-spec-constant-default-value pass from a mapping from spec-ids 275 // to the default values in the form of string. 276 // A set-spec-constant-default-value pass sets the default values for the 277 // spec constants that have SpecId decorations (i.e., those defined by 278 // OpSpecConstant{|True|False} instructions). 279 Optimizer::PassToken CreateSetSpecConstantDefaultValuePass( 280 const std::unordered_map<uint32_t, std::string>& id_value_map); 281 282 // Creates a set-spec-constant-default-value pass from a mapping from spec-ids 283 // to the default values in the form of bit pattern. 284 // A set-spec-constant-default-value pass sets the default values for the 285 // spec constants that have SpecId decorations (i.e., those defined by 286 // OpSpecConstant{|True|False} instructions). 287 Optimizer::PassToken CreateSetSpecConstantDefaultValuePass( 288 const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map); 289 290 // Creates a flatten-decoration pass. 291 // A flatten-decoration pass replaces grouped decorations with equivalent 292 // ungrouped decorations. That is, it replaces each OpDecorationGroup 293 // instruction and associated OpGroupDecorate and OpGroupMemberDecorate 294 // instructions with equivalent OpDecorate and OpMemberDecorate instructions. 295 // The pass does not attempt to preserve debug information for instructions 296 // it removes. 297 Optimizer::PassToken CreateFlattenDecorationPass(); 298 299 // Creates a freeze-spec-constant-value pass. 300 // A freeze-spec-constant pass specializes the value of spec constants to 301 // their default values. This pass only processes the spec constants that have 302 // SpecId decorations (defined by OpSpecConstant, OpSpecConstantTrue, or 303 // OpSpecConstantFalse instructions) and replaces them with their normal 304 // counterparts (OpConstant, OpConstantTrue, or OpConstantFalse). The 305 // corresponding SpecId annotation instructions will also be removed. This 306 // pass does not fold the newly added normal constants and does not process 307 // other spec constants defined by OpSpecConstantComposite or 308 // OpSpecConstantOp. 309 Optimizer::PassToken CreateFreezeSpecConstantValuePass(); 310 311 // Creates a fold-spec-constant-op-and-composite pass. 312 // A fold-spec-constant-op-and-composite pass folds spec constants defined by 313 // OpSpecConstantOp or OpSpecConstantComposite instruction, to normal Constants 314 // defined by OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull, or 315 // OpConstantComposite instructions. Note that spec constants defined with 316 // OpSpecConstant, OpSpecConstantTrue, or OpSpecConstantFalse instructions are 317 // not handled, as these instructions indicate their value are not determined 318 // and can be changed in future. A spec constant is foldable if all of its 319 // value(s) can be determined from the module. E.g., an integer spec constant 320 // defined with OpSpecConstantOp instruction can be folded if its value won't 321 // change later. This pass will replace the original OpSpecConstantOp 322 // instruction with an OpConstant instruction. When folding composite spec 323 // constants, new instructions may be inserted to define the components of the 324 // composite constant first, then the original spec constants will be replaced 325 // by OpConstantComposite instructions. 326 // 327 // There are some operations not supported yet: 328 // OpSConvert, OpFConvert, OpQuantizeToF16 and 329 // all the operations under Kernel capability. 330 // TODO(qining): Add support for the operations listed above. 331 Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass(); 332 333 // Creates a unify-constant pass. 334 // A unify-constant pass de-duplicates the constants. Constants with the exact 335 // same value and identical form will be unified and only one constant will 336 // be kept for each unique pair of type and value. 337 // There are several cases not handled by this pass: 338 // 1) Constants defined by OpConstantNull instructions (null constants) and 339 // constants defined by OpConstantFalse, OpConstant or OpConstantComposite 340 // with value 0 (zero-valued normal constants) are not considered equivalent. 341 // So null constants won't be used to replace zero-valued normal constants, 342 // vice versa. 343 // 2) Whenever there are decorations to the constant's result id id, the 344 // constant won't be handled, which means, it won't be used to replace any 345 // other constants, neither can other constants replace it. 346 // 3) NaN in float point format with different bit patterns are not unified. 347 Optimizer::PassToken CreateUnifyConstantPass(); 348 349 // Creates a eliminate-dead-constant pass. 350 // A eliminate-dead-constant pass removes dead constants, including normal 351 // constants defined by OpConstant, OpConstantComposite, OpConstantTrue, or 352 // OpConstantFalse and spec constants defined by OpSpecConstant, 353 // OpSpecConstantComposite, OpSpecConstantTrue, OpSpecConstantFalse or 354 // OpSpecConstantOp. 355 Optimizer::PassToken CreateEliminateDeadConstantPass(); 356 357 // Creates a strength-reduction pass. 358 // A strength-reduction pass will look for opportunities to replace an 359 // instruction with an equivalent and less expensive one. For example, 360 // multiplying by a power of 2 can be replaced by a bit shift. 361 Optimizer::PassToken CreateStrengthReductionPass(); 362 363 // Creates a block merge pass. 364 // This pass searches for blocks with a single Branch to a block with no 365 // other predecessors and merges the blocks into a single block. Continue 366 // blocks and Merge blocks are not candidates for the second block. 367 // 368 // The pass is most useful after Dead Branch Elimination, which can leave 369 // such sequences of blocks. Merging them makes subsequent passes more 370 // effective, such as single block local store-load elimination. 371 // 372 // While this pass reduces the number of occurrences of this sequence, at 373 // this time it does not guarantee all such sequences are eliminated. 374 // 375 // Presence of phi instructions can inhibit this optimization. Handling 376 // these is left for future improvements. 377 Optimizer::PassToken CreateBlockMergePass(); 378 379 // Creates an exhaustive inline pass. 380 // An exhaustive inline pass attempts to exhaustively inline all function 381 // calls in all functions in an entry point call tree. The intent is to enable, 382 // albeit through brute force, analysis and optimization across function 383 // calls by subsequent optimization passes. As the inlining is exhaustive, 384 // there is no attempt to optimize for size or runtime performance. Functions 385 // that are not in the call tree of an entry point are not changed. 386 Optimizer::PassToken CreateInlineExhaustivePass(); 387 388 // Creates an opaque inline pass. 389 // An opaque inline pass inlines all function calls in all functions in all 390 // entry point call trees where the called function contains an opaque type 391 // in either its parameter types or return type. An opaque type is currently 392 // defined as Image, Sampler or SampledImage. The intent is to enable, albeit 393 // through brute force, analysis and optimization across these function calls 394 // by subsequent passes in order to remove the storing of opaque types which is 395 // not legal in Vulkan. Functions that are not in the call tree of an entry 396 // point are not changed. 397 Optimizer::PassToken CreateInlineOpaquePass(); 398 399 // Creates a single-block local variable load/store elimination pass. 400 // For every entry point function, do single block memory optimization of 401 // function variables referenced only with non-access-chain loads and stores. 402 // For each targeted variable load, if previous store to that variable in the 403 // block, replace the load's result id with the value id of the store. 404 // If previous load within the block, replace the current load's result id 405 // with the previous load's result id. In either case, delete the current 406 // load. Finally, check if any remaining stores are useless, and delete store 407 // and variable if possible. 408 // 409 // The presence of access chain references and function calls can inhibit 410 // the above optimization. 411 // 412 // Only modules with relaxed logical addressing (see opt/instruction.h) are 413 // currently processed. 414 // 415 // This pass is most effective if preceded by Inlining and 416 // LocalAccessChainConvert. This pass will reduce the work needed to be done 417 // by LocalSingleStoreElim and LocalMultiStoreElim. 418 // 419 // Only functions in the call tree of an entry point are processed. 420 Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass(); 421 422 // Create dead branch elimination pass. 423 // For each entry point function, this pass will look for SelectionMerge 424 // BranchConditionals with constant condition and convert to a Branch to 425 // the indicated label. It will delete resulting dead blocks. 426 // 427 // For all phi functions in merge block, replace all uses with the id 428 // corresponding to the living predecessor. 429 // 430 // Note that some branches and blocks may be left to avoid creating invalid 431 // control flow. Improving this is left to future work. 432 // 433 // This pass is most effective when preceded by passes which eliminate 434 // local loads and stores, effectively propagating constant values where 435 // possible. 436 Optimizer::PassToken CreateDeadBranchElimPass(); 437 438 // Creates an SSA local variable load/store elimination pass. 439 // For every entry point function, eliminate all loads and stores of function 440 // scope variables only referenced with non-access-chain loads and stores. 441 // Eliminate the variables as well. 442 // 443 // The presence of access chain references and function calls can inhibit 444 // the above optimization. 445 // 446 // Only shader modules with relaxed logical addressing (see opt/instruction.h) 447 // are currently processed. Currently modules with any extensions enabled are 448 // not processed. This is left for future work. 449 // 450 // This pass is most effective if preceded by Inlining and 451 // LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim 452 // will reduce the work that this pass has to do. 453 Optimizer::PassToken CreateLocalMultiStoreElimPass(); 454 455 // Creates a local access chain conversion pass. 456 // A local access chain conversion pass identifies all function scope 457 // variables which are accessed only with loads, stores and access chains 458 // with constant indices. It then converts all loads and stores of such 459 // variables into equivalent sequences of loads, stores, extracts and inserts. 460 // 461 // This pass only processes entry point functions. It currently only converts 462 // non-nested, non-ptr access chains. It does not process modules with 463 // non-32-bit integer types present. Optional memory access options on loads 464 // and stores are ignored as we are only processing function scope variables. 465 // 466 // This pass unifies access to these variables to a single mode and simplifies 467 // subsequent analysis and elimination of these variables along with their 468 // loads and stores allowing values to propagate to their points of use where 469 // possible. 470 Optimizer::PassToken CreateLocalAccessChainConvertPass(); 471 472 // Creates a local single store elimination pass. 473 // For each entry point function, this pass eliminates loads and stores for 474 // function scope variable that are stored to only once, where possible. Only 475 // whole variable loads and stores are eliminated; access-chain references are 476 // not optimized. Replace all loads of such variables with the value that is 477 // stored and eliminate any resulting dead code. 478 // 479 // Currently, the presence of access chains and function calls can inhibit this 480 // pass, however the Inlining and LocalAccessChainConvert passes can make it 481 // more effective. In additional, many non-load/store memory operations are 482 // not supported and will prohibit optimization of a function. Support of 483 // these operations are future work. 484 // 485 // Only shader modules with relaxed logical addressing (see opt/instruction.h) 486 // are currently processed. 487 // 488 // This pass will reduce the work needed to be done by LocalSingleBlockElim 489 // and LocalMultiStoreElim and can improve the effectiveness of other passes 490 // such as DeadBranchElimination which depend on values for their analysis. 491 Optimizer::PassToken CreateLocalSingleStoreElimPass(); 492 493 // Creates an insert/extract elimination pass. 494 // This pass processes each entry point function in the module, searching for 495 // extracts on a sequence of inserts. It further searches the sequence for an 496 // insert with indices identical to the extract. If such an insert can be 497 // found before hitting a conflicting insert, the extract's result id is 498 // replaced with the id of the values from the insert. 499 // 500 // Besides removing extracts this pass enables subsequent dead code elimination 501 // passes to delete the inserts. This pass performs best after access chains are 502 // converted to inserts and extracts and local loads and stores are eliminated. 503 Optimizer::PassToken CreateInsertExtractElimPass(); 504 505 // Creates a dead insert elimination pass. 506 // This pass processes each entry point function in the module, searching for 507 // unreferenced inserts into composite types. These are most often unused 508 // stores to vector components. They are unused because they are never 509 // referenced, or because there is another insert to the same component between 510 // the insert and the reference. After removing the inserts, dead code 511 // elimination is attempted on the inserted values. 512 // 513 // This pass performs best after access chains are converted to inserts and 514 // extracts and local loads and stores are eliminated. While executing this 515 // pass can be advantageous on its own, it is also advantageous to execute 516 // this pass after CreateInsertExtractPass() as it will remove any unused 517 // inserts created by that pass. 518 Optimizer::PassToken CreateDeadInsertElimPass(); 519 520 // Create aggressive dead code elimination pass 521 // This pass eliminates unused code from the module. In addition, 522 // it detects and eliminates code which may have spurious uses but which do 523 // not contribute to the output of the function. The most common cause of 524 // such code sequences is summations in loops whose result is no longer used 525 // due to dead code elimination. This optimization has additional compile 526 // time cost over standard dead code elimination. 527 // 528 // This pass only processes entry point functions. It also only processes 529 // shaders with relaxed logical addressing (see opt/instruction.h). It 530 // currently will not process functions with function calls. Unreachable 531 // functions are deleted. 532 // 533 // This pass will be made more effective by first running passes that remove 534 // dead control flow and inlines function calls. 535 // 536 // This pass can be especially useful after running Local Access Chain 537 // Conversion, which tends to cause cycles of dead code to be left after 538 // Store/Load elimination passes are completed. These cycles cannot be 539 // eliminated with standard dead code elimination. 540 // 541 // If |preserve_interface| is true, all non-io variables in the entry point 542 // interface are considered live and are not eliminated. This mode is needed 543 // by GPU-Assisted validation instrumentation, where a change in the interface 544 // is not allowed. 545 // 546 // If |remove_outputs| is true, allow outputs to be removed from the interface. 547 // This is only safe if the caller knows that there is no corresponding input 548 // variable in the following shader. It is false by default. 549 Optimizer::PassToken CreateAggressiveDCEPass(); 550 Optimizer::PassToken CreateAggressiveDCEPass(bool preserve_interface); 551 Optimizer::PassToken CreateAggressiveDCEPass(bool preserve_interface, 552 bool remove_outputs); 553 554 // Creates a remove-unused-interface-variables pass. 555 // Removes variables referenced on the |OpEntryPoint| instruction that are not 556 // referenced in the entry point function or any function in its call tree. Note 557 // that this could cause the shader interface to no longer match other shader 558 // stages. 559 Optimizer::PassToken CreateRemoveUnusedInterfaceVariablesPass(); 560 561 // Creates an empty pass. 562 // This is deprecated and will be removed. 563 // TODO(jaebaek): remove this pass after handling glslang's broken unit tests. 564 // https://github.com/KhronosGroup/glslang/pull/2440 565 Optimizer::PassToken CreatePropagateLineInfoPass(); 566 567 // Creates an empty pass. 568 // This is deprecated and will be removed. 569 // TODO(jaebaek): remove this pass after handling glslang's broken unit tests. 570 // https://github.com/KhronosGroup/glslang/pull/2440 571 Optimizer::PassToken CreateRedundantLineInfoElimPass(); 572 573 // Creates a compact ids pass. 574 // The pass remaps result ids to a compact and gapless range starting from %1. 575 Optimizer::PassToken CreateCompactIdsPass(); 576 577 // Creates a remove duplicate pass. 578 // This pass removes various duplicates: 579 // * duplicate capabilities; 580 // * duplicate extended instruction imports; 581 // * duplicate types; 582 // * duplicate decorations. 583 Optimizer::PassToken CreateRemoveDuplicatesPass(); 584 585 // Creates a CFG cleanup pass. 586 // This pass removes cruft from the control flow graph of functions that are 587 // reachable from entry points and exported functions. It currently includes the 588 // following functionality: 589 // 590 // - Removal of unreachable basic blocks. 591 Optimizer::PassToken CreateCFGCleanupPass(); 592 593 // Create dead variable elimination pass. 594 // This pass will delete module scope variables, along with their decorations, 595 // that are not referenced. 596 Optimizer::PassToken CreateDeadVariableEliminationPass(); 597 598 // create merge return pass. 599 // changes functions that have multiple return statements so they have a single 600 // return statement. 601 // 602 // for structured control flow it is assumed that the only unreachable blocks in 603 // the function are trivial merge and continue blocks. 604 // 605 // a trivial merge block contains the label and an opunreachable instructions, 606 // nothing else. a trivial continue block contain a label and an opbranch to 607 // the header, nothing else. 608 // 609 // these conditions are guaranteed to be met after running dead-branch 610 // elimination. 611 Optimizer::PassToken CreateMergeReturnPass(); 612 613 // Create value numbering pass. 614 // This pass will look for instructions in the same basic block that compute the 615 // same value, and remove the redundant ones. 616 Optimizer::PassToken CreateLocalRedundancyEliminationPass(); 617 618 // Create LICM pass. 619 // This pass will look for invariant instructions inside loops and hoist them to 620 // the loops preheader. 621 Optimizer::PassToken CreateLoopInvariantCodeMotionPass(); 622 623 // Creates a loop fission pass. 624 // This pass will split all top level loops whose register pressure exceedes the 625 // given |threshold|. 626 Optimizer::PassToken CreateLoopFissionPass(size_t threshold); 627 628 // Creates a loop fusion pass. 629 // This pass will look for adjacent loops that are compatible and legal to be 630 // fused. The fuse all such loops as long as the register usage for the fused 631 // loop stays under the threshold defined by |max_registers_per_loop|. 632 Optimizer::PassToken CreateLoopFusionPass(size_t max_registers_per_loop); 633 634 // Creates a loop peeling pass. 635 // This pass will look for conditions inside a loop that are true or false only 636 // for the N first or last iteration. For loop with such condition, those N 637 // iterations of the loop will be executed outside of the main loop. 638 // To limit code size explosion, the loop peeling can only happen if the code 639 // size growth for each loop is under |code_growth_threshold|. 640 Optimizer::PassToken CreateLoopPeelingPass(); 641 642 // Creates a loop unswitch pass. 643 // This pass will look for loop independent branch conditions and move the 644 // condition out of the loop and version the loop based on the taken branch. 645 // Works best after LICM and local multi store elimination pass. 646 Optimizer::PassToken CreateLoopUnswitchPass(); 647 648 // Create global value numbering pass. 649 // This pass will look for instructions where the same value is computed on all 650 // paths leading to the instruction. Those instructions are deleted. 651 Optimizer::PassToken CreateRedundancyEliminationPass(); 652 653 // Create scalar replacement pass. 654 // This pass replaces composite function scope variables with variables for each 655 // element if those elements are accessed individually. The parameter is a 656 // limit on the number of members in the composite variable that the pass will 657 // consider replacing. 658 Optimizer::PassToken CreateScalarReplacementPass(uint32_t size_limit = 100); 659 660 // Create a private to local pass. 661 // This pass looks for variables declared in the private storage class that are 662 // used in only one function. Those variables are moved to the function storage 663 // class in the function that they are used. 664 Optimizer::PassToken CreatePrivateToLocalPass(); 665 666 // Creates a conditional constant propagation (CCP) pass. 667 // This pass implements the SSA-CCP algorithm in 668 // 669 // Constant propagation with conditional branches, 670 // Wegman and Zadeck, ACM TOPLAS 13(2):181-210. 671 // 672 // Constant values in expressions and conditional jumps are folded and 673 // simplified. This may reduce code size by removing never executed jump targets 674 // and computations with constant operands. 675 Optimizer::PassToken CreateCCPPass(); 676 677 // Creates a workaround driver bugs pass. This pass attempts to work around 678 // a known driver bug (issue #1209) by identifying the bad code sequences and 679 // rewriting them. 680 // 681 // Current workaround: Avoid OpUnreachable instructions in loops. 682 Optimizer::PassToken CreateWorkaround1209Pass(); 683 684 // Creates a pass that converts if-then-else like assignments into OpSelect. 685 Optimizer::PassToken CreateIfConversionPass(); 686 687 // Creates a pass that will replace instructions that are not valid for the 688 // current shader stage by constants. Has no effect on non-shader modules. 689 Optimizer::PassToken CreateReplaceInvalidOpcodePass(); 690 691 // Creates a pass that simplifies instructions using the instruction folder. 692 Optimizer::PassToken CreateSimplificationPass(); 693 694 // Create loop unroller pass. 695 // Creates a pass to unroll loops which have the "Unroll" loop control 696 // mask set. The loops must meet a specific criteria in order to be unrolled 697 // safely this criteria is checked before doing the unroll by the 698 // LoopUtils::CanPerformUnroll method. Any loop that does not meet the criteria 699 // won't be unrolled. See CanPerformUnroll LoopUtils.h for more information. 700 Optimizer::PassToken CreateLoopUnrollPass(bool fully_unroll, int factor = 0); 701 702 // Create the SSA rewrite pass. 703 // This pass converts load/store operations on function local variables into 704 // operations on SSA IDs. This allows SSA optimizers to act on these variables. 705 // Only variables that are local to the function and of supported types are 706 // processed (see IsSSATargetVar for details). 707 Optimizer::PassToken CreateSSARewritePass(); 708 709 // Create pass to convert relaxed precision instructions to half precision. 710 // This pass converts as many relaxed float32 arithmetic operations to half as 711 // possible. It converts any float32 operands to half if needed. It converts 712 // any resulting half precision values back to float32 as needed. No variables 713 // are changed. No image operations are changed. 714 // 715 // Best if run after function scope store/load and composite operation 716 // eliminations are run. Also best if followed by instruction simplification, 717 // redundancy elimination and DCE. 718 Optimizer::PassToken CreateConvertRelaxedToHalfPass(); 719 720 // Create relax float ops pass. 721 // This pass decorates all float32 result instructions with RelaxedPrecision 722 // if not already so decorated. 723 Optimizer::PassToken CreateRelaxFloatOpsPass(); 724 725 // Create copy propagate arrays pass. 726 // This pass looks to copy propagate memory references for arrays. It looks 727 // for specific code patterns to recognize array copies. 728 Optimizer::PassToken CreateCopyPropagateArraysPass(); 729 730 // Create a vector dce pass. 731 // This pass looks for components of vectors that are unused, and removes them 732 // from the vector. Note this would still leave around lots of dead code that 733 // a pass of ADCE will be able to remove. 734 Optimizer::PassToken CreateVectorDCEPass(); 735 736 // Create a pass to reduce the size of loads. 737 // This pass looks for loads of structures where only a few of its members are 738 // used. It replaces the loads feeding an OpExtract with an OpAccessChain and 739 // a load of the specific elements. The parameter is a threshold to determine 740 // whether we have to replace the load or not. If the ratio of the used 741 // components of the load is less than the threshold, we replace the load. 742 Optimizer::PassToken CreateReduceLoadSizePass( 743 double load_replacement_threshold = 0.9); 744 745 // Create a pass to combine chained access chains. 746 // This pass looks for access chains fed by other access chains and combines 747 // them into a single instruction where possible. 748 Optimizer::PassToken CreateCombineAccessChainsPass(); 749 750 // Create a pass to instrument bindless descriptor checking 751 // This pass instruments all bindless references to check that descriptor 752 // array indices are inbounds, and if the descriptor indexing extension is 753 // enabled, that the descriptor has been initialized. If the reference is 754 // invalid, a record is written to the debug output buffer (if space allows) 755 // and a null value is returned. This pass is designed to support bindless 756 // validation in the Vulkan validation layers. 757 // 758 // TODO(greg-lunarg): Add support for buffer references. Currently only does 759 // checking for image references. 760 // 761 // Dead code elimination should be run after this pass as the original, 762 // potentially invalid code is not removed and could cause undefined behavior, 763 // including crashes. It may also be beneficial to run Simplification 764 // (ie Constant Propagation), DeadBranchElim and BlockMerge after this pass to 765 // optimize instrument code involving the testing of compile-time constants. 766 // It is also generally recommended that this pass (and all 767 // instrumentation passes) be run after any legalization and optimization 768 // passes. This will give better analysis for the instrumentation and avoid 769 // potentially de-optimizing the instrument code, for example, inlining 770 // the debug record output function throughout the module. 771 // 772 // The instrumentation will write |shader_id| in each output record 773 // to identify the shader module which generated the record. 774 Optimizer::PassToken CreateInstBindlessCheckPass(uint32_t shader_id); 775 776 // Create a pass to instrument physical buffer address checking 777 // This pass instruments all physical buffer address references to check that 778 // all referenced bytes fall in a valid buffer. If the reference is 779 // invalid, a record is written to the debug output buffer (if space allows) 780 // and a null value is returned. This pass is designed to support buffer 781 // address validation in the Vulkan validation layers. 782 // 783 // Dead code elimination should be run after this pass as the original, 784 // potentially invalid code is not removed and could cause undefined behavior, 785 // including crashes. Instruction simplification would likely also be 786 // beneficial. It is also generally recommended that this pass (and all 787 // instrumentation passes) be run after any legalization and optimization 788 // passes. This will give better analysis for the instrumentation and avoid 789 // potentially de-optimizing the instrument code, for example, inlining 790 // the debug record output function throughout the module. 791 // 792 // The instrumentation will read and write buffers in debug 793 // descriptor set |desc_set|. It will write |shader_id| in each output record 794 // to identify the shader module which generated the record. 795 Optimizer::PassToken CreateInstBuffAddrCheckPass(uint32_t shader_id); 796 797 // Create a pass to instrument OpDebugPrintf instructions. 798 // This pass replaces all OpDebugPrintf instructions with instructions to write 799 // a record containing the string id and the all specified values into a special 800 // printf output buffer (if space allows). This pass is designed to support 801 // the printf validation in the Vulkan validation layers. 802 // 803 // The instrumentation will write buffers in debug descriptor set |desc_set|. 804 // It will write |shader_id| in each output record to identify the shader 805 // module which generated the record. 806 Optimizer::PassToken CreateInstDebugPrintfPass(uint32_t desc_set, 807 uint32_t shader_id); 808 809 // Create a pass to upgrade to the VulkanKHR memory model. 810 // This pass upgrades the Logical GLSL450 memory model to Logical VulkanKHR. 811 // Additionally, it modifies memory, image, atomic and barrier operations to 812 // conform to that model's requirements. 813 Optimizer::PassToken CreateUpgradeMemoryModelPass(); 814 815 // Create a pass to do code sinking. Code sinking is a transformation 816 // where an instruction is moved into a more deeply nested construct. 817 Optimizer::PassToken CreateCodeSinkingPass(); 818 819 // Create a pass to fix incorrect storage classes. In order to make code 820 // generation simpler, DXC may generate code where the storage classes do not 821 // match up correctly. This pass will fix the errors that it can. 822 Optimizer::PassToken CreateFixStorageClassPass(); 823 824 // Creates a graphics robust access pass. 825 // 826 // This pass injects code to clamp indexed accesses to buffers and internal 827 // arrays, providing guarantees satisfying Vulkan's robustBufferAccess rules. 828 // 829 // TODO(dneto): Clamps coordinates and sample index for pointer calculations 830 // into storage images (OpImageTexelPointer). For an cube array image, it 831 // assumes the maximum layer count times 6 is at most 0xffffffff. 832 // 833 // NOTE: This pass will fail with a message if: 834 // - The module is not a Shader module. 835 // - The module declares VariablePointers, VariablePointersStorageBuffer, or 836 // RuntimeDescriptorArrayEXT capabilities. 837 // - The module uses an addressing model other than Logical 838 // - Access chain indices are wider than 64 bits. 839 // - Access chain index for a struct is not an OpConstant integer or is out 840 // of range. (The module is already invalid if that is the case.) 841 // - TODO(dneto): The OpImageTexelPointer coordinate component is not 32-bits 842 // wide. 843 // 844 // NOTE: Access chain indices are always treated as signed integers. So 845 // if an array has a fixed size of more than 2^31 elements, then elements 846 // from 2^31 and above are never accessible with a 32-bit index, 847 // signed or unsigned. For this case, this pass will clamp the index 848 // between 0 and at 2^31-1, inclusive. 849 // Similarly, if an array has more then 2^15 element and is accessed with 850 // a 16-bit index, then elements from 2^15 and above are not accessible. 851 // In this case, the pass will clamp the index between 0 and 2^15-1 852 // inclusive. 853 Optimizer::PassToken CreateGraphicsRobustAccessPass(); 854 855 // Create a pass to spread Volatile semantics to variables with SMIDNV, 856 // WarpIDNV, SubgroupSize, SubgroupLocalInvocationId, SubgroupEqMask, 857 // SubgroupGeMask, SubgroupGtMask, SubgroupLeMask, or SubgroupLtMask BuiltIn 858 // decorations or OpLoad for them when the shader model is the ray generation, 859 // closest hit, miss, intersection, or callable. This pass can be used for 860 // VUID-StandaloneSpirv-VulkanMemoryModel-04678 and 861 // VUID-StandaloneSpirv-VulkanMemoryModel-04679 (See "Standalone SPIR-V 862 // Validation" section of Vulkan spec "Appendix A: Vulkan Environment for 863 // SPIR-V"). When the SPIR-V version is 1.6 or above, the pass also spreads 864 // the Volatile semantics to a variable with HelperInvocation BuiltIn decoration 865 // in the fragement shader. 866 Optimizer::PassToken CreateSpreadVolatileSemanticsPass(); 867 868 // Create a pass to replace a descriptor access using variable index. 869 // This pass replaces every access using a variable index to array variable 870 // |desc| that has a DescriptorSet and Binding decorations with a constant 871 // element of the array. In order to replace the access using a variable index 872 // with the constant element, it uses a switch statement. 873 Optimizer::PassToken CreateReplaceDescArrayAccessUsingVarIndexPass(); 874 875 // Create descriptor scalar replacement pass. 876 // This pass replaces every array variable |desc| that has a DescriptorSet and 877 // Binding decorations with a new variable for each element of the array. 878 // Suppose |desc| was bound at binding |b|. Then the variable corresponding to 879 // |desc[i]| will have binding |b+i|. The descriptor set will be the same. It 880 // is assumed that no other variable already has a binding that will used by one 881 // of the new variables. If not, the pass will generate invalid Spir-V. All 882 // accesses to |desc| must be OpAccessChain instructions with a literal index 883 // for the first index. 884 Optimizer::PassToken CreateDescriptorScalarReplacementPass(); 885 886 // Create a pass to replace each OpKill instruction with a function call to a 887 // function that has a single OpKill. Also replace each OpTerminateInvocation 888 // instruction with a function call to a function that has a single 889 // OpTerminateInvocation. This allows more code to be inlined. 890 Optimizer::PassToken CreateWrapOpKillPass(); 891 892 // Replaces the extensions VK_AMD_shader_ballot,VK_AMD_gcn_shader, and 893 // VK_AMD_shader_trinary_minmax with equivalent code using core instructions and 894 // capabilities. 895 Optimizer::PassToken CreateAmdExtToKhrPass(); 896 897 // Replaces the internal version of GLSLstd450 InterpolateAt* extended 898 // instructions with the externally valid version. The internal version allows 899 // an OpLoad of the interpolant for the first argument. This pass removes the 900 // OpLoad and replaces it with its pointer. glslang and possibly other 901 // frontends will create the internal version for HLSL. This pass will be part 902 // of HLSL legalization and should be called after interpolants have been 903 // propagated into their final positions. 904 Optimizer::PassToken CreateInterpolateFixupPass(); 905 906 // Removes unused components from composite input variables. Current 907 // implementation just removes trailing unused components from input arrays 908 // and structs. The pass performs best after maximizing dead code removal. 909 // A subsequent dead code elimination pass would be beneficial in removing 910 // newly unused component types. 911 // 912 // WARNING: This pass can only be safely applied standalone to vertex shaders 913 // as it can otherwise cause interface incompatibilities with the preceding 914 // shader in the pipeline. If applied to non-vertex shaders, the user should 915 // follow by applying EliminateDeadOutputStores and 916 // EliminateDeadOutputComponents to the preceding shader. 917 Optimizer::PassToken CreateEliminateDeadInputComponentsPass(); 918 919 // Removes unused components from composite output variables. Current 920 // implementation just removes trailing unused components from output arrays 921 // and structs. The pass performs best after eliminating dead output stores. 922 // A subsequent dead code elimination pass would be beneficial in removing 923 // newly unused component types. Currently only supports vertex and fragment 924 // shaders. 925 // 926 // WARNING: This pass cannot be safely applied standalone as it can cause 927 // interface incompatibility with the following shader in the pipeline. The 928 // user should first apply EliminateDeadInputComponents to the following 929 // shader, then apply EliminateDeadOutputStores to this shader. 930 Optimizer::PassToken CreateEliminateDeadOutputComponentsPass(); 931 932 // Removes unused components from composite input variables. This safe 933 // version will not cause interface incompatibilities since it only changes 934 // vertex shaders. The current implementation just removes trailing unused 935 // components from input structs and input arrays. The pass performs best 936 // after maximizing dead code removal. A subsequent dead code elimination 937 // pass would be beneficial in removing newly unused component types. 938 Optimizer::PassToken CreateEliminateDeadInputComponentsSafePass(); 939 940 // Analyzes shader and populates |live_locs| and |live_builtins|. Best results 941 // will be obtained if shader has all dead code eliminated first. |live_locs| 942 // and |live_builtins| are subsequently used when calling 943 // CreateEliminateDeadOutputStoresPass on the preceding shader. Currently only 944 // supports tesc, tese, geom, and frag shaders. 945 Optimizer::PassToken CreateAnalyzeLiveInputPass( 946 std::unordered_set<uint32_t>* live_locs, 947 std::unordered_set<uint32_t>* live_builtins); 948 949 // Removes stores to output locations not listed in |live_locs| or 950 // |live_builtins|. Best results are obtained if constant propagation is 951 // performed first. A subsequent call to ADCE will eliminate any dead code 952 // created by the removal of the stores. A subsequent call to 953 // CreateEliminateDeadOutputComponentsPass will eliminate any dead output 954 // components created by the elimination of the stores. Currently only supports 955 // vert, tesc, tese, and geom shaders. 956 Optimizer::PassToken CreateEliminateDeadOutputStoresPass( 957 std::unordered_set<uint32_t>* live_locs, 958 std::unordered_set<uint32_t>* live_builtins); 959 960 // Creates a convert-to-sampled-image pass to convert images and/or 961 // samplers with given pairs of descriptor set and binding to sampled image. 962 // If a pair of an image and a sampler have the same pair of descriptor set and 963 // binding that is one of the given pairs, they will be converted to a sampled 964 // image. In addition, if only an image has the descriptor set and binding that 965 // is one of the given pairs, it will be converted to a sampled image as well. 966 Optimizer::PassToken CreateConvertToSampledImagePass( 967 const std::vector<opt::DescriptorSetAndBinding>& 968 descriptor_set_binding_pairs); 969 970 // Create an interface-variable-scalar-replacement pass that replaces array or 971 // matrix interface variables with a series of scalar or vector interface 972 // variables. For example, it replaces `float3 foo[2]` with `float3 foo0, foo1`. 973 Optimizer::PassToken CreateInterfaceVariableScalarReplacementPass(); 974 975 // Creates a remove-dont-inline pass to remove the |DontInline| function control 976 // from every function in the module. This is useful if you want the inliner to 977 // inline these functions some reason. 978 Optimizer::PassToken CreateRemoveDontInlinePass(); 979 // Create a fix-func-call-param pass to fix non memory argument for the function 980 // call, as spirv-validation requires function parameters to be an memory 981 // object, currently the pass would remove accesschain pointer argument passed 982 // to the function 983 Optimizer::PassToken CreateFixFuncCallArgumentsPass(); 984 985 // Creates a trim-capabilities pass. 986 // This pass removes unused capabilities for a given module, and if possible, 987 // associated extensions. 988 // See `trim_capabilities.h` for the list of supported capabilities. 989 // 990 // If the module contains unsupported capabilities, this pass will ignore them. 991 // This should be fine in most cases, but could yield to incorrect results if 992 // the unknown capability interacts with one of the trimmed capabilities. 993 Optimizer::PassToken CreateTrimCapabilitiesPass(); 994 995 // Creates a switch-descriptorset pass. 996 // This pass changes any DescriptorSet decorations with the value |ds_from| to 997 // use the new value |ds_to|. 998 Optimizer::PassToken CreateSwitchDescriptorSetPass(uint32_t ds_from, 999 uint32_t ds_to); 1000 1001 // Creates an invocation interlock placement pass. 1002 // This pass ensures that an entry point will have at most one 1003 // OpBeginInterlockInvocationEXT and one OpEndInterlockInvocationEXT, in that 1004 // order. 1005 Optimizer::PassToken CreateInvocationInterlockPlacementPass(); 1006 1007 // Creates a pass to add/remove maximal reconvergence execution mode. 1008 // This pass either adds or removes maximal reconvergence from all entry points. 1009 Optimizer::PassToken CreateModifyMaximalReconvergencePass(bool add); 1010 } // namespace spvtools 1011 1012 #endif // INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ 1013