blob: 6f08efd1d5478c643e5c6a4c51e6267b8ca3300f [file] [log] [blame]
Lei Zhangf18e1f22016-09-12 14:11:46 -04001// 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
dan sinclair58a68762018-08-03 08:05:33 -040015#ifndef INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_
16#define INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_
Lei Zhangf18e1f22016-09-12 14:11:46 -040017
18#include <memory>
David Netoc32e79e2018-01-04 12:59:50 -050019#include <ostream>
Lei Zhangf18e1f22016-09-12 14:11:46 -040020#include <string>
21#include <unordered_map>
22#include <vector>
23
24#include "libspirv.hpp"
Lei Zhangf18e1f22016-09-12 14:11:46 -040025
26namespace spvtools {
27
Arseny Kapoulkinef765d162018-05-22 14:31:26 -070028namespace opt {
29class Pass;
30}
31
Lei Zhangf18e1f22016-09-12 14:11:46 -040032// 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.
37class 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
Arseny Kapoulkinef765d162018-05-22 14:31:26 -070048 // 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
Lei Zhangf18e1f22016-09-12 14:11:46 -040054 // 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
Diego Novillo99fe61e2018-07-25 15:21:44 -040086 // Returns a reference to the registered message consumer.
87 const MessageConsumer& consumer() const;
88
Lei Zhangf18e1f22016-09-12 14:11:46 -040089 // 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
Diego Novilloc90d7302017-08-30 14:19:22 -040094 // 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
Lei Zhangaec60b82017-11-17 16:50:43 -0500104 // Registers passes that attempt to legalize the generated code.
105 //
Diego Novillo99fe61e2018-07-25 15:21:44 -0400106 // Note: this recipe is specially designed for legalizing SPIR-V. It should be
107 // used by compilers after translating HLSL source code literally. It should
Lei Zhangaec60b82017-11-17 16:50:43 -0500108 // *not* be used by general workloads for performance or size improvement.
109 //
110 // This sequence of passes is subject to constant review and will change
111 // from time to time.
112 Optimizer& RegisterLegalizationPasses();
113
Diego Novillo99fe61e2018-07-25 15:21:44 -0400114 // Register passes specified in the list of |flags|. Each flag must be a
115 // string of a form accepted by Optimizer::FlagHasValidForm().
116 //
117 // If the list of flags contains an invalid entry, it returns false and an
118 // error message is emitted to the MessageConsumer object (use
119 // Optimizer::SetMessageConsumer to define a message consumer, if needed).
120 //
121 // If all the passes are registered successfully, it returns true.
122 bool RegisterPassesFromFlags(const std::vector<std::string>& flags);
123
124 // Registers the optimization pass associated with |flag|. This only accepts
125 // |flag| values of the form "--pass_name[=pass_args]". If no such pass
126 // exists, it returns false. Otherwise, the pass is registered and it returns
127 // true.
128 //
129 // The following flags have special meaning:
130 //
131 // -O: Registers all performance optimization passes
132 // (Optimizer::RegisterPerformancePasses)
133 //
134 // -Os: Registers all size optimization passes
135 // (Optimizer::RegisterSizePasses).
136 //
137 // --legalize-hlsl: Registers all passes that legalize SPIR-V generated by an
138 // HLSL front-end.
139 bool RegisterPassFromFlag(const std::string& flag);
140
141 // Validates that |flag| has a valid format. Strings accepted:
142 //
143 // --pass_name[=pass_args]
144 // -O
145 // -Os
146 //
147 // If |flag| takes one of the forms above, it returns true. Otherwise, it
148 // returns false.
149 bool FlagHasValidForm(const std::string& flag) const;
150
Lei Zhangf18e1f22016-09-12 14:11:46 -0400151 // Optimizes the given SPIR-V module |original_binary| and writes the
152 // optimized binary into |optimized_binary|.
153 // Returns true on successful optimization, whether or not the module is
Steven Perronbcb0b692018-08-13 13:18:46 -0400154 // modified. Returns false if |original_binary| fails to validate or if errors
155 // occur when processing |original_binary| using any of the registered passes.
156 // In that case, no further passes are executed and the contents in
157 // |optimized_binary| may be invalid.
Lei Zhangf18e1f22016-09-12 14:11:46 -0400158 //
159 // It's allowed to alias |original_binary| to the start of |optimized_binary|.
160 bool Run(const uint32_t* original_binary, size_t original_binary_size,
161 std::vector<uint32_t>* optimized_binary) const;
Steven Perronbcb0b692018-08-13 13:18:46 -0400162
Steven Perron75c1bf22018-09-10 11:49:41 -0400163 // DEPRECATED: Same as above, except passes |options| to the validator when
164 // trying to validate the binary. If |skip_validation| is true, then the
165 // caller is guaranteeing that |original_binary| is valid, and the validator
166 // will not be run. The |max_id_bound| is the limit on the max id in the
167 // module.
Steven Perronbcb0b692018-08-13 13:18:46 -0400168 bool Run(const uint32_t* original_binary, const size_t original_binary_size,
Steven Perron5c8b4f52018-08-08 11:16:19 -0400169 std::vector<uint32_t>* optimized_binary,
Steven Perron75c1bf22018-09-10 11:49:41 -0400170 const ValidatorOptions& options, bool skip_validation) const;
171
172 // Same as above, except it takes an options object. See the documentation
173 // for |OptimizerOptions| to see which options can be set.
174 bool Run(const uint32_t* original_binary, const size_t original_binary_size,
175 std::vector<uint32_t>* optimized_binary,
176 const spv_optimizer_options opt_options) const;
Lei Zhangf18e1f22016-09-12 14:11:46 -0400177
Diego Novilloc90d7302017-08-30 14:19:22 -0400178 // Returns a vector of strings with all the pass names added to this
179 // optimizer's pass manager. These strings are valid until the associated
180 // pass manager is destroyed.
Steven Perron58347192017-10-20 12:17:41 -0400181 std::vector<const char*> GetPassNames() const;
Diego Novilloc90d7302017-08-30 14:19:22 -0400182
David Netoc32e79e2018-01-04 12:59:50 -0500183 // Sets the option to print the disassembly before each pass and after the
184 // last pass. If |out| is null, then no output is generated. Otherwise,
185 // output is sent to the |out| output stream.
186 Optimizer& SetPrintAll(std::ostream* out);
187
Jaebaek Seo3b594e12018-03-07 09:25:51 -0500188 // Sets the option to print the resource utilization of each pass. If |out|
189 // is null, then no output is generated. Otherwise, output is sent to the
190 // |out| output stream.
191 Optimizer& SetTimeReport(std::ostream* out);
192
Lei Zhangf18e1f22016-09-12 14:11:46 -0400193 private:
194 struct Impl; // Opaque struct for holding internal data.
195 std::unique_ptr<Impl> impl_; // Unique pointer to internal data.
196};
197
198// Creates a null pass.
199// A null pass does nothing to the SPIR-V module to be optimized.
200Optimizer::PassToken CreateNullPass();
201
202// Creates a strip-debug-info pass.
203// A strip-debug-info pass removes all debug instructions (as documented in
204// Section 3.32.2 of the SPIR-V spec) of the SPIR-V module to be optimized.
205Optimizer::PassToken CreateStripDebugInfoPass();
206
David Neto844e1862018-03-09 16:08:57 -0500207// Creates a strip-reflect-info pass.
208// A strip-reflect-info pass removes all reflections instructions.
209// For now, this is limited to removing decorations defined in
210// SPV_GOOGLE_hlsl_functionality1. The coverage may expand in
211// the future.
212Optimizer::PassToken CreateStripReflectInfoPass();
213
Steven Perrone43c9102017-09-19 10:12:13 -0400214// Creates an eliminate-dead-functions pass.
Steven Perron58347192017-10-20 12:17:41 -0400215// An eliminate-dead-functions pass will remove all functions that are not in
216// the call trees rooted at entry points and exported functions. These
217// functions are not needed because they will never be called.
Steven Perrone43c9102017-09-19 10:12:13 -0400218Optimizer::PassToken CreateEliminateDeadFunctionsPass();
219
qining144f59e2017-04-19 18:10:59 -0400220// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
221// to the default values in the form of string.
Lei Zhangf18e1f22016-09-12 14:11:46 -0400222// A set-spec-constant-default-value pass sets the default values for the
223// spec constants that have SpecId decorations (i.e., those defined by
224// OpSpecConstant{|True|False} instructions).
225Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
226 const std::unordered_map<uint32_t, std::string>& id_value_map);
227
qining144f59e2017-04-19 18:10:59 -0400228// Creates a set-spec-constant-default-value pass from a mapping from spec-ids
229// to the default values in the form of bit pattern.
230// A set-spec-constant-default-value pass sets the default values for the
231// spec constants that have SpecId decorations (i.e., those defined by
232// OpSpecConstant{|True|False} instructions).
233Optimizer::PassToken CreateSetSpecConstantDefaultValuePass(
234 const std::unordered_map<uint32_t, std::vector<uint32_t>>& id_value_map);
235
David Neto11a867f2017-04-01 16:10:16 -0400236// Creates a flatten-decoration pass.
237// A flatten-decoration pass replaces grouped decorations with equivalent
238// ungrouped decorations. That is, it replaces each OpDecorationGroup
239// instruction and associated OpGroupDecorate and OpGroupMemberDecorate
240// instructions with equivalent OpDecorate and OpMemberDecorate instructions.
241// The pass does not attempt to preserve debug information for instructions
242// it removes.
243Optimizer::PassToken CreateFlattenDecorationPass();
244
Lei Zhangf18e1f22016-09-12 14:11:46 -0400245// Creates a freeze-spec-constant-value pass.
246// A freeze-spec-constant pass specializes the value of spec constants to
247// their default values. This pass only processes the spec constants that have
248// SpecId decorations (defined by OpSpecConstant, OpSpecConstantTrue, or
249// OpSpecConstantFalse instructions) and replaces them with their normal
250// counterparts (OpConstant, OpConstantTrue, or OpConstantFalse). The
251// corresponding SpecId annotation instructions will also be removed. This
252// pass does not fold the newly added normal constants and does not process
253// other spec constants defined by OpSpecConstantComposite or
254// OpSpecConstantOp.
255Optimizer::PassToken CreateFreezeSpecConstantValuePass();
256
257// Creates a fold-spec-constant-op-and-composite pass.
258// A fold-spec-constant-op-and-composite pass folds spec constants defined by
259// OpSpecConstantOp or OpSpecConstantComposite instruction, to normal Constants
260// defined by OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull, or
261// OpConstantComposite instructions. Note that spec constants defined with
262// OpSpecConstant, OpSpecConstantTrue, or OpSpecConstantFalse instructions are
263// not handled, as these instructions indicate their value are not determined
264// and can be changed in future. A spec constant is foldable if all of its
265// value(s) can be determined from the module. E.g., an integer spec constant
266// defined with OpSpecConstantOp instruction can be folded if its value won't
267// change later. This pass will replace the original OpSpecContantOp instruction
268// with an OpConstant instruction. When folding composite spec constants,
269// new instructions may be inserted to define the components of the composite
270// constant first, then the original spec constants will be replaced by
271// OpConstantComposite instructions.
272//
273// There are some operations not supported yet:
274// OpSConvert, OpFConvert, OpQuantizeToF16 and
275// all the operations under Kernel capability.
276// TODO(qining): Add support for the operations listed above.
277Optimizer::PassToken CreateFoldSpecConstantOpAndCompositePass();
278
279// Creates a unify-constant pass.
280// A unify-constant pass de-duplicates the constants. Constants with the exact
281// same value and identical form will be unified and only one constant will
282// be kept for each unique pair of type and value.
283// There are several cases not handled by this pass:
284// 1) Constants defined by OpConstantNull instructions (null constants) and
285// constants defined by OpConstantFalse, OpConstant or OpConstantComposite
286// with value 0 (zero-valued normal constants) are not considered equivalent.
287// So null constants won't be used to replace zero-valued normal constants,
288// vice versa.
289// 2) Whenever there are decorations to the constant's result id id, the
290// constant won't be handled, which means, it won't be used to replace any
291// other constants, neither can other constants replace it.
292// 3) NaN in float point format with different bit patterns are not unified.
293Optimizer::PassToken CreateUnifyConstantPass();
294
295// Creates a eliminate-dead-constant pass.
296// A eliminate-dead-constant pass removes dead constants, including normal
297// contants defined by OpConstant, OpConstantComposite, OpConstantTrue, or
298// OpConstantFalse and spec constants defined by OpSpecConstant,
299// OpSpecConstantComposite, OpSpecConstantTrue, OpSpecConstantFalse or
300// OpSpecConstantOp.
301Optimizer::PassToken CreateEliminateDeadConstantPass();
302
Steven Perrone4c7d8e2017-09-08 12:08:03 -0400303// Creates a strength-reduction pass.
304// A strength-reduction pass will look for opportunities to replace an
305// instruction with an equivalent and less expensive one. For example,
306// multiplying by a power of 2 can be replaced by a bit shift.
307Optimizer::PassToken CreateStrengthReductionPass();
308
GregFad1d0352017-06-07 15:28:53 -0600309// Creates a block merge pass.
310// This pass searches for blocks with a single Branch to a block with no
311// other predecessors and merges the blocks into a single block. Continue
312// blocks and Merge blocks are not candidates for the second block.
313//
314// The pass is most useful after Dead Branch Elimination, which can leave
315// such sequences of blocks. Merging them makes subsequent passes more
316// effective, such as single block local store-load elimination.
317//
318// While this pass reduces the number of occurrences of this sequence, at
319// this time it does not guarantee all such sequences are eliminated.
320//
321// Presence of phi instructions can inhibit this optimization. Handling
Steven Perrone43c9102017-09-19 10:12:13 -0400322// these is left for future improvements.
GregFad1d0352017-06-07 15:28:53 -0600323Optimizer::PassToken CreateBlockMergePass();
324
GregF429ca052017-08-15 17:58:28 -0600325// Creates an exhaustive inline pass.
326// An exhaustive inline pass attempts to exhaustively inline all function
327// calls in all functions in an entry point call tree. The intent is to enable,
328// albeit through brute force, analysis and optimization across function
329// calls by subsequent optimization passes. As the inlining is exhaustive,
330// there is no attempt to optimize for size or runtime performance. Functions
331// that are not in the call tree of an entry point are not changed.
GregFe28bd392017-08-01 17:20:13 -0600332Optimizer::PassToken CreateInlineExhaustivePass();
Steven Perrone43c9102017-09-19 10:12:13 -0400333
GregF429ca052017-08-15 17:58:28 -0600334// Creates an opaque inline pass.
335// An opaque inline pass inlines all function calls in all functions in all
336// entry point call trees where the called function contains an opaque type
337// in either its parameter types or return type. An opaque type is currently
338// defined as Image, Sampler or SampledImage. The intent is to enable, albeit
339// through brute force, analysis and optimization across these function calls
340// by subsequent passes in order to remove the storing of opaque types which is
341// not legal in Vulkan. Functions that are not in the call tree of an entry
342// point are not changed.
343Optimizer::PassToken CreateInlineOpaquePass();
Steven Perrone43c9102017-09-19 10:12:13 -0400344
GregF7c8da662017-05-18 14:51:55 -0600345// Creates a single-block local variable load/store elimination pass.
Steven Perrone43c9102017-09-19 10:12:13 -0400346// For every entry point function, do single block memory optimization of
GregF7c8da662017-05-18 14:51:55 -0600347// function variables referenced only with non-access-chain loads and stores.
348// For each targeted variable load, if previous store to that variable in the
349// block, replace the load's result id with the value id of the store.
350// If previous load within the block, replace the current load's result id
351// with the previous load's result id. In either case, delete the current
352// load. Finally, check if any remaining stores are useless, and delete store
353// and variable if possible.
354//
355// The presence of access chain references and function calls can inhibit
356// the above optimization.
357//
Steven Perron79a00642017-12-11 13:10:24 -0500358// Only modules with relaxed logical addressing (see opt/instruction.h) are
359// currently processed.
GregF7c8da662017-05-18 14:51:55 -0600360//
Steven Perrone43c9102017-09-19 10:12:13 -0400361// This pass is most effective if preceeded by Inlining and
GregF7c8da662017-05-18 14:51:55 -0600362// LocalAccessChainConvert. This pass will reduce the work needed to be done
GregFcc8bad32017-06-16 15:37:31 -0600363// by LocalSingleStoreElim and LocalMultiStoreElim.
GregF429ca052017-08-15 17:58:28 -0600364//
365// Only functions in the call tree of an entry point are processed.
GregF7c8da662017-05-18 14:51:55 -0600366Optimizer::PassToken CreateLocalSingleBlockLoadStoreElimPass();
Greg Fischer04fcc662016-11-10 10:11:50 -0700367
GregF52e247f2017-06-02 13:23:20 -0600368// Create dead branch elimination pass.
369// For each entry point function, this pass will look for SelectionMerge
370// BranchConditionals with constant condition and convert to a Branch to
371// the indicated label. It will delete resulting dead blocks.
372//
Andrey Tuganov4b1577a2017-10-05 16:26:09 -0400373// For all phi functions in merge block, replace all uses with the id
374// corresponding to the living predecessor.
375//
Alan Baker1b6cfd32018-01-04 17:04:03 -0500376// Note that some branches and blocks may be left to avoid creating invalid
377// control flow. Improving this is left to future work.
GregF52e247f2017-06-02 13:23:20 -0600378//
379// This pass is most effective when preceeded by passes which eliminate
380// local loads and stores, effectively propagating constant values where
381// possible.
382Optimizer::PassToken CreateDeadBranchElimPass();
383
GregFcc8bad32017-06-16 15:37:31 -0600384// Creates an SSA local variable load/store elimination pass.
385// For every entry point function, eliminate all loads and stores of function
386// scope variables only referenced with non-access-chain loads and stores.
Steven Perrone43c9102017-09-19 10:12:13 -0400387// Eliminate the variables as well.
GregFcc8bad32017-06-16 15:37:31 -0600388//
389// The presence of access chain references and function calls can inhibit
390// the above optimization.
391//
Steven Perron79a00642017-12-11 13:10:24 -0500392// Only shader modules with relaxed logical addressing (see opt/instruction.h)
393// are currently processed. Currently modules with any extensions enabled are
394// not processed. This is left for future work.
GregFcc8bad32017-06-16 15:37:31 -0600395//
Steven Perrone43c9102017-09-19 10:12:13 -0400396// This pass is most effective if preceeded by Inlining and
GregFcc8bad32017-06-16 15:37:31 -0600397// LocalAccessChainConvert. LocalSingleStoreElim and LocalSingleBlockElim
398// will reduce the work that this pass has to do.
399Optimizer::PassToken CreateLocalMultiStoreElimPass();
400
GregFaa7e6872017-05-12 17:27:21 -0600401// Creates a local access chain conversion pass.
402// A local access chain conversion pass identifies all function scope
403// variables which are accessed only with loads, stores and access chains
404// with constant indices. It then converts all loads and stores of such
405// variables into equivalent sequences of loads, stores, extracts and inserts.
406//
407// This pass only processes entry point functions. It currently only converts
408// non-nested, non-ptr access chains. It does not process modules with
409// non-32-bit integer types present. Optional memory access options on loads
410// and stores are ignored as we are only processing function scope variables.
411//
412// This pass unifies access to these variables to a single mode and simplifies
413// subsequent analysis and elimination of these variables along with their
414// loads and stores allowing values to propagate to their points of use where
415// possible.
416Optimizer::PassToken CreateLocalAccessChainConvertPass();
417
GregF0c5722f2017-05-19 17:31:28 -0600418// Creates a local single store elimination pass.
Steven Perrone43c9102017-09-19 10:12:13 -0400419// For each entry point function, this pass eliminates loads and stores for
GregF0c5722f2017-05-19 17:31:28 -0600420// function scope variable that are stored to only once, where possible. Only
421// whole variable loads and stores are eliminated; access-chain references are
422// not optimized. Replace all loads of such variables with the value that is
423// stored and eliminate any resulting dead code.
424//
425// Currently, the presence of access chains and function calls can inhibit this
426// pass, however the Inlining and LocalAccessChainConvert passes can make it
427// more effective. In additional, many non-load/store memory operations are
428// not supported and will prohibit optimization of a function. Support of
429// these operations are future work.
430//
Steven Perron79a00642017-12-11 13:10:24 -0500431// Only shader modules with relaxed logical addressing (see opt/instruction.h)
432// are currently processed.
433//
GregF0c5722f2017-05-19 17:31:28 -0600434// This pass will reduce the work needed to be done by LocalSingleBlockElim
GregFcc8bad32017-06-16 15:37:31 -0600435// and LocalMultiStoreElim and can improve the effectiveness of other passes
436// such as DeadBranchElimination which depend on values for their analysis.
GregF0c5722f2017-05-19 17:31:28 -0600437Optimizer::PassToken CreateLocalSingleStoreElimPass();
438
GregF6136bf92017-05-26 10:33:11 -0600439// Creates an insert/extract elimination pass.
440// This pass processes each entry point function in the module, searching for
441// extracts on a sequence of inserts. It further searches the sequence for an
442// insert with indices identical to the extract. If such an insert can be
443// found before hitting a conflicting insert, the extract's result id is
444// replaced with the id of the values from the insert.
445//
446// Besides removing extracts this pass enables subsequent dead code elimination
447// passes to delete the inserts. This pass performs best after access chains are
448// converted to inserts and extracts and local loads and stores are eliminated.
449Optimizer::PassToken CreateInsertExtractElimPass();
450
GregFf28b1062018-01-26 17:05:33 -0700451// Creates a dead insert elimination pass.
452// This pass processes each entry point function in the module, searching for
453// unreferenced inserts into composite types. These are most often unused
454// stores to vector components. They are unused because they are never
455// referenced, or because there is another insert to the same component between
456// the insert and the reference. After removing the inserts, dead code
457// elimination is attempted on the inserted values.
458//
459// This pass performs best after access chains are converted to inserts and
460// extracts and local loads and stores are eliminated. While executing this
461// pass can be advantageous on its own, it is also advantageous to execute
462// this pass after CreateInsertExtractPass() as it will remove any unused
463// inserts created by that pass.
464Optimizer::PassToken CreateDeadInsertElimPass();
465
GregFf4b29f32017-07-03 17:23:04 -0600466// Creates a pass to consolidate uniform references.
467// For each entry point function in the module, first change all constant index
Steven Perrone43c9102017-09-19 10:12:13 -0400468// access chain loads into equivalent composite extracts. Then consolidate
GregFf4b29f32017-07-03 17:23:04 -0600469// identical uniform loads into one uniform load. Finally, consolidate
470// identical uniform extracts into one uniform extract. This may require
471// moving a load or extract to a point which dominates all uses.
472//
473// This pass requires a module to have structured control flow ie shader
474// capability. It also requires logical addressing ie Addresses capability
475// is not enabled. It also currently does not support any extensions.
476//
477// This pass currently only optimizes loads with a single index.
478Optimizer::PassToken CreateCommonUniformElimPass();
479
GregF9de4e692017-06-08 10:37:21 -0600480// Create aggressive dead code elimination pass
Alan Baker3a054e12017-12-18 12:13:10 -0500481// This pass eliminates unused code from the module. In addition,
GregF9de4e692017-06-08 10:37:21 -0600482// it detects and eliminates code which may have spurious uses but which do
483// not contribute to the output of the function. The most common cause of
484// such code sequences is summations in loops whose result is no longer used
485// due to dead code elimination. This optimization has additional compile
486// time cost over standard dead code elimination.
487//
488// This pass only processes entry point functions. It also only processes
Alan Baker3a054e12017-12-18 12:13:10 -0500489// shaders with relaxed logical addressing (see opt/instruction.h). It
490// currently will not process functions with function calls. Unreachable
491// functions are deleted.
GregF9de4e692017-06-08 10:37:21 -0600492//
493// This pass will be made more effective by first running passes that remove
494// dead control flow and inlines function calls.
495//
496// This pass can be especially useful after running Local Access Chain
497// Conversion, which tends to cause cycles of dead code to be left after
498// Store/Load elimination passes are completed. These cycles cannot be
499// eliminated with standard dead code elimination.
500Optimizer::PassToken CreateAggressiveDCEPass();
501
Andrey Tuganov1e309af2017-04-11 15:11:04 -0400502// Creates a compact ids pass.
503// The pass remaps result ids to a compact and gapless range starting from %1.
504Optimizer::PassToken CreateCompactIdsPass();
505
Pierre Moreau7183ad52018-01-03 01:54:55 +0100506// Creates a remove duplicate pass.
507// This pass removes various duplicates:
508// * duplicate capabilities;
509// * duplicate extended instruction imports;
510// * duplicate types;
511// * duplicate decorations.
Pierre Moreau86627f72017-07-13 02:16:51 +0200512Optimizer::PassToken CreateRemoveDuplicatesPass();
513
Diego Novilloc75704e2017-09-06 08:56:41 -0400514// Creates a CFG cleanup pass.
515// This pass removes cruft from the control flow graph of functions that are
516// reachable from entry points and exported functions. It currently includes the
517// following functionality:
518//
519// - Removal of unreachable basic blocks.
520Optimizer::PassToken CreateCFGCleanupPass();
521
Steven Perron58347192017-10-20 12:17:41 -0400522// Create dead variable elimination pass.
523// This pass will delete module scope variables, along with their decorations,
524// that are not referenced.
525Optimizer::PassToken CreateDeadVariableEliminationPass();
526
Steven Perronb3daa932018-03-06 11:20:28 -0500527// create merge return pass.
528// changes functions that have multiple return statements so they have a single
529// return statement.
Alan Bakera92d69b2017-11-08 16:22:10 -0500530//
Steven Perronb3daa932018-03-06 11:20:28 -0500531// for structured control flow it is assumed that the only unreachable blocks in
532// the function are trivial merge and continue blocks.
Alan Bakera92d69b2017-11-08 16:22:10 -0500533//
Steven Perronb3daa932018-03-06 11:20:28 -0500534// a trivial merge block contains the label and an opunreachable instructions,
535// nothing else. a trivial continue block contain a label and an opbranch to
536// the header, nothing else.
537//
538// these conditions are guaranteed to be met after running dead-branch
539// elimination.
Alan Bakera92d69b2017-11-08 16:22:10 -0500540Optimizer::PassToken CreateMergeReturnPass();
541
Steven Perron28c41552017-11-10 20:26:55 -0500542// Create value numbering pass.
543// This pass will look for instructions in the same basic block that compute the
544// same value, and remove the redundant ones.
545Optimizer::PassToken CreateLocalRedundancyEliminationPass();
Steven Perron5d602ab2017-12-04 12:29:51 -0500546
Alexander Johnston84ccd0b2018-01-29 10:39:55 +0000547// Create LICM pass.
548// This pass will look for invariant instructions inside loops and hoist them to
549// the loops preheader.
550Optimizer::PassToken CreateLoopInvariantCodeMotionPass();
551
Stephen McGroarty9a5dd6f2018-04-23 21:01:12 +0100552// Creates a loop fission pass.
553// This pass will split all top level loops whose register pressure exceedes the
554// given |threshold|.
555Optimizer::PassToken CreateLoopFissionPass(size_t threshold);
556
Toomas Remmelg1dc24582018-04-20 15:14:45 +0100557// Creates a loop fusion pass.
558// This pass will look for adjacent loops that are compatible and legal to be
559// fused. The fuse all such loops as long as the register usage for the fused
560// loop stays under the threshold defined by |max_registers_per_loop|.
561Optimizer::PassToken CreateLoopFusionPass(size_t max_registers_per_loop);
562
Victor Lomuller10e5d7c2018-03-29 12:22:42 +0100563// Creates a loop peeling pass.
564// This pass will look for conditions inside a loop that are true or false only
565// for the N first or last iteration. For loop with such condition, those N
566// iterations of the loop will be executed outside of the main loop.
567// To limit code size explosion, the loop peeling can only happen if the code
568// size growth for each loop is under |code_growth_threshold|.
569Optimizer::PassToken CreateLoopPeelingPass();
570
Victor Lomuller3497a942018-02-12 21:42:15 +0000571// Creates a loop unswitch pass.
572// This pass will look for loop independent branch conditions and move the
573// condition out of the loop and version the loop based on the taken branch.
574// Works best after LICM and local multi store elimination pass.
575Optimizer::PassToken CreateLoopUnswitchPass();
576
Steven Perron5d602ab2017-12-04 12:29:51 -0500577// Create global value numbering pass.
578// This pass will look for instructions where the same value is computed on all
579// paths leading to the instruction. Those instructions are deleted.
580Optimizer::PassToken CreateRedundancyEliminationPass();
Alan Baker867451f2017-11-30 17:03:06 -0500581
582// Create scalar replacement pass.
583// This pass replaces composite function scope variables with variables for each
Steven Perrona579e722018-04-16 09:58:00 -0400584// element if those elements are accessed individually. The parameter is a
585// limit on the number of members in the composite variable that the pass will
586// consider replacing.
587Optimizer::PassToken CreateScalarReplacementPass(uint32_t size_limit = 100);
Steven Perronb86eb682017-12-11 13:10:24 -0500588
589// Create a private to local pass.
590// This pass looks for variables delcared in the private storage class that are
591// used in only one function. Those variables are moved to the function storage
592// class in the function that they are used.
593Optimizer::PassToken CreatePrivateToLocalPass();
Diego Novillo4ba9dcc2017-12-05 11:39:25 -0500594
595// Creates a conditional constant propagation (CCP) pass.
596// This pass implements the SSA-CCP algorithm in
597//
598// Constant propagation with conditional branches,
599// Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
600//
601// Constant values in expressions and conditional jumps are folded and
602// simplified. This may reduce code size by removing never executed jump targets
603// and computations with constant operands.
604Optimizer::PassToken CreateCCPPass();
605
Steven Perron34d42942018-01-17 14:57:37 -0500606// Creates a workaround driver bugs pass. This pass attempts to work around
607// a known driver bug (issue #1209) by identifying the bad code sequences and
608// rewriting them.
609//
610// Current workaround: Avoid OpUnreachable instructions in loops.
611Optimizer::PassToken CreateWorkaround1209Pass();
612
Alan Baker2e93e802018-01-16 11:15:06 -0500613// Creates a pass that converts if-then-else like assignments into OpSelect.
614Optimizer::PassToken CreateIfConversionPass();
615
Steven Perron61d8c032018-01-30 11:24:03 -0500616// Creates a pass that will replace instructions that are not valid for the
617// current shader stage by constants. Has no effect on non-shader modules.
618Optimizer::PassToken CreateReplaceInvalidOpcodePass();
619
Steven Perron06cdb962018-02-02 11:55:05 -0500620// Creates a pass that simplifies instructions using the instruction folder.
621Optimizer::PassToken CreateSimplificationPass();
622
Stephen McGroartydd8400e2018-02-14 17:03:12 +0000623// Create loop unroller pass.
Stephen McGroartye3549842018-02-27 11:50:08 +0000624// Creates a pass to unroll loops which have the "Unroll" loop control
Stephen McGroartydd8400e2018-02-14 17:03:12 +0000625// mask set. The loops must meet a specific criteria in order to be unrolled
626// safely this criteria is checked before doing the unroll by the
627// LoopUtils::CanPerformUnroll method. Any loop that does not meet the criteria
628// won't be unrolled. See CanPerformUnroll LoopUtils.h for more information.
Stephen McGroartye3549842018-02-27 11:50:08 +0000629Optimizer::PassToken CreateLoopUnrollPass(bool fully_unroll, int factor = 0);
Stephen McGroartydd8400e2018-02-14 17:03:12 +0000630
Diego Novillo735d8a52018-02-22 16:18:29 -0500631// Create the SSA rewrite pass.
632// This pass converts load/store operations on function local variables into
633// operations on SSA IDs. This allows SSA optimizers to act on these variables.
634// Only variables that are local to the function and of supported types are
635// processed (see IsSSATargetVar for details).
636Optimizer::PassToken CreateSSARewritePass();
637
Steven Perronc4dc0462018-03-20 23:33:24 -0400638// Create copy propagate arrays pass.
639// This pass looks to copy propagate memory references for arrays. It looks
640// for specific code patterns to recognize array copies.
641Optimizer::PassToken CreateCopyPropagateArraysPass();
Steven Perron2c0ce872018-04-23 11:13:07 -0400642
643// Create a vector dce pass.
644// This pass looks for components of vectors that are unused, and removes them
645// from the vector. Note this would still leave around lots of dead code that
646// a pass of ADCE will be able to remove.
647Optimizer::PassToken CreateVectorDCEPass();
648
Steven Perronaf430ec2018-05-07 12:31:03 -0400649// Create a pass to reduce the size of loads.
650// This pass looks for loads of structures where only a few of its members are
651// used. It replaces the loads feeding an OpExtract with an OpAccessChain and
652// a load of the specific elements.
653Optimizer::PassToken CreateReduceLoadSizePass();
654
Alan Baker755e5c92018-07-23 11:23:11 -0400655// Create a pass to combine chained access chains.
656// This pass looks for access chains fed by other access chains and combines
657// them into a single instruction where possible.
658Optimizer::PassToken CreateCombineAccessChainsPass();
659
greg-lunarg1e9fc1a2018-11-08 11:54:54 -0700660// Create a pass to instrument bindless descriptor checking
661// This pass instruments all bindless references to check that descriptor
662// array indices are inbounds. If the reference is invalid, a record is
663// written to the debug output buffer (if space allows) and a null value is
664// returned. This pass is designed to support bindless validation in the Vulkan
665// validation layers.
666//
667// Dead code elimination should be run after this pass as the original,
668// potentially invalid code is not removed and could cause undefined behavior,
669// including crashes. It may also be beneficial to run Simplification
670// (ie Constant Propagation), DeadBranchElim and BlockMerge after this pass to
671// optimize instrument code involving the testing of compile-time constants.
672// It is also generally recommended that this pass (and all
673// instrumentation passes) be run after any legalization and optimization
674// passes. This will give better analysis for the instrumentation and avoid
675// potentially de-optimizing the instrument code, for example, inlining
676// the debug record output function throughout the module.
677//
678// The instrumentation will read and write buffers in debug
679// descriptor set |desc_set|. It will write |shader_id| in each output record
680// to identify the shader module which generated the record.
681//
682// TODO(greg-lunarg): Add support for vk_ext_descriptor_indexing.
683Optimizer::PassToken CreateInstBindlessCheckPass(uint32_t desc_set,
684 uint32_t shader_id);
685
Lei Zhangf18e1f22016-09-12 14:11:46 -0400686} // namespace spvtools
687
dan sinclair58a68762018-08-03 08:05:33 -0400688#endif // INCLUDE_SPIRV_TOOLS_OPTIMIZER_HPP_