constants.cpp 20 KB

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