unify_const_pass.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. #include "source/opt/unify_const_pass.h"
  15. #include <memory>
  16. #include <unordered_map>
  17. #include <utility>
  18. #include <vector>
  19. #include "source/opt/def_use_manager.h"
  20. #include "source/opt/ir_context.h"
  21. #include "source/util/make_unique.h"
  22. namespace spvtools {
  23. namespace opt {
  24. namespace {
  25. // The trie that stores a bunch of result ids and, for a given instruction,
  26. // searches the result id that has been defined with the same opcode, type and
  27. // operands.
  28. class ResultIdTrie {
  29. public:
  30. ResultIdTrie() : root_(new Node) {}
  31. // For a given instruction, extracts its opcode, type id and operand words
  32. // as an array of keys, looks up the trie to find a result id which is stored
  33. // with the same opcode, type id and operand words. If none of such result id
  34. // is found, creates a trie node with those keys, stores the instruction's
  35. // result id and returns that result id. If an existing result id is found,
  36. // returns the existing result id.
  37. uint32_t LookupEquivalentResultFor(const Instruction& inst) {
  38. auto keys = GetLookUpKeys(inst);
  39. auto* node = root_.get();
  40. for (uint32_t key : keys) {
  41. node = node->GetOrCreateTrieNodeFor(key);
  42. }
  43. if (node->result_id() == 0) {
  44. node->SetResultId(inst.result_id());
  45. }
  46. return node->result_id();
  47. }
  48. private:
  49. // The trie node to store result ids.
  50. class Node {
  51. public:
  52. using TrieNodeMap = std::unordered_map<uint32_t, std::unique_ptr<Node>>;
  53. Node() : result_id_(0), next_() {}
  54. uint32_t result_id() const { return result_id_; }
  55. // Sets the result id stored in this node.
  56. void SetResultId(uint32_t id) { result_id_ = id; }
  57. // Searches for the child trie node with the given key. If the node is
  58. // found, returns that node. Otherwise creates an empty child node with
  59. // that key and returns that newly created node.
  60. Node* GetOrCreateTrieNodeFor(uint32_t key) {
  61. auto iter = next_.find(key);
  62. if (iter == next_.end()) {
  63. // insert a new node and return the node.
  64. return next_.insert(std::make_pair(key, MakeUnique<Node>()))
  65. .first->second.get();
  66. }
  67. return iter->second.get();
  68. }
  69. private:
  70. // The result id stored in this node. 0 means this node is empty.
  71. uint32_t result_id_;
  72. // The mapping from the keys to the child nodes of this node.
  73. TrieNodeMap next_;
  74. };
  75. // Returns a vector of the opcode followed by the words in the raw SPIR-V
  76. // instruction encoding but without the result id.
  77. std::vector<uint32_t> GetLookUpKeys(const Instruction& inst) {
  78. std::vector<uint32_t> keys;
  79. // Need to use the opcode, otherwise there might be a conflict with the
  80. // following case when <op>'s binary value equals xx's id:
  81. // OpSpecConstantOp tt <op> yy zz
  82. // OpSpecConstantComposite tt xx yy zz;
  83. keys.push_back(static_cast<uint32_t>(inst.opcode()));
  84. for (const auto& operand : inst) {
  85. if (operand.type == SPV_OPERAND_TYPE_RESULT_ID) continue;
  86. keys.insert(keys.end(), operand.words.cbegin(), operand.words.cend());
  87. }
  88. return keys;
  89. }
  90. std::unique_ptr<Node> root_; // The root node of the trie.
  91. };
  92. } // anonymous namespace
  93. Pass::Status UnifyConstantPass::Process() {
  94. bool modified = false;
  95. ResultIdTrie defined_constants;
  96. for (Instruction *next_instruction,
  97. *inst = &*(context()->types_values_begin());
  98. inst; inst = next_instruction) {
  99. next_instruction = inst->NextNode();
  100. // Do not handle the instruction when there are decorations upon the result
  101. // id.
  102. if (get_def_use_mgr()->GetAnnotations(inst->result_id()).size() != 0) {
  103. continue;
  104. }
  105. // The overall algorithm is to store the result ids of all the eligible
  106. // constants encountered so far in a trie. For a constant defining
  107. // instruction under consideration, use its opcode, result type id and
  108. // words in operands as an array of keys to lookup the trie. If a result id
  109. // can be found for that array of keys, a constant with exactly the same
  110. // value must has been defined before, the constant under processing
  111. // should be replaced by the constant previously defined. If no such result
  112. // id can be found for that array of keys, this must be the first time a
  113. // constant with its value be defined, we then create a new trie node to
  114. // store the result id with the keys. When replacing a duplicated constant
  115. // with a previously defined constant, all the uses of the duplicated
  116. // constant, which must be placed after the duplicated constant defining
  117. // instruction, will be updated. This way, the descendants of the
  118. // previously defined constant and the duplicated constant will both refer
  119. // to the previously defined constant. So that the operand ids which are
  120. // used in key arrays will be the ids of the unified constants, when
  121. // processing is up to a descendant. This makes comparing the key array
  122. // always valid for judging duplication.
  123. switch (inst->opcode()) {
  124. case SpvOp::SpvOpConstantTrue:
  125. case SpvOp::SpvOpConstantFalse:
  126. case SpvOp::SpvOpConstant:
  127. case SpvOp::SpvOpConstantNull:
  128. case SpvOp::SpvOpConstantSampler:
  129. case SpvOp::SpvOpConstantComposite:
  130. // Only spec constants defined with OpSpecConstantOp and
  131. // OpSpecConstantComposite should be processed in this pass. Spec
  132. // constants defined with OpSpecConstant{|True|False} are decorated with
  133. // 'SpecId' decoration and all of them should be treated as unique.
  134. // 'SpecId' is not applicable to SpecConstants defined with
  135. // OpSpecConstant{Op|Composite}, their values are not necessary to be
  136. // unique. When all the operands/compoents are the same between two
  137. // OpSpecConstant{Op|Composite} results, their result values must be the
  138. // same so are unifiable.
  139. case SpvOp::SpvOpSpecConstantOp:
  140. case SpvOp::SpvOpSpecConstantComposite: {
  141. uint32_t id = defined_constants.LookupEquivalentResultFor(*inst);
  142. if (id != inst->result_id()) {
  143. // The constant is a duplicated one, use the cached constant to
  144. // replace the uses of this duplicated one, then turn it to nop.
  145. context()->ReplaceAllUsesWith(inst->result_id(), id);
  146. context()->KillInst(inst);
  147. modified = true;
  148. }
  149. break;
  150. }
  151. default:
  152. break;
  153. }
  154. }
  155. return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
  156. }
  157. } // namespace opt
  158. } // namespace spvtools