constants.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. 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 SpvOp::SpvOpConstantTrue:
  275. literal_words_or_ids.push_back(true);
  276. break;
  277. case SpvOp::SpvOpConstantFalse:
  278. literal_words_or_ids.push_back(false);
  279. break;
  280. case SpvOp::SpvOpConstantNull:
  281. case SpvOp::SpvOpConstant:
  282. case SpvOp::SpvOpConstantComposite:
  283. case SpvOp::SpvOpSpecConstantComposite:
  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(), SpvOp::SpvOpConstantNull, type,
  296. id, std::initializer_list<Operand>{});
  297. } else if (const BoolConstant* bc = c->AsBoolConstant()) {
  298. return MakeUnique<Instruction>(
  299. context(),
  300. bc->value() ? SpvOp::SpvOpConstantTrue : SpvOp::SpvOpConstantFalse,
  301. type, id, std::initializer_list<Operand>{});
  302. } else if (const IntConstant* ic = c->AsIntConstant()) {
  303. return MakeUnique<Instruction>(
  304. context(), SpvOp::SpvOpConstant, 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(), SpvOp::SpvOpConstant, 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() == SpvOpTypeStruct) {
  328. component_type_id = type_inst->GetSingleWordInOperand(component_index);
  329. } else if (type_inst && type_inst->opcode() == SpvOpTypeArray) {
  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(), SpvOp::SpvOpConstantComposite, 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::GetNumericVectorConstantWithWords(
  354. const Vector* type, const std::vector<uint32_t>& literal_words) {
  355. const auto* element_type = type->element_type();
  356. uint32_t words_per_element = 0;
  357. if (const auto* float_type = element_type->AsFloat())
  358. words_per_element = float_type->width() / 32;
  359. else if (const auto* int_type = element_type->AsInteger())
  360. words_per_element = int_type->width() / 32;
  361. if (words_per_element != 1 && words_per_element != 2) return nullptr;
  362. if (words_per_element * type->element_count() !=
  363. static_cast<uint32_t>(literal_words.size())) {
  364. return nullptr;
  365. }
  366. std::vector<uint32_t> element_ids;
  367. for (uint32_t i = 0; i < type->element_count(); ++i) {
  368. auto first_word = literal_words.begin() + (words_per_element * i);
  369. std::vector<uint32_t> const_data(first_word,
  370. first_word + words_per_element);
  371. const analysis::Constant* element_constant =
  372. GetConstant(element_type, const_data);
  373. auto element_id = GetDefiningInstruction(element_constant)->result_id();
  374. element_ids.push_back(element_id);
  375. }
  376. return GetConstant(type, element_ids);
  377. }
  378. uint32_t ConstantManager::GetFloatConst(float val) {
  379. Type* float_type = context()->get_type_mgr()->GetFloatType();
  380. utils::FloatProxy<float> v(val);
  381. const Constant* c = GetConstant(float_type, v.GetWords());
  382. return GetDefiningInstruction(c)->result_id();
  383. }
  384. uint32_t ConstantManager::GetSIntConst(int32_t val) {
  385. Type* sint_type = context()->get_type_mgr()->GetSIntType();
  386. const Constant* c = GetConstant(sint_type, {static_cast<uint32_t>(val)});
  387. return GetDefiningInstruction(c)->result_id();
  388. }
  389. uint32_t ConstantManager::GetUIntConst(uint32_t val) {
  390. Type* uint_type = context()->get_type_mgr()->GetUIntType();
  391. const Constant* c = GetConstant(uint_type, {val});
  392. return GetDefiningInstruction(c)->result_id();
  393. }
  394. std::vector<const analysis::Constant*> Constant::GetVectorComponents(
  395. analysis::ConstantManager* const_mgr) const {
  396. std::vector<const analysis::Constant*> components;
  397. const analysis::VectorConstant* a = this->AsVectorConstant();
  398. const analysis::Vector* vector_type = this->type()->AsVector();
  399. assert(vector_type != nullptr);
  400. if (a != nullptr) {
  401. for (uint32_t i = 0; i < vector_type->element_count(); ++i) {
  402. components.push_back(a->GetComponents()[i]);
  403. }
  404. } else {
  405. const analysis::Type* element_type = vector_type->element_type();
  406. const analysis::Constant* element_null_const =
  407. const_mgr->GetConstant(element_type, {});
  408. for (uint32_t i = 0; i < vector_type->element_count(); ++i) {
  409. components.push_back(element_null_const);
  410. }
  411. }
  412. return components;
  413. }
  414. } // namespace analysis
  415. } // namespace opt
  416. } // namespace spvtools