constants.h 29 KB

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