aggressive_dead_code_elim_pass.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // Copyright (c) 2017 The Khronos Group Inc.
  2. // Copyright (c) 2017 Valve Corporation
  3. // Copyright (c) 2017 LunarG Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. #ifndef SOURCE_OPT_AGGRESSIVE_DEAD_CODE_ELIM_PASS_H_
  17. #define SOURCE_OPT_AGGRESSIVE_DEAD_CODE_ELIM_PASS_H_
  18. #include <algorithm>
  19. #include <list>
  20. #include <map>
  21. #include <queue>
  22. #include <string>
  23. #include <unordered_map>
  24. #include <unordered_set>
  25. #include <utility>
  26. #include <vector>
  27. #include "source/opt/basic_block.h"
  28. #include "source/opt/def_use_manager.h"
  29. #include "source/opt/mem_pass.h"
  30. #include "source/opt/module.h"
  31. #include "source/util/bit_vector.h"
  32. namespace spvtools {
  33. namespace opt {
  34. // See optimizer.hpp for documentation.
  35. class AggressiveDCEPass : public MemPass {
  36. using cbb_ptr = const BasicBlock*;
  37. public:
  38. using GetBlocksFunction =
  39. std::function<std::vector<BasicBlock*>*(const BasicBlock*)>;
  40. AggressiveDCEPass(bool preserve_interface = false,
  41. bool remove_outputs = false)
  42. : preserve_interface_(preserve_interface),
  43. remove_outputs_(remove_outputs) {}
  44. const char* name() const override { return "eliminate-dead-code-aggressive"; }
  45. Status Process() override;
  46. IRContext::Analysis GetPreservedAnalyses() override {
  47. return IRContext::kAnalysisDefUse |
  48. IRContext::kAnalysisInstrToBlockMapping |
  49. IRContext::kAnalysisConstants | IRContext::kAnalysisTypes;
  50. }
  51. private:
  52. // Preserve entry point interface if true. All variables in interface
  53. // will be marked live and will not be eliminated. This mode is needed by
  54. // GPU-Assisted Validation instrumentation where a change in the interface
  55. // is not allowed.
  56. bool preserve_interface_;
  57. // Output variables can be removed from the interface if this is true.
  58. // This is safe if the caller knows that the corresponding input variable
  59. // in the following shader has been removed. It is false by default.
  60. bool remove_outputs_;
  61. // Return true if |varId| is a variable of |storageClass|. |varId| must either
  62. // be 0 or the result of an instruction.
  63. bool IsVarOfStorage(uint32_t varId, spv::StorageClass storageClass);
  64. // Return true if the instance of the variable |varId| can only be access in
  65. // |func|. For example, a function scope variable, or a private variable
  66. // where |func| is an entry point with no function calls.
  67. bool IsLocalVar(uint32_t varId, Function* func);
  68. // Return true if |inst| is marked live.
  69. bool IsLive(const Instruction* inst) const {
  70. return live_insts_.Get(inst->unique_id());
  71. }
  72. // Adds entry points, execution modes and workgroup size decorations to the
  73. // worklist for processing with the first function.
  74. void InitializeModuleScopeLiveInstructions();
  75. // Add |inst| to worklist_ and live_insts_.
  76. void AddToWorklist(Instruction* inst) {
  77. if (!live_insts_.Set(inst->unique_id())) {
  78. worklist_.push(inst);
  79. }
  80. }
  81. // Add all store instruction which use |ptrId|, directly or indirectly,
  82. // to the live instruction worklist.
  83. void AddStores(Function* func, uint32_t ptrId);
  84. // Initialize extensions allowlist
  85. void InitExtensions();
  86. // Return true if all extensions in this module are supported by this pass.
  87. bool AllExtensionsSupported() const;
  88. // Returns true if the target of |inst| is dead. An instruction is dead if
  89. // its result id is used in decoration or debug instructions only. |inst| is
  90. // assumed to be OpName, OpMemberName or an annotation instruction.
  91. bool IsTargetDead(Instruction* inst);
  92. // If |varId| is local, mark all stores of varId as live.
  93. void ProcessLoad(Function* func, uint32_t varId);
  94. // Add branch to |labelId| to end of block |bp|.
  95. void AddBranch(uint32_t labelId, BasicBlock* bp);
  96. // Add all break and continue branches in the construct associated with
  97. // |mergeInst| to worklist if not already live
  98. void AddBreaksAndContinuesToWorklist(Instruction* mergeInst);
  99. // Eliminates dead debug2 and annotation instructions. Marks dead globals for
  100. // removal (e.g. types, constants and variables).
  101. bool ProcessGlobalValues();
  102. // Erases functions that are unreachable from the entry points of the module.
  103. bool EliminateDeadFunctions();
  104. // For function |func|, mark all Stores to non-function-scope variables
  105. // and block terminating instructions as live. Recursively mark the values
  106. // they use. When complete, mark any non-live instructions to be deleted.
  107. // Returns true if the function has been modified.
  108. //
  109. // Note: This function does not delete useless control structures. All
  110. // existing control structures will remain. This can leave not-insignificant
  111. // sequences of ultimately useless code.
  112. // TODO(): Remove useless control constructs.
  113. bool AggressiveDCE(Function* func);
  114. Pass::Status ProcessImpl();
  115. // Adds instructions which must be kept because of they have side-effects
  116. // that ADCE cannot model to the work list.
  117. void InitializeWorkList(Function* func,
  118. std::list<BasicBlock*>& structured_order);
  119. // Process each instruction in the work list by marking any instruction that
  120. // that it depends on as live, and adding it to the work list. The work list
  121. // will be empty at the end.
  122. void ProcessWorkList(Function* func);
  123. // Kills any instructions in |func| that have not been marked as live.
  124. bool KillDeadInstructions(const Function* func,
  125. std::list<BasicBlock*>& structured_order);
  126. // Adds the instructions that define the operands of |inst| to the work list.
  127. void AddOperandsToWorkList(const Instruction* inst);
  128. // Marks all of the labels and branch that inst requires as live.
  129. void MarkBlockAsLive(Instruction* inst);
  130. // Marks any variables from which |inst| may require data as live.
  131. void MarkLoadedVariablesAsLive(Function* func, Instruction* inst);
  132. // Returns the id of the variable that |ptr_id| point to. |ptr_id| must be a
  133. // value whose type is a pointer.
  134. uint32_t GetVariableId(uint32_t ptr_id);
  135. // Returns all of the ids for the variables from which |inst| will load data.
  136. std::vector<uint32_t> GetLoadedVariables(Instruction* inst);
  137. // Returns all of the ids for the variables from which |inst| will load data.
  138. // The opcode of |inst| must be OpFunctionCall.
  139. std::vector<uint32_t> GetLoadedVariablesFromFunctionCall(
  140. const Instruction* inst);
  141. // Returns the id of the variable from which |inst| will load data. |inst|
  142. // must not be an OpFunctionCall. Returns 0 if no data is read or the
  143. // variable cannot be determined. Note that in logical addressing mode the
  144. // latter is not possible for function and private storage class because there
  145. // cannot be variable pointers pointing to those storage classes.
  146. uint32_t GetLoadedVariableFromNonFunctionCalls(Instruction* inst);
  147. // Adds all decorations of |inst| to the work list.
  148. void AddDecorationsToWorkList(const Instruction* inst);
  149. // Adds DebugScope instruction associated with |inst| to the work list.
  150. void AddDebugScopeToWorkList(const Instruction* inst);
  151. // Adds all debug instruction associated with |inst| to the work list.
  152. void AddDebugInstructionsToWorkList(const Instruction* inst);
  153. // Marks all of the OpFunctionParameter instructions in |func| as live.
  154. void MarkFunctionParameterAsLive(const Function* func);
  155. // Returns the terminator instruction in the header for the innermost
  156. // construct that contains |blk|. Returns nullptr if no such header exists.
  157. Instruction* GetHeaderBranch(BasicBlock* blk);
  158. // Returns the header for the innermost construct that contains |blk|. A loop
  159. // header will be its own header. Returns nullptr if no such header exists.
  160. BasicBlock* GetHeaderBlock(BasicBlock* blk) const;
  161. // Returns the same as |GetHeaderBlock| except if |blk| is a loop header it
  162. // will return the header of the next enclosing construct. Returns nullptr if
  163. // no such header exists.
  164. Instruction* GetBranchForNextHeader(BasicBlock* blk);
  165. // Returns the merge instruction in the same basic block as |inst|. Returns
  166. // nullptr if one does not exist.
  167. Instruction* GetMergeInstruction(Instruction* inst);
  168. // Returns true if |bb| is in the construct with header |header_block|.
  169. bool BlockIsInConstruct(BasicBlock* header_block, BasicBlock* bb);
  170. // Returns true if |func| is an entry point that does not have any function
  171. // calls.
  172. bool IsEntryPointWithNoCalls(Function* func);
  173. // Returns true if |func| is an entry point.
  174. bool IsEntryPoint(Function* func);
  175. // Returns true if |func| contains a function call.
  176. bool HasCall(Function* func);
  177. // Marks the first block, which is the entry block, in |func| as live.
  178. void MarkFirstBlockAsLive(Function* func);
  179. // Adds an OpUnreachable instruction at the end of |block|.
  180. void AddUnreachable(BasicBlock*& block);
  181. // Marks the OpLoopMerge and the terminator in |basic_block| as live if
  182. // |basic_block| is a loop header.
  183. void MarkLoopConstructAsLiveIfLoopHeader(BasicBlock* basic_block);
  184. // The cached results for |IsEntryPointWithNoCalls|. It maps the function's
  185. // result id to the return value.
  186. std::unordered_map<uint32_t, bool> entry_point_with_no_calls_cache_;
  187. // Live Instruction Worklist. An instruction is added to this list
  188. // if it might have a side effect, either directly or indirectly.
  189. // If we don't know, then add it to this list. Instructions are
  190. // removed from this list as the algorithm traces side effects,
  191. // building up the live instructions set |live_insts_|.
  192. std::queue<Instruction*> worklist_;
  193. // Live Instructions
  194. utils::BitVector live_insts_;
  195. // Live Local Variables
  196. std::unordered_set<uint32_t> live_local_vars_;
  197. // List of instructions to delete. Deletion is delayed until debug and
  198. // annotation instructions are processed.
  199. std::vector<Instruction*> to_kill_;
  200. // Extensions supported by this pass.
  201. std::unordered_set<std::string> extensions_allowlist_;
  202. };
  203. } // namespace opt
  204. } // namespace spvtools
  205. #endif // SOURCE_OPT_AGGRESSIVE_DEAD_CODE_ELIM_PASS_H_