Coverage Report

Created: 2024-09-11 07:09

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