fold.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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/fold.h"
  15. #include <cassert>
  16. #include <cstdint>
  17. #include <vector>
  18. #include "source/opt/const_folding_rules.h"
  19. #include "source/opt/def_use_manager.h"
  20. #include "source/opt/folding_rules.h"
  21. #include "source/opt/ir_builder.h"
  22. #include "source/opt/ir_context.h"
  23. namespace spvtools {
  24. namespace opt {
  25. namespace {
  26. #ifndef INT32_MIN
  27. #define INT32_MIN (-2147483648)
  28. #endif
  29. #ifndef INT32_MAX
  30. #define INT32_MAX 2147483647
  31. #endif
  32. #ifndef UINT32_MAX
  33. #define UINT32_MAX 0xffffffff /* 4294967295U */
  34. #endif
  35. } // namespace
  36. uint32_t InstructionFolder::UnaryOperate(spv::Op opcode,
  37. uint32_t operand) const {
  38. switch (opcode) {
  39. // Arthimetics
  40. case spv::Op::OpSNegate: {
  41. int32_t s_operand = static_cast<int32_t>(operand);
  42. if (s_operand == std::numeric_limits<int32_t>::min()) {
  43. return s_operand;
  44. }
  45. return -s_operand;
  46. }
  47. case spv::Op::OpNot:
  48. return ~operand;
  49. case spv::Op::OpLogicalNot:
  50. return !static_cast<bool>(operand);
  51. case spv::Op::OpUConvert:
  52. return operand;
  53. case spv::Op::OpSConvert:
  54. return operand;
  55. default:
  56. assert(false &&
  57. "Unsupported unary operation for OpSpecConstantOp instruction");
  58. return 0u;
  59. }
  60. }
  61. uint32_t InstructionFolder::BinaryOperate(spv::Op opcode, uint32_t a,
  62. uint32_t b) const {
  63. switch (opcode) {
  64. // Arthimetics
  65. case spv::Op::OpIAdd:
  66. return a + b;
  67. case spv::Op::OpISub:
  68. return a - b;
  69. case spv::Op::OpIMul:
  70. return a * b;
  71. case spv::Op::OpUDiv:
  72. if (b != 0) {
  73. return a / b;
  74. } else {
  75. // Dividing by 0 is undefined, so we will just pick 0.
  76. return 0;
  77. }
  78. case spv::Op::OpSDiv:
  79. if (b != 0u) {
  80. return (static_cast<int32_t>(a)) / (static_cast<int32_t>(b));
  81. } else {
  82. // Dividing by 0 is undefined, so we will just pick 0.
  83. return 0;
  84. }
  85. case spv::Op::OpSRem: {
  86. // The sign of non-zero result comes from the first operand: a. This is
  87. // guaranteed by C++11 rules for integer division operator. The division
  88. // result is rounded toward zero, so the result of '%' has the sign of
  89. // the first operand.
  90. if (b != 0u) {
  91. return static_cast<int32_t>(a) % static_cast<int32_t>(b);
  92. } else {
  93. // Remainder when dividing with 0 is undefined, so we will just pick 0.
  94. return 0;
  95. }
  96. }
  97. case spv::Op::OpSMod: {
  98. // The sign of non-zero result comes from the second operand: b
  99. if (b != 0u) {
  100. int32_t rem = BinaryOperate(spv::Op::OpSRem, a, b);
  101. int32_t b_prim = static_cast<int32_t>(b);
  102. return (rem + b_prim) % b_prim;
  103. } else {
  104. // Mod with 0 is undefined, so we will just pick 0.
  105. return 0;
  106. }
  107. }
  108. case spv::Op::OpUMod:
  109. if (b != 0u) {
  110. return (a % b);
  111. } else {
  112. // Mod with 0 is undefined, so we will just pick 0.
  113. return 0;
  114. }
  115. // Shifting
  116. case spv::Op::OpShiftRightLogical:
  117. if (b >= 32) {
  118. // This is undefined behaviour when |b| > 32. Choose 0 for consistency.
  119. // When |b| == 32, doing the shift in C++ in undefined, but the result
  120. // will be 0, so just return that value.
  121. return 0;
  122. }
  123. return a >> b;
  124. case spv::Op::OpShiftRightArithmetic:
  125. if (b > 32) {
  126. // This is undefined behaviour. Choose 0 for consistency.
  127. return 0;
  128. }
  129. if (b == 32) {
  130. // Doing the shift in C++ is undefined, but the result is defined in the
  131. // spir-v spec. Find that value another way.
  132. if (static_cast<int32_t>(a) >= 0) {
  133. return 0;
  134. } else {
  135. return static_cast<uint32_t>(-1);
  136. }
  137. }
  138. return (static_cast<int32_t>(a)) >> b;
  139. case spv::Op::OpShiftLeftLogical:
  140. if (b >= 32) {
  141. // This is undefined behaviour when |b| > 32. Choose 0 for consistency.
  142. // When |b| == 32, doing the shift in C++ in undefined, but the result
  143. // will be 0, so just return that value.
  144. return 0;
  145. }
  146. return a << b;
  147. // Bitwise operations
  148. case spv::Op::OpBitwiseOr:
  149. return a | b;
  150. case spv::Op::OpBitwiseAnd:
  151. return a & b;
  152. case spv::Op::OpBitwiseXor:
  153. return a ^ b;
  154. // Logical
  155. case spv::Op::OpLogicalEqual:
  156. return (static_cast<bool>(a)) == (static_cast<bool>(b));
  157. case spv::Op::OpLogicalNotEqual:
  158. return (static_cast<bool>(a)) != (static_cast<bool>(b));
  159. case spv::Op::OpLogicalOr:
  160. return (static_cast<bool>(a)) || (static_cast<bool>(b));
  161. case spv::Op::OpLogicalAnd:
  162. return (static_cast<bool>(a)) && (static_cast<bool>(b));
  163. // Comparison
  164. case spv::Op::OpIEqual:
  165. return a == b;
  166. case spv::Op::OpINotEqual:
  167. return a != b;
  168. case spv::Op::OpULessThan:
  169. return a < b;
  170. case spv::Op::OpSLessThan:
  171. return (static_cast<int32_t>(a)) < (static_cast<int32_t>(b));
  172. case spv::Op::OpUGreaterThan:
  173. return a > b;
  174. case spv::Op::OpSGreaterThan:
  175. return (static_cast<int32_t>(a)) > (static_cast<int32_t>(b));
  176. case spv::Op::OpULessThanEqual:
  177. return a <= b;
  178. case spv::Op::OpSLessThanEqual:
  179. return (static_cast<int32_t>(a)) <= (static_cast<int32_t>(b));
  180. case spv::Op::OpUGreaterThanEqual:
  181. return a >= b;
  182. case spv::Op::OpSGreaterThanEqual:
  183. return (static_cast<int32_t>(a)) >= (static_cast<int32_t>(b));
  184. default:
  185. assert(false &&
  186. "Unsupported binary operation for OpSpecConstantOp instruction");
  187. return 0u;
  188. }
  189. }
  190. uint32_t InstructionFolder::TernaryOperate(spv::Op opcode, uint32_t a,
  191. uint32_t b, uint32_t c) const {
  192. switch (opcode) {
  193. case spv::Op::OpSelect:
  194. return (static_cast<bool>(a)) ? b : c;
  195. default:
  196. assert(false &&
  197. "Unsupported ternary operation for OpSpecConstantOp instruction");
  198. return 0u;
  199. }
  200. }
  201. uint32_t InstructionFolder::OperateWords(
  202. spv::Op opcode, const std::vector<uint32_t>& operand_words) const {
  203. switch (operand_words.size()) {
  204. case 1:
  205. return UnaryOperate(opcode, operand_words.front());
  206. case 2:
  207. return BinaryOperate(opcode, operand_words.front(), operand_words.back());
  208. case 3:
  209. return TernaryOperate(opcode, operand_words[0], operand_words[1],
  210. operand_words[2]);
  211. default:
  212. assert(false && "Invalid number of operands");
  213. return 0;
  214. }
  215. }
  216. bool InstructionFolder::FoldInstructionInternal(Instruction* inst) const {
  217. auto identity_map = [](uint32_t id) { return id; };
  218. Instruction* folded_inst = FoldInstructionToConstant(inst, identity_map);
  219. if (folded_inst != nullptr) {
  220. inst->SetOpcode(spv::Op::OpCopyObject);
  221. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {folded_inst->result_id()}}});
  222. return true;
  223. }
  224. analysis::ConstantManager* const_manager = context_->get_constant_mgr();
  225. std::vector<const analysis::Constant*> constants =
  226. const_manager->GetOperandConstants(inst);
  227. for (const FoldingRule& rule :
  228. GetFoldingRules().GetRulesForInstruction(inst)) {
  229. if (rule(context_, inst, constants)) {
  230. return true;
  231. }
  232. }
  233. return false;
  234. }
  235. // Returns the result of performing an operation on scalar constant operands.
  236. // This function extracts the operand values as 32 bit words and returns the
  237. // result in 32 bit word. Scalar constants with longer than 32-bit width are
  238. // not accepted in this function.
  239. uint32_t InstructionFolder::FoldScalars(
  240. spv::Op opcode,
  241. const std::vector<const analysis::Constant*>& operands) const {
  242. assert(IsFoldableOpcode(opcode) &&
  243. "Unhandled instruction opcode in FoldScalars");
  244. std::vector<uint32_t> operand_values_in_raw_words;
  245. for (const auto& operand : operands) {
  246. if (const analysis::ScalarConstant* scalar = operand->AsScalarConstant()) {
  247. const auto& scalar_words = scalar->words();
  248. assert(scalar_words.size() == 1 &&
  249. "Scalar constants with longer than 32-bit width are not allowed "
  250. "in FoldScalars()");
  251. operand_values_in_raw_words.push_back(scalar_words.front());
  252. } else if (operand->AsNullConstant()) {
  253. operand_values_in_raw_words.push_back(0u);
  254. } else {
  255. assert(false &&
  256. "FoldScalars() only accepts ScalarConst or NullConst type of "
  257. "constant");
  258. }
  259. }
  260. return OperateWords(opcode, operand_values_in_raw_words);
  261. }
  262. bool InstructionFolder::FoldBinaryIntegerOpToConstant(
  263. Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
  264. uint32_t* result) const {
  265. spv::Op opcode = inst->opcode();
  266. analysis::ConstantManager* const_manger = context_->get_constant_mgr();
  267. uint32_t ids[2];
  268. const analysis::IntConstant* constants[2];
  269. for (uint32_t i = 0; i < 2; i++) {
  270. const Operand* operand = &inst->GetInOperand(i);
  271. if (operand->type != SPV_OPERAND_TYPE_ID) {
  272. return false;
  273. }
  274. ids[i] = id_map(operand->words[0]);
  275. const analysis::Constant* constant =
  276. const_manger->FindDeclaredConstant(ids[i]);
  277. constants[i] = (constant != nullptr ? constant->AsIntConstant() : nullptr);
  278. }
  279. switch (opcode) {
  280. // Arthimetics
  281. case spv::Op::OpIMul:
  282. for (uint32_t i = 0; i < 2; i++) {
  283. if (constants[i] != nullptr && constants[i]->IsZero()) {
  284. *result = 0;
  285. return true;
  286. }
  287. }
  288. break;
  289. case spv::Op::OpUDiv:
  290. case spv::Op::OpSDiv:
  291. case spv::Op::OpSRem:
  292. case spv::Op::OpSMod:
  293. case spv::Op::OpUMod:
  294. // This changes undefined behaviour (ie divide by 0) into a 0.
  295. for (uint32_t i = 0; i < 2; i++) {
  296. if (constants[i] != nullptr && constants[i]->IsZero()) {
  297. *result = 0;
  298. return true;
  299. }
  300. }
  301. break;
  302. // Shifting
  303. case spv::Op::OpShiftRightLogical:
  304. case spv::Op::OpShiftLeftLogical:
  305. if (constants[1] != nullptr) {
  306. // When shifting by a value larger than the size of the result, the
  307. // result is undefined. We are setting the undefined behaviour to a
  308. // result of 0. If the shift amount is the same as the size of the
  309. // result, then the result is defined, and it 0.
  310. uint32_t shift_amount = constants[1]->GetU32BitValue();
  311. if (shift_amount >= 32) {
  312. *result = 0;
  313. return true;
  314. }
  315. }
  316. break;
  317. // Bitwise operations
  318. case spv::Op::OpBitwiseOr:
  319. for (uint32_t i = 0; i < 2; i++) {
  320. if (constants[i] != nullptr) {
  321. // TODO: Change the mask against a value based on the bit width of the
  322. // instruction result type. This way we can handle say 16-bit values
  323. // as well.
  324. uint32_t mask = constants[i]->GetU32BitValue();
  325. if (mask == 0xFFFFFFFF) {
  326. *result = 0xFFFFFFFF;
  327. return true;
  328. }
  329. }
  330. }
  331. break;
  332. case spv::Op::OpBitwiseAnd:
  333. for (uint32_t i = 0; i < 2; i++) {
  334. if (constants[i] != nullptr) {
  335. if (constants[i]->IsZero()) {
  336. *result = 0;
  337. return true;
  338. }
  339. }
  340. }
  341. break;
  342. // Comparison
  343. case spv::Op::OpULessThan:
  344. if (constants[0] != nullptr &&
  345. constants[0]->GetU32BitValue() == UINT32_MAX) {
  346. *result = false;
  347. return true;
  348. }
  349. if (constants[1] != nullptr && constants[1]->GetU32BitValue() == 0) {
  350. *result = false;
  351. return true;
  352. }
  353. break;
  354. case spv::Op::OpSLessThan:
  355. if (constants[0] != nullptr &&
  356. constants[0]->GetS32BitValue() == INT32_MAX) {
  357. *result = false;
  358. return true;
  359. }
  360. if (constants[1] != nullptr &&
  361. constants[1]->GetS32BitValue() == INT32_MIN) {
  362. *result = false;
  363. return true;
  364. }
  365. break;
  366. case spv::Op::OpUGreaterThan:
  367. if (constants[0] != nullptr && constants[0]->IsZero()) {
  368. *result = false;
  369. return true;
  370. }
  371. if (constants[1] != nullptr &&
  372. constants[1]->GetU32BitValue() == UINT32_MAX) {
  373. *result = false;
  374. return true;
  375. }
  376. break;
  377. case spv::Op::OpSGreaterThan:
  378. if (constants[0] != nullptr &&
  379. constants[0]->GetS32BitValue() == INT32_MIN) {
  380. *result = false;
  381. return true;
  382. }
  383. if (constants[1] != nullptr &&
  384. constants[1]->GetS32BitValue() == INT32_MAX) {
  385. *result = false;
  386. return true;
  387. }
  388. break;
  389. case spv::Op::OpULessThanEqual:
  390. if (constants[0] != nullptr && constants[0]->IsZero()) {
  391. *result = true;
  392. return true;
  393. }
  394. if (constants[1] != nullptr &&
  395. constants[1]->GetU32BitValue() == UINT32_MAX) {
  396. *result = true;
  397. return true;
  398. }
  399. break;
  400. case spv::Op::OpSLessThanEqual:
  401. if (constants[0] != nullptr &&
  402. constants[0]->GetS32BitValue() == INT32_MIN) {
  403. *result = true;
  404. return true;
  405. }
  406. if (constants[1] != nullptr &&
  407. constants[1]->GetS32BitValue() == INT32_MAX) {
  408. *result = true;
  409. return true;
  410. }
  411. break;
  412. case spv::Op::OpUGreaterThanEqual:
  413. if (constants[0] != nullptr &&
  414. constants[0]->GetU32BitValue() == UINT32_MAX) {
  415. *result = true;
  416. return true;
  417. }
  418. if (constants[1] != nullptr && constants[1]->GetU32BitValue() == 0) {
  419. *result = true;
  420. return true;
  421. }
  422. break;
  423. case spv::Op::OpSGreaterThanEqual:
  424. if (constants[0] != nullptr &&
  425. constants[0]->GetS32BitValue() == INT32_MAX) {
  426. *result = true;
  427. return true;
  428. }
  429. if (constants[1] != nullptr &&
  430. constants[1]->GetS32BitValue() == INT32_MIN) {
  431. *result = true;
  432. return true;
  433. }
  434. break;
  435. default:
  436. break;
  437. }
  438. return false;
  439. }
  440. bool InstructionFolder::FoldBinaryBooleanOpToConstant(
  441. Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
  442. uint32_t* result) const {
  443. spv::Op opcode = inst->opcode();
  444. analysis::ConstantManager* const_manger = context_->get_constant_mgr();
  445. uint32_t ids[2];
  446. const analysis::BoolConstant* constants[2];
  447. for (uint32_t i = 0; i < 2; i++) {
  448. const Operand* operand = &inst->GetInOperand(i);
  449. if (operand->type != SPV_OPERAND_TYPE_ID) {
  450. return false;
  451. }
  452. ids[i] = id_map(operand->words[0]);
  453. const analysis::Constant* constant =
  454. const_manger->FindDeclaredConstant(ids[i]);
  455. constants[i] = (constant != nullptr ? constant->AsBoolConstant() : nullptr);
  456. }
  457. switch (opcode) {
  458. // Logical
  459. case spv::Op::OpLogicalOr:
  460. for (uint32_t i = 0; i < 2; i++) {
  461. if (constants[i] != nullptr) {
  462. if (constants[i]->value()) {
  463. *result = true;
  464. return true;
  465. }
  466. }
  467. }
  468. break;
  469. case spv::Op::OpLogicalAnd:
  470. for (uint32_t i = 0; i < 2; i++) {
  471. if (constants[i] != nullptr) {
  472. if (!constants[i]->value()) {
  473. *result = false;
  474. return true;
  475. }
  476. }
  477. }
  478. break;
  479. default:
  480. break;
  481. }
  482. return false;
  483. }
  484. bool InstructionFolder::FoldIntegerOpToConstant(
  485. Instruction* inst, const std::function<uint32_t(uint32_t)>& id_map,
  486. uint32_t* result) const {
  487. assert(IsFoldableOpcode(inst->opcode()) &&
  488. "Unhandled instruction opcode in FoldScalars");
  489. switch (inst->NumInOperands()) {
  490. case 2:
  491. return FoldBinaryIntegerOpToConstant(inst, id_map, result) ||
  492. FoldBinaryBooleanOpToConstant(inst, id_map, result);
  493. default:
  494. return false;
  495. }
  496. }
  497. std::vector<uint32_t> InstructionFolder::FoldVectors(
  498. spv::Op opcode, uint32_t num_dims,
  499. const std::vector<const analysis::Constant*>& operands) const {
  500. assert(IsFoldableOpcode(opcode) &&
  501. "Unhandled instruction opcode in FoldVectors");
  502. std::vector<uint32_t> result;
  503. for (uint32_t d = 0; d < num_dims; d++) {
  504. std::vector<uint32_t> operand_values_for_one_dimension;
  505. for (const auto& operand : operands) {
  506. if (const analysis::VectorConstant* vector_operand =
  507. operand->AsVectorConstant()) {
  508. // Extract the raw value of the scalar component constants
  509. // in 32-bit words here. The reason of not using FoldScalars() here
  510. // is that we do not create temporary null constants as components
  511. // when the vector operand is a NullConstant because Constant creation
  512. // may need extra checks for the validity and that is not managed in
  513. // here.
  514. if (const analysis::ScalarConstant* scalar_component =
  515. vector_operand->GetComponents().at(d)->AsScalarConstant()) {
  516. const auto& scalar_words = scalar_component->words();
  517. assert(
  518. scalar_words.size() == 1 &&
  519. "Vector components with longer than 32-bit width are not allowed "
  520. "in FoldVectors()");
  521. operand_values_for_one_dimension.push_back(scalar_words.front());
  522. } else if (operand->AsNullConstant()) {
  523. operand_values_for_one_dimension.push_back(0u);
  524. } else {
  525. assert(false &&
  526. "VectorConst should only has ScalarConst or NullConst as "
  527. "components");
  528. }
  529. } else if (operand->AsNullConstant()) {
  530. operand_values_for_one_dimension.push_back(0u);
  531. } else {
  532. assert(false &&
  533. "FoldVectors() only accepts VectorConst or NullConst type of "
  534. "constant");
  535. }
  536. }
  537. result.push_back(OperateWords(opcode, operand_values_for_one_dimension));
  538. }
  539. return result;
  540. }
  541. bool InstructionFolder::IsFoldableOpcode(spv::Op opcode) const {
  542. // NOTE: Extend to more opcodes as new cases are handled in the folder
  543. // functions.
  544. switch (opcode) {
  545. case spv::Op::OpBitwiseAnd:
  546. case spv::Op::OpBitwiseOr:
  547. case spv::Op::OpBitwiseXor:
  548. case spv::Op::OpIAdd:
  549. case spv::Op::OpIEqual:
  550. case spv::Op::OpIMul:
  551. case spv::Op::OpINotEqual:
  552. case spv::Op::OpISub:
  553. case spv::Op::OpLogicalAnd:
  554. case spv::Op::OpLogicalEqual:
  555. case spv::Op::OpLogicalNot:
  556. case spv::Op::OpLogicalNotEqual:
  557. case spv::Op::OpLogicalOr:
  558. case spv::Op::OpNot:
  559. case spv::Op::OpSDiv:
  560. case spv::Op::OpSelect:
  561. case spv::Op::OpSGreaterThan:
  562. case spv::Op::OpSGreaterThanEqual:
  563. case spv::Op::OpShiftLeftLogical:
  564. case spv::Op::OpShiftRightArithmetic:
  565. case spv::Op::OpShiftRightLogical:
  566. case spv::Op::OpSLessThan:
  567. case spv::Op::OpSLessThanEqual:
  568. case spv::Op::OpSMod:
  569. case spv::Op::OpSNegate:
  570. case spv::Op::OpSRem:
  571. case spv::Op::OpSConvert:
  572. case spv::Op::OpUConvert:
  573. case spv::Op::OpUDiv:
  574. case spv::Op::OpUGreaterThan:
  575. case spv::Op::OpUGreaterThanEqual:
  576. case spv::Op::OpULessThan:
  577. case spv::Op::OpULessThanEqual:
  578. case spv::Op::OpUMod:
  579. return true;
  580. default:
  581. return false;
  582. }
  583. }
  584. bool InstructionFolder::IsFoldableConstant(
  585. const analysis::Constant* cst) const {
  586. // Currently supported constants are 32-bit values or null constants.
  587. if (const analysis::ScalarConstant* scalar = cst->AsScalarConstant())
  588. return scalar->words().size() == 1;
  589. else
  590. return cst->AsNullConstant() != nullptr;
  591. }
  592. Instruction* InstructionFolder::FoldInstructionToConstant(
  593. Instruction* inst, std::function<uint32_t(uint32_t)> id_map) const {
  594. analysis::ConstantManager* const_mgr = context_->get_constant_mgr();
  595. if (!inst->IsFoldableByFoldScalar() && !HasConstFoldingRule(inst)) {
  596. return nullptr;
  597. }
  598. // Collect the values of the constant parameters.
  599. std::vector<const analysis::Constant*> constants;
  600. bool missing_constants = false;
  601. inst->ForEachInId([&constants, &missing_constants, const_mgr,
  602. &id_map](uint32_t* op_id) {
  603. uint32_t id = id_map(*op_id);
  604. const analysis::Constant* const_op = const_mgr->FindDeclaredConstant(id);
  605. if (!const_op) {
  606. constants.push_back(nullptr);
  607. missing_constants = true;
  608. } else {
  609. constants.push_back(const_op);
  610. }
  611. });
  612. const analysis::Constant* folded_const = nullptr;
  613. for (auto rule : GetConstantFoldingRules().GetRulesForInstruction(inst)) {
  614. folded_const = rule(context_, inst, constants);
  615. if (folded_const != nullptr) {
  616. Instruction* const_inst =
  617. const_mgr->GetDefiningInstruction(folded_const, inst->type_id());
  618. if (const_inst == nullptr) {
  619. return nullptr;
  620. }
  621. assert(const_inst->type_id() == inst->type_id());
  622. // May be a new instruction that needs to be analysed.
  623. context_->UpdateDefUse(const_inst);
  624. return const_inst;
  625. }
  626. }
  627. uint32_t result_val = 0;
  628. bool successful = false;
  629. // If all parameters are constant, fold the instruction to a constant.
  630. if (!missing_constants && inst->IsFoldableByFoldScalar()) {
  631. result_val = FoldScalars(inst->opcode(), constants);
  632. successful = true;
  633. }
  634. if (!successful && inst->IsFoldableByFoldScalar()) {
  635. successful = FoldIntegerOpToConstant(inst, id_map, &result_val);
  636. }
  637. if (successful) {
  638. const analysis::Constant* result_const =
  639. const_mgr->GetConstant(const_mgr->GetType(inst), {result_val});
  640. Instruction* folded_inst =
  641. const_mgr->GetDefiningInstruction(result_const, inst->type_id());
  642. return folded_inst;
  643. }
  644. return nullptr;
  645. }
  646. bool InstructionFolder::IsFoldableType(Instruction* type_inst) const {
  647. // Support 32-bit integers.
  648. if (type_inst->opcode() == spv::Op::OpTypeInt) {
  649. return type_inst->GetSingleWordInOperand(0) == 32;
  650. }
  651. // Support booleans.
  652. if (type_inst->opcode() == spv::Op::OpTypeBool) {
  653. return true;
  654. }
  655. // Nothing else yet.
  656. return false;
  657. }
  658. bool InstructionFolder::FoldInstruction(Instruction* inst) const {
  659. bool modified = false;
  660. Instruction* folded_inst(inst);
  661. while (folded_inst->opcode() != spv::Op::OpCopyObject &&
  662. FoldInstructionInternal(&*folded_inst)) {
  663. modified = true;
  664. }
  665. return modified;
  666. }
  667. } // namespace opt
  668. } // namespace spvtools