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