• 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 #ifndef SOURCE_OPT_DEF_USE_MANAGER_H_
16 #define SOURCE_OPT_DEF_USE_MANAGER_H_
17 
18 #include <set>
19 #include <unordered_map>
20 #include <vector>
21 
22 #include "source/opt/instruction.h"
23 #include "source/opt/module.h"
24 #include "spirv-tools/libspirv.hpp"
25 
26 namespace spvtools {
27 namespace opt {
28 namespace analysis {
29 
30 // Class for representing a use of id. Note that:
31 // * Result type id is a use.
32 // * Ids referenced in OpSectionMerge & OpLoopMerge are considered as use.
33 // * Ids referenced in OpPhi's in operands are considered as use.
34 struct Use {
35   Instruction* inst;       // Instruction using the id.
36   uint32_t operand_index;  // logical operand index of the id use. This can be
37                            // the index of result type id.
38 };
39 
40 inline bool operator==(const Use& lhs, const Use& rhs) {
41   return lhs.inst == rhs.inst && lhs.operand_index == rhs.operand_index;
42 }
43 
44 inline bool operator!=(const Use& lhs, const Use& rhs) { return !(lhs == rhs); }
45 
46 inline bool operator<(const Use& lhs, const Use& rhs) {
47   if (lhs.inst < rhs.inst) return true;
48   if (lhs.inst > rhs.inst) return false;
49   return lhs.operand_index < rhs.operand_index;
50 }
51 
52 // Definition should never be null. User can be null, however, such an entry
53 // should be used only for searching (e.g. all users of a particular definition)
54 // and never stored in a container.
55 struct UserEntry {
56   Instruction* def;
57   Instruction* user;
58 };
59 
60 inline bool operator==(const UserEntry& lhs, const UserEntry& rhs) {
61   return lhs.def == rhs.def && lhs.user == rhs.user;
62 }
63 
64 // Orders UserEntry for use in associative containers (i.e. less than ordering).
65 //
66 // The definition of an UserEntry is treated as the major key and the users as
67 // the minor key so that all the users of a particular definition are
68 // consecutive in a container.
69 //
70 // A null user always compares less than a real user. This is done to provide
71 // easy values to search for the beginning of the users of a particular
72 // definition (i.e. using {def, nullptr}).
73 struct UserEntryLess {
operatorUserEntryLess74   bool operator()(const UserEntry& lhs, const UserEntry& rhs) const {
75     // If lhs.def and rhs.def are both null, fall through to checking the
76     // second entries.
77     if (!lhs.def && rhs.def) return true;
78     if (lhs.def && !rhs.def) return false;
79 
80     // If neither definition is null, then compare unique ids.
81     if (lhs.def && rhs.def) {
82       if (lhs.def->unique_id() < rhs.def->unique_id()) return true;
83       if (rhs.def->unique_id() < lhs.def->unique_id()) return false;
84     }
85 
86     // Return false on equality.
87     if (!lhs.user && !rhs.user) return false;
88     if (!lhs.user) return true;
89     if (!rhs.user) return false;
90 
91     // If neither user is null then compare unique ids.
92     return lhs.user->unique_id() < rhs.user->unique_id();
93   }
94 };
95 
96 // A class for analyzing and managing defs and uses in an Module.
97 class DefUseManager {
98  public:
99   using IdToDefMap = std::unordered_map<uint32_t, Instruction*>;
100 
101   // Constructs a def-use manager from the given |module|. All internal messages
102   // will be communicated to the outside via the given message |consumer|. This
103   // instance only keeps a reference to the |consumer|, so the |consumer| should
104   // outlive this instance.
DefUseManager(Module * module)105   DefUseManager(Module* module) { AnalyzeDefUse(module); }
106 
107   DefUseManager(const DefUseManager&) = delete;
108   DefUseManager(DefUseManager&&) = delete;
109   DefUseManager& operator=(const DefUseManager&) = delete;
110   DefUseManager& operator=(DefUseManager&&) = delete;
111 
112   // Analyzes the defs in the given |inst|.
113   void AnalyzeInstDef(Instruction* inst);
114 
115   // Analyzes the uses in the given |inst|.
116   //
117   // All operands of |inst| must be analyzed as defs.
118   void AnalyzeInstUse(Instruction* inst);
119 
120   // Analyzes the defs and uses in the given |inst|.
121   void AnalyzeInstDefUse(Instruction* inst);
122 
123   // Returns the def instruction for the given |id|. If there is no instruction
124   // defining |id|, returns nullptr.
125   Instruction* GetDef(uint32_t id);
126   const Instruction* GetDef(uint32_t id) const;
127 
128   // Runs the given function |f| on each unique user instruction of |def| (or
129   // |id|).
130   //
131   // If one instruction uses |def| in multiple operands, that instruction will
132   // only be visited once.
133   //
134   // |def| (or |id|) must be registered as a definition.
135   void ForEachUser(const Instruction* def,
136                    const std::function<void(Instruction*)>& f) const;
137   void ForEachUser(uint32_t id,
138                    const std::function<void(Instruction*)>& f) const;
139 
140   // Runs the given function |f| on each unique user instruction of |def| (or
141   // |id|). If |f| returns false, iteration is terminated and this function
142   // returns false.
143   //
144   // If one instruction uses |def| in multiple operands, that instruction will
145   // be only be visited once.
146   //
147   // |def| (or |id|) must be registered as a definition.
148   bool WhileEachUser(const Instruction* def,
149                      const std::function<bool(Instruction*)>& f) const;
150   bool WhileEachUser(uint32_t id,
151                      const std::function<bool(Instruction*)>& f) const;
152 
153   // Runs the given function |f| on each unique use of |def| (or
154   // |id|).
155   //
156   // If one instruction uses |def| in multiple operands, each operand will be
157   // visited separately.
158   //
159   // |def| (or |id|) must be registered as a definition.
160   void ForEachUse(
161       const Instruction* def,
162       const std::function<void(Instruction*, uint32_t operand_index)>& f) const;
163   void ForEachUse(
164       uint32_t id,
165       const std::function<void(Instruction*, uint32_t operand_index)>& f) const;
166 
167   // Runs the given function |f| on each unique use of |def| (or
168   // |id|). If |f| returns false, iteration is terminated and this function
169   // returns false.
170   //
171   // If one instruction uses |def| in multiple operands, each operand will be
172   // visited separately.
173   //
174   // |def| (or |id|) must be registered as a definition.
175   bool WhileEachUse(
176       const Instruction* def,
177       const std::function<bool(Instruction*, uint32_t operand_index)>& f) const;
178   bool WhileEachUse(
179       uint32_t id,
180       const std::function<bool(Instruction*, uint32_t operand_index)>& f) const;
181 
182   // Returns the number of users of |def| (or |id|).
183   uint32_t NumUsers(const Instruction* def) const;
184   uint32_t NumUsers(uint32_t id) const;
185 
186   // Returns the number of uses of |def| (or |id|).
187   uint32_t NumUses(const Instruction* def) const;
188   uint32_t NumUses(uint32_t id) const;
189 
190   // Returns the annotation instrunctions which are a direct use of the given
191   // |id|. This means when the decorations are applied through decoration
192   // group(s), this function will just return the OpGroupDecorate
193   // instruction(s) which refer to the given id as an operand. The OpDecorate
194   // instructions which decorate the decoration group will not be returned.
195   std::vector<Instruction*> GetAnnotations(uint32_t id) const;
196 
197   // Returns the map from ids to their def instructions.
id_to_defs()198   const IdToDefMap& id_to_defs() const { return id_to_def_; }
199 
200   // Clear the internal def-use record of the given instruction |inst|. This
201   // method will update the use information of the operand ids of |inst|. The
202   // record: |inst| uses an |id|, will be removed from the use records of |id|.
203   // If |inst| defines an result id, the use record of this result id will also
204   // be removed. Does nothing if |inst| was not analyzed before.
205   void ClearInst(Instruction* inst);
206 
207   // Erases the records that a given instruction uses its operand ids.
208   void EraseUseRecordsOfOperandIds(const Instruction* inst);
209 
210   friend bool CompareAndPrintDifferences(const DefUseManager&,
211                                          const DefUseManager&);
212 
213   // If |inst| has not already been analysed, then analyses its definition and
214   // uses.
215   void UpdateDefUse(Instruction* inst);
216 
217  private:
218   using IdToUsersMap = std::set<UserEntry, UserEntryLess>;
219   using InstToUsedIdsMap =
220       std::unordered_map<const Instruction*, std::vector<uint32_t>>;
221 
222   // Returns the first location that {|def|, nullptr} could be inserted into the
223   // users map without violating ordering.
224   IdToUsersMap::const_iterator UsersBegin(const Instruction* def) const;
225 
226   // Returns true if |iter| has not reached the end of |def|'s users.
227   //
228   // In the first version |iter| is compared against the end of the map for
229   // validity before other checks. In the second version, |iter| is compared
230   // against |cached_end| for validity before other checks. This allows caching
231   // the map's end which is a performance improvement on some platforms.
232   bool UsersNotEnd(const IdToUsersMap::const_iterator& iter,
233                    const Instruction* def) const;
234   bool UsersNotEnd(const IdToUsersMap::const_iterator& iter,
235                    const IdToUsersMap::const_iterator& cached_end,
236                    const Instruction* def) const;
237 
238   // Analyzes the defs and uses in the given |module| and populates data
239   // structures in this class. Does nothing if |module| is nullptr.
240   void AnalyzeDefUse(Module* module);
241 
242   IdToDefMap id_to_def_;      // Mapping from ids to their definitions
243   IdToUsersMap id_to_users_;  // Mapping from ids to their users
244   // Mapping from instructions to the ids used in the instruction.
245   InstToUsedIdsMap inst_to_used_ids_;
246 };
247 
248 }  // namespace analysis
249 }  // namespace opt
250 }  // namespace spvtools
251 
252 #endif  // SOURCE_OPT_DEF_USE_MANAGER_H_
253