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_CONSTANTS_H_
16 #define SOURCE_OPT_CONSTANTS_H_
17 
18 #include <cinttypes>
19 #include <map>
20 #include <memory>
21 #include <unordered_map>
22 #include <unordered_set>
23 #include <utility>
24 #include <vector>
25 
26 #include "source/opt/module.h"
27 #include "source/opt/type_manager.h"
28 #include "source/opt/types.h"
29 #include "source/util/hex_float.h"
30 #include "source/util/make_unique.h"
31 
32 namespace spvtools {
33 namespace opt {
34 
35 class IRContext;
36 
37 namespace analysis {
38 
39 // Class hierarchy to represent the normal constants defined through
40 // OpConstantTrue, OpConstantFalse, OpConstant, OpConstantNull and
41 // OpConstantComposite instructions.
42 // TODO(qining): Add class for constants defined with OpConstantSampler.
43 class Constant;
44 class ScalarConstant;
45 class IntConstant;
46 class FloatConstant;
47 class BoolConstant;
48 class CompositeConstant;
49 class StructConstant;
50 class VectorConstant;
51 class MatrixConstant;
52 class ArrayConstant;
53 class NullConstant;
54 class ConstantManager;
55 
56 // Abstract class for a SPIR-V constant. It has a bunch of As<subclass> methods,
57 // which is used as a way to probe the actual <subclass>
58 class Constant {
59  public:
60   Constant() = delete;
61   virtual ~Constant() = default;
62 
63   // Make a deep copy of this constant.
64   virtual std::unique_ptr<Constant> Copy() const = 0;
65 
66   // reflections
AsScalarConstant()67   virtual ScalarConstant* AsScalarConstant() { return nullptr; }
AsIntConstant()68   virtual IntConstant* AsIntConstant() { return nullptr; }
AsFloatConstant()69   virtual FloatConstant* AsFloatConstant() { return nullptr; }
AsBoolConstant()70   virtual BoolConstant* AsBoolConstant() { return nullptr; }
AsCompositeConstant()71   virtual CompositeConstant* AsCompositeConstant() { return nullptr; }
AsStructConstant()72   virtual StructConstant* AsStructConstant() { return nullptr; }
AsVectorConstant()73   virtual VectorConstant* AsVectorConstant() { return nullptr; }
AsMatrixConstant()74   virtual MatrixConstant* AsMatrixConstant() { return nullptr; }
AsArrayConstant()75   virtual ArrayConstant* AsArrayConstant() { return nullptr; }
AsNullConstant()76   virtual NullConstant* AsNullConstant() { return nullptr; }
77 
AsScalarConstant()78   virtual const ScalarConstant* AsScalarConstant() const { return nullptr; }
AsIntConstant()79   virtual const IntConstant* AsIntConstant() const { return nullptr; }
AsFloatConstant()80   virtual const FloatConstant* AsFloatConstant() const { return nullptr; }
AsBoolConstant()81   virtual const BoolConstant* AsBoolConstant() const { return nullptr; }
AsCompositeConstant()82   virtual const CompositeConstant* AsCompositeConstant() const {
83     return nullptr;
84   }
AsStructConstant()85   virtual const StructConstant* AsStructConstant() const { return nullptr; }
AsVectorConstant()86   virtual const VectorConstant* AsVectorConstant() const { return nullptr; }
AsMatrixConstant()87   virtual const MatrixConstant* AsMatrixConstant() const { return nullptr; }
AsArrayConstant()88   virtual const ArrayConstant* AsArrayConstant() const { return nullptr; }
AsNullConstant()89   virtual const NullConstant* AsNullConstant() const { return nullptr; }
90 
91   // Returns the float representation of the constant. Must be a 32 bit
92   // Float type.
93   float GetFloat() const;
94 
95   // Returns the double representation of the constant. Must be a 64 bit
96   // Float type.
97   double GetDouble() const;
98 
99   // Returns the double representation of the constant. Must be a 32-bit or
100   // 64-bit Float type.
101   double GetValueAsDouble() const;
102 
103   // Returns uint32_t representation of the constant. Must be a 32 bit
104   // Integer type.
105   uint32_t GetU32() const;
106 
107   // Returns uint64_t representation of the constant. Must be a 64 bit
108   // Integer type.
109   uint64_t GetU64() const;
110 
111   // Returns int32_t representation of the constant. Must be a 32 bit
112   // Integer type.
113   int32_t GetS32() const;
114 
115   // Returns int64_t representation of the constant. Must be a 64 bit
116   // Integer type.
117   int64_t GetS64() const;
118 
119   // Returns the zero-extended representation of an integer constant. Must
120   // be an integral constant of at most 64 bits.
121   uint64_t GetZeroExtendedValue() const;
122 
123   // Returns the sign-extended representation of an integer constant. Must
124   // be an integral constant of at most 64 bits.
125   int64_t GetSignExtendedValue() const;
126 
127   // Returns true if the constant is a zero or a composite containing 0s.
IsZero()128   virtual bool IsZero() const { return false; }
129 
type()130   const Type* type() const { return type_; }
131 
132   // Returns an std::vector containing the elements of |constant|.  The type of
133   // |constant| must be |Vector|.
134   std::vector<const Constant*> GetVectorComponents(
135       ConstantManager* const_mgr) const;
136 
137  protected:
Constant(const Type * ty)138   Constant(const Type* ty) : type_(ty) {}
139 
140   // The type of this constant.
141   const Type* type_;
142 };
143 
144 // Abstract class for scalar type constants.
145 class ScalarConstant : public Constant {
146  public:
147   ScalarConstant() = delete;
AsScalarConstant()148   ScalarConstant* AsScalarConstant() override { return this; }
AsScalarConstant()149   const ScalarConstant* AsScalarConstant() const override { return this; }
150 
151   // Returns a const reference of the value of this constant in 32-bit words.
words()152   virtual const std::vector<uint32_t>& words() const { return words_; }
153 
154   // Returns true if the value is zero.
IsZero()155   bool IsZero() const override {
156     bool is_zero = true;
157     for (uint32_t v : words()) {
158       if (v != 0) {
159         is_zero = false;
160         break;
161       }
162     }
163     return is_zero;
164   }
165 
166  protected:
ScalarConstant(const Type * ty,const std::vector<uint32_t> & w)167   ScalarConstant(const Type* ty, const std::vector<uint32_t>& w)
168       : Constant(ty), words_(w) {}
ScalarConstant(const Type * ty,std::vector<uint32_t> && w)169   ScalarConstant(const Type* ty, std::vector<uint32_t>&& w)
170       : Constant(ty), words_(std::move(w)) {}
171   std::vector<uint32_t> words_;
172 };
173 
174 // Integer type constant.
175 class IntConstant : public ScalarConstant {
176  public:
IntConstant(const Integer * ty,const std::vector<uint32_t> & w)177   IntConstant(const Integer* ty, const std::vector<uint32_t>& w)
178       : ScalarConstant(ty, w) {}
IntConstant(const Integer * ty,std::vector<uint32_t> && w)179   IntConstant(const Integer* ty, std::vector<uint32_t>&& w)
180       : ScalarConstant(ty, std::move(w)) {}
181 
AsIntConstant()182   IntConstant* AsIntConstant() override { return this; }
AsIntConstant()183   const IntConstant* AsIntConstant() const override { return this; }
184 
GetS32BitValue()185   int32_t GetS32BitValue() const {
186     // Relies on signed values smaller than 32-bit being sign extended.  See
187     // section 2.2.1 of the SPIR-V spec.
188     assert(words().size() == 1);
189     return words()[0];
190   }
191 
GetU32BitValue()192   uint32_t GetU32BitValue() const {
193     // Relies on unsigned values smaller than 32-bit being zero extended.  See
194     // section 2.2.1 of the SPIR-V spec.
195     assert(words().size() == 1);
196     return words()[0];
197   }
198 
GetS64BitValue()199   int64_t GetS64BitValue() const {
200     // Relies on unsigned values smaller than 64-bit being sign extended.  See
201     // section 2.2.1 of the SPIR-V spec.
202     assert(words().size() == 2);
203     return static_cast<uint64_t>(words()[1]) << 32 |
204            static_cast<uint64_t>(words()[0]);
205   }
206 
GetU64BitValue()207   uint64_t GetU64BitValue() const {
208     // Relies on unsigned values smaller than 64-bit being zero extended.  See
209     // section 2.2.1 of the SPIR-V spec.
210     assert(words().size() == 2);
211     return static_cast<uint64_t>(words()[1]) << 32 |
212            static_cast<uint64_t>(words()[0]);
213   }
214 
215   // Make a copy of this IntConstant instance.
CopyIntConstant()216   std::unique_ptr<IntConstant> CopyIntConstant() const {
217     return MakeUnique<IntConstant>(type_->AsInteger(), words_);
218   }
Copy()219   std::unique_ptr<Constant> Copy() const override {
220     return std::unique_ptr<Constant>(CopyIntConstant().release());
221   }
222 };
223 
224 // Float type constant.
225 class FloatConstant : public ScalarConstant {
226  public:
FloatConstant(const Float * ty,const std::vector<uint32_t> & w)227   FloatConstant(const Float* ty, const std::vector<uint32_t>& w)
228       : ScalarConstant(ty, w) {}
FloatConstant(const Float * ty,std::vector<uint32_t> && w)229   FloatConstant(const Float* ty, std::vector<uint32_t>&& w)
230       : ScalarConstant(ty, std::move(w)) {}
231 
AsFloatConstant()232   FloatConstant* AsFloatConstant() override { return this; }
AsFloatConstant()233   const FloatConstant* AsFloatConstant() const override { return this; }
234 
235   // Make a copy of this FloatConstant instance.
CopyFloatConstant()236   std::unique_ptr<FloatConstant> CopyFloatConstant() const {
237     return MakeUnique<FloatConstant>(type_->AsFloat(), words_);
238   }
Copy()239   std::unique_ptr<Constant> Copy() const override {
240     return std::unique_ptr<Constant>(CopyFloatConstant().release());
241   }
242 
243   // Returns the float value of |this|.  The type of |this| must be |Float| with
244   // width of 32.
GetFloatValue()245   float GetFloatValue() const {
246     assert(type()->AsFloat()->width() == 32 &&
247            "Not a 32-bit floating point value.");
248     utils::FloatProxy<float> a(words()[0]);
249     return a.getAsFloat();
250   }
251 
252   // Returns the double value of |this|.  The type of |this| must be |Float|
253   // with width of 64.
GetDoubleValue()254   double GetDoubleValue() const {
255     assert(type()->AsFloat()->width() == 64 &&
256            "Not a 32-bit floating point value.");
257     uint64_t combined_words = words()[1];
258     combined_words = combined_words << 32;
259     combined_words |= words()[0];
260     utils::FloatProxy<double> a(combined_words);
261     return a.getAsFloat();
262   }
263 };
264 
265 // Bool type constant.
266 class BoolConstant : public ScalarConstant {
267  public:
BoolConstant(const Bool * ty,bool v)268   BoolConstant(const Bool* ty, bool v)
269       : ScalarConstant(ty, {static_cast<uint32_t>(v)}), value_(v) {}
270 
AsBoolConstant()271   BoolConstant* AsBoolConstant() override { return this; }
AsBoolConstant()272   const BoolConstant* AsBoolConstant() const override { return this; }
273 
274   // Make a copy of this BoolConstant instance.
CopyBoolConstant()275   std::unique_ptr<BoolConstant> CopyBoolConstant() const {
276     return MakeUnique<BoolConstant>(type_->AsBool(), value_);
277   }
Copy()278   std::unique_ptr<Constant> Copy() const override {
279     return std::unique_ptr<Constant>(CopyBoolConstant().release());
280   }
281 
value()282   bool value() const { return value_; }
283 
284  private:
285   bool value_;
286 };
287 
288 // Abstract class for composite constants.
289 class CompositeConstant : public Constant {
290  public:
291   CompositeConstant() = delete;
AsCompositeConstant()292   CompositeConstant* AsCompositeConstant() override { return this; }
AsCompositeConstant()293   const CompositeConstant* AsCompositeConstant() const override { return this; }
294 
295   // Returns a const reference of the components held in this composite
296   // constant.
GetComponents()297   virtual const std::vector<const Constant*>& GetComponents() const {
298     return components_;
299   }
300 
IsZero()301   bool IsZero() const override {
302     for (const Constant* c : GetComponents()) {
303       if (!c->IsZero()) {
304         return false;
305       }
306     }
307     return true;
308   }
309 
310  protected:
CompositeConstant(const Type * ty)311   CompositeConstant(const Type* ty) : Constant(ty), components_() {}
CompositeConstant(const Type * ty,const std::vector<const Constant * > & components)312   CompositeConstant(const Type* ty,
313                     const std::vector<const Constant*>& components)
314       : Constant(ty), components_(components) {}
CompositeConstant(const Type * ty,std::vector<const Constant * > && components)315   CompositeConstant(const Type* ty, std::vector<const Constant*>&& components)
316       : Constant(ty), components_(std::move(components)) {}
317   std::vector<const Constant*> components_;
318 };
319 
320 // Struct type constant.
321 class StructConstant : public CompositeConstant {
322  public:
StructConstant(const Struct * ty)323   StructConstant(const Struct* ty) : CompositeConstant(ty) {}
StructConstant(const Struct * ty,const std::vector<const Constant * > & components)324   StructConstant(const Struct* ty,
325                  const std::vector<const Constant*>& components)
326       : CompositeConstant(ty, components) {}
StructConstant(const Struct * ty,std::vector<const Constant * > && components)327   StructConstant(const Struct* ty, std::vector<const Constant*>&& components)
328       : CompositeConstant(ty, std::move(components)) {}
329 
AsStructConstant()330   StructConstant* AsStructConstant() override { return this; }
AsStructConstant()331   const StructConstant* AsStructConstant() const override { return this; }
332 
333   // Make a copy of this StructConstant instance.
CopyStructConstant()334   std::unique_ptr<StructConstant> CopyStructConstant() const {
335     return MakeUnique<StructConstant>(type_->AsStruct(), components_);
336   }
Copy()337   std::unique_ptr<Constant> Copy() const override {
338     return std::unique_ptr<Constant>(CopyStructConstant().release());
339   }
340 };
341 
342 // Vector type constant.
343 class VectorConstant : public CompositeConstant {
344  public:
VectorConstant(const Vector * ty)345   VectorConstant(const Vector* ty)
346       : CompositeConstant(ty), component_type_(ty->element_type()) {}
VectorConstant(const Vector * ty,const std::vector<const Constant * > & components)347   VectorConstant(const Vector* ty,
348                  const std::vector<const Constant*>& components)
349       : CompositeConstant(ty, components),
350         component_type_(ty->element_type()) {}
VectorConstant(const Vector * ty,std::vector<const Constant * > && components)351   VectorConstant(const Vector* ty, std::vector<const Constant*>&& components)
352       : CompositeConstant(ty, std::move(components)),
353         component_type_(ty->element_type()) {}
354 
AsVectorConstant()355   VectorConstant* AsVectorConstant() override { return this; }
AsVectorConstant()356   const VectorConstant* AsVectorConstant() const override { return this; }
357 
358   // Make a copy of this VectorConstant instance.
CopyVectorConstant()359   std::unique_ptr<VectorConstant> CopyVectorConstant() const {
360     auto another = MakeUnique<VectorConstant>(type_->AsVector());
361     another->components_.insert(another->components_.end(), components_.begin(),
362                                 components_.end());
363     return another;
364   }
Copy()365   std::unique_ptr<Constant> Copy() const override {
366     return std::unique_ptr<Constant>(CopyVectorConstant().release());
367   }
368 
component_type()369   const Type* component_type() const { return component_type_; }
370 
371  private:
372   const Type* component_type_;
373 };
374 
375 // Matrix type constant.
376 class MatrixConstant : public CompositeConstant {
377  public:
MatrixConstant(const Matrix * ty)378   MatrixConstant(const Matrix* ty)
379       : CompositeConstant(ty), component_type_(ty->element_type()) {}
MatrixConstant(const Matrix * ty,const std::vector<const Constant * > & components)380   MatrixConstant(const Matrix* ty,
381                  const std::vector<const Constant*>& components)
382       : CompositeConstant(ty, components),
383         component_type_(ty->element_type()) {}
MatrixConstant(const Vector * ty,std::vector<const Constant * > && components)384   MatrixConstant(const Vector* ty, std::vector<const Constant*>&& components)
385       : CompositeConstant(ty, std::move(components)),
386         component_type_(ty->element_type()) {}
387 
AsMatrixConstant()388   MatrixConstant* AsMatrixConstant() override { return this; }
AsMatrixConstant()389   const MatrixConstant* AsMatrixConstant() const override { return this; }
390 
391   // Make a copy of this MatrixConstant instance.
CopyMatrixConstant()392   std::unique_ptr<MatrixConstant> CopyMatrixConstant() const {
393     auto another = MakeUnique<MatrixConstant>(type_->AsMatrix());
394     another->components_.insert(another->components_.end(), components_.begin(),
395                                 components_.end());
396     return another;
397   }
Copy()398   std::unique_ptr<Constant> Copy() const override {
399     return std::unique_ptr<Constant>(CopyMatrixConstant().release());
400   }
401 
component_type()402   const Type* component_type() { return component_type_; }
403 
404  private:
405   const Type* component_type_;
406 };
407 
408 // Array type constant.
409 class ArrayConstant : public CompositeConstant {
410  public:
ArrayConstant(const Array * ty)411   ArrayConstant(const Array* ty) : CompositeConstant(ty) {}
ArrayConstant(const Array * ty,const std::vector<const Constant * > & components)412   ArrayConstant(const Array* ty, const std::vector<const Constant*>& components)
413       : CompositeConstant(ty, components) {}
ArrayConstant(const Array * ty,std::vector<const Constant * > && components)414   ArrayConstant(const Array* ty, std::vector<const Constant*>&& components)
415       : CompositeConstant(ty, std::move(components)) {}
416 
AsArrayConstant()417   ArrayConstant* AsArrayConstant() override { return this; }
AsArrayConstant()418   const ArrayConstant* AsArrayConstant() const override { return this; }
419 
420   // Make a copy of this ArrayConstant instance.
CopyArrayConstant()421   std::unique_ptr<ArrayConstant> CopyArrayConstant() const {
422     return MakeUnique<ArrayConstant>(type_->AsArray(), components_);
423   }
Copy()424   std::unique_ptr<Constant> Copy() const override {
425     return std::unique_ptr<Constant>(CopyArrayConstant().release());
426   }
427 };
428 
429 // Null type constant.
430 class NullConstant : public Constant {
431  public:
NullConstant(const Type * ty)432   NullConstant(const Type* ty) : Constant(ty) {}
AsNullConstant()433   NullConstant* AsNullConstant() override { return this; }
AsNullConstant()434   const NullConstant* AsNullConstant() const override { return this; }
435 
436   // Make a copy of this NullConstant instance.
CopyNullConstant()437   std::unique_ptr<NullConstant> CopyNullConstant() const {
438     return MakeUnique<NullConstant>(type_);
439   }
Copy()440   std::unique_ptr<Constant> Copy() const override {
441     return std::unique_ptr<Constant>(CopyNullConstant().release());
442   }
IsZero()443   bool IsZero() const override { return true; }
444 };
445 
446 // Hash function for Constant instances. Use the structure of the constant as
447 // the key.
448 struct ConstantHash {
add_pointerConstantHash449   void add_pointer(std::u32string* h, const void* p) const {
450     uint64_t ptr_val = reinterpret_cast<uint64_t>(p);
451     h->push_back(static_cast<uint32_t>(ptr_val >> 32));
452     h->push_back(static_cast<uint32_t>(ptr_val));
453   }
454 
operatorConstantHash455   size_t operator()(const Constant* const_val) const {
456     std::u32string h;
457     add_pointer(&h, const_val->type());
458     if (const auto scalar = const_val->AsScalarConstant()) {
459       for (const auto& w : scalar->words()) {
460         h.push_back(w);
461       }
462     } else if (const auto composite = const_val->AsCompositeConstant()) {
463       for (const auto& c : composite->GetComponents()) {
464         add_pointer(&h, c);
465       }
466     } else if (const_val->AsNullConstant()) {
467       h.push_back(0);
468     } else {
469       assert(
470           false &&
471           "Tried to compute the hash value of an invalid Constant instance.");
472     }
473 
474     return std::hash<std::u32string>()(h);
475   }
476 };
477 
478 // Equality comparison structure for two constants.
479 struct ConstantEqual {
operatorConstantEqual480   bool operator()(const Constant* c1, const Constant* c2) const {
481     if (c1->type() != c2->type()) {
482       return false;
483     }
484 
485     if (const auto& s1 = c1->AsScalarConstant()) {
486       const auto& s2 = c2->AsScalarConstant();
487       return s2 && s1->words() == s2->words();
488     } else if (const auto& composite1 = c1->AsCompositeConstant()) {
489       const auto& composite2 = c2->AsCompositeConstant();
490       return composite2 &&
491              composite1->GetComponents() == composite2->GetComponents();
492     } else if (c1->AsNullConstant()) {
493       return c2->AsNullConstant() != nullptr;
494     } else {
495       assert(false && "Tried to compare two invalid Constant instances.");
496     }
497     return false;
498   }
499 };
500 
501 // This class represents a pool of constants.
502 class ConstantManager {
503  public:
504   ConstantManager(IRContext* ctx);
505 
context()506   IRContext* context() const { return ctx_; }
507 
508   // Gets or creates a unique Constant instance of type |type| and a vector of
509   // constant defining words or ids for elements of Vector type
510   // |literal_words_or_ids|. If a Constant instance existed already in the
511   // constant pool, it returns a pointer to it. Otherwise, it creates one using
512   // CreateConstant. If a new Constant instance cannot be created, it returns
513   // nullptr.
514   const Constant* GetConstant(
515       const Type* type, const std::vector<uint32_t>& literal_words_or_ids);
516 
517   template <class C>
GetConstant(const Type * type,const C & literal_words_or_ids)518   const Constant* GetConstant(const Type* type, const C& literal_words_or_ids) {
519     return GetConstant(type, std::vector<uint32_t>(literal_words_or_ids.begin(),
520                                                    literal_words_or_ids.end()));
521   }
522 
523   // Gets or creates a unique Constant instance of Vector type |type| with
524   // numeric elements and a vector of constant defining words |literal_words|.
525   // If a Constant instance existed already in the constant pool, it returns a
526   // pointer to it. Otherwise, it creates one using CreateConstant. If a new
527   // Constant instance cannot be created, it returns nullptr.
528   const Constant* GetNumericVectorConstantWithWords(
529       const Vector* type, const std::vector<uint32_t>& literal_words);
530 
531   // Gets or creates a Constant instance to hold the constant value of the given
532   // instruction. It returns a pointer to a Constant instance or nullptr if it
533   // could not create the constant.
534   const Constant* GetConstantFromInst(const Instruction* inst);
535 
536   // Gets or creates a constant defining instruction for the given Constant |c|.
537   // If |c| had already been defined, it returns a pointer to the existing
538   // declaration. Otherwise, it calls BuildInstructionAndAddToModule. If the
539   // optional |pos| is given, it will insert any newly created instructions at
540   // the given instruction iterator position. Otherwise, it inserts the new
541   // instruction at the end of the current module's types section.
542   //
543   // |type_id| is an optional argument for disambiguating equivalent types. If
544   // |type_id| is specified, the contant returned will have that type id.
545   Instruction* GetDefiningInstruction(const Constant* c, uint32_t type_id = 0,
546                                       Module::inst_iterator* pos = nullptr);
547 
548   // Creates a constant defining instruction for the given Constant instance
549   // and inserts the instruction at the position specified by the given
550   // instruction iterator. Returns a pointer to the created instruction if
551   // succeeded, otherwise returns a null pointer. The instruction iterator
552   // points to the same instruction before and after the insertion. This is the
553   // only method that actually manages id creation/assignment and instruction
554   // creation/insertion for a new Constant instance.
555   //
556   // |type_id| is an optional argument for disambiguating equivalent types. If
557   // |type_id| is specified, it is used as the type of the constant. Otherwise
558   // the type of the constant is derived by getting an id from the type manager
559   // for |c|.
560   Instruction* BuildInstructionAndAddToModule(const Constant* c,
561                                               Module::inst_iterator* pos,
562                                               uint32_t type_id = 0);
563 
564   // A helper function to get the result type of the given instruction. Returns
565   // nullptr if the instruction does not have a type id (type id is 0).
566   Type* GetType(const Instruction* inst) const;
567 
568   // A helper function to get the collected normal constant with the given id.
569   // Returns the pointer to the Constant instance in case it is found.
570   // Otherwise, it returns a null pointer.
FindDeclaredConstant(uint32_t id)571   const Constant* FindDeclaredConstant(uint32_t id) const {
572     auto iter = id_to_const_val_.find(id);
573     return (iter != id_to_const_val_.end()) ? iter->second : nullptr;
574   }
575 
576   // A helper function to get the id of a collected constant with the pointer
577   // to the Constant instance. Returns 0 in case the constant is not found.
578   uint32_t FindDeclaredConstant(const Constant* c, uint32_t type_id) const;
579 
580   // Returns the canonical constant that has the same structure and value as the
581   // given Constant |cst|. If none is found, it returns nullptr.
582   //
583   // TODO: Should be able to give a type id to disambiguate types with the same
584   // structure.
FindConstant(const Constant * c)585   const Constant* FindConstant(const Constant* c) const {
586     auto it = const_pool_.find(c);
587     return (it != const_pool_.end()) ? *it : nullptr;
588   }
589 
590   // Registers a new constant |cst| in the constant pool. If the constant
591   // existed already, it returns a pointer to the previously existing Constant
592   // in the pool. Otherwise, it returns |cst|.
RegisterConstant(std::unique_ptr<Constant> cst)593   const Constant* RegisterConstant(std::unique_ptr<Constant> cst) {
594     auto ret = const_pool_.insert(cst.get());
595     if (ret.second) {
596       owned_constants_.emplace_back(std::move(cst));
597     }
598     return *ret.first;
599   }
600 
601   // A helper function to get a vector of Constant instances with the specified
602   // ids. If it can not find the Constant instance for any one of the ids,
603   // it returns an empty vector.
604   std::vector<const Constant*> GetConstantsFromIds(
605       const std::vector<uint32_t>& ids) const;
606 
607   // Returns a vector of constants representing each in operand. If an operand
608   // is not constant its entry is nullptr.
609   std::vector<const Constant*> GetOperandConstants(
610       const Instruction* inst) const;
611 
612   // Records a mapping between |inst| and the constant value generated by it.
613   // It returns true if a new Constant was successfully mapped, false if |inst|
614   // generates no constant values.
MapInst(Instruction * inst)615   bool MapInst(Instruction* inst) {
616     if (auto cst = GetConstantFromInst(inst)) {
617       MapConstantToInst(cst, inst);
618       return true;
619     }
620     return false;
621   }
622 
RemoveId(uint32_t id)623   void RemoveId(uint32_t id) {
624     auto it = id_to_const_val_.find(id);
625     if (it != id_to_const_val_.end()) {
626       const_val_to_id_.erase(it->second);
627       id_to_const_val_.erase(it);
628     }
629   }
630 
631   // Records a new mapping between |inst| and |const_value|. This updates the
632   // two mappings |id_to_const_val_| and |const_val_to_id_|.
MapConstantToInst(const Constant * const_value,Instruction * inst)633   void MapConstantToInst(const Constant* const_value, Instruction* inst) {
634     if (id_to_const_val_.insert({inst->result_id(), const_value}).second) {
635       const_val_to_id_.insert({const_value, inst->result_id()});
636     }
637   }
638 
639   // Returns the id of a 32-bit floating point constant with value |val|.
640   uint32_t GetFloatConst(float val);
641 
642   // Returns the id of a 32-bit signed integer constant with value |val|.
643   uint32_t GetSIntConst(int32_t val);
644 
645   // Returns the id of a 32-bit unsigned integer constant with value |val|.
646   uint32_t GetUIntConst(uint32_t val);
647 
648  private:
649   // Creates a Constant instance with the given type and a vector of constant
650   // defining words. Returns a unique pointer to the created Constant instance
651   // if the Constant instance can be created successfully. To create scalar
652   // type constants, the vector should contain the constant value in 32 bit
653   // words and the given type must be of type Bool, Integer or Float. To create
654   // composite type constants, the vector should contain the component ids, and
655   // those component ids should have been recorded before as Normal Constants.
656   // And the given type must be of type Struct, Vector or Array. When creating
657   // VectorType Constant instance, the components must be scalars of the same
658   // type, either Bool, Integer or Float. If any of the rules above failed, the
659   // creation will fail and nullptr will be returned. If the vector is empty,
660   // a NullConstant instance will be created with the given type.
661   std::unique_ptr<Constant> CreateConstant(
662       const Type* type,
663       const std::vector<uint32_t>& literal_words_or_ids) const;
664 
665   // Creates an instruction with the given result id to declare a constant
666   // represented by the given Constant instance. Returns an unique pointer to
667   // the created instruction if the instruction can be created successfully.
668   // Otherwise, returns a null pointer.
669   //
670   // |type_id| is an optional argument for disambiguating equivalent types. If
671   // |type_id| is specified, it is used as the type of the constant. Otherwise
672   // the type of the constant is derived by getting an id from the type manager
673   // for |c|.
674   std::unique_ptr<Instruction> CreateInstruction(uint32_t result_id,
675                                                  const Constant* c,
676                                                  uint32_t type_id = 0) const;
677 
678   // Creates an OpConstantComposite instruction with the given result id and
679   // the CompositeConst instance which represents a composite constant. Returns
680   // an unique pointer to the created instruction if succeeded. Otherwise
681   // returns a null pointer.
682   //
683   // |type_id| is an optional argument for disambiguating equivalent types. If
684   // |type_id| is specified, it is used as the type of the constant. Otherwise
685   // the type of the constant is derived by getting an id from the type manager
686   // for |c|.
687   std::unique_ptr<Instruction> CreateCompositeInstruction(
688       uint32_t result_id, const CompositeConstant* cc,
689       uint32_t type_id = 0) const;
690 
691   // IR context that owns this constant manager.
692   IRContext* ctx_;
693 
694   // A mapping from the result ids of Normal Constants to their
695   // Constant instances. All Normal Constants in the module, either
696   // existing ones before optimization or the newly generated ones, should have
697   // their Constant instance stored and their result id registered in this map.
698   std::unordered_map<uint32_t, const Constant*> id_to_const_val_;
699 
700   // A mapping from the Constant instance of Normal Constants to their
701   // result id in the module. This is a mirror map of |id_to_const_val_|. All
702   // Normal Constants that defining instructions in the module should have
703   // their Constant and their result id registered here.
704   std::multimap<const Constant*, uint32_t> const_val_to_id_;
705 
706   // The constant pool.  All created constants are registered here.
707   std::unordered_set<const Constant*, ConstantHash, ConstantEqual> const_pool_;
708 
709   // The constant that are owned by the constant manager.  Every constant in
710   // |const_pool_| should be in |owned_constants_| as well.
711   std::vector<std::unique_ptr<Constant>> owned_constants_;
712 };
713 
714 }  // namespace analysis
715 }  // namespace opt
716 }  // namespace spvtools
717 
718 #endif  // SOURCE_OPT_CONSTANTS_H_
719