constants.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. // Copyright (c) 2017 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. #include "source/opt/constants.h"
  15. #include <unordered_map>
  16. #include <vector>
  17. #include "source/opt/ir_context.h"
  18. namespace spvtools {
  19. namespace opt {
  20. namespace analysis {
  21. float Constant::GetFloat() const {
  22. assert(type()->AsFloat() != nullptr && type()->AsFloat()->width() == 32);
  23. if (const FloatConstant* fc = AsFloatConstant()) {
  24. return fc->GetFloatValue();
  25. } else {
  26. assert(AsNullConstant() && "Must be a floating point constant.");
  27. return 0.0f;
  28. }
  29. }
  30. double Constant::GetDouble() const {
  31. assert(type()->AsFloat() != nullptr && type()->AsFloat()->width() == 64);
  32. if (const FloatConstant* fc = AsFloatConstant()) {
  33. return fc->GetDoubleValue();
  34. } else {
  35. assert(AsNullConstant() && "Must be a floating point constant.");
  36. return 0.0;
  37. }
  38. }
  39. double Constant::GetValueAsDouble() const {
  40. assert(type()->AsFloat() != nullptr);
  41. if (type()->AsFloat()->width() == 32) {
  42. return GetFloat();
  43. } else {
  44. assert(type()->AsFloat()->width() == 64);
  45. return GetDouble();
  46. }
  47. }
  48. uint32_t Constant::GetU32() const {
  49. assert(type()->AsInteger() != nullptr);
  50. assert(type()->AsInteger()->width() == 32);
  51. if (const IntConstant* ic = AsIntConstant()) {
  52. return ic->GetU32BitValue();
  53. } else {
  54. assert(AsNullConstant() && "Must be an integer constant.");
  55. return 0u;
  56. }
  57. }
  58. uint64_t Constant::GetU64() const {
  59. assert(type()->AsInteger() != nullptr);
  60. assert(type()->AsInteger()->width() == 64);
  61. if (const IntConstant* ic = AsIntConstant()) {
  62. return ic->GetU64BitValue();
  63. } else {
  64. assert(AsNullConstant() && "Must be an integer constant.");
  65. return 0u;
  66. }
  67. }
  68. int32_t Constant::GetS32() const {
  69. assert(type()->AsInteger() != nullptr);
  70. assert(type()->AsInteger()->width() == 32);
  71. if (const IntConstant* ic = AsIntConstant()) {
  72. return ic->GetS32BitValue();
  73. } else {
  74. assert(AsNullConstant() && "Must be an integer constant.");
  75. return 0;
  76. }
  77. }
  78. int64_t Constant::GetS64() const {
  79. assert(type()->AsInteger() != nullptr);
  80. assert(type()->AsInteger()->width() == 64);
  81. if (const IntConstant* ic = AsIntConstant()) {
  82. return ic->GetS64BitValue();
  83. } else {
  84. assert(AsNullConstant() && "Must be an integer constant.");
  85. return 0;
  86. }
  87. }
  88. uint64_t Constant::GetZeroExtendedValue() const {
  89. const auto* int_type = type()->AsInteger();
  90. assert(int_type != nullptr);
  91. const auto width = int_type->width();
  92. assert(width <= 64);
  93. uint64_t value = 0;
  94. if (const IntConstant* ic = AsIntConstant()) {
  95. if (width <= 32) {
  96. value = ic->GetU32BitValue();
  97. } else {
  98. value = ic->GetU64BitValue();
  99. }
  100. } else {
  101. assert(AsNullConstant() && "Must be an integer constant.");
  102. }
  103. return value;
  104. }
  105. int64_t Constant::GetSignExtendedValue() const {
  106. const auto* int_type = type()->AsInteger();
  107. assert(int_type != nullptr);
  108. const auto width = int_type->width();
  109. assert(width <= 64);
  110. int64_t value = 0;
  111. if (const IntConstant* ic = AsIntConstant()) {
  112. if (width <= 32) {
  113. // Let the C++ compiler do the sign extension.
  114. value = int64_t(ic->GetS32BitValue());
  115. } else {
  116. value = ic->GetS64BitValue();
  117. }
  118. } else {
  119. assert(AsNullConstant() && "Must be an integer constant.");
  120. }
  121. return value;
  122. }
  123. ConstantManager::ConstantManager(IRContext* ctx) : ctx_(ctx) {
  124. // Populate the constant table with values from constant declarations in the
  125. // module. The values of each OpConstant declaration is the identity
  126. // assignment (i.e., each constant is its own value).
  127. for (const auto& inst : ctx_->module()->GetConstants()) {
  128. MapInst(inst);
  129. }
  130. }
  131. Type* ConstantManager::GetType(const Instruction* inst) const {
  132. return context()->get_type_mgr()->GetType(inst->type_id());
  133. }
  134. std::vector<const Constant*> ConstantManager::GetOperandConstants(
  135. const Instruction* inst) const {
  136. std::vector<const Constant*> constants;
  137. constants.reserve(inst->NumInOperands());
  138. for (uint32_t i = 0; i < inst->NumInOperands(); i++) {
  139. const Operand* operand = &inst->GetInOperand(i);
  140. if (operand->type != SPV_OPERAND_TYPE_ID) {
  141. constants.push_back(nullptr);
  142. } else {
  143. uint32_t id = operand->words[0];
  144. const analysis::Constant* constant = FindDeclaredConstant(id);
  145. constants.push_back(constant);
  146. }
  147. }
  148. return constants;
  149. }
  150. uint32_t ConstantManager::FindDeclaredConstant(const Constant* c,
  151. uint32_t type_id) const {
  152. c = FindConstant(c);
  153. if (c == nullptr) {
  154. return 0;
  155. }
  156. for (auto range = const_val_to_id_.equal_range(c);
  157. range.first != range.second; ++range.first) {
  158. Instruction* const_def =
  159. context()->get_def_use_mgr()->GetDef(range.first->second);
  160. if (type_id == 0 || const_def->type_id() == type_id) {
  161. return range.first->second;
  162. }
  163. }
  164. return 0;
  165. }
  166. std::vector<const Constant*> ConstantManager::GetConstantsFromIds(
  167. const std::vector<uint32_t>& ids) const {
  168. std::vector<const Constant*> constants;
  169. for (uint32_t id : ids) {
  170. if (const Constant* c = FindDeclaredConstant(id)) {
  171. constants.push_back(c);
  172. } else {
  173. return {};
  174. }
  175. }
  176. return constants;
  177. }
  178. Instruction* ConstantManager::BuildInstructionAndAddToModule(
  179. const Constant* new_const, Module::inst_iterator* pos, uint32_t type_id) {
  180. // TODO(1841): Handle id overflow.
  181. uint32_t new_id = context()->TakeNextId();
  182. if (new_id == 0) {
  183. return nullptr;
  184. }
  185. auto new_inst = CreateInstruction(new_id, new_const, type_id);
  186. if (!new_inst) {
  187. return nullptr;
  188. }
  189. auto* new_inst_ptr = new_inst.get();
  190. *pos = pos->InsertBefore(std::move(new_inst));
  191. ++(*pos);
  192. if (context()->AreAnalysesValid(IRContext::Analysis::kAnalysisDefUse))
  193. context()->get_def_use_mgr()->AnalyzeInstDefUse(new_inst_ptr);
  194. MapConstantToInst(new_const, new_inst_ptr);
  195. return new_inst_ptr;
  196. }
  197. Instruction* ConstantManager::GetDefiningInstruction(
  198. const Constant* c, uint32_t type_id, Module::inst_iterator* pos) {
  199. uint32_t decl_id = FindDeclaredConstant(c, type_id);
  200. if (decl_id == 0) {
  201. auto iter = context()->types_values_end();
  202. if (pos == nullptr) pos = &iter;
  203. return BuildInstructionAndAddToModule(c, pos, type_id);
  204. } else {
  205. auto def = context()->get_def_use_mgr()->GetDef(decl_id);
  206. assert(def != nullptr);
  207. assert((type_id == 0 || def->type_id() == type_id) &&
  208. "This constant already has an instruction with a different type.");
  209. return def;
  210. }
  211. }
  212. std::unique_ptr<Constant> ConstantManager::CreateConstant(
  213. const Type* type, const std::vector<uint32_t>& literal_words_or_ids) const {
  214. if (literal_words_or_ids.size() == 0) {
  215. // Constant declared with OpConstantNull
  216. return MakeUnique<NullConstant>(type);
  217. } else if (auto* bt = type->AsBool()) {
  218. assert(literal_words_or_ids.size() == 1 &&
  219. "Bool constant should be declared with one operand");
  220. return MakeUnique<BoolConstant>(bt, literal_words_or_ids.front());
  221. } else if (auto* it = type->AsInteger()) {
  222. return MakeUnique<IntConstant>(it, literal_words_or_ids);
  223. } else if (auto* ft = type->AsFloat()) {
  224. return MakeUnique<FloatConstant>(ft, literal_words_or_ids);
  225. } else if (auto* vt = type->AsVector()) {
  226. auto components = GetConstantsFromIds(literal_words_or_ids);
  227. if (components.empty()) return nullptr;
  228. // All components of VectorConstant must be of type Bool, Integer or Float.
  229. if (!std::all_of(components.begin(), components.end(),
  230. [](const Constant* c) {
  231. if (c->type()->AsBool() || c->type()->AsInteger() ||
  232. c->type()->AsFloat()) {
  233. return true;
  234. } else {
  235. return false;
  236. }
  237. }))
  238. return nullptr;
  239. // All components of VectorConstant must be in the same type.
  240. const auto* component_type = components.front()->type();
  241. if (!std::all_of(components.begin(), components.end(),
  242. [&component_type](const Constant* c) {
  243. if (c->type() == component_type) return true;
  244. return false;
  245. }))
  246. return nullptr;
  247. return MakeUnique<VectorConstant>(vt, components);
  248. } else if (auto* mt = type->AsMatrix()) {
  249. auto components = GetConstantsFromIds(literal_words_or_ids);
  250. if (components.empty()) return nullptr;
  251. return MakeUnique<MatrixConstant>(mt, components);
  252. } else if (auto* st = type->AsStruct()) {
  253. auto components = GetConstantsFromIds(literal_words_or_ids);
  254. if (components.empty()) return nullptr;
  255. return MakeUnique<StructConstant>(st, components);
  256. } else if (auto* at = type->AsArray()) {
  257. auto components = GetConstantsFromIds(literal_words_or_ids);
  258. if (components.empty()) return nullptr;
  259. return MakeUnique<ArrayConstant>(at, components);
  260. } else {
  261. return nullptr;
  262. }
  263. }
  264. const Constant* ConstantManager::GetConstantFromInst(const Instruction* inst) {
  265. std::vector<uint32_t> literal_words_or_ids;
  266. // Collect the constant defining literals or component ids.
  267. for (uint32_t i = 0; i < inst->NumInOperands(); i++) {
  268. literal_words_or_ids.insert(literal_words_or_ids.end(),
  269. inst->GetInOperand(i).words.begin(),
  270. inst->GetInOperand(i).words.end());
  271. }
  272. switch (inst->opcode()) {
  273. // OpConstant{True|False} have the value embedded in the opcode. So they
  274. // are not handled by the for-loop above. Here we add the value explicitly.
  275. case spv::Op::OpConstantTrue:
  276. literal_words_or_ids.push_back(true);
  277. break;
  278. case spv::Op::OpConstantFalse:
  279. literal_words_or_ids.push_back(false);
  280. break;
  281. case spv::Op::OpConstantNull:
  282. case spv::Op::OpConstant:
  283. case spv::Op::OpConstantComposite:
  284. case spv::Op::OpSpecConstantComposite:
  285. break;
  286. default:
  287. return nullptr;
  288. }
  289. return GetConstant(GetType(inst), literal_words_or_ids);
  290. }
  291. std::unique_ptr<Instruction> ConstantManager::CreateInstruction(
  292. uint32_t id, const Constant* c, uint32_t type_id) const {
  293. uint32_t type =
  294. (type_id == 0) ? context()->get_type_mgr()->GetId(c->type()) : type_id;
  295. if (c->AsNullConstant()) {
  296. return MakeUnique<Instruction>(context(), spv::Op::OpConstantNull, type, id,
  297. std::initializer_list<Operand>{});
  298. } else if (const BoolConstant* bc = c->AsBoolConstant()) {
  299. return MakeUnique<Instruction>(
  300. context(),
  301. bc->value() ? spv::Op::OpConstantTrue : spv::Op::OpConstantFalse, type,
  302. id, std::initializer_list<Operand>{});
  303. } else if (const IntConstant* ic = c->AsIntConstant()) {
  304. return MakeUnique<Instruction>(
  305. context(), spv::Op::OpConstant, type, id,
  306. std::initializer_list<Operand>{
  307. Operand(spv_operand_type_t::SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER,
  308. ic->words())});
  309. } else if (const FloatConstant* fc = c->AsFloatConstant()) {
  310. return MakeUnique<Instruction>(
  311. context(), spv::Op::OpConstant, type, id,
  312. std::initializer_list<Operand>{
  313. Operand(spv_operand_type_t::SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER,
  314. fc->words())});
  315. } else if (const CompositeConstant* cc = c->AsCompositeConstant()) {
  316. return CreateCompositeInstruction(id, cc, type_id);
  317. } else {
  318. return nullptr;
  319. }
  320. }
  321. std::unique_ptr<Instruction> ConstantManager::CreateCompositeInstruction(
  322. uint32_t result_id, const CompositeConstant* cc, uint32_t type_id) const {
  323. std::vector<Operand> operands;
  324. Instruction* type_inst = context()->get_def_use_mgr()->GetDef(type_id);
  325. uint32_t component_index = 0;
  326. for (const Constant* component_const : cc->GetComponents()) {
  327. uint32_t component_type_id = 0;
  328. if (type_inst && type_inst->opcode() == spv::Op::OpTypeStruct) {
  329. component_type_id = type_inst->GetSingleWordInOperand(component_index);
  330. } else if (type_inst && type_inst->opcode() == spv::Op::OpTypeArray) {
  331. component_type_id = type_inst->GetSingleWordInOperand(0);
  332. }
  333. uint32_t id = FindDeclaredConstant(component_const, component_type_id);
  334. if (id == 0) {
  335. // Cannot get the id of the component constant, while all components
  336. // should have been added to the module prior to the composite constant.
  337. // Cannot create OpConstantComposite instruction in this case.
  338. return nullptr;
  339. }
  340. operands.emplace_back(spv_operand_type_t::SPV_OPERAND_TYPE_ID,
  341. std::initializer_list<uint32_t>{id});
  342. component_index++;
  343. }
  344. uint32_t type =
  345. (type_id == 0) ? context()->get_type_mgr()->GetId(cc->type()) : type_id;
  346. return MakeUnique<Instruction>(context(), spv::Op::OpConstantComposite, type,
  347. result_id, std::move(operands));
  348. }
  349. const Constant* ConstantManager::GetConstant(
  350. const Type* type, const std::vector<uint32_t>& literal_words_or_ids) {
  351. auto cst = CreateConstant(type, literal_words_or_ids);
  352. return cst ? RegisterConstant(std::move(cst)) : nullptr;
  353. }
  354. const Constant* ConstantManager::GetNullCompositeConstant(const Type* type) {
  355. std::vector<uint32_t> literal_words_or_id;
  356. if (type->AsVector()) {
  357. const Type* element_type = type->AsVector()->element_type();
  358. const uint32_t null_id = GetNullConstId(element_type);
  359. const uint32_t element_count = type->AsVector()->element_count();
  360. for (uint32_t i = 0; i < element_count; i++) {
  361. literal_words_or_id.push_back(null_id);
  362. }
  363. } else if (type->AsMatrix()) {
  364. const Type* element_type = type->AsMatrix()->element_type();
  365. const uint32_t null_id = GetNullConstId(element_type);
  366. const uint32_t element_count = type->AsMatrix()->element_count();
  367. for (uint32_t i = 0; i < element_count; i++) {
  368. literal_words_or_id.push_back(null_id);
  369. }
  370. } else if (type->AsStruct()) {
  371. // TODO (sfricke-lunarg) add proper struct support
  372. return nullptr;
  373. } else if (type->AsArray()) {
  374. const Type* element_type = type->AsArray()->element_type();
  375. const uint32_t null_id = GetNullConstId(element_type);
  376. assert(type->AsArray()->length_info().words[0] ==
  377. analysis::Array::LengthInfo::kConstant &&
  378. "unexpected array length");
  379. const uint32_t element_count = type->AsArray()->length_info().words[0];
  380. for (uint32_t i = 0; i < element_count; i++) {
  381. literal_words_or_id.push_back(null_id);
  382. }
  383. } else {
  384. return nullptr;
  385. }
  386. return GetConstant(type, literal_words_or_id);
  387. }
  388. const Constant* ConstantManager::GetNumericVectorConstantWithWords(
  389. const Vector* type, const std::vector<uint32_t>& literal_words) {
  390. const auto* element_type = type->element_type();
  391. uint32_t words_per_element = 0;
  392. if (const auto* float_type = element_type->AsFloat())
  393. words_per_element = float_type->width() / 32;
  394. else if (const auto* int_type = element_type->AsInteger())
  395. words_per_element = int_type->width() / 32;
  396. if (words_per_element != 1 && words_per_element != 2) return nullptr;
  397. if (words_per_element * type->element_count() !=
  398. static_cast<uint32_t>(literal_words.size())) {
  399. return nullptr;
  400. }
  401. std::vector<uint32_t> element_ids;
  402. for (uint32_t i = 0; i < type->element_count(); ++i) {
  403. auto first_word = literal_words.begin() + (words_per_element * i);
  404. std::vector<uint32_t> const_data(first_word,
  405. first_word + words_per_element);
  406. const analysis::Constant* element_constant =
  407. GetConstant(element_type, const_data);
  408. auto element_id = GetDefiningInstruction(element_constant)->result_id();
  409. element_ids.push_back(element_id);
  410. }
  411. return GetConstant(type, element_ids);
  412. }
  413. uint32_t ConstantManager::GetFloatConstId(float val) {
  414. const Constant* c = GetFloatConst(val);
  415. return GetDefiningInstruction(c)->result_id();
  416. }
  417. const Constant* ConstantManager::GetFloatConst(float val) {
  418. Type* float_type = context()->get_type_mgr()->GetFloatType();
  419. utils::FloatProxy<float> v(val);
  420. const Constant* c = GetConstant(float_type, v.GetWords());
  421. return c;
  422. }
  423. uint32_t ConstantManager::GetDoubleConstId(double val) {
  424. const Constant* c = GetDoubleConst(val);
  425. return GetDefiningInstruction(c)->result_id();
  426. }
  427. const Constant* ConstantManager::GetDoubleConst(double val) {
  428. Type* float_type = context()->get_type_mgr()->GetDoubleType();
  429. utils::FloatProxy<double> v(val);
  430. const Constant* c = GetConstant(float_type, v.GetWords());
  431. return c;
  432. }
  433. uint32_t ConstantManager::GetSIntConstId(int32_t val) {
  434. Type* sint_type = context()->get_type_mgr()->GetSIntType();
  435. const Constant* c = GetConstant(sint_type, {static_cast<uint32_t>(val)});
  436. return GetDefiningInstruction(c)->result_id();
  437. }
  438. uint32_t ConstantManager::GetUIntConstId(uint32_t val) {
  439. Type* uint_type = context()->get_type_mgr()->GetUIntType();
  440. const Constant* c = GetConstant(uint_type, {val});
  441. return GetDefiningInstruction(c)->result_id();
  442. }
  443. uint32_t ConstantManager::GetNullConstId(const Type* type) {
  444. const Constant* c = GetConstant(type, {});
  445. return GetDefiningInstruction(c)->result_id();
  446. }
  447. std::vector<const analysis::Constant*> Constant::GetVectorComponents(
  448. analysis::ConstantManager* const_mgr) const {
  449. std::vector<const analysis::Constant*> components;
  450. const analysis::VectorConstant* a = this->AsVectorConstant();
  451. const analysis::Vector* vector_type = this->type()->AsVector();
  452. assert(vector_type != nullptr);
  453. if (a != nullptr) {
  454. for (uint32_t i = 0; i < vector_type->element_count(); ++i) {
  455. components.push_back(a->GetComponents()[i]);
  456. }
  457. } else {
  458. const analysis::Type* element_type = vector_type->element_type();
  459. const analysis::Constant* element_null_const =
  460. const_mgr->GetConstant(element_type, {});
  461. for (uint32_t i = 0; i < vector_type->element_count(); ++i) {
  462. components.push_back(element_null_const);
  463. }
  464. }
  465. return components;
  466. }
  467. } // namespace analysis
  468. } // namespace opt
  469. } // namespace spvtools