unify_const_pass.cpp 6.9 KB

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