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