Chris Forbes | cc5697f | 2019-01-30 11:54:08 -0800 | [diff] [blame^] | 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 <vector> |
| 23 | |
| 24 | #include "libspirv.hpp" |
| 25 | |
| 26 | namespace spvtools { |
| 27 | |
| 28 | namespace opt { |
| 29 | class Pass; |
| 30 | } |
| 31 | |
| 32 | // C++ interface for SPIR-V optimization functionalities. It wraps the context |
| 33 | // (including target environment and the corresponding SPIR-V grammar) and |
| 34 | // provides methods for registering optimization passes and optimizing. |
| 35 | // |
| 36 | // Instances of this class provides basic thread-safety guarantee. |
| 37 | class Optimizer { |
| 38 | public: |
| 39 | // The token for an optimization pass. It is returned via one of the |
| 40 | // Create*Pass() standalone functions at the end of this header file and |
| 41 | // consumed by the RegisterPass() method. Tokens are one-time objects that |
| 42 | // only support move; copying is not allowed. |
| 43 | struct PassToken { |
| 44 | struct Impl; // Opaque struct for holding inernal data. |
| 45 | |
| 46 | PassToken(std::unique_ptr<Impl>); |
| 47 | |
| 48 | // Tokens for built-in passes should be created using Create*Pass functions |
| 49 | // below; for out-of-tree passes, use this constructor instead. |
| 50 | // Note that this API isn't guaranteed to be stable and may change without |
| 51 | // preserving source or binary compatibility in the future. |
| 52 | PassToken(std::unique_ptr<opt::Pass>&& pass); |
| 53 | |
| 54 | // Tokens can only be moved. Copying is disabled. |
| 55 | PassToken(const PassToken&) = delete; |
| 56 | PassToken(PassToken&&); |
| 57 | PassToken& operator=(const PassToken&) = delete; |
| 58 | PassToken& operator=(PassToken&&); |
| 59 | |
| 60 | ~PassToken(); |
| 61 | |
| 62 | std::unique_ptr<Impl> impl_; // Unique pointer to internal data. |
| 63 | }; |
| 64 | |
| 65 | // Constructs an instance with the given target |env|, which is used to decode |
| 66 | // the binaries to be optimized later. |
| 67 | // |
| 68 | // The constructed instance will have an empty message consumer, which just |
| 69 | // ignores all messages from the library. Use SetMessageConsumer() to supply |
| 70 | // one if messages are of concern. |
| 71 | explicit Optimizer(spv_target_env env); |
| 72 | |
| 73 | // Disables copy/move constructor/assignment operations. |
| 74 | Optimizer(const Optimizer&) = delete; |
| 75 | Optimizer(Optimizer&&) = delete; |
| 76 | Optimizer& operator=(const Optimizer&) = delete; |
| 77 | Optimizer& operator=(Optimizer&&) = delete; |
| 78 | |
| 79 | // Destructs this instance. |
| 80 | ~Optimizer(); |
| 81 | |
| 82 | // Sets the message consumer to the given |consumer|. The |consumer| will be |
| 83 | // invoked once for each message communicated from the library. |
| 84 | void SetMessageConsumer(MessageConsumer consumer); |
| 85 | |
| 86 | // Returns a reference to the registered message consumer. |
| 87 | const MessageConsumer& consumer() const; |
| 88 | |
| 89 | // Registers the given |pass| to this optimizer. Passes will be run in the |
| 90 | // exact order of registration. The token passed in will be consumed by this |
| 91 | // method. |
| 92 | Optimizer& RegisterPass(PassToken&& pass); |
| 93 | |
| 94 | // Registers passes that attempt to improve performance of generated code. |
| 95 | // This sequence of passes is subject to constant review and will change |
| 96 | // from time to time. |
| 97 | Optimizer& RegisterPerformancePasses(); |
| 98 | |
| 99 | // Registers passes that attempt to improve the size of generated code. |
| 100 | // This sequence of passes is subject to constant review and will change |
| 101 | // from time to time. |
| 102 | Optimizer& RegisterSizePasses(); |
| 103 | |
| 104 | // Registers passes that have been prescribed for WebGPU environments. |
| 105 | // This sequence of passes is subject to constant review and will change |
| 106 | // from time to time. |
| 107 | Optimizer& RegisterWebGPUPasses(); |
| 108 | |
| 109 | // Registers passes that attempt to legalize the generated code. |
| 110 | // |
| 111 | // Note: this recipe is specially designed for legalizing SPIR-V. It should be |
| 112 | // used by compilers after translating HLSL source code literally. It should |
| 113 | // *not* be used by general workloads for performance or size improvement. |
| 114 | // |
| 115 | // This sequence of passes is subject to constant review and will change |
| 116 | // from time to time. |
| 117 | Optimizer& RegisterLegalizationPasses(); |
| 118 | |
| 119 | // Register passes specified in the list of |flags|. Each flag must be a |
| 120 | // string of a form accepted by Optimizer::FlagHasValidForm(). |
| 121 | // |
| 122 | // If the list of flags contains an invalid entry, it returns false and an |
| 123 | // error message is emitted to the MessageConsumer object (use |
| 124 | // Optimizer::SetMessageConsumer to define a message consumer, if needed). |
| 125 | // |
| 126 | // If all the passes are registered successfully, it returns true. |
| 127 | bool RegisterPassesFromFlags(const std::vector<std::string>& flags); |
| 128 | |
| 129 | // Registers the optimization pass associated with |flag|. This only accepts |
| 130 | // |flag| values of the form "--pass_name[=pass_args]". If no such pass |
| 131 | // exists, it returns false. Otherwise, the pass is registered and it returns |
| 132 | // true. |
| 133 | // |
| 134 | // The following flags have special meaning: |
| 135 | // |
| 136 | // -O: Registers all performance optimization passes |
| 137 | // (Optimizer::RegisterPerformancePasses) |
| 138 | // |
| 139 | // -Os: Registers all size optimization passes |
| 140 | // (Optimizer::RegisterSizePasses). |
| 141 | // |
| 142 | // --legalize-hlsl: Registers all passes that legalize SPIR-V generated by an |
| 143 | // HLSL front-end. |
| 144 | bool RegisterPassFromFlag(const std::string& flag); |
| 145 | |
| 146 | // Validates that |flag| has a valid format. Strings accepted: |
| 147 | // |
| 148 | // --pass_name[=pass_args] |
| 149 | // -O |
| 150 | // -Os |
| 151 | // |
| 152 | // If |flag| takes one of the forms above, it returns true. Otherwise, it |
| 153 | // returns false. |
| 154 | bool FlagHasValidForm(const std::string& flag) const; |
| 155 | |
| 156 | // Allows changing, after creation time, the target environment to be |
| 157 | // optimized for. Should be called before calling Run(). |
| 158 | void SetTargetEnv(const spv_target_env env); |
| 159 | |
| 160 | // Optimizes the given SPIR-V module |original_binary| and writes the |
| 161 | // optimized binary into |optimized_binary|. |
| 162 | // Returns true on successful optimization, whether or not the module is |
| 163 | // modified. Returns false if |original_binary| fails to validate or if errors |
| 164 | // occur when processing |original_binary| using any of the registered passes. |
| 165 | // In that case, no further passes are executed and the contents in |
| 166 | // |optimized_binary| may be invalid. |
| 167 | // |
| 168 | // It's allowed to alias |original_binary| to the start of |optimized_binary|. |
| 169 | bool Run(const uint32_t* original_binary, size_t original_binary_size, |
| 170 | std::vector<uint32_t>* optimized_binary) const; |
| 171 | |
| 172 | // DEPRECATED: Same as above, except passes |options| to the validator when |
| 173 | // trying to validate the binary. If |skip_validation| is true, then the |
| 174 | // caller is guaranteeing that |original_binary| is valid, and the validator |
| 175 | // will not be run. The |max_id_bound| is the limit on the max id in the |
| 176 | // module. |
| 177 | bool Run(const uint32_t* original_binary, const size_t original_binary_size, |
| 178 | std::vector<uint32_t>* optimized_binary, |
| 179 | const ValidatorOptions& options, bool skip_validation) const; |
| 180 | |
| 181 | // Same as above, except it takes an options object. See the documentation |
| 182 | // for |OptimizerOptions| to see which options can be set. |
| 183 | bool Run(const uint32_t* original_binary, const size_t original_binary_size, |
| 184 | std::vector<uint32_t>* optimized_binary, |
| 185 | const spv_optimizer_options opt_options) const; |
| 186 | |
| 187 | // Returns a vector of strings with all the pass names added to this |
| 188 | // optimizer's pass manager. These strings are valid until the associated |
| 189 | // pass manager is destroyed. |
| 190 | std::vector<const char*> GetPassNames() const; |
| 191 | |
| 192 | // Sets the option to print the disassembly before each pass and after the |
| 193 | // last pass. If |out| is null, then no output is generated. Otherwise, |
| 194 | // output is sent to the |out| output stream. |
| 195 | Optimizer& SetPrintAll(std::ostream* out); |
| 196 | |
| 197 | // Sets the option to print the resource utilization of each pass. If |out| |
| 198 | // is null, then no output is generated. Otherwise, output is sent to the |
| 199 | // |out| output stream. |
| 200 | Optimizer& SetTimeReport(std::ostream* out); |
| 201 | |
| 202 | private: |
| 203 | struct Impl; // Opaque struct for holding internal data. |
| 204 | std::unique_ptr<Impl> impl_; // Unique pointer to internal data. |
| 205 | }; |
| 206 | |
| 207 | // Creates a null pass. |
| 208 | // A null pass does nothing to the SPIR-V module to be optimized. |
| 209 | Optimizer::PassToken CreateNullPass(); |
| 210 | |
| 211 | // Creates a strip-debug-info pass. |
| 212 | // A strip-debug-info pass removes all debug instructions (as documented in |
| 213 | // Section 3.32.2 of the SPIR-V spec) of the SPIR-V module to be optimized. |
| 214 | Optimizer::PassToken CreateStripDebugInfoPass(); |
| 215 | |
| 216 | // Creates a strip-reflect-info pass. |
| 217 | // A strip-reflect-info pass removes all reflections instructions. |
| 218 | // For now, this is limited to removing decorations defined in |
| 219 | // SPV_GOOGLE_hlsl_functionality1. The coverage may expand in |
| 220 | // the future. |
| 221 | Optimizer::PassToken CreateStripReflectInfoPass(); |
| 222 | |
| 223 | // Creates an eliminate-dead-functions pass. |
| 224 | // An eliminate-dead-functions pass will remove all functions that are not in |
| 225 | // the call trees rooted at entry points and exported functions. These |
| 226 | // functions are not needed because they will never be called. |
| 227 | Optimizer::PassToken CreateEliminateDeadFunctionsPass(); |
| 228 | |
| 229 | // Creates a set-spec-constant-default-value pass from a mapping from spec-ids |
| 230 | // to the default values in the form of string. |
| 231 | // A set-spec-constant-default-value pass sets the default values for the |
| 232 | // spec constants that have SpecId decorations (i.e., those defined by |
| 233 | // OpSpecConstant{|True|False} instructions). |
| 234 | Optimizer::PassToken CreateSetSpecConstantDefaultValuePass( |
| 235 | const std::unordered_map<uint32_t, std::string>& id_value_map); |
| 236 | |
| 237 | // Creates a set-spec-constant-default-value pass from a mapping from spec-ids |
| 238 | // to the default values in the form of bit pattern. |
| 239 | // A set-spec-constant-default-value pass sets the default values for the |
| 240 | // spec constants that have SpecId decorations (i.e., those defined by |
| 241 | // OpSpecConstant{|True|False} instructions). |
| 242 | Optimizer::PassToken CreateSetSpecConstantDefaultValuePass( |
| 243 | const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map); |
| 244 | |
| 245 | // Creates a flatten-decoration pass. |
| 246 | // A flatten-decoration pass replaces grouped decorations with equivalent |
| 247 | // ungrouped decorations. That is, it replaces each OpDecorationGroup |
| 248 | // instruction and associated OpGroupDecorate and OpGroupMemberDecorate |
| 249 | // instructions with equivalent OpDecorate and OpMemberDecorate instructions. |
| 250 | // The pass does not attempt to preserve debug information for instructions |
| 251 | // it removes. |
| 252 | Optimizer::PassToken CreateFlattenDecorationPass(); |
| 253 | |
| 254 | // Creates a freeze-spec-constant-value pass. |
| 255 | // A freeze-spec-constant pass specializes the value of spec constants to |
| 256 | // their default values. This pass only processes the spec constants that have |
| 257 | // SpecId decorations (defined by OpSpecConstant, OpSpecConstantTrue, or |
| 258 | // OpSpecConstantFalse instructions) and replaces them with their normal |
| 259 | // counterparts (OpConstant, OpConstantTrue, or OpConstantFalse). The |
| 260 | // corresponding SpecId annotation instructions will also be removed. This |
| 261 | // pass does not fold the newly added normal constants and does not process |
| 262 | // other spec constants defined by OpSpecConstantComposite or |
| 263 | // OpSpecConstantOp. |
| 264 | Optimizer::PassToken CreateFreezeSpecConstantValuePass(); |
| 265 | |
| 266 | // Creates a fold-spec-constant-op-and-composite pass. |
| 267 | // A fold-spec-constant-op-and-composite pass folds spec constants defined by |
| 268 | // OpSpecConstantOp or OpSpecConstantComposite instruction, to normal Constants |
| 269 | // defined by OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull, or |
| 270 | // OpConstantComposite instructions. Note that spec constants defined with |
| 271 | // OpSpecConstant, OpSpecConstantTrue, or OpSpecConstantFalse instructions are |
| 272 | // not handled, as these instructions indicate their value are not determined |
| 273 | // and can be changed in future. A spec constant is foldable if all of its |
| 274 | // value(s) can be determined from the module. E.g., an integer spec constant |
| 275 | // defined with OpSpecConstantOp instruction can be folded if its value won't |
| 276 | // change later. This pass will replace the original OpSpecContantOp instruction |
| 277 | // with an OpConstant instruction. When folding composite spec constants, |
| 278 | // new instructions may be inserted to define the components of the composite |
| 279 | // constant first, then the original spec constants will be replaced by |
| 280 | // OpConstantComposite instructions. |
| 281 | // |
| 282 | // There are some operations not supported yet: |
| 283 | // OpSConvert, OpFConvert, OpQuantizeToF16 and |
| 284 | // all the operations under Kernel capability. |
| 285 | // TODO(qining): Add support for the operations listed above. |
| 286 | Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass(); |
| 287 | |
| 288 | // Creates a unify-constant pass. |
| 289 | // A unify-constant pass de-duplicates the constants. Constants with the exact |
| 290 | // same value and identical form will be unified and only one constant will |
| 291 | // be kept for each unique pair of type and value. |
| 292 | // There are several cases not handled by this pass: |
| 293 | // 1) Constants defined by OpConstantNull instructions (null constants) and |
| 294 | // constants defined by OpConstantFalse, OpConstant or OpConstantComposite |
| 295 | // with value 0 (zero-valued normal constants) are not considered equivalent. |
| 296 | // So null constants won't be used to replace zero-valued normal constants, |
| 297 | // vice versa. |
| 298 | // 2) Whenever there are decorations to the constant's result id id, the |
| 299 | // constant won't be handled, which means, it won't be used to replace any |
| 300 | // other constants, neither can other constants replace it. |
| 301 | // 3) NaN in float point format with different bit patterns are not unified. |
| 302 | Optimizer::PassToken CreateUnifyConstantPass(); |
| 303 | |
| 304 | // Creates a eliminate-dead-constant pass. |
| 305 | // A eliminate-dead-constant pass removes dead constants, including normal |
| 306 | // contants defined by OpConstant, OpConstantComposite, OpConstantTrue, or |
| 307 | // OpConstantFalse and spec constants defined by OpSpecConstant, |
| 308 | // OpSpecConstantComposite, OpSpecConstantTrue, OpSpecConstantFalse or |
| 309 | // OpSpecConstantOp. |
| 310 | Optimizer::PassToken CreateEliminateDeadConstantPass(); |
| 311 | |
| 312 | // Creates a strength-reduction pass. |
| 313 | // A strength-reduction pass will look for opportunities to replace an |
| 314 | // instruction with an equivalent and less expensive one. For example, |
| 315 | // multiplying by a power of 2 can be replaced by a bit shift. |
| 316 | Optimizer::PassToken CreateStrengthReductionPass(); |
| 317 | |
| 318 | // Creates a block merge pass. |
| 319 | // This pass searches for blocks with a single Branch to a block with no |
| 320 | // other predecessors and merges the blocks into a single block. Continue |
| 321 | // blocks and Merge blocks are not candidates for the second block. |
| 322 | // |
| 323 | // The pass is most useful after Dead Branch Elimination, which can leave |
| 324 | // such sequences of blocks. Merging them makes subsequent passes more |
| 325 | // effective, such as single block local store-load elimination. |
| 326 | // |
| 327 | // While this pass reduces the number of occurrences of this sequence, at |
| 328 | // this time it does not guarantee all such sequences are eliminated. |
| 329 | // |
| 330 | // Presence of phi instructions can inhibit this optimization. Handling |
| 331 | // these is left for future improvements. |
| 332 | Optimizer::PassToken CreateBlockMergePass(); |
| 333 | |
| 334 | // Creates an exhaustive inline pass. |
| 335 | // An exhaustive inline pass attempts to exhaustively inline all function |
| 336 | // calls in all functions in an entry point call tree. The intent is to enable, |
| 337 | // albeit through brute force, analysis and optimization across function |
| 338 | // calls by subsequent optimization passes. As the inlining is exhaustive, |
| 339 | // there is no attempt to optimize for size or runtime performance. Functions |
| 340 | // that are not in the call tree of an entry point are not changed. |
| 341 | Optimizer::PassToken CreateInlineExhaustivePass(); |
| 342 | |
| 343 | // Creates an opaque inline pass. |
| 344 | // An opaque inline pass inlines all function calls in all functions in all |
| 345 | // entry point call trees where the called function contains an opaque type |
| 346 | // in either its parameter types or return type. An opaque type is currently |
| 347 | // defined as Image, Sampler or SampledImage. The intent is to enable, albeit |
| 348 | // through brute force, analysis and optimization across these function calls |
| 349 | // by subsequent passes in order to remove the storing of opaque types which is |
| 350 | // not legal in Vulkan. Functions that are not in the call tree of an entry |
| 351 | // point are not changed. |
| 352 | Optimizer::PassToken CreateInlineOpaquePass(); |
| 353 | |
| 354 | // Creates a single-block local variable load/store elimination pass. |
| 355 | // For every entry point function, do single block memory optimization of |
| 356 | // function variables referenced only with non-access-chain loads and stores. |
| 357 | // For each targeted variable load, if previous store to that variable in the |
| 358 | // block, replace the load's result id with the value id of the store. |
| 359 | // If previous load within the block, replace the current load's result id |
| 360 | // with the previous load's result id. In either case, delete the current |
| 361 | // load. Finally, check if any remaining stores are useless, and delete store |
| 362 | // and variable if possible. |
| 363 | // |
| 364 | // The presence of access chain references and function calls can inhibit |
| 365 | // the above optimization. |
| 366 | // |
| 367 | // Only modules with relaxed logical addressing (see opt/instruction.h) are |
| 368 | // currently processed. |
| 369 | // |
| 370 | // This pass is most effective if preceeded by Inlining and |
| 371 | // LocalAccessChainConvert. This pass will reduce the work needed to be done |
| 372 | // by LocalSingleStoreElim and LocalMultiStoreElim. |
| 373 | // |
| 374 | // Only functions in the call tree of an entry point are processed. |
| 375 | Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass(); |
| 376 | |
| 377 | // Create dead branch elimination pass. |
| 378 | // For each entry point function, this pass will look for SelectionMerge |
| 379 | // BranchConditionals with constant condition and convert to a Branch to |
| 380 | // the indicated label. It will delete resulting dead blocks. |
| 381 | // |
| 382 | // For all phi functions in merge block, replace all uses with the id |
| 383 | // corresponding to the living predecessor. |
| 384 | // |
| 385 | // Note that some branches and blocks may be left to avoid creating invalid |
| 386 | // control flow. Improving this is left to future work. |
| 387 | // |
| 388 | // This pass is most effective when preceeded by passes which eliminate |
| 389 | // local loads and stores, effectively propagating constant values where |
| 390 | // possible. |
| 391 | Optimizer::PassToken CreateDeadBranchElimPass(); |
| 392 | |
| 393 | // Creates an SSA local variable load/store elimination pass. |
| 394 | // For every entry point function, eliminate all loads and stores of function |
| 395 | // scope variables only referenced with non-access-chain loads and stores. |
| 396 | // Eliminate the variables as well. |
| 397 | // |
| 398 | // The presence of access chain references and function calls can inhibit |
| 399 | // the above optimization. |
| 400 | // |
| 401 | // Only shader modules with relaxed logical addressing (see opt/instruction.h) |
| 402 | // are currently processed. Currently modules with any extensions enabled are |
| 403 | // not processed. This is left for future work. |
| 404 | // |
| 405 | // This pass is most effective if preceeded by Inlining and |
| 406 | // LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim |
| 407 | // will reduce the work that this pass has to do. |
| 408 | Optimizer::PassToken CreateLocalMultiStoreElimPass(); |
| 409 | |
| 410 | // Creates a local access chain conversion pass. |
| 411 | // A local access chain conversion pass identifies all function scope |
| 412 | // variables which are accessed only with loads, stores and access chains |
| 413 | // with constant indices. It then converts all loads and stores of such |
| 414 | // variables into equivalent sequences of loads, stores, extracts and inserts. |
| 415 | // |
| 416 | // This pass only processes entry point functions. It currently only converts |
| 417 | // non-nested, non-ptr access chains. It does not process modules with |
| 418 | // non-32-bit integer types present. Optional memory access options on loads |
| 419 | // and stores are ignored as we are only processing function scope variables. |
| 420 | // |
| 421 | // This pass unifies access to these variables to a single mode and simplifies |
| 422 | // subsequent analysis and elimination of these variables along with their |
| 423 | // loads and stores allowing values to propagate to their points of use where |
| 424 | // possible. |
| 425 | Optimizer::PassToken CreateLocalAccessChainConvertPass(); |
| 426 | |
| 427 | // Creates a local single store elimination pass. |
| 428 | // For each entry point function, this pass eliminates loads and stores for |
| 429 | // function scope variable that are stored to only once, where possible. Only |
| 430 | // whole variable loads and stores are eliminated; access-chain references are |
| 431 | // not optimized. Replace all loads of such variables with the value that is |
| 432 | // stored and eliminate any resulting dead code. |
| 433 | // |
| 434 | // Currently, the presence of access chains and function calls can inhibit this |
| 435 | // pass, however the Inlining and LocalAccessChainConvert passes can make it |
| 436 | // more effective. In additional, many non-load/store memory operations are |
| 437 | // not supported and will prohibit optimization of a function. Support of |
| 438 | // these operations are future work. |
| 439 | // |
| 440 | // Only shader modules with relaxed logical addressing (see opt/instruction.h) |
| 441 | // are currently processed. |
| 442 | // |
| 443 | // This pass will reduce the work needed to be done by LocalSingleBlockElim |
| 444 | // and LocalMultiStoreElim and can improve the effectiveness of other passes |
| 445 | // such as DeadBranchElimination which depend on values for their analysis. |
| 446 | Optimizer::PassToken CreateLocalSingleStoreElimPass(); |
| 447 | |
| 448 | // Creates an insert/extract elimination pass. |
| 449 | // This pass processes each entry point function in the module, searching for |
| 450 | // extracts on a sequence of inserts. It further searches the sequence for an |
| 451 | // insert with indices identical to the extract. If such an insert can be |
| 452 | // found before hitting a conflicting insert, the extract's result id is |
| 453 | // replaced with the id of the values from the insert. |
| 454 | // |
| 455 | // Besides removing extracts this pass enables subsequent dead code elimination |
| 456 | // passes to delete the inserts. This pass performs best after access chains are |
| 457 | // converted to inserts and extracts and local loads and stores are eliminated. |
| 458 | Optimizer::PassToken CreateInsertExtractElimPass(); |
| 459 | |
| 460 | // Creates a dead insert elimination pass. |
| 461 | // This pass processes each entry point function in the module, searching for |
| 462 | // unreferenced inserts into composite types. These are most often unused |
| 463 | // stores to vector components. They are unused because they are never |
| 464 | // referenced, or because there is another insert to the same component between |
| 465 | // the insert and the reference. After removing the inserts, dead code |
| 466 | // elimination is attempted on the inserted values. |
| 467 | // |
| 468 | // This pass performs best after access chains are converted to inserts and |
| 469 | // extracts and local loads and stores are eliminated. While executing this |
| 470 | // pass can be advantageous on its own, it is also advantageous to execute |
| 471 | // this pass after CreateInsertExtractPass() as it will remove any unused |
| 472 | // inserts created by that pass. |
| 473 | Optimizer::PassToken CreateDeadInsertElimPass(); |
| 474 | |
| 475 | // Creates a pass to consolidate uniform references. |
| 476 | // For each entry point function in the module, first change all constant index |
| 477 | // access chain loads into equivalent composite extracts. Then consolidate |
| 478 | // identical uniform loads into one uniform load. Finally, consolidate |
| 479 | // identical uniform extracts into one uniform extract. This may require |
| 480 | // moving a load or extract to a point which dominates all uses. |
| 481 | // |
| 482 | // This pass requires a module to have structured control flow ie shader |
| 483 | // capability. It also requires logical addressing ie Addresses capability |
| 484 | // is not enabled. It also currently does not support any extensions. |
| 485 | // |
| 486 | // This pass currently only optimizes loads with a single index. |
| 487 | Optimizer::PassToken CreateCommonUniformElimPass(); |
| 488 | |
| 489 | // Create aggressive dead code elimination pass |
| 490 | // This pass eliminates unused code from the module. In addition, |
| 491 | // it detects and eliminates code which may have spurious uses but which do |
| 492 | // not contribute to the output of the function. The most common cause of |
| 493 | // such code sequences is summations in loops whose result is no longer used |
| 494 | // due to dead code elimination. This optimization has additional compile |
| 495 | // time cost over standard dead code elimination. |
| 496 | // |
| 497 | // This pass only processes entry point functions. It also only processes |
| 498 | // shaders with relaxed logical addressing (see opt/instruction.h). It |
| 499 | // currently will not process functions with function calls. Unreachable |
| 500 | // functions are deleted. |
| 501 | // |
| 502 | // This pass will be made more effective by first running passes that remove |
| 503 | // dead control flow and inlines function calls. |
| 504 | // |
| 505 | // This pass can be especially useful after running Local Access Chain |
| 506 | // Conversion, which tends to cause cycles of dead code to be left after |
| 507 | // Store/Load elimination passes are completed. These cycles cannot be |
| 508 | // eliminated with standard dead code elimination. |
| 509 | Optimizer::PassToken CreateAggressiveDCEPass(); |
| 510 | |
| 511 | // Create line propagation pass |
| 512 | // This pass propagates line information based on the rules for OpLine and |
| 513 | // OpNoline and clones an appropriate line instruction into every instruction |
| 514 | // which does not already have debug line instructions. |
| 515 | // |
| 516 | // This pass is intended to maximize preservation of source line information |
| 517 | // through passes which delete, move and clone instructions. Ideally it should |
| 518 | // be run before any such pass. It is a bookend pass with EliminateDeadLines |
| 519 | // which can be used to remove redundant line instructions at the end of a |
| 520 | // run of such passes and reduce final output file size. |
| 521 | Optimizer::PassToken CreatePropagateLineInfoPass(); |
| 522 | |
| 523 | // Create dead line elimination pass |
| 524 | // This pass eliminates redundant line instructions based on the rules for |
| 525 | // OpLine and OpNoline. Its main purpose is to reduce the size of the file |
| 526 | // need to store the SPIR-V without losing line information. |
| 527 | // |
| 528 | // This is a bookend pass with PropagateLines which attaches line instructions |
| 529 | // to every instruction to preserve line information during passes which |
| 530 | // delete, move and clone instructions. DeadLineElim should be run after |
| 531 | // PropagateLines and all such subsequent passes. Normally it would be one |
| 532 | // of the last passes to be run. |
| 533 | Optimizer::PassToken CreateRedundantLineInfoElimPass(); |
| 534 | |
| 535 | // Creates a compact ids pass. |
| 536 | // The pass remaps result ids to a compact and gapless range starting from %1. |
| 537 | Optimizer::PassToken CreateCompactIdsPass(); |
| 538 | |
| 539 | // Creates a remove duplicate pass. |
| 540 | // This pass removes various duplicates: |
| 541 | // * duplicate capabilities; |
| 542 | // * duplicate extended instruction imports; |
| 543 | // * duplicate types; |
| 544 | // * duplicate decorations. |
| 545 | Optimizer::PassToken CreateRemoveDuplicatesPass(); |
| 546 | |
| 547 | // Creates a CFG cleanup pass. |
| 548 | // This pass removes cruft from the control flow graph of functions that are |
| 549 | // reachable from entry points and exported functions. It currently includes the |
| 550 | // following functionality: |
| 551 | // |
| 552 | // - Removal of unreachable basic blocks. |
| 553 | Optimizer::PassToken CreateCFGCleanupPass(); |
| 554 | |
| 555 | // Create dead variable elimination pass. |
| 556 | // This pass will delete module scope variables, along with their decorations, |
| 557 | // that are not referenced. |
| 558 | Optimizer::PassToken CreateDeadVariableEliminationPass(); |
| 559 | |
| 560 | // create merge return pass. |
| 561 | // changes functions that have multiple return statements so they have a single |
| 562 | // return statement. |
| 563 | // |
| 564 | // for structured control flow it is assumed that the only unreachable blocks in |
| 565 | // the function are trivial merge and continue blocks. |
| 566 | // |
| 567 | // a trivial merge block contains the label and an opunreachable instructions, |
| 568 | // nothing else. a trivial continue block contain a label and an opbranch to |
| 569 | // the header, nothing else. |
| 570 | // |
| 571 | // these conditions are guaranteed to be met after running dead-branch |
| 572 | // elimination. |
| 573 | Optimizer::PassToken CreateMergeReturnPass(); |
| 574 | |
| 575 | // Create value numbering pass. |
| 576 | // This pass will look for instructions in the same basic block that compute the |
| 577 | // same value, and remove the redundant ones. |
| 578 | Optimizer::PassToken CreateLocalRedundancyEliminationPass(); |
| 579 | |
| 580 | // Create LICM pass. |
| 581 | // This pass will look for invariant instructions inside loops and hoist them to |
| 582 | // the loops preheader. |
| 583 | Optimizer::PassToken CreateLoopInvariantCodeMotionPass(); |
| 584 | |
| 585 | // Creates a loop fission pass. |
| 586 | // This pass will split all top level loops whose register pressure exceedes the |
| 587 | // given |threshold|. |
| 588 | Optimizer::PassToken CreateLoopFissionPass(size_t threshold); |
| 589 | |
| 590 | // Creates a loop fusion pass. |
| 591 | // This pass will look for adjacent loops that are compatible and legal to be |
| 592 | // fused. The fuse all such loops as long as the register usage for the fused |
| 593 | // loop stays under the threshold defined by |max_registers_per_loop|. |
| 594 | Optimizer::PassToken CreateLoopFusionPass(size_t max_registers_per_loop); |
| 595 | |
| 596 | // Creates a loop peeling pass. |
| 597 | // This pass will look for conditions inside a loop that are true or false only |
| 598 | // for the N first or last iteration. For loop with such condition, those N |
| 599 | // iterations of the loop will be executed outside of the main loop. |
| 600 | // To limit code size explosion, the loop peeling can only happen if the code |
| 601 | // size growth for each loop is under |code_growth_threshold|. |
| 602 | Optimizer::PassToken CreateLoopPeelingPass(); |
| 603 | |
| 604 | // Creates a loop unswitch pass. |
| 605 | // This pass will look for loop independent branch conditions and move the |
| 606 | // condition out of the loop and version the loop based on the taken branch. |
| 607 | // Works best after LICM and local multi store elimination pass. |
| 608 | Optimizer::PassToken CreateLoopUnswitchPass(); |
| 609 | |
| 610 | // Create global value numbering pass. |
| 611 | // This pass will look for instructions where the same value is computed on all |
| 612 | // paths leading to the instruction. Those instructions are deleted. |
| 613 | Optimizer::PassToken CreateRedundancyEliminationPass(); |
| 614 | |
| 615 | // Create scalar replacement pass. |
| 616 | // This pass replaces composite function scope variables with variables for each |
| 617 | // element if those elements are accessed individually. The parameter is a |
| 618 | // limit on the number of members in the composite variable that the pass will |
| 619 | // consider replacing. |
| 620 | Optimizer::PassToken CreateScalarReplacementPass(uint32_t size_limit = 100); |
| 621 | |
| 622 | // Create a private to local pass. |
| 623 | // This pass looks for variables delcared in the private storage class that are |
| 624 | // used in only one function. Those variables are moved to the function storage |
| 625 | // class in the function that they are used. |
| 626 | Optimizer::PassToken CreatePrivateToLocalPass(); |
| 627 | |
| 628 | // Creates a conditional constant propagation (CCP) pass. |
| 629 | // This pass implements the SSA-CCP algorithm in |
| 630 | // |
| 631 | // Constant propagation with conditional branches, |
| 632 | // Wegman and Zadeck, ACM TOPLAS 13(2):181-210. |
| 633 | // |
| 634 | // Constant values in expressions and conditional jumps are folded and |
| 635 | // simplified. This may reduce code size by removing never executed jump targets |
| 636 | // and computations with constant operands. |
| 637 | Optimizer::PassToken CreateCCPPass(); |
| 638 | |
| 639 | // Creates a workaround driver bugs pass. This pass attempts to work around |
| 640 | // a known driver bug (issue #1209) by identifying the bad code sequences and |
| 641 | // rewriting them. |
| 642 | // |
| 643 | // Current workaround: Avoid OpUnreachable instructions in loops. |
| 644 | Optimizer::PassToken CreateWorkaround1209Pass(); |
| 645 | |
| 646 | // Creates a pass that converts if-then-else like assignments into OpSelect. |
| 647 | Optimizer::PassToken CreateIfConversionPass(); |
| 648 | |
| 649 | // Creates a pass that will replace instructions that are not valid for the |
| 650 | // current shader stage by constants. Has no effect on non-shader modules. |
| 651 | Optimizer::PassToken CreateReplaceInvalidOpcodePass(); |
| 652 | |
| 653 | // Creates a pass that simplifies instructions using the instruction folder. |
| 654 | Optimizer::PassToken CreateSimplificationPass(); |
| 655 | |
| 656 | // Create loop unroller pass. |
| 657 | // Creates a pass to unroll loops which have the "Unroll" loop control |
| 658 | // mask set. The loops must meet a specific criteria in order to be unrolled |
| 659 | // safely this criteria is checked before doing the unroll by the |
| 660 | // LoopUtils::CanPerformUnroll method. Any loop that does not meet the criteria |
| 661 | // won't be unrolled. See CanPerformUnroll LoopUtils.h for more information. |
| 662 | Optimizer::PassToken CreateLoopUnrollPass(bool fully_unroll, int factor = 0); |
| 663 | |
| 664 | // Create the SSA rewrite pass. |
| 665 | // This pass converts load/store operations on function local variables into |
| 666 | // operations on SSA IDs. This allows SSA optimizers to act on these variables. |
| 667 | // Only variables that are local to the function and of supported types are |
| 668 | // processed (see IsSSATargetVar for details). |
| 669 | Optimizer::PassToken CreateSSARewritePass(); |
| 670 | |
| 671 | // Create copy propagate arrays pass. |
| 672 | // This pass looks to copy propagate memory references for arrays. It looks |
| 673 | // for specific code patterns to recognize array copies. |
| 674 | Optimizer::PassToken CreateCopyPropagateArraysPass(); |
| 675 | |
| 676 | // Create a vector dce pass. |
| 677 | // This pass looks for components of vectors that are unused, and removes them |
| 678 | // from the vector. Note this would still leave around lots of dead code that |
| 679 | // a pass of ADCE will be able to remove. |
| 680 | Optimizer::PassToken CreateVectorDCEPass(); |
| 681 | |
| 682 | // Create a pass to reduce the size of loads. |
| 683 | // This pass looks for loads of structures where only a few of its members are |
| 684 | // used. It replaces the loads feeding an OpExtract with an OpAccessChain and |
| 685 | // a load of the specific elements. |
| 686 | Optimizer::PassToken CreateReduceLoadSizePass(); |
| 687 | |
| 688 | // Create a pass to combine chained access chains. |
| 689 | // This pass looks for access chains fed by other access chains and combines |
| 690 | // them into a single instruction where possible. |
| 691 | Optimizer::PassToken CreateCombineAccessChainsPass(); |
| 692 | |
| 693 | // Create a pass to instrument bindless descriptor checking |
| 694 | // This pass instruments all bindless references to check that descriptor |
| 695 | // array indices are inbounds. If the reference is invalid, a record is |
| 696 | // written to the debug output buffer (if space allows) and a null value is |
| 697 | // returned. This pass is designed to support bindless validation in the Vulkan |
| 698 | // validation layers. |
| 699 | // |
| 700 | // Dead code elimination should be run after this pass as the original, |
| 701 | // potentially invalid code is not removed and could cause undefined behavior, |
| 702 | // including crashes. It may also be beneficial to run Simplification |
| 703 | // (ie Constant Propagation), DeadBranchElim and BlockMerge after this pass to |
| 704 | // optimize instrument code involving the testing of compile-time constants. |
| 705 | // It is also generally recommended that this pass (and all |
| 706 | // instrumentation passes) be run after any legalization and optimization |
| 707 | // passes. This will give better analysis for the instrumentation and avoid |
| 708 | // potentially de-optimizing the instrument code, for example, inlining |
| 709 | // the debug record output function throughout the module. |
| 710 | // |
| 711 | // The instrumentation will read and write buffers in debug |
| 712 | // descriptor set |desc_set|. It will write |shader_id| in each output record |
| 713 | // to identify the shader module which generated the record. |
| 714 | // |
| 715 | // TODO(greg-lunarg): Add support for vk_ext_descriptor_indexing. |
| 716 | Optimizer::PassToken CreateInstBindlessCheckPass(uint32_t desc_set, |
| 717 | uint32_t shader_id); |
| 718 | |
| 719 | // Create a pass to upgrade to the VulkanKHR memory model. |
| 720 | // This pass upgrades the Logical GLSL450 memory model to Logical VulkanKHR. |
| 721 | // Additionally, it modifies memory, image, atomic and barrier operations to |
| 722 | // conform to that model's requirements. |
| 723 | Optimizer::PassToken CreateUpgradeMemoryModelPass(); |
| 724 | |
| 725 | // Create a pass to do code sinking. Code sinking is a transformation |
| 726 | // where an instruction is moved into a more deeply nested construct. |
| 727 | Optimizer::PassToken CreateCodeSinkingPass(); |
| 728 | |
| 729 | } // namespace spvtools |
| 730 | |
| 731 | #endif // INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_ |