folding_rules.cpp 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618
  1. // Copyright (c) 2018 Google LLC
  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/folding_rules.h"
  15. #include <limits>
  16. #include <memory>
  17. #include <utility>
  18. #include "ir_builder.h"
  19. #include "source/latest_version_glsl_std_450_header.h"
  20. #include "source/opt/ir_context.h"
  21. namespace spvtools {
  22. namespace opt {
  23. namespace {
  24. const uint32_t kExtractCompositeIdInIdx = 0;
  25. const uint32_t kInsertObjectIdInIdx = 0;
  26. const uint32_t kInsertCompositeIdInIdx = 1;
  27. const uint32_t kExtInstSetIdInIdx = 0;
  28. const uint32_t kExtInstInstructionInIdx = 1;
  29. const uint32_t kFMixXIdInIdx = 2;
  30. const uint32_t kFMixYIdInIdx = 3;
  31. const uint32_t kFMixAIdInIdx = 4;
  32. const uint32_t kStoreObjectInIdx = 1;
  33. // Some image instructions may contain an "image operands" argument.
  34. // Returns the operand index for the "image operands".
  35. // Returns -1 if the instruction does not have image operands.
  36. int32_t ImageOperandsMaskInOperandIndex(Instruction* inst) {
  37. const auto opcode = inst->opcode();
  38. switch (opcode) {
  39. case SpvOpImageSampleImplicitLod:
  40. case SpvOpImageSampleExplicitLod:
  41. case SpvOpImageSampleProjImplicitLod:
  42. case SpvOpImageSampleProjExplicitLod:
  43. case SpvOpImageFetch:
  44. case SpvOpImageRead:
  45. case SpvOpImageSparseSampleImplicitLod:
  46. case SpvOpImageSparseSampleExplicitLod:
  47. case SpvOpImageSparseSampleProjImplicitLod:
  48. case SpvOpImageSparseSampleProjExplicitLod:
  49. case SpvOpImageSparseFetch:
  50. case SpvOpImageSparseRead:
  51. return inst->NumOperands() > 4 ? 2 : -1;
  52. case SpvOpImageSampleDrefImplicitLod:
  53. case SpvOpImageSampleDrefExplicitLod:
  54. case SpvOpImageSampleProjDrefImplicitLod:
  55. case SpvOpImageSampleProjDrefExplicitLod:
  56. case SpvOpImageGather:
  57. case SpvOpImageDrefGather:
  58. case SpvOpImageSparseSampleDrefImplicitLod:
  59. case SpvOpImageSparseSampleDrefExplicitLod:
  60. case SpvOpImageSparseSampleProjDrefImplicitLod:
  61. case SpvOpImageSparseSampleProjDrefExplicitLod:
  62. case SpvOpImageSparseGather:
  63. case SpvOpImageSparseDrefGather:
  64. return inst->NumOperands() > 5 ? 3 : -1;
  65. case SpvOpImageWrite:
  66. return inst->NumOperands() > 3 ? 3 : -1;
  67. default:
  68. return -1;
  69. }
  70. }
  71. // Returns the element width of |type|.
  72. uint32_t ElementWidth(const analysis::Type* type) {
  73. if (const analysis::Vector* vec_type = type->AsVector()) {
  74. return ElementWidth(vec_type->element_type());
  75. } else if (const analysis::Float* float_type = type->AsFloat()) {
  76. return float_type->width();
  77. } else {
  78. assert(type->AsInteger());
  79. return type->AsInteger()->width();
  80. }
  81. }
  82. // Returns true if |type| is Float or a vector of Float.
  83. bool HasFloatingPoint(const analysis::Type* type) {
  84. if (type->AsFloat()) {
  85. return true;
  86. } else if (const analysis::Vector* vec_type = type->AsVector()) {
  87. return vec_type->element_type()->AsFloat() != nullptr;
  88. }
  89. return false;
  90. }
  91. // Returns false if |val| is NaN, infinite or subnormal.
  92. template <typename T>
  93. bool IsValidResult(T val) {
  94. int classified = std::fpclassify(val);
  95. switch (classified) {
  96. case FP_NAN:
  97. case FP_INFINITE:
  98. case FP_SUBNORMAL:
  99. return false;
  100. default:
  101. return true;
  102. }
  103. }
  104. const analysis::Constant* ConstInput(
  105. const std::vector<const analysis::Constant*>& constants) {
  106. return constants[0] ? constants[0] : constants[1];
  107. }
  108. Instruction* NonConstInput(IRContext* context, const analysis::Constant* c,
  109. Instruction* inst) {
  110. uint32_t in_op = c ? 1u : 0u;
  111. return context->get_def_use_mgr()->GetDef(
  112. inst->GetSingleWordInOperand(in_op));
  113. }
  114. std::vector<uint32_t> ExtractInts(uint64_t val) {
  115. std::vector<uint32_t> words;
  116. words.push_back(static_cast<uint32_t>(val));
  117. words.push_back(static_cast<uint32_t>(val >> 32));
  118. return words;
  119. }
  120. std::vector<uint32_t> GetWordsFromScalarIntConstant(
  121. const analysis::IntConstant* c) {
  122. assert(c != nullptr);
  123. uint32_t width = c->type()->AsInteger()->width();
  124. assert(width == 32 || width == 64);
  125. if (width == 64) {
  126. uint64_t uval = static_cast<uint64_t>(c->GetU64());
  127. return ExtractInts(uval);
  128. }
  129. return {c->GetU32()};
  130. }
  131. std::vector<uint32_t> GetWordsFromScalarFloatConstant(
  132. const analysis::FloatConstant* c) {
  133. assert(c != nullptr);
  134. uint32_t width = c->type()->AsFloat()->width();
  135. assert(width == 32 || width == 64);
  136. if (width == 64) {
  137. utils::FloatProxy<double> result(c->GetDouble());
  138. return result.GetWords();
  139. }
  140. utils::FloatProxy<float> result(c->GetFloat());
  141. return result.GetWords();
  142. }
  143. std::vector<uint32_t> GetWordsFromNumericScalarOrVectorConstant(
  144. analysis::ConstantManager* const_mgr, const analysis::Constant* c) {
  145. if (const auto* float_constant = c->AsFloatConstant()) {
  146. return GetWordsFromScalarFloatConstant(float_constant);
  147. } else if (const auto* int_constant = c->AsIntConstant()) {
  148. return GetWordsFromScalarIntConstant(int_constant);
  149. } else if (const auto* vec_constant = c->AsVectorConstant()) {
  150. std::vector<uint32_t> words;
  151. for (const auto* comp : vec_constant->GetComponents()) {
  152. auto comp_in_words =
  153. GetWordsFromNumericScalarOrVectorConstant(const_mgr, comp);
  154. words.insert(words.end(), comp_in_words.begin(), comp_in_words.end());
  155. }
  156. return words;
  157. }
  158. return {};
  159. }
  160. const analysis::Constant* ConvertWordsToNumericScalarOrVectorConstant(
  161. analysis::ConstantManager* const_mgr, const std::vector<uint32_t>& words,
  162. const analysis::Type* type) {
  163. if (type->AsInteger() || type->AsFloat())
  164. return const_mgr->GetConstant(type, words);
  165. if (const auto* vec_type = type->AsVector())
  166. return const_mgr->GetNumericVectorConstantWithWords(vec_type, words);
  167. return nullptr;
  168. }
  169. // Returns the negation of |c|. |c| must be a 32 or 64 bit floating point
  170. // constant.
  171. uint32_t NegateFloatingPointConstant(analysis::ConstantManager* const_mgr,
  172. const analysis::Constant* c) {
  173. assert(c);
  174. assert(c->type()->AsFloat());
  175. uint32_t width = c->type()->AsFloat()->width();
  176. assert(width == 32 || width == 64);
  177. std::vector<uint32_t> words;
  178. if (width == 64) {
  179. utils::FloatProxy<double> result(c->GetDouble() * -1.0);
  180. words = result.GetWords();
  181. } else {
  182. utils::FloatProxy<float> result(c->GetFloat() * -1.0f);
  183. words = result.GetWords();
  184. }
  185. const analysis::Constant* negated_const =
  186. const_mgr->GetConstant(c->type(), std::move(words));
  187. return const_mgr->GetDefiningInstruction(negated_const)->result_id();
  188. }
  189. // Negates the integer constant |c|. Returns the id of the defining instruction.
  190. uint32_t NegateIntegerConstant(analysis::ConstantManager* const_mgr,
  191. const analysis::Constant* c) {
  192. assert(c);
  193. assert(c->type()->AsInteger());
  194. uint32_t width = c->type()->AsInteger()->width();
  195. assert(width == 32 || width == 64);
  196. std::vector<uint32_t> words;
  197. if (width == 64) {
  198. uint64_t uval = static_cast<uint64_t>(0 - c->GetU64());
  199. words = ExtractInts(uval);
  200. } else {
  201. words.push_back(static_cast<uint32_t>(0 - c->GetU32()));
  202. }
  203. const analysis::Constant* negated_const =
  204. const_mgr->GetConstant(c->type(), std::move(words));
  205. return const_mgr->GetDefiningInstruction(negated_const)->result_id();
  206. }
  207. // Negates the vector constant |c|. Returns the id of the defining instruction.
  208. uint32_t NegateVectorConstant(analysis::ConstantManager* const_mgr,
  209. const analysis::Constant* c) {
  210. assert(const_mgr && c);
  211. assert(c->type()->AsVector());
  212. if (c->AsNullConstant()) {
  213. // 0.0 vs -0.0 shouldn't matter.
  214. return const_mgr->GetDefiningInstruction(c)->result_id();
  215. } else {
  216. const analysis::Type* component_type =
  217. c->AsVectorConstant()->component_type();
  218. std::vector<uint32_t> words;
  219. for (auto& comp : c->AsVectorConstant()->GetComponents()) {
  220. if (component_type->AsFloat()) {
  221. words.push_back(NegateFloatingPointConstant(const_mgr, comp));
  222. } else {
  223. assert(component_type->AsInteger());
  224. words.push_back(NegateIntegerConstant(const_mgr, comp));
  225. }
  226. }
  227. const analysis::Constant* negated_const =
  228. const_mgr->GetConstant(c->type(), std::move(words));
  229. return const_mgr->GetDefiningInstruction(negated_const)->result_id();
  230. }
  231. }
  232. // Negates |c|. Returns the id of the defining instruction.
  233. uint32_t NegateConstant(analysis::ConstantManager* const_mgr,
  234. const analysis::Constant* c) {
  235. if (c->type()->AsVector()) {
  236. return NegateVectorConstant(const_mgr, c);
  237. } else if (c->type()->AsFloat()) {
  238. return NegateFloatingPointConstant(const_mgr, c);
  239. } else {
  240. assert(c->type()->AsInteger());
  241. return NegateIntegerConstant(const_mgr, c);
  242. }
  243. }
  244. // Takes the reciprocal of |c|. |c|'s type must be Float or a vector of Float.
  245. // Returns 0 if the reciprocal is NaN, infinite or subnormal.
  246. uint32_t Reciprocal(analysis::ConstantManager* const_mgr,
  247. const analysis::Constant* c) {
  248. assert(const_mgr && c);
  249. assert(c->type()->AsFloat());
  250. uint32_t width = c->type()->AsFloat()->width();
  251. assert(width == 32 || width == 64);
  252. std::vector<uint32_t> words;
  253. if (width == 64) {
  254. spvtools::utils::FloatProxy<double> result(1.0 / c->GetDouble());
  255. if (!IsValidResult(result.getAsFloat())) return 0;
  256. words = result.GetWords();
  257. } else {
  258. spvtools::utils::FloatProxy<float> result(1.0f / c->GetFloat());
  259. if (!IsValidResult(result.getAsFloat())) return 0;
  260. words = result.GetWords();
  261. }
  262. const analysis::Constant* negated_const =
  263. const_mgr->GetConstant(c->type(), std::move(words));
  264. return const_mgr->GetDefiningInstruction(negated_const)->result_id();
  265. }
  266. // Replaces fdiv where second operand is constant with fmul.
  267. FoldingRule ReciprocalFDiv() {
  268. return [](IRContext* context, Instruction* inst,
  269. const std::vector<const analysis::Constant*>& constants) {
  270. assert(inst->opcode() == SpvOpFDiv);
  271. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  272. const analysis::Type* type =
  273. context->get_type_mgr()->GetType(inst->type_id());
  274. if (!inst->IsFloatingPointFoldingAllowed()) return false;
  275. uint32_t width = ElementWidth(type);
  276. if (width != 32 && width != 64) return false;
  277. if (constants[1] != nullptr) {
  278. uint32_t id = 0;
  279. if (const analysis::VectorConstant* vector_const =
  280. constants[1]->AsVectorConstant()) {
  281. std::vector<uint32_t> neg_ids;
  282. for (auto& comp : vector_const->GetComponents()) {
  283. id = Reciprocal(const_mgr, comp);
  284. if (id == 0) return false;
  285. neg_ids.push_back(id);
  286. }
  287. const analysis::Constant* negated_const =
  288. const_mgr->GetConstant(constants[1]->type(), std::move(neg_ids));
  289. id = const_mgr->GetDefiningInstruction(negated_const)->result_id();
  290. } else if (constants[1]->AsFloatConstant()) {
  291. id = Reciprocal(const_mgr, constants[1]);
  292. if (id == 0) return false;
  293. } else {
  294. // Don't fold a null constant.
  295. return false;
  296. }
  297. inst->SetOpcode(SpvOpFMul);
  298. inst->SetInOperands(
  299. {{SPV_OPERAND_TYPE_ID, {inst->GetSingleWordInOperand(0u)}},
  300. {SPV_OPERAND_TYPE_ID, {id}}});
  301. return true;
  302. }
  303. return false;
  304. };
  305. }
  306. // Elides consecutive negate instructions.
  307. FoldingRule MergeNegateArithmetic() {
  308. return [](IRContext* context, Instruction* inst,
  309. const std::vector<const analysis::Constant*>& constants) {
  310. assert(inst->opcode() == SpvOpFNegate || inst->opcode() == SpvOpSNegate);
  311. (void)constants;
  312. const analysis::Type* type =
  313. context->get_type_mgr()->GetType(inst->type_id());
  314. if (HasFloatingPoint(type) && !inst->IsFloatingPointFoldingAllowed())
  315. return false;
  316. Instruction* op_inst =
  317. context->get_def_use_mgr()->GetDef(inst->GetSingleWordInOperand(0u));
  318. if (HasFloatingPoint(type) && !op_inst->IsFloatingPointFoldingAllowed())
  319. return false;
  320. if (op_inst->opcode() == inst->opcode()) {
  321. // Elide negates.
  322. inst->SetOpcode(SpvOpCopyObject);
  323. inst->SetInOperands(
  324. {{SPV_OPERAND_TYPE_ID, {op_inst->GetSingleWordInOperand(0u)}}});
  325. return true;
  326. }
  327. return false;
  328. };
  329. }
  330. // Merges negate into a mul or div operation if that operation contains a
  331. // constant operand.
  332. // Cases:
  333. // -(x * 2) = x * -2
  334. // -(2 * x) = x * -2
  335. // -(x / 2) = x / -2
  336. // -(2 / x) = -2 / x
  337. FoldingRule MergeNegateMulDivArithmetic() {
  338. return [](IRContext* context, Instruction* inst,
  339. const std::vector<const analysis::Constant*>& constants) {
  340. assert(inst->opcode() == SpvOpFNegate || inst->opcode() == SpvOpSNegate);
  341. (void)constants;
  342. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  343. const analysis::Type* type =
  344. context->get_type_mgr()->GetType(inst->type_id());
  345. if (HasFloatingPoint(type) && !inst->IsFloatingPointFoldingAllowed())
  346. return false;
  347. Instruction* op_inst =
  348. context->get_def_use_mgr()->GetDef(inst->GetSingleWordInOperand(0u));
  349. if (HasFloatingPoint(type) && !op_inst->IsFloatingPointFoldingAllowed())
  350. return false;
  351. uint32_t width = ElementWidth(type);
  352. if (width != 32 && width != 64) return false;
  353. SpvOp opcode = op_inst->opcode();
  354. if (opcode == SpvOpFMul || opcode == SpvOpFDiv || opcode == SpvOpIMul ||
  355. opcode == SpvOpSDiv || opcode == SpvOpUDiv) {
  356. std::vector<const analysis::Constant*> op_constants =
  357. const_mgr->GetOperandConstants(op_inst);
  358. // Merge negate into mul or div if one operand is constant.
  359. if (op_constants[0] || op_constants[1]) {
  360. bool zero_is_variable = op_constants[0] == nullptr;
  361. const analysis::Constant* c = ConstInput(op_constants);
  362. uint32_t neg_id = NegateConstant(const_mgr, c);
  363. uint32_t non_const_id = zero_is_variable
  364. ? op_inst->GetSingleWordInOperand(0u)
  365. : op_inst->GetSingleWordInOperand(1u);
  366. // Change this instruction to a mul/div.
  367. inst->SetOpcode(op_inst->opcode());
  368. if (opcode == SpvOpFDiv || opcode == SpvOpUDiv || opcode == SpvOpSDiv) {
  369. uint32_t op0 = zero_is_variable ? non_const_id : neg_id;
  370. uint32_t op1 = zero_is_variable ? neg_id : non_const_id;
  371. inst->SetInOperands(
  372. {{SPV_OPERAND_TYPE_ID, {op0}}, {SPV_OPERAND_TYPE_ID, {op1}}});
  373. } else {
  374. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {non_const_id}},
  375. {SPV_OPERAND_TYPE_ID, {neg_id}}});
  376. }
  377. return true;
  378. }
  379. }
  380. return false;
  381. };
  382. }
  383. // Merges negate into a add or sub operation if that operation contains a
  384. // constant operand.
  385. // Cases:
  386. // -(x + 2) = -2 - x
  387. // -(2 + x) = -2 - x
  388. // -(x - 2) = 2 - x
  389. // -(2 - x) = x - 2
  390. FoldingRule MergeNegateAddSubArithmetic() {
  391. return [](IRContext* context, Instruction* inst,
  392. const std::vector<const analysis::Constant*>& constants) {
  393. assert(inst->opcode() == SpvOpFNegate || inst->opcode() == SpvOpSNegate);
  394. (void)constants;
  395. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  396. const analysis::Type* type =
  397. context->get_type_mgr()->GetType(inst->type_id());
  398. if (HasFloatingPoint(type) && !inst->IsFloatingPointFoldingAllowed())
  399. return false;
  400. Instruction* op_inst =
  401. context->get_def_use_mgr()->GetDef(inst->GetSingleWordInOperand(0u));
  402. if (HasFloatingPoint(type) && !op_inst->IsFloatingPointFoldingAllowed())
  403. return false;
  404. uint32_t width = ElementWidth(type);
  405. if (width != 32 && width != 64) return false;
  406. if (op_inst->opcode() == SpvOpFAdd || op_inst->opcode() == SpvOpFSub ||
  407. op_inst->opcode() == SpvOpIAdd || op_inst->opcode() == SpvOpISub) {
  408. std::vector<const analysis::Constant*> op_constants =
  409. const_mgr->GetOperandConstants(op_inst);
  410. if (op_constants[0] || op_constants[1]) {
  411. bool zero_is_variable = op_constants[0] == nullptr;
  412. bool is_add = (op_inst->opcode() == SpvOpFAdd) ||
  413. (op_inst->opcode() == SpvOpIAdd);
  414. bool swap_operands = !is_add || zero_is_variable;
  415. bool negate_const = is_add;
  416. const analysis::Constant* c = ConstInput(op_constants);
  417. uint32_t const_id = 0;
  418. if (negate_const) {
  419. const_id = NegateConstant(const_mgr, c);
  420. } else {
  421. const_id = zero_is_variable ? op_inst->GetSingleWordInOperand(1u)
  422. : op_inst->GetSingleWordInOperand(0u);
  423. }
  424. // Swap operands if necessary and make the instruction a subtraction.
  425. uint32_t op0 =
  426. zero_is_variable ? op_inst->GetSingleWordInOperand(0u) : const_id;
  427. uint32_t op1 =
  428. zero_is_variable ? const_id : op_inst->GetSingleWordInOperand(1u);
  429. if (swap_operands) std::swap(op0, op1);
  430. inst->SetOpcode(HasFloatingPoint(type) ? SpvOpFSub : SpvOpISub);
  431. inst->SetInOperands(
  432. {{SPV_OPERAND_TYPE_ID, {op0}}, {SPV_OPERAND_TYPE_ID, {op1}}});
  433. return true;
  434. }
  435. }
  436. return false;
  437. };
  438. }
  439. // Returns true if |c| has a zero element.
  440. bool HasZero(const analysis::Constant* c) {
  441. if (c->AsNullConstant()) {
  442. return true;
  443. }
  444. if (const analysis::VectorConstant* vec_const = c->AsVectorConstant()) {
  445. for (auto& comp : vec_const->GetComponents())
  446. if (HasZero(comp)) return true;
  447. } else {
  448. assert(c->AsScalarConstant());
  449. return c->AsScalarConstant()->IsZero();
  450. }
  451. return false;
  452. }
  453. // Performs |input1| |opcode| |input2| and returns the merged constant result
  454. // id. Returns 0 if the result is not a valid value. The input types must be
  455. // Float.
  456. uint32_t PerformFloatingPointOperation(analysis::ConstantManager* const_mgr,
  457. SpvOp opcode,
  458. const analysis::Constant* input1,
  459. const analysis::Constant* input2) {
  460. const analysis::Type* type = input1->type();
  461. assert(type->AsFloat());
  462. uint32_t width = type->AsFloat()->width();
  463. assert(width == 32 || width == 64);
  464. std::vector<uint32_t> words;
  465. #define FOLD_OP(op) \
  466. if (width == 64) { \
  467. utils::FloatProxy<double> val = \
  468. input1->GetDouble() op input2->GetDouble(); \
  469. double dval = val.getAsFloat(); \
  470. if (!IsValidResult(dval)) return 0; \
  471. words = val.GetWords(); \
  472. } else { \
  473. utils::FloatProxy<float> val = input1->GetFloat() op input2->GetFloat(); \
  474. float fval = val.getAsFloat(); \
  475. if (!IsValidResult(fval)) return 0; \
  476. words = val.GetWords(); \
  477. } static_assert(true, "require extra semicolon")
  478. switch (opcode) {
  479. case SpvOpFMul:
  480. FOLD_OP(*);
  481. break;
  482. case SpvOpFDiv:
  483. if (HasZero(input2)) return 0;
  484. FOLD_OP(/);
  485. break;
  486. case SpvOpFAdd:
  487. FOLD_OP(+);
  488. break;
  489. case SpvOpFSub:
  490. FOLD_OP(-);
  491. break;
  492. default:
  493. assert(false && "Unexpected operation");
  494. break;
  495. }
  496. #undef FOLD_OP
  497. const analysis::Constant* merged_const = const_mgr->GetConstant(type, words);
  498. return const_mgr->GetDefiningInstruction(merged_const)->result_id();
  499. }
  500. // Performs |input1| |opcode| |input2| and returns the merged constant result
  501. // id. Returns 0 if the result is not a valid value. The input types must be
  502. // Integers.
  503. uint32_t PerformIntegerOperation(analysis::ConstantManager* const_mgr,
  504. SpvOp opcode, const analysis::Constant* input1,
  505. const analysis::Constant* input2) {
  506. assert(input1->type()->AsInteger());
  507. const analysis::Integer* type = input1->type()->AsInteger();
  508. uint32_t width = type->AsInteger()->width();
  509. assert(width == 32 || width == 64);
  510. std::vector<uint32_t> words;
  511. #define FOLD_OP(op) \
  512. if (width == 64) { \
  513. if (type->IsSigned()) { \
  514. int64_t val = input1->GetS64() op input2->GetS64(); \
  515. words = ExtractInts(static_cast<uint64_t>(val)); \
  516. } else { \
  517. uint64_t val = input1->GetU64() op input2->GetU64(); \
  518. words = ExtractInts(val); \
  519. } \
  520. } else { \
  521. if (type->IsSigned()) { \
  522. int32_t val = input1->GetS32() op input2->GetS32(); \
  523. words.push_back(static_cast<uint32_t>(val)); \
  524. } else { \
  525. uint32_t val = input1->GetU32() op input2->GetU32(); \
  526. words.push_back(val); \
  527. } \
  528. } static_assert(true, "require extra semicalon")
  529. switch (opcode) {
  530. case SpvOpIMul:
  531. FOLD_OP(*);
  532. break;
  533. case SpvOpSDiv:
  534. case SpvOpUDiv:
  535. assert(false && "Should not merge integer division");
  536. break;
  537. case SpvOpIAdd:
  538. FOLD_OP(+);
  539. break;
  540. case SpvOpISub:
  541. FOLD_OP(-);
  542. break;
  543. default:
  544. assert(false && "Unexpected operation");
  545. break;
  546. }
  547. #undef FOLD_OP
  548. const analysis::Constant* merged_const = const_mgr->GetConstant(type, words);
  549. return const_mgr->GetDefiningInstruction(merged_const)->result_id();
  550. }
  551. // Performs |input1| |opcode| |input2| and returns the merged constant result
  552. // id. Returns 0 if the result is not a valid value. The input types must be
  553. // Integers, Floats or Vectors of such.
  554. uint32_t PerformOperation(analysis::ConstantManager* const_mgr, SpvOp opcode,
  555. const analysis::Constant* input1,
  556. const analysis::Constant* input2) {
  557. assert(input1 && input2);
  558. const analysis::Type* type = input1->type();
  559. std::vector<uint32_t> words;
  560. if (const analysis::Vector* vector_type = type->AsVector()) {
  561. const analysis::Type* ele_type = vector_type->element_type();
  562. for (uint32_t i = 0; i != vector_type->element_count(); ++i) {
  563. uint32_t id = 0;
  564. const analysis::Constant* input1_comp = nullptr;
  565. if (const analysis::VectorConstant* input1_vector =
  566. input1->AsVectorConstant()) {
  567. input1_comp = input1_vector->GetComponents()[i];
  568. } else {
  569. assert(input1->AsNullConstant());
  570. input1_comp = const_mgr->GetConstant(ele_type, {});
  571. }
  572. const analysis::Constant* input2_comp = nullptr;
  573. if (const analysis::VectorConstant* input2_vector =
  574. input2->AsVectorConstant()) {
  575. input2_comp = input2_vector->GetComponents()[i];
  576. } else {
  577. assert(input2->AsNullConstant());
  578. input2_comp = const_mgr->GetConstant(ele_type, {});
  579. }
  580. if (ele_type->AsFloat()) {
  581. id = PerformFloatingPointOperation(const_mgr, opcode, input1_comp,
  582. input2_comp);
  583. } else {
  584. assert(ele_type->AsInteger());
  585. id = PerformIntegerOperation(const_mgr, opcode, input1_comp,
  586. input2_comp);
  587. }
  588. if (id == 0) return 0;
  589. words.push_back(id);
  590. }
  591. const analysis::Constant* merged_const =
  592. const_mgr->GetConstant(type, words);
  593. return const_mgr->GetDefiningInstruction(merged_const)->result_id();
  594. } else if (type->AsFloat()) {
  595. return PerformFloatingPointOperation(const_mgr, opcode, input1, input2);
  596. } else {
  597. assert(type->AsInteger());
  598. return PerformIntegerOperation(const_mgr, opcode, input1, input2);
  599. }
  600. }
  601. // Merges consecutive multiplies where each contains one constant operand.
  602. // Cases:
  603. // 2 * (x * 2) = x * 4
  604. // 2 * (2 * x) = x * 4
  605. // (x * 2) * 2 = x * 4
  606. // (2 * x) * 2 = x * 4
  607. FoldingRule MergeMulMulArithmetic() {
  608. return [](IRContext* context, Instruction* inst,
  609. const std::vector<const analysis::Constant*>& constants) {
  610. assert(inst->opcode() == SpvOpFMul || inst->opcode() == SpvOpIMul);
  611. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  612. const analysis::Type* type =
  613. context->get_type_mgr()->GetType(inst->type_id());
  614. if (HasFloatingPoint(type) && !inst->IsFloatingPointFoldingAllowed())
  615. return false;
  616. uint32_t width = ElementWidth(type);
  617. if (width != 32 && width != 64) return false;
  618. // Determine the constant input and the variable input in |inst|.
  619. const analysis::Constant* const_input1 = ConstInput(constants);
  620. if (!const_input1) return false;
  621. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  622. if (HasFloatingPoint(type) && !other_inst->IsFloatingPointFoldingAllowed())
  623. return false;
  624. if (other_inst->opcode() == inst->opcode()) {
  625. std::vector<const analysis::Constant*> other_constants =
  626. const_mgr->GetOperandConstants(other_inst);
  627. const analysis::Constant* const_input2 = ConstInput(other_constants);
  628. if (!const_input2) return false;
  629. bool other_first_is_variable = other_constants[0] == nullptr;
  630. uint32_t merged_id = PerformOperation(const_mgr, inst->opcode(),
  631. const_input1, const_input2);
  632. if (merged_id == 0) return false;
  633. uint32_t non_const_id = other_first_is_variable
  634. ? other_inst->GetSingleWordInOperand(0u)
  635. : other_inst->GetSingleWordInOperand(1u);
  636. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {non_const_id}},
  637. {SPV_OPERAND_TYPE_ID, {merged_id}}});
  638. return true;
  639. }
  640. return false;
  641. };
  642. }
  643. // Merges divides into subsequent multiplies if each instruction contains one
  644. // constant operand. Does not support integer operations.
  645. // Cases:
  646. // 2 * (x / 2) = x * 1
  647. // 2 * (2 / x) = 4 / x
  648. // (x / 2) * 2 = x * 1
  649. // (2 / x) * 2 = 4 / x
  650. // (y / x) * x = y
  651. // x * (y / x) = y
  652. FoldingRule MergeMulDivArithmetic() {
  653. return [](IRContext* context, Instruction* inst,
  654. const std::vector<const analysis::Constant*>& constants) {
  655. assert(inst->opcode() == SpvOpFMul);
  656. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  657. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  658. const analysis::Type* type =
  659. context->get_type_mgr()->GetType(inst->type_id());
  660. if (!inst->IsFloatingPointFoldingAllowed()) return false;
  661. uint32_t width = ElementWidth(type);
  662. if (width != 32 && width != 64) return false;
  663. for (uint32_t i = 0; i < 2; i++) {
  664. uint32_t op_id = inst->GetSingleWordInOperand(i);
  665. Instruction* op_inst = def_use_mgr->GetDef(op_id);
  666. if (op_inst->opcode() == SpvOpFDiv) {
  667. if (op_inst->GetSingleWordInOperand(1) ==
  668. inst->GetSingleWordInOperand(1 - i)) {
  669. inst->SetOpcode(SpvOpCopyObject);
  670. inst->SetInOperands(
  671. {{SPV_OPERAND_TYPE_ID, {op_inst->GetSingleWordInOperand(0)}}});
  672. return true;
  673. }
  674. }
  675. }
  676. const analysis::Constant* const_input1 = ConstInput(constants);
  677. if (!const_input1) return false;
  678. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  679. if (!other_inst->IsFloatingPointFoldingAllowed()) return false;
  680. if (other_inst->opcode() == SpvOpFDiv) {
  681. std::vector<const analysis::Constant*> other_constants =
  682. const_mgr->GetOperandConstants(other_inst);
  683. const analysis::Constant* const_input2 = ConstInput(other_constants);
  684. if (!const_input2 || HasZero(const_input2)) return false;
  685. bool other_first_is_variable = other_constants[0] == nullptr;
  686. // If the variable value is the second operand of the divide, multiply
  687. // the constants together. Otherwise divide the constants.
  688. uint32_t merged_id = PerformOperation(
  689. const_mgr,
  690. other_first_is_variable ? other_inst->opcode() : inst->opcode(),
  691. const_input1, const_input2);
  692. if (merged_id == 0) return false;
  693. uint32_t non_const_id = other_first_is_variable
  694. ? other_inst->GetSingleWordInOperand(0u)
  695. : other_inst->GetSingleWordInOperand(1u);
  696. // If the variable value is on the second operand of the div, then this
  697. // operation is a div. Otherwise it should be a multiply.
  698. inst->SetOpcode(other_first_is_variable ? inst->opcode()
  699. : other_inst->opcode());
  700. if (other_first_is_variable) {
  701. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {non_const_id}},
  702. {SPV_OPERAND_TYPE_ID, {merged_id}}});
  703. } else {
  704. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {merged_id}},
  705. {SPV_OPERAND_TYPE_ID, {non_const_id}}});
  706. }
  707. return true;
  708. }
  709. return false;
  710. };
  711. }
  712. // Merges multiply of constant and negation.
  713. // Cases:
  714. // (-x) * 2 = x * -2
  715. // 2 * (-x) = x * -2
  716. FoldingRule MergeMulNegateArithmetic() {
  717. return [](IRContext* context, Instruction* inst,
  718. const std::vector<const analysis::Constant*>& constants) {
  719. assert(inst->opcode() == SpvOpFMul || inst->opcode() == SpvOpIMul);
  720. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  721. const analysis::Type* type =
  722. context->get_type_mgr()->GetType(inst->type_id());
  723. bool uses_float = HasFloatingPoint(type);
  724. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  725. uint32_t width = ElementWidth(type);
  726. if (width != 32 && width != 64) return false;
  727. const analysis::Constant* const_input1 = ConstInput(constants);
  728. if (!const_input1) return false;
  729. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  730. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  731. return false;
  732. if (other_inst->opcode() == SpvOpFNegate ||
  733. other_inst->opcode() == SpvOpSNegate) {
  734. uint32_t neg_id = NegateConstant(const_mgr, const_input1);
  735. inst->SetInOperands(
  736. {{SPV_OPERAND_TYPE_ID, {other_inst->GetSingleWordInOperand(0u)}},
  737. {SPV_OPERAND_TYPE_ID, {neg_id}}});
  738. return true;
  739. }
  740. return false;
  741. };
  742. }
  743. // Merges consecutive divides if each instruction contains one constant operand.
  744. // Does not support integer division.
  745. // Cases:
  746. // 2 / (x / 2) = 4 / x
  747. // 4 / (2 / x) = 2 * x
  748. // (4 / x) / 2 = 2 / x
  749. // (x / 2) / 2 = x / 4
  750. FoldingRule MergeDivDivArithmetic() {
  751. return [](IRContext* context, Instruction* inst,
  752. const std::vector<const analysis::Constant*>& constants) {
  753. assert(inst->opcode() == SpvOpFDiv);
  754. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  755. const analysis::Type* type =
  756. context->get_type_mgr()->GetType(inst->type_id());
  757. if (!inst->IsFloatingPointFoldingAllowed()) return false;
  758. uint32_t width = ElementWidth(type);
  759. if (width != 32 && width != 64) return false;
  760. const analysis::Constant* const_input1 = ConstInput(constants);
  761. if (!const_input1 || HasZero(const_input1)) return false;
  762. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  763. if (!other_inst->IsFloatingPointFoldingAllowed()) return false;
  764. bool first_is_variable = constants[0] == nullptr;
  765. if (other_inst->opcode() == inst->opcode()) {
  766. std::vector<const analysis::Constant*> other_constants =
  767. const_mgr->GetOperandConstants(other_inst);
  768. const analysis::Constant* const_input2 = ConstInput(other_constants);
  769. if (!const_input2 || HasZero(const_input2)) return false;
  770. bool other_first_is_variable = other_constants[0] == nullptr;
  771. SpvOp merge_op = inst->opcode();
  772. if (other_first_is_variable) {
  773. // Constants magnify.
  774. merge_op = SpvOpFMul;
  775. }
  776. // This is an x / (*) case. Swap the inputs. Doesn't harm multiply
  777. // because it is commutative.
  778. if (first_is_variable) std::swap(const_input1, const_input2);
  779. uint32_t merged_id =
  780. PerformOperation(const_mgr, merge_op, const_input1, const_input2);
  781. if (merged_id == 0) return false;
  782. uint32_t non_const_id = other_first_is_variable
  783. ? other_inst->GetSingleWordInOperand(0u)
  784. : other_inst->GetSingleWordInOperand(1u);
  785. SpvOp op = inst->opcode();
  786. if (!first_is_variable && !other_first_is_variable) {
  787. // Effectively div of 1/x, so change to multiply.
  788. op = SpvOpFMul;
  789. }
  790. uint32_t op1 = merged_id;
  791. uint32_t op2 = non_const_id;
  792. if (first_is_variable && other_first_is_variable) std::swap(op1, op2);
  793. inst->SetOpcode(op);
  794. inst->SetInOperands(
  795. {{SPV_OPERAND_TYPE_ID, {op1}}, {SPV_OPERAND_TYPE_ID, {op2}}});
  796. return true;
  797. }
  798. return false;
  799. };
  800. }
  801. // Fold multiplies succeeded by divides where each instruction contains a
  802. // constant operand. Does not support integer divide.
  803. // Cases:
  804. // 4 / (x * 2) = 2 / x
  805. // 4 / (2 * x) = 2 / x
  806. // (x * 4) / 2 = x * 2
  807. // (4 * x) / 2 = x * 2
  808. // (x * y) / x = y
  809. // (y * x) / x = y
  810. FoldingRule MergeDivMulArithmetic() {
  811. return [](IRContext* context, Instruction* inst,
  812. const std::vector<const analysis::Constant*>& constants) {
  813. assert(inst->opcode() == SpvOpFDiv);
  814. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  815. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  816. const analysis::Type* type =
  817. context->get_type_mgr()->GetType(inst->type_id());
  818. if (!inst->IsFloatingPointFoldingAllowed()) return false;
  819. uint32_t width = ElementWidth(type);
  820. if (width != 32 && width != 64) return false;
  821. uint32_t op_id = inst->GetSingleWordInOperand(0);
  822. Instruction* op_inst = def_use_mgr->GetDef(op_id);
  823. if (op_inst->opcode() == SpvOpFMul) {
  824. for (uint32_t i = 0; i < 2; i++) {
  825. if (op_inst->GetSingleWordInOperand(i) ==
  826. inst->GetSingleWordInOperand(1)) {
  827. inst->SetOpcode(SpvOpCopyObject);
  828. inst->SetInOperands({{SPV_OPERAND_TYPE_ID,
  829. {op_inst->GetSingleWordInOperand(1 - i)}}});
  830. return true;
  831. }
  832. }
  833. }
  834. const analysis::Constant* const_input1 = ConstInput(constants);
  835. if (!const_input1 || HasZero(const_input1)) return false;
  836. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  837. if (!other_inst->IsFloatingPointFoldingAllowed()) return false;
  838. bool first_is_variable = constants[0] == nullptr;
  839. if (other_inst->opcode() == SpvOpFMul) {
  840. std::vector<const analysis::Constant*> other_constants =
  841. const_mgr->GetOperandConstants(other_inst);
  842. const analysis::Constant* const_input2 = ConstInput(other_constants);
  843. if (!const_input2) return false;
  844. bool other_first_is_variable = other_constants[0] == nullptr;
  845. // This is an x / (*) case. Swap the inputs.
  846. if (first_is_variable) std::swap(const_input1, const_input2);
  847. uint32_t merged_id = PerformOperation(const_mgr, inst->opcode(),
  848. const_input1, const_input2);
  849. if (merged_id == 0) return false;
  850. uint32_t non_const_id = other_first_is_variable
  851. ? other_inst->GetSingleWordInOperand(0u)
  852. : other_inst->GetSingleWordInOperand(1u);
  853. uint32_t op1 = merged_id;
  854. uint32_t op2 = non_const_id;
  855. if (first_is_variable) std::swap(op1, op2);
  856. // Convert to multiply
  857. if (first_is_variable) inst->SetOpcode(other_inst->opcode());
  858. inst->SetInOperands(
  859. {{SPV_OPERAND_TYPE_ID, {op1}}, {SPV_OPERAND_TYPE_ID, {op2}}});
  860. return true;
  861. }
  862. return false;
  863. };
  864. }
  865. // Fold divides of a constant and a negation.
  866. // Cases:
  867. // (-x) / 2 = x / -2
  868. // 2 / (-x) = -2 / x
  869. FoldingRule MergeDivNegateArithmetic() {
  870. return [](IRContext* context, Instruction* inst,
  871. const std::vector<const analysis::Constant*>& constants) {
  872. assert(inst->opcode() == SpvOpFDiv || inst->opcode() == SpvOpSDiv);
  873. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  874. const analysis::Type* type =
  875. context->get_type_mgr()->GetType(inst->type_id());
  876. bool uses_float = HasFloatingPoint(type);
  877. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  878. uint32_t width = ElementWidth(type);
  879. if (width != 32 && width != 64) return false;
  880. const analysis::Constant* const_input1 = ConstInput(constants);
  881. if (!const_input1) return false;
  882. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  883. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  884. return false;
  885. bool first_is_variable = constants[0] == nullptr;
  886. if (other_inst->opcode() == SpvOpFNegate ||
  887. other_inst->opcode() == SpvOpSNegate) {
  888. uint32_t neg_id = NegateConstant(const_mgr, const_input1);
  889. if (first_is_variable) {
  890. inst->SetInOperands(
  891. {{SPV_OPERAND_TYPE_ID, {other_inst->GetSingleWordInOperand(0u)}},
  892. {SPV_OPERAND_TYPE_ID, {neg_id}}});
  893. } else {
  894. inst->SetInOperands(
  895. {{SPV_OPERAND_TYPE_ID, {neg_id}},
  896. {SPV_OPERAND_TYPE_ID, {other_inst->GetSingleWordInOperand(0u)}}});
  897. }
  898. return true;
  899. }
  900. return false;
  901. };
  902. }
  903. // Folds addition of a constant and a negation.
  904. // Cases:
  905. // (-x) + 2 = 2 - x
  906. // 2 + (-x) = 2 - x
  907. FoldingRule MergeAddNegateArithmetic() {
  908. return [](IRContext* context, Instruction* inst,
  909. const std::vector<const analysis::Constant*>& constants) {
  910. assert(inst->opcode() == SpvOpFAdd || inst->opcode() == SpvOpIAdd);
  911. const analysis::Type* type =
  912. context->get_type_mgr()->GetType(inst->type_id());
  913. bool uses_float = HasFloatingPoint(type);
  914. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  915. const analysis::Constant* const_input1 = ConstInput(constants);
  916. if (!const_input1) return false;
  917. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  918. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  919. return false;
  920. if (other_inst->opcode() == SpvOpSNegate ||
  921. other_inst->opcode() == SpvOpFNegate) {
  922. inst->SetOpcode(HasFloatingPoint(type) ? SpvOpFSub : SpvOpISub);
  923. uint32_t const_id = constants[0] ? inst->GetSingleWordInOperand(0u)
  924. : inst->GetSingleWordInOperand(1u);
  925. inst->SetInOperands(
  926. {{SPV_OPERAND_TYPE_ID, {const_id}},
  927. {SPV_OPERAND_TYPE_ID, {other_inst->GetSingleWordInOperand(0u)}}});
  928. return true;
  929. }
  930. return false;
  931. };
  932. }
  933. // Folds subtraction of a constant and a negation.
  934. // Cases:
  935. // (-x) - 2 = -2 - x
  936. // 2 - (-x) = x + 2
  937. FoldingRule MergeSubNegateArithmetic() {
  938. return [](IRContext* context, Instruction* inst,
  939. const std::vector<const analysis::Constant*>& constants) {
  940. assert(inst->opcode() == SpvOpFSub || inst->opcode() == SpvOpISub);
  941. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  942. const analysis::Type* type =
  943. context->get_type_mgr()->GetType(inst->type_id());
  944. bool uses_float = HasFloatingPoint(type);
  945. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  946. uint32_t width = ElementWidth(type);
  947. if (width != 32 && width != 64) return false;
  948. const analysis::Constant* const_input1 = ConstInput(constants);
  949. if (!const_input1) return false;
  950. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  951. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  952. return false;
  953. if (other_inst->opcode() == SpvOpSNegate ||
  954. other_inst->opcode() == SpvOpFNegate) {
  955. uint32_t op1 = 0;
  956. uint32_t op2 = 0;
  957. SpvOp opcode = inst->opcode();
  958. if (constants[0] != nullptr) {
  959. op1 = other_inst->GetSingleWordInOperand(0u);
  960. op2 = inst->GetSingleWordInOperand(0u);
  961. opcode = HasFloatingPoint(type) ? SpvOpFAdd : SpvOpIAdd;
  962. } else {
  963. op1 = NegateConstant(const_mgr, const_input1);
  964. op2 = other_inst->GetSingleWordInOperand(0u);
  965. }
  966. inst->SetOpcode(opcode);
  967. inst->SetInOperands(
  968. {{SPV_OPERAND_TYPE_ID, {op1}}, {SPV_OPERAND_TYPE_ID, {op2}}});
  969. return true;
  970. }
  971. return false;
  972. };
  973. }
  974. // Folds addition of an addition where each operation has a constant operand.
  975. // Cases:
  976. // (x + 2) + 2 = x + 4
  977. // (2 + x) + 2 = x + 4
  978. // 2 + (x + 2) = x + 4
  979. // 2 + (2 + x) = x + 4
  980. FoldingRule MergeAddAddArithmetic() {
  981. return [](IRContext* context, Instruction* inst,
  982. const std::vector<const analysis::Constant*>& constants) {
  983. assert(inst->opcode() == SpvOpFAdd || inst->opcode() == SpvOpIAdd);
  984. const analysis::Type* type =
  985. context->get_type_mgr()->GetType(inst->type_id());
  986. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  987. bool uses_float = HasFloatingPoint(type);
  988. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  989. uint32_t width = ElementWidth(type);
  990. if (width != 32 && width != 64) return false;
  991. const analysis::Constant* const_input1 = ConstInput(constants);
  992. if (!const_input1) return false;
  993. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  994. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  995. return false;
  996. if (other_inst->opcode() == SpvOpFAdd ||
  997. other_inst->opcode() == SpvOpIAdd) {
  998. std::vector<const analysis::Constant*> other_constants =
  999. const_mgr->GetOperandConstants(other_inst);
  1000. const analysis::Constant* const_input2 = ConstInput(other_constants);
  1001. if (!const_input2) return false;
  1002. Instruction* non_const_input =
  1003. NonConstInput(context, other_constants[0], other_inst);
  1004. uint32_t merged_id = PerformOperation(const_mgr, inst->opcode(),
  1005. const_input1, const_input2);
  1006. if (merged_id == 0) return false;
  1007. inst->SetInOperands(
  1008. {{SPV_OPERAND_TYPE_ID, {non_const_input->result_id()}},
  1009. {SPV_OPERAND_TYPE_ID, {merged_id}}});
  1010. return true;
  1011. }
  1012. return false;
  1013. };
  1014. }
  1015. // Folds addition of a subtraction where each operation has a constant operand.
  1016. // Cases:
  1017. // (x - 2) + 2 = x + 0
  1018. // (2 - x) + 2 = 4 - x
  1019. // 2 + (x - 2) = x + 0
  1020. // 2 + (2 - x) = 4 - x
  1021. FoldingRule MergeAddSubArithmetic() {
  1022. return [](IRContext* context, Instruction* inst,
  1023. const std::vector<const analysis::Constant*>& constants) {
  1024. assert(inst->opcode() == SpvOpFAdd || inst->opcode() == SpvOpIAdd);
  1025. const analysis::Type* type =
  1026. context->get_type_mgr()->GetType(inst->type_id());
  1027. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  1028. bool uses_float = HasFloatingPoint(type);
  1029. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  1030. uint32_t width = ElementWidth(type);
  1031. if (width != 32 && width != 64) return false;
  1032. const analysis::Constant* const_input1 = ConstInput(constants);
  1033. if (!const_input1) return false;
  1034. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  1035. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  1036. return false;
  1037. if (other_inst->opcode() == SpvOpFSub ||
  1038. other_inst->opcode() == SpvOpISub) {
  1039. std::vector<const analysis::Constant*> other_constants =
  1040. const_mgr->GetOperandConstants(other_inst);
  1041. const analysis::Constant* const_input2 = ConstInput(other_constants);
  1042. if (!const_input2) return false;
  1043. bool first_is_variable = other_constants[0] == nullptr;
  1044. SpvOp op = inst->opcode();
  1045. uint32_t op1 = 0;
  1046. uint32_t op2 = 0;
  1047. if (first_is_variable) {
  1048. // Subtract constants. Non-constant operand is first.
  1049. op1 = other_inst->GetSingleWordInOperand(0u);
  1050. op2 = PerformOperation(const_mgr, other_inst->opcode(), const_input1,
  1051. const_input2);
  1052. } else {
  1053. // Add constants. Constant operand is first. Change the opcode.
  1054. op1 = PerformOperation(const_mgr, inst->opcode(), const_input1,
  1055. const_input2);
  1056. op2 = other_inst->GetSingleWordInOperand(1u);
  1057. op = other_inst->opcode();
  1058. }
  1059. if (op1 == 0 || op2 == 0) return false;
  1060. inst->SetOpcode(op);
  1061. inst->SetInOperands(
  1062. {{SPV_OPERAND_TYPE_ID, {op1}}, {SPV_OPERAND_TYPE_ID, {op2}}});
  1063. return true;
  1064. }
  1065. return false;
  1066. };
  1067. }
  1068. // Folds subtraction of an addition where each operand has a constant operand.
  1069. // Cases:
  1070. // (x + 2) - 2 = x + 0
  1071. // (2 + x) - 2 = x + 0
  1072. // 2 - (x + 2) = 0 - x
  1073. // 2 - (2 + x) = 0 - x
  1074. FoldingRule MergeSubAddArithmetic() {
  1075. return [](IRContext* context, Instruction* inst,
  1076. const std::vector<const analysis::Constant*>& constants) {
  1077. assert(inst->opcode() == SpvOpFSub || inst->opcode() == SpvOpISub);
  1078. const analysis::Type* type =
  1079. context->get_type_mgr()->GetType(inst->type_id());
  1080. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  1081. bool uses_float = HasFloatingPoint(type);
  1082. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  1083. uint32_t width = ElementWidth(type);
  1084. if (width != 32 && width != 64) return false;
  1085. const analysis::Constant* const_input1 = ConstInput(constants);
  1086. if (!const_input1) return false;
  1087. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  1088. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  1089. return false;
  1090. if (other_inst->opcode() == SpvOpFAdd ||
  1091. other_inst->opcode() == SpvOpIAdd) {
  1092. std::vector<const analysis::Constant*> other_constants =
  1093. const_mgr->GetOperandConstants(other_inst);
  1094. const analysis::Constant* const_input2 = ConstInput(other_constants);
  1095. if (!const_input2) return false;
  1096. Instruction* non_const_input =
  1097. NonConstInput(context, other_constants[0], other_inst);
  1098. // If the first operand of the sub is not a constant, swap the constants
  1099. // so the subtraction has the correct operands.
  1100. if (constants[0] == nullptr) std::swap(const_input1, const_input2);
  1101. // Subtract the constants.
  1102. uint32_t merged_id = PerformOperation(const_mgr, inst->opcode(),
  1103. const_input1, const_input2);
  1104. SpvOp op = inst->opcode();
  1105. uint32_t op1 = 0;
  1106. uint32_t op2 = 0;
  1107. if (constants[0] == nullptr) {
  1108. // Non-constant operand is first. Change the opcode.
  1109. op1 = non_const_input->result_id();
  1110. op2 = merged_id;
  1111. op = other_inst->opcode();
  1112. } else {
  1113. // Constant operand is first.
  1114. op1 = merged_id;
  1115. op2 = non_const_input->result_id();
  1116. }
  1117. if (op1 == 0 || op2 == 0) return false;
  1118. inst->SetOpcode(op);
  1119. inst->SetInOperands(
  1120. {{SPV_OPERAND_TYPE_ID, {op1}}, {SPV_OPERAND_TYPE_ID, {op2}}});
  1121. return true;
  1122. }
  1123. return false;
  1124. };
  1125. }
  1126. // Folds subtraction of a subtraction where each operand has a constant operand.
  1127. // Cases:
  1128. // (x - 2) - 2 = x - 4
  1129. // (2 - x) - 2 = 0 - x
  1130. // 2 - (x - 2) = 4 - x
  1131. // 2 - (2 - x) = x + 0
  1132. FoldingRule MergeSubSubArithmetic() {
  1133. return [](IRContext* context, Instruction* inst,
  1134. const std::vector<const analysis::Constant*>& constants) {
  1135. assert(inst->opcode() == SpvOpFSub || inst->opcode() == SpvOpISub);
  1136. const analysis::Type* type =
  1137. context->get_type_mgr()->GetType(inst->type_id());
  1138. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  1139. bool uses_float = HasFloatingPoint(type);
  1140. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  1141. uint32_t width = ElementWidth(type);
  1142. if (width != 32 && width != 64) return false;
  1143. const analysis::Constant* const_input1 = ConstInput(constants);
  1144. if (!const_input1) return false;
  1145. Instruction* other_inst = NonConstInput(context, constants[0], inst);
  1146. if (uses_float && !other_inst->IsFloatingPointFoldingAllowed())
  1147. return false;
  1148. if (other_inst->opcode() == SpvOpFSub ||
  1149. other_inst->opcode() == SpvOpISub) {
  1150. std::vector<const analysis::Constant*> other_constants =
  1151. const_mgr->GetOperandConstants(other_inst);
  1152. const analysis::Constant* const_input2 = ConstInput(other_constants);
  1153. if (!const_input2) return false;
  1154. Instruction* non_const_input =
  1155. NonConstInput(context, other_constants[0], other_inst);
  1156. // Merge the constants.
  1157. uint32_t merged_id = 0;
  1158. SpvOp merge_op = inst->opcode();
  1159. if (other_constants[0] == nullptr) {
  1160. merge_op = uses_float ? SpvOpFAdd : SpvOpIAdd;
  1161. } else if (constants[0] == nullptr) {
  1162. std::swap(const_input1, const_input2);
  1163. }
  1164. merged_id =
  1165. PerformOperation(const_mgr, merge_op, const_input1, const_input2);
  1166. if (merged_id == 0) return false;
  1167. SpvOp op = inst->opcode();
  1168. if (constants[0] != nullptr && other_constants[0] != nullptr) {
  1169. // Change the operation.
  1170. op = uses_float ? SpvOpFAdd : SpvOpIAdd;
  1171. }
  1172. uint32_t op1 = 0;
  1173. uint32_t op2 = 0;
  1174. if ((constants[0] == nullptr) ^ (other_constants[0] == nullptr)) {
  1175. op1 = merged_id;
  1176. op2 = non_const_input->result_id();
  1177. } else {
  1178. op1 = non_const_input->result_id();
  1179. op2 = merged_id;
  1180. }
  1181. inst->SetOpcode(op);
  1182. inst->SetInOperands(
  1183. {{SPV_OPERAND_TYPE_ID, {op1}}, {SPV_OPERAND_TYPE_ID, {op2}}});
  1184. return true;
  1185. }
  1186. return false;
  1187. };
  1188. }
  1189. // Helper function for MergeGenericAddSubArithmetic. If |addend| and
  1190. // subtrahend of |sub| is the same, merge to copy of minuend of |sub|.
  1191. bool MergeGenericAddendSub(uint32_t addend, uint32_t sub, Instruction* inst) {
  1192. IRContext* context = inst->context();
  1193. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1194. Instruction* sub_inst = def_use_mgr->GetDef(sub);
  1195. if (sub_inst->opcode() != SpvOpFSub && sub_inst->opcode() != SpvOpISub)
  1196. return false;
  1197. if (sub_inst->opcode() == SpvOpFSub &&
  1198. !sub_inst->IsFloatingPointFoldingAllowed())
  1199. return false;
  1200. if (addend != sub_inst->GetSingleWordInOperand(1)) return false;
  1201. inst->SetOpcode(SpvOpCopyObject);
  1202. inst->SetInOperands(
  1203. {{SPV_OPERAND_TYPE_ID, {sub_inst->GetSingleWordInOperand(0)}}});
  1204. context->UpdateDefUse(inst);
  1205. return true;
  1206. }
  1207. // Folds addition of a subtraction where the subtrahend is equal to the
  1208. // other addend. Return a copy of the minuend. Accepts generic (const and
  1209. // non-const) operands.
  1210. // Cases:
  1211. // (a - b) + b = a
  1212. // b + (a - b) = a
  1213. FoldingRule MergeGenericAddSubArithmetic() {
  1214. return [](IRContext* context, Instruction* inst,
  1215. const std::vector<const analysis::Constant*>&) {
  1216. assert(inst->opcode() == SpvOpFAdd || inst->opcode() == SpvOpIAdd);
  1217. const analysis::Type* type =
  1218. context->get_type_mgr()->GetType(inst->type_id());
  1219. bool uses_float = HasFloatingPoint(type);
  1220. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  1221. uint32_t width = ElementWidth(type);
  1222. if (width != 32 && width != 64) return false;
  1223. uint32_t add_op0 = inst->GetSingleWordInOperand(0);
  1224. uint32_t add_op1 = inst->GetSingleWordInOperand(1);
  1225. if (MergeGenericAddendSub(add_op0, add_op1, inst)) return true;
  1226. return MergeGenericAddendSub(add_op1, add_op0, inst);
  1227. };
  1228. }
  1229. // Helper function for FactorAddMuls. If |factor0_0| is the same as |factor1_0|,
  1230. // generate |factor0_0| * (|factor0_1| + |factor1_1|).
  1231. bool FactorAddMulsOpnds(uint32_t factor0_0, uint32_t factor0_1,
  1232. uint32_t factor1_0, uint32_t factor1_1,
  1233. Instruction* inst) {
  1234. IRContext* context = inst->context();
  1235. if (factor0_0 != factor1_0) return false;
  1236. InstructionBuilder ir_builder(
  1237. context, inst,
  1238. IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
  1239. Instruction* new_add_inst = ir_builder.AddBinaryOp(
  1240. inst->type_id(), inst->opcode(), factor0_1, factor1_1);
  1241. inst->SetOpcode(inst->opcode() == SpvOpFAdd ? SpvOpFMul : SpvOpIMul);
  1242. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {factor0_0}},
  1243. {SPV_OPERAND_TYPE_ID, {new_add_inst->result_id()}}});
  1244. context->UpdateDefUse(inst);
  1245. return true;
  1246. }
  1247. // Perform the following factoring identity, handling all operand order
  1248. // combinations: (a * b) + (a * c) = a * (b + c)
  1249. FoldingRule FactorAddMuls() {
  1250. return [](IRContext* context, Instruction* inst,
  1251. const std::vector<const analysis::Constant*>&) {
  1252. assert(inst->opcode() == SpvOpFAdd || inst->opcode() == SpvOpIAdd);
  1253. const analysis::Type* type =
  1254. context->get_type_mgr()->GetType(inst->type_id());
  1255. bool uses_float = HasFloatingPoint(type);
  1256. if (uses_float && !inst->IsFloatingPointFoldingAllowed()) return false;
  1257. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1258. uint32_t add_op0 = inst->GetSingleWordInOperand(0);
  1259. Instruction* add_op0_inst = def_use_mgr->GetDef(add_op0);
  1260. if (add_op0_inst->opcode() != SpvOpFMul &&
  1261. add_op0_inst->opcode() != SpvOpIMul)
  1262. return false;
  1263. uint32_t add_op1 = inst->GetSingleWordInOperand(1);
  1264. Instruction* add_op1_inst = def_use_mgr->GetDef(add_op1);
  1265. if (add_op1_inst->opcode() != SpvOpFMul &&
  1266. add_op1_inst->opcode() != SpvOpIMul)
  1267. return false;
  1268. // Only perform this optimization if both of the muls only have one use.
  1269. // Otherwise this is a deoptimization in size and performance.
  1270. if (def_use_mgr->NumUses(add_op0_inst) > 1) return false;
  1271. if (def_use_mgr->NumUses(add_op1_inst) > 1) return false;
  1272. if (add_op0_inst->opcode() == SpvOpFMul &&
  1273. (!add_op0_inst->IsFloatingPointFoldingAllowed() ||
  1274. !add_op1_inst->IsFloatingPointFoldingAllowed()))
  1275. return false;
  1276. for (int i = 0; i < 2; i++) {
  1277. for (int j = 0; j < 2; j++) {
  1278. // Check if operand i in add_op0_inst matches operand j in add_op1_inst.
  1279. if (FactorAddMulsOpnds(add_op0_inst->GetSingleWordInOperand(i),
  1280. add_op0_inst->GetSingleWordInOperand(1 - i),
  1281. add_op1_inst->GetSingleWordInOperand(j),
  1282. add_op1_inst->GetSingleWordInOperand(1 - j),
  1283. inst))
  1284. return true;
  1285. }
  1286. }
  1287. return false;
  1288. };
  1289. }
  1290. FoldingRule IntMultipleBy1() {
  1291. return [](IRContext*, Instruction* inst,
  1292. const std::vector<const analysis::Constant*>& constants) {
  1293. assert(inst->opcode() == SpvOpIMul && "Wrong opcode. Should be OpIMul.");
  1294. for (uint32_t i = 0; i < 2; i++) {
  1295. if (constants[i] == nullptr) {
  1296. continue;
  1297. }
  1298. const analysis::IntConstant* int_constant = constants[i]->AsIntConstant();
  1299. if (int_constant) {
  1300. uint32_t width = ElementWidth(int_constant->type());
  1301. if (width != 32 && width != 64) return false;
  1302. bool is_one = (width == 32) ? int_constant->GetU32BitValue() == 1u
  1303. : int_constant->GetU64BitValue() == 1ull;
  1304. if (is_one) {
  1305. inst->SetOpcode(SpvOpCopyObject);
  1306. inst->SetInOperands(
  1307. {{SPV_OPERAND_TYPE_ID, {inst->GetSingleWordInOperand(1 - i)}}});
  1308. return true;
  1309. }
  1310. }
  1311. }
  1312. return false;
  1313. };
  1314. }
  1315. FoldingRule CompositeConstructFeedingExtract() {
  1316. return [](IRContext* context, Instruction* inst,
  1317. const std::vector<const analysis::Constant*>&) {
  1318. // If the input to an OpCompositeExtract is an OpCompositeConstruct,
  1319. // then we can simply use the appropriate element in the construction.
  1320. assert(inst->opcode() == SpvOpCompositeExtract &&
  1321. "Wrong opcode. Should be OpCompositeExtract.");
  1322. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1323. analysis::TypeManager* type_mgr = context->get_type_mgr();
  1324. // If there are no index operands, then this rule cannot do anything.
  1325. if (inst->NumInOperands() <= 1) {
  1326. return false;
  1327. }
  1328. uint32_t cid = inst->GetSingleWordInOperand(kExtractCompositeIdInIdx);
  1329. Instruction* cinst = def_use_mgr->GetDef(cid);
  1330. if (cinst->opcode() != SpvOpCompositeConstruct) {
  1331. return false;
  1332. }
  1333. std::vector<Operand> operands;
  1334. analysis::Type* composite_type = type_mgr->GetType(cinst->type_id());
  1335. if (composite_type->AsVector() == nullptr) {
  1336. // Get the element being extracted from the OpCompositeConstruct
  1337. // Since it is not a vector, it is simple to extract the single element.
  1338. uint32_t element_index = inst->GetSingleWordInOperand(1);
  1339. uint32_t element_id = cinst->GetSingleWordInOperand(element_index);
  1340. operands.push_back({SPV_OPERAND_TYPE_ID, {element_id}});
  1341. // Add the remaining indices for extraction.
  1342. for (uint32_t i = 2; i < inst->NumInOperands(); ++i) {
  1343. operands.push_back({SPV_OPERAND_TYPE_LITERAL_INTEGER,
  1344. {inst->GetSingleWordInOperand(i)}});
  1345. }
  1346. } else {
  1347. // With vectors we have to handle the case where it is concatenating
  1348. // vectors.
  1349. assert(inst->NumInOperands() == 2 &&
  1350. "Expecting a vector of scalar values.");
  1351. uint32_t element_index = inst->GetSingleWordInOperand(1);
  1352. for (uint32_t construct_index = 0;
  1353. construct_index < cinst->NumInOperands(); ++construct_index) {
  1354. uint32_t element_id = cinst->GetSingleWordInOperand(construct_index);
  1355. Instruction* element_def = def_use_mgr->GetDef(element_id);
  1356. analysis::Vector* element_type =
  1357. type_mgr->GetType(element_def->type_id())->AsVector();
  1358. if (element_type) {
  1359. uint32_t vector_size = element_type->element_count();
  1360. if (vector_size <= element_index) {
  1361. // The element we want comes after this vector.
  1362. element_index -= vector_size;
  1363. } else {
  1364. // We want an element of this vector.
  1365. operands.push_back({SPV_OPERAND_TYPE_ID, {element_id}});
  1366. operands.push_back(
  1367. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {element_index}});
  1368. break;
  1369. }
  1370. } else {
  1371. if (element_index == 0) {
  1372. // This is a scalar, and we this is the element we are extracting.
  1373. operands.push_back({SPV_OPERAND_TYPE_ID, {element_id}});
  1374. break;
  1375. } else {
  1376. // Skip over this scalar value.
  1377. --element_index;
  1378. }
  1379. }
  1380. }
  1381. }
  1382. // If there were no extra indices, then we have the final object. No need
  1383. // to extract even more.
  1384. if (operands.size() == 1) {
  1385. inst->SetOpcode(SpvOpCopyObject);
  1386. }
  1387. inst->SetInOperands(std::move(operands));
  1388. return true;
  1389. };
  1390. }
  1391. // If the OpCompositeConstruct is simply putting back together elements that
  1392. // where extracted from the same source, we can simply reuse the source.
  1393. //
  1394. // This is a common code pattern because of the way that scalar replacement
  1395. // works.
  1396. bool CompositeExtractFeedingConstruct(
  1397. IRContext* context, Instruction* inst,
  1398. const std::vector<const analysis::Constant*>&) {
  1399. assert(inst->opcode() == SpvOpCompositeConstruct &&
  1400. "Wrong opcode. Should be OpCompositeConstruct.");
  1401. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1402. uint32_t original_id = 0;
  1403. if (inst->NumInOperands() == 0) {
  1404. // The struct being constructed has no members.
  1405. return false;
  1406. }
  1407. // Check each element to make sure they are:
  1408. // - extractions
  1409. // - extracting the same position they are inserting
  1410. // - all extract from the same id.
  1411. for (uint32_t i = 0; i < inst->NumInOperands(); ++i) {
  1412. const uint32_t element_id = inst->GetSingleWordInOperand(i);
  1413. Instruction* element_inst = def_use_mgr->GetDef(element_id);
  1414. if (element_inst->opcode() != SpvOpCompositeExtract) {
  1415. return false;
  1416. }
  1417. if (element_inst->NumInOperands() != 2) {
  1418. return false;
  1419. }
  1420. if (element_inst->GetSingleWordInOperand(1) != i) {
  1421. return false;
  1422. }
  1423. if (i == 0) {
  1424. original_id =
  1425. element_inst->GetSingleWordInOperand(kExtractCompositeIdInIdx);
  1426. } else if (original_id !=
  1427. element_inst->GetSingleWordInOperand(kExtractCompositeIdInIdx)) {
  1428. return false;
  1429. }
  1430. }
  1431. // The last check it to see that the object being extracted from is the
  1432. // correct type.
  1433. Instruction* original_inst = def_use_mgr->GetDef(original_id);
  1434. if (original_inst->type_id() != inst->type_id()) {
  1435. return false;
  1436. }
  1437. // Simplify by using the original object.
  1438. inst->SetOpcode(SpvOpCopyObject);
  1439. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {original_id}}});
  1440. return true;
  1441. }
  1442. FoldingRule InsertFeedingExtract() {
  1443. return [](IRContext* context, Instruction* inst,
  1444. const std::vector<const analysis::Constant*>&) {
  1445. assert(inst->opcode() == SpvOpCompositeExtract &&
  1446. "Wrong opcode. Should be OpCompositeExtract.");
  1447. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1448. uint32_t cid = inst->GetSingleWordInOperand(kExtractCompositeIdInIdx);
  1449. Instruction* cinst = def_use_mgr->GetDef(cid);
  1450. if (cinst->opcode() != SpvOpCompositeInsert) {
  1451. return false;
  1452. }
  1453. // Find the first position where the list of insert and extract indicies
  1454. // differ, if at all.
  1455. uint32_t i;
  1456. for (i = 1; i < inst->NumInOperands(); ++i) {
  1457. if (i + 1 >= cinst->NumInOperands()) {
  1458. break;
  1459. }
  1460. if (inst->GetSingleWordInOperand(i) !=
  1461. cinst->GetSingleWordInOperand(i + 1)) {
  1462. break;
  1463. }
  1464. }
  1465. // We are extracting the element that was inserted.
  1466. if (i == inst->NumInOperands() && i + 1 == cinst->NumInOperands()) {
  1467. inst->SetOpcode(SpvOpCopyObject);
  1468. inst->SetInOperands(
  1469. {{SPV_OPERAND_TYPE_ID,
  1470. {cinst->GetSingleWordInOperand(kInsertObjectIdInIdx)}}});
  1471. return true;
  1472. }
  1473. // Extracting the value that was inserted along with values for the base
  1474. // composite. Cannot do anything.
  1475. if (i == inst->NumInOperands()) {
  1476. return false;
  1477. }
  1478. // Extracting an element of the value that was inserted. Extract from
  1479. // that value directly.
  1480. if (i + 1 == cinst->NumInOperands()) {
  1481. std::vector<Operand> operands;
  1482. operands.push_back(
  1483. {SPV_OPERAND_TYPE_ID,
  1484. {cinst->GetSingleWordInOperand(kInsertObjectIdInIdx)}});
  1485. for (; i < inst->NumInOperands(); ++i) {
  1486. operands.push_back({SPV_OPERAND_TYPE_LITERAL_INTEGER,
  1487. {inst->GetSingleWordInOperand(i)}});
  1488. }
  1489. inst->SetInOperands(std::move(operands));
  1490. return true;
  1491. }
  1492. // Extracting a value that is disjoint from the element being inserted.
  1493. // Rewrite the extract to use the composite input to the insert.
  1494. std::vector<Operand> operands;
  1495. operands.push_back(
  1496. {SPV_OPERAND_TYPE_ID,
  1497. {cinst->GetSingleWordInOperand(kInsertCompositeIdInIdx)}});
  1498. for (i = 1; i < inst->NumInOperands(); ++i) {
  1499. operands.push_back({SPV_OPERAND_TYPE_LITERAL_INTEGER,
  1500. {inst->GetSingleWordInOperand(i)}});
  1501. }
  1502. inst->SetInOperands(std::move(operands));
  1503. return true;
  1504. };
  1505. }
  1506. // When a VectorShuffle is feeding an Extract, we can extract from one of the
  1507. // operands of the VectorShuffle. We just need to adjust the index in the
  1508. // extract instruction.
  1509. FoldingRule VectorShuffleFeedingExtract() {
  1510. return [](IRContext* context, Instruction* inst,
  1511. const std::vector<const analysis::Constant*>&) {
  1512. assert(inst->opcode() == SpvOpCompositeExtract &&
  1513. "Wrong opcode. Should be OpCompositeExtract.");
  1514. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1515. analysis::TypeManager* type_mgr = context->get_type_mgr();
  1516. uint32_t cid = inst->GetSingleWordInOperand(kExtractCompositeIdInIdx);
  1517. Instruction* cinst = def_use_mgr->GetDef(cid);
  1518. if (cinst->opcode() != SpvOpVectorShuffle) {
  1519. return false;
  1520. }
  1521. // Find the size of the first vector operand of the VectorShuffle
  1522. Instruction* first_input =
  1523. def_use_mgr->GetDef(cinst->GetSingleWordInOperand(0));
  1524. analysis::Type* first_input_type =
  1525. type_mgr->GetType(first_input->type_id());
  1526. assert(first_input_type->AsVector() &&
  1527. "Input to vector shuffle should be vectors.");
  1528. uint32_t first_input_size = first_input_type->AsVector()->element_count();
  1529. // Get index of the element the vector shuffle is placing in the position
  1530. // being extracted.
  1531. uint32_t new_index =
  1532. cinst->GetSingleWordInOperand(2 + inst->GetSingleWordInOperand(1));
  1533. // Extracting an undefined value so fold this extract into an undef.
  1534. const uint32_t undef_literal_value = 0xffffffff;
  1535. if (new_index == undef_literal_value) {
  1536. inst->SetOpcode(SpvOpUndef);
  1537. inst->SetInOperands({});
  1538. return true;
  1539. }
  1540. // Get the id of the of the vector the elemtent comes from, and update the
  1541. // index if needed.
  1542. uint32_t new_vector = 0;
  1543. if (new_index < first_input_size) {
  1544. new_vector = cinst->GetSingleWordInOperand(0);
  1545. } else {
  1546. new_vector = cinst->GetSingleWordInOperand(1);
  1547. new_index -= first_input_size;
  1548. }
  1549. // Update the extract instruction.
  1550. inst->SetInOperand(kExtractCompositeIdInIdx, {new_vector});
  1551. inst->SetInOperand(1, {new_index});
  1552. return true;
  1553. };
  1554. }
  1555. // When an FMix with is feeding an Extract that extracts an element whose
  1556. // corresponding |a| in the FMix is 0 or 1, we can extract from one of the
  1557. // operands of the FMix.
  1558. FoldingRule FMixFeedingExtract() {
  1559. return [](IRContext* context, Instruction* inst,
  1560. const std::vector<const analysis::Constant*>&) {
  1561. assert(inst->opcode() == SpvOpCompositeExtract &&
  1562. "Wrong opcode. Should be OpCompositeExtract.");
  1563. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1564. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  1565. uint32_t composite_id =
  1566. inst->GetSingleWordInOperand(kExtractCompositeIdInIdx);
  1567. Instruction* composite_inst = def_use_mgr->GetDef(composite_id);
  1568. if (composite_inst->opcode() != SpvOpExtInst) {
  1569. return false;
  1570. }
  1571. uint32_t inst_set_id =
  1572. context->get_feature_mgr()->GetExtInstImportId_GLSLstd450();
  1573. if (composite_inst->GetSingleWordInOperand(kExtInstSetIdInIdx) !=
  1574. inst_set_id ||
  1575. composite_inst->GetSingleWordInOperand(kExtInstInstructionInIdx) !=
  1576. GLSLstd450FMix) {
  1577. return false;
  1578. }
  1579. // Get the |a| for the FMix instruction.
  1580. uint32_t a_id = composite_inst->GetSingleWordInOperand(kFMixAIdInIdx);
  1581. std::unique_ptr<Instruction> a(inst->Clone(context));
  1582. a->SetInOperand(kExtractCompositeIdInIdx, {a_id});
  1583. context->get_instruction_folder().FoldInstruction(a.get());
  1584. if (a->opcode() != SpvOpCopyObject) {
  1585. return false;
  1586. }
  1587. const analysis::Constant* a_const =
  1588. const_mgr->FindDeclaredConstant(a->GetSingleWordInOperand(0));
  1589. if (!a_const) {
  1590. return false;
  1591. }
  1592. bool use_x = false;
  1593. assert(a_const->type()->AsFloat());
  1594. double element_value = a_const->GetValueAsDouble();
  1595. if (element_value == 0.0) {
  1596. use_x = true;
  1597. } else if (element_value == 1.0) {
  1598. use_x = false;
  1599. } else {
  1600. return false;
  1601. }
  1602. // Get the id of the of the vector the element comes from.
  1603. uint32_t new_vector = 0;
  1604. if (use_x) {
  1605. new_vector = composite_inst->GetSingleWordInOperand(kFMixXIdInIdx);
  1606. } else {
  1607. new_vector = composite_inst->GetSingleWordInOperand(kFMixYIdInIdx);
  1608. }
  1609. // Update the extract instruction.
  1610. inst->SetInOperand(kExtractCompositeIdInIdx, {new_vector});
  1611. return true;
  1612. };
  1613. }
  1614. FoldingRule RedundantPhi() {
  1615. // An OpPhi instruction where all values are the same or the result of the phi
  1616. // itself, can be replaced by the value itself.
  1617. return [](IRContext*, Instruction* inst,
  1618. const std::vector<const analysis::Constant*>&) {
  1619. assert(inst->opcode() == SpvOpPhi && "Wrong opcode. Should be OpPhi.");
  1620. uint32_t incoming_value = 0;
  1621. for (uint32_t i = 0; i < inst->NumInOperands(); i += 2) {
  1622. uint32_t op_id = inst->GetSingleWordInOperand(i);
  1623. if (op_id == inst->result_id()) {
  1624. continue;
  1625. }
  1626. if (incoming_value == 0) {
  1627. incoming_value = op_id;
  1628. } else if (op_id != incoming_value) {
  1629. // Found two possible value. Can't simplify.
  1630. return false;
  1631. }
  1632. }
  1633. if (incoming_value == 0) {
  1634. // Code looks invalid. Don't do anything.
  1635. return false;
  1636. }
  1637. // We have a single incoming value. Simplify using that value.
  1638. inst->SetOpcode(SpvOpCopyObject);
  1639. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {incoming_value}}});
  1640. return true;
  1641. };
  1642. }
  1643. FoldingRule BitCastScalarOrVector() {
  1644. return [](IRContext* context, Instruction* inst,
  1645. const std::vector<const analysis::Constant*>& constants) {
  1646. assert(inst->opcode() == SpvOpBitcast && constants.size() == 1);
  1647. if (constants[0] == nullptr) return false;
  1648. const analysis::Type* type =
  1649. context->get_type_mgr()->GetType(inst->type_id());
  1650. if (HasFloatingPoint(type) && !inst->IsFloatingPointFoldingAllowed())
  1651. return false;
  1652. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  1653. std::vector<uint32_t> words =
  1654. GetWordsFromNumericScalarOrVectorConstant(const_mgr, constants[0]);
  1655. if (words.size() == 0) return false;
  1656. const analysis::Constant* bitcasted_constant =
  1657. ConvertWordsToNumericScalarOrVectorConstant(const_mgr, words, type);
  1658. if (!bitcasted_constant) return false;
  1659. auto new_feeder_id =
  1660. const_mgr->GetDefiningInstruction(bitcasted_constant, inst->type_id())
  1661. ->result_id();
  1662. inst->SetOpcode(SpvOpCopyObject);
  1663. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {new_feeder_id}}});
  1664. return true;
  1665. };
  1666. }
  1667. FoldingRule RedundantSelect() {
  1668. // An OpSelect instruction where both values are the same or the condition is
  1669. // constant can be replaced by one of the values
  1670. return [](IRContext*, Instruction* inst,
  1671. const std::vector<const analysis::Constant*>& constants) {
  1672. assert(inst->opcode() == SpvOpSelect &&
  1673. "Wrong opcode. Should be OpSelect.");
  1674. assert(inst->NumInOperands() == 3);
  1675. assert(constants.size() == 3);
  1676. uint32_t true_id = inst->GetSingleWordInOperand(1);
  1677. uint32_t false_id = inst->GetSingleWordInOperand(2);
  1678. if (true_id == false_id) {
  1679. // Both results are the same, condition doesn't matter
  1680. inst->SetOpcode(SpvOpCopyObject);
  1681. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {true_id}}});
  1682. return true;
  1683. } else if (constants[0]) {
  1684. const analysis::Type* type = constants[0]->type();
  1685. if (type->AsBool()) {
  1686. // Scalar constant value, select the corresponding value.
  1687. inst->SetOpcode(SpvOpCopyObject);
  1688. if (constants[0]->AsNullConstant() ||
  1689. !constants[0]->AsBoolConstant()->value()) {
  1690. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {false_id}}});
  1691. } else {
  1692. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {true_id}}});
  1693. }
  1694. return true;
  1695. } else {
  1696. assert(type->AsVector());
  1697. if (constants[0]->AsNullConstant()) {
  1698. // All values come from false id.
  1699. inst->SetOpcode(SpvOpCopyObject);
  1700. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {false_id}}});
  1701. return true;
  1702. } else {
  1703. // Convert to a vector shuffle.
  1704. std::vector<Operand> ops;
  1705. ops.push_back({SPV_OPERAND_TYPE_ID, {true_id}});
  1706. ops.push_back({SPV_OPERAND_TYPE_ID, {false_id}});
  1707. const analysis::VectorConstant* vector_const =
  1708. constants[0]->AsVectorConstant();
  1709. uint32_t size =
  1710. static_cast<uint32_t>(vector_const->GetComponents().size());
  1711. for (uint32_t i = 0; i != size; ++i) {
  1712. const analysis::Constant* component =
  1713. vector_const->GetComponents()[i];
  1714. if (component->AsNullConstant() ||
  1715. !component->AsBoolConstant()->value()) {
  1716. // Selecting from the false vector which is the second input
  1717. // vector to the shuffle. Offset the index by |size|.
  1718. ops.push_back({SPV_OPERAND_TYPE_LITERAL_INTEGER, {i + size}});
  1719. } else {
  1720. // Selecting from true vector which is the first input vector to
  1721. // the shuffle.
  1722. ops.push_back({SPV_OPERAND_TYPE_LITERAL_INTEGER, {i}});
  1723. }
  1724. }
  1725. inst->SetOpcode(SpvOpVectorShuffle);
  1726. inst->SetInOperands(std::move(ops));
  1727. return true;
  1728. }
  1729. }
  1730. }
  1731. return false;
  1732. };
  1733. }
  1734. enum class FloatConstantKind { Unknown, Zero, One };
  1735. FloatConstantKind getFloatConstantKind(const analysis::Constant* constant) {
  1736. if (constant == nullptr) {
  1737. return FloatConstantKind::Unknown;
  1738. }
  1739. assert(HasFloatingPoint(constant->type()) && "Unexpected constant type");
  1740. if (constant->AsNullConstant()) {
  1741. return FloatConstantKind::Zero;
  1742. } else if (const analysis::VectorConstant* vc =
  1743. constant->AsVectorConstant()) {
  1744. const std::vector<const analysis::Constant*>& components =
  1745. vc->GetComponents();
  1746. assert(!components.empty());
  1747. FloatConstantKind kind = getFloatConstantKind(components[0]);
  1748. for (size_t i = 1; i < components.size(); ++i) {
  1749. if (getFloatConstantKind(components[i]) != kind) {
  1750. return FloatConstantKind::Unknown;
  1751. }
  1752. }
  1753. return kind;
  1754. } else if (const analysis::FloatConstant* fc = constant->AsFloatConstant()) {
  1755. if (fc->IsZero()) return FloatConstantKind::Zero;
  1756. uint32_t width = fc->type()->AsFloat()->width();
  1757. if (width != 32 && width != 64) return FloatConstantKind::Unknown;
  1758. double value = (width == 64) ? fc->GetDoubleValue() : fc->GetFloatValue();
  1759. if (value == 0.0) {
  1760. return FloatConstantKind::Zero;
  1761. } else if (value == 1.0) {
  1762. return FloatConstantKind::One;
  1763. } else {
  1764. return FloatConstantKind::Unknown;
  1765. }
  1766. } else {
  1767. return FloatConstantKind::Unknown;
  1768. }
  1769. }
  1770. FoldingRule RedundantFAdd() {
  1771. return [](IRContext*, Instruction* inst,
  1772. const std::vector<const analysis::Constant*>& constants) {
  1773. assert(inst->opcode() == SpvOpFAdd && "Wrong opcode. Should be OpFAdd.");
  1774. assert(constants.size() == 2);
  1775. if (!inst->IsFloatingPointFoldingAllowed()) {
  1776. return false;
  1777. }
  1778. FloatConstantKind kind0 = getFloatConstantKind(constants[0]);
  1779. FloatConstantKind kind1 = getFloatConstantKind(constants[1]);
  1780. if (kind0 == FloatConstantKind::Zero || kind1 == FloatConstantKind::Zero) {
  1781. inst->SetOpcode(SpvOpCopyObject);
  1782. inst->SetInOperands({{SPV_OPERAND_TYPE_ID,
  1783. {inst->GetSingleWordInOperand(
  1784. kind0 == FloatConstantKind::Zero ? 1 : 0)}}});
  1785. return true;
  1786. }
  1787. return false;
  1788. };
  1789. }
  1790. FoldingRule RedundantFSub() {
  1791. return [](IRContext*, Instruction* inst,
  1792. const std::vector<const analysis::Constant*>& constants) {
  1793. assert(inst->opcode() == SpvOpFSub && "Wrong opcode. Should be OpFSub.");
  1794. assert(constants.size() == 2);
  1795. if (!inst->IsFloatingPointFoldingAllowed()) {
  1796. return false;
  1797. }
  1798. FloatConstantKind kind0 = getFloatConstantKind(constants[0]);
  1799. FloatConstantKind kind1 = getFloatConstantKind(constants[1]);
  1800. if (kind0 == FloatConstantKind::Zero) {
  1801. inst->SetOpcode(SpvOpFNegate);
  1802. inst->SetInOperands(
  1803. {{SPV_OPERAND_TYPE_ID, {inst->GetSingleWordInOperand(1)}}});
  1804. return true;
  1805. }
  1806. if (kind1 == FloatConstantKind::Zero) {
  1807. inst->SetOpcode(SpvOpCopyObject);
  1808. inst->SetInOperands(
  1809. {{SPV_OPERAND_TYPE_ID, {inst->GetSingleWordInOperand(0)}}});
  1810. return true;
  1811. }
  1812. return false;
  1813. };
  1814. }
  1815. FoldingRule RedundantFMul() {
  1816. return [](IRContext*, Instruction* inst,
  1817. const std::vector<const analysis::Constant*>& constants) {
  1818. assert(inst->opcode() == SpvOpFMul && "Wrong opcode. Should be OpFMul.");
  1819. assert(constants.size() == 2);
  1820. if (!inst->IsFloatingPointFoldingAllowed()) {
  1821. return false;
  1822. }
  1823. FloatConstantKind kind0 = getFloatConstantKind(constants[0]);
  1824. FloatConstantKind kind1 = getFloatConstantKind(constants[1]);
  1825. if (kind0 == FloatConstantKind::Zero || kind1 == FloatConstantKind::Zero) {
  1826. inst->SetOpcode(SpvOpCopyObject);
  1827. inst->SetInOperands({{SPV_OPERAND_TYPE_ID,
  1828. {inst->GetSingleWordInOperand(
  1829. kind0 == FloatConstantKind::Zero ? 0 : 1)}}});
  1830. return true;
  1831. }
  1832. if (kind0 == FloatConstantKind::One || kind1 == FloatConstantKind::One) {
  1833. inst->SetOpcode(SpvOpCopyObject);
  1834. inst->SetInOperands({{SPV_OPERAND_TYPE_ID,
  1835. {inst->GetSingleWordInOperand(
  1836. kind0 == FloatConstantKind::One ? 1 : 0)}}});
  1837. return true;
  1838. }
  1839. return false;
  1840. };
  1841. }
  1842. FoldingRule RedundantFDiv() {
  1843. return [](IRContext*, Instruction* inst,
  1844. const std::vector<const analysis::Constant*>& constants) {
  1845. assert(inst->opcode() == SpvOpFDiv && "Wrong opcode. Should be OpFDiv.");
  1846. assert(constants.size() == 2);
  1847. if (!inst->IsFloatingPointFoldingAllowed()) {
  1848. return false;
  1849. }
  1850. FloatConstantKind kind0 = getFloatConstantKind(constants[0]);
  1851. FloatConstantKind kind1 = getFloatConstantKind(constants[1]);
  1852. if (kind0 == FloatConstantKind::Zero) {
  1853. inst->SetOpcode(SpvOpCopyObject);
  1854. inst->SetInOperands(
  1855. {{SPV_OPERAND_TYPE_ID, {inst->GetSingleWordInOperand(0)}}});
  1856. return true;
  1857. }
  1858. if (kind1 == FloatConstantKind::One) {
  1859. inst->SetOpcode(SpvOpCopyObject);
  1860. inst->SetInOperands(
  1861. {{SPV_OPERAND_TYPE_ID, {inst->GetSingleWordInOperand(0)}}});
  1862. return true;
  1863. }
  1864. return false;
  1865. };
  1866. }
  1867. FoldingRule RedundantFMix() {
  1868. return [](IRContext* context, Instruction* inst,
  1869. const std::vector<const analysis::Constant*>& constants) {
  1870. assert(inst->opcode() == SpvOpExtInst &&
  1871. "Wrong opcode. Should be OpExtInst.");
  1872. if (!inst->IsFloatingPointFoldingAllowed()) {
  1873. return false;
  1874. }
  1875. uint32_t instSetId =
  1876. context->get_feature_mgr()->GetExtInstImportId_GLSLstd450();
  1877. if (inst->GetSingleWordInOperand(kExtInstSetIdInIdx) == instSetId &&
  1878. inst->GetSingleWordInOperand(kExtInstInstructionInIdx) ==
  1879. GLSLstd450FMix) {
  1880. assert(constants.size() == 5);
  1881. FloatConstantKind kind4 = getFloatConstantKind(constants[4]);
  1882. if (kind4 == FloatConstantKind::Zero || kind4 == FloatConstantKind::One) {
  1883. inst->SetOpcode(SpvOpCopyObject);
  1884. inst->SetInOperands(
  1885. {{SPV_OPERAND_TYPE_ID,
  1886. {inst->GetSingleWordInOperand(kind4 == FloatConstantKind::Zero
  1887. ? kFMixXIdInIdx
  1888. : kFMixYIdInIdx)}}});
  1889. return true;
  1890. }
  1891. }
  1892. return false;
  1893. };
  1894. }
  1895. // This rule handles addition of zero for integers.
  1896. FoldingRule RedundantIAdd() {
  1897. return [](IRContext* context, Instruction* inst,
  1898. const std::vector<const analysis::Constant*>& constants) {
  1899. assert(inst->opcode() == SpvOpIAdd && "Wrong opcode. Should be OpIAdd.");
  1900. uint32_t operand = std::numeric_limits<uint32_t>::max();
  1901. const analysis::Type* operand_type = nullptr;
  1902. if (constants[0] && constants[0]->IsZero()) {
  1903. operand = inst->GetSingleWordInOperand(1);
  1904. operand_type = constants[0]->type();
  1905. } else if (constants[1] && constants[1]->IsZero()) {
  1906. operand = inst->GetSingleWordInOperand(0);
  1907. operand_type = constants[1]->type();
  1908. }
  1909. if (operand != std::numeric_limits<uint32_t>::max()) {
  1910. const analysis::Type* inst_type =
  1911. context->get_type_mgr()->GetType(inst->type_id());
  1912. if (inst_type->IsSame(operand_type)) {
  1913. inst->SetOpcode(SpvOpCopyObject);
  1914. } else {
  1915. inst->SetOpcode(SpvOpBitcast);
  1916. }
  1917. inst->SetInOperands({{SPV_OPERAND_TYPE_ID, {operand}}});
  1918. return true;
  1919. }
  1920. return false;
  1921. };
  1922. }
  1923. // This rule look for a dot with a constant vector containing a single 1 and
  1924. // the rest 0s. This is the same as doing an extract.
  1925. FoldingRule DotProductDoingExtract() {
  1926. return [](IRContext* context, Instruction* inst,
  1927. const std::vector<const analysis::Constant*>& constants) {
  1928. assert(inst->opcode() == SpvOpDot && "Wrong opcode. Should be OpDot.");
  1929. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  1930. if (!inst->IsFloatingPointFoldingAllowed()) {
  1931. return false;
  1932. }
  1933. for (int i = 0; i < 2; ++i) {
  1934. if (!constants[i]) {
  1935. continue;
  1936. }
  1937. const analysis::Vector* vector_type = constants[i]->type()->AsVector();
  1938. assert(vector_type && "Inputs to OpDot must be vectors.");
  1939. const analysis::Float* element_type =
  1940. vector_type->element_type()->AsFloat();
  1941. assert(element_type && "Inputs to OpDot must be vectors of floats.");
  1942. uint32_t element_width = element_type->width();
  1943. if (element_width != 32 && element_width != 64) {
  1944. return false;
  1945. }
  1946. std::vector<const analysis::Constant*> components;
  1947. components = constants[i]->GetVectorComponents(const_mgr);
  1948. const uint32_t kNotFound = std::numeric_limits<uint32_t>::max();
  1949. uint32_t component_with_one = kNotFound;
  1950. bool all_others_zero = true;
  1951. for (uint32_t j = 0; j < components.size(); ++j) {
  1952. const analysis::Constant* element = components[j];
  1953. double value =
  1954. (element_width == 32 ? element->GetFloat() : element->GetDouble());
  1955. if (value == 0.0) {
  1956. continue;
  1957. } else if (value == 1.0) {
  1958. if (component_with_one == kNotFound) {
  1959. component_with_one = j;
  1960. } else {
  1961. component_with_one = kNotFound;
  1962. break;
  1963. }
  1964. } else {
  1965. all_others_zero = false;
  1966. break;
  1967. }
  1968. }
  1969. if (!all_others_zero || component_with_one == kNotFound) {
  1970. continue;
  1971. }
  1972. std::vector<Operand> operands;
  1973. operands.push_back(
  1974. {SPV_OPERAND_TYPE_ID, {inst->GetSingleWordInOperand(1u - i)}});
  1975. operands.push_back(
  1976. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {component_with_one}});
  1977. inst->SetOpcode(SpvOpCompositeExtract);
  1978. inst->SetInOperands(std::move(operands));
  1979. return true;
  1980. }
  1981. return false;
  1982. };
  1983. }
  1984. // If we are storing an undef, then we can remove the store.
  1985. //
  1986. // TODO: We can do something similar for OpImageWrite, but checking for volatile
  1987. // is complicated. Waiting to see if it is needed.
  1988. FoldingRule StoringUndef() {
  1989. return [](IRContext* context, Instruction* inst,
  1990. const std::vector<const analysis::Constant*>&) {
  1991. assert(inst->opcode() == SpvOpStore && "Wrong opcode. Should be OpStore.");
  1992. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  1993. // If this is a volatile store, the store cannot be removed.
  1994. if (inst->NumInOperands() == 3) {
  1995. if (inst->GetSingleWordInOperand(2) & SpvMemoryAccessVolatileMask) {
  1996. return false;
  1997. }
  1998. }
  1999. uint32_t object_id = inst->GetSingleWordInOperand(kStoreObjectInIdx);
  2000. Instruction* object_inst = def_use_mgr->GetDef(object_id);
  2001. if (object_inst->opcode() == SpvOpUndef) {
  2002. inst->ToNop();
  2003. return true;
  2004. }
  2005. return false;
  2006. };
  2007. }
  2008. FoldingRule VectorShuffleFeedingShuffle() {
  2009. return [](IRContext* context, Instruction* inst,
  2010. const std::vector<const analysis::Constant*>&) {
  2011. assert(inst->opcode() == SpvOpVectorShuffle &&
  2012. "Wrong opcode. Should be OpVectorShuffle.");
  2013. analysis::DefUseManager* def_use_mgr = context->get_def_use_mgr();
  2014. analysis::TypeManager* type_mgr = context->get_type_mgr();
  2015. Instruction* feeding_shuffle_inst =
  2016. def_use_mgr->GetDef(inst->GetSingleWordInOperand(0));
  2017. analysis::Vector* op0_type =
  2018. type_mgr->GetType(feeding_shuffle_inst->type_id())->AsVector();
  2019. uint32_t op0_length = op0_type->element_count();
  2020. bool feeder_is_op0 = true;
  2021. if (feeding_shuffle_inst->opcode() != SpvOpVectorShuffle) {
  2022. feeding_shuffle_inst =
  2023. def_use_mgr->GetDef(inst->GetSingleWordInOperand(1));
  2024. feeder_is_op0 = false;
  2025. }
  2026. if (feeding_shuffle_inst->opcode() != SpvOpVectorShuffle) {
  2027. return false;
  2028. }
  2029. Instruction* feeder2 =
  2030. def_use_mgr->GetDef(feeding_shuffle_inst->GetSingleWordInOperand(0));
  2031. analysis::Vector* feeder_op0_type =
  2032. type_mgr->GetType(feeder2->type_id())->AsVector();
  2033. uint32_t feeder_op0_length = feeder_op0_type->element_count();
  2034. uint32_t new_feeder_id = 0;
  2035. std::vector<Operand> new_operands;
  2036. new_operands.resize(
  2037. 2, {SPV_OPERAND_TYPE_ID, {0}}); // Place holders for vector operands.
  2038. const uint32_t undef_literal = 0xffffffff;
  2039. for (uint32_t op = 2; op < inst->NumInOperands(); ++op) {
  2040. uint32_t component_index = inst->GetSingleWordInOperand(op);
  2041. // Do not interpret the undefined value literal as coming from operand 1.
  2042. if (component_index != undef_literal &&
  2043. feeder_is_op0 == (component_index < op0_length)) {
  2044. // This component comes from the feeding_shuffle_inst. Update
  2045. // |component_index| to be the index into the operand of the feeder.
  2046. // Adjust component_index to get the index into the operands of the
  2047. // feeding_shuffle_inst.
  2048. if (component_index >= op0_length) {
  2049. component_index -= op0_length;
  2050. }
  2051. component_index =
  2052. feeding_shuffle_inst->GetSingleWordInOperand(component_index + 2);
  2053. // Check if we are using a component from the first or second operand of
  2054. // the feeding instruction.
  2055. if (component_index < feeder_op0_length) {
  2056. if (new_feeder_id == 0) {
  2057. // First time through, save the id of the operand the element comes
  2058. // from.
  2059. new_feeder_id = feeding_shuffle_inst->GetSingleWordInOperand(0);
  2060. } else if (new_feeder_id !=
  2061. feeding_shuffle_inst->GetSingleWordInOperand(0)) {
  2062. // We need both elements of the feeding_shuffle_inst, so we cannot
  2063. // fold.
  2064. return false;
  2065. }
  2066. } else {
  2067. if (new_feeder_id == 0) {
  2068. // First time through, save the id of the operand the element comes
  2069. // from.
  2070. new_feeder_id = feeding_shuffle_inst->GetSingleWordInOperand(1);
  2071. } else if (new_feeder_id !=
  2072. feeding_shuffle_inst->GetSingleWordInOperand(1)) {
  2073. // We need both elements of the feeding_shuffle_inst, so we cannot
  2074. // fold.
  2075. return false;
  2076. }
  2077. component_index -= feeder_op0_length;
  2078. }
  2079. if (!feeder_is_op0) {
  2080. component_index += op0_length;
  2081. }
  2082. }
  2083. new_operands.push_back(
  2084. {SPV_OPERAND_TYPE_LITERAL_INTEGER, {component_index}});
  2085. }
  2086. if (new_feeder_id == 0) {
  2087. analysis::ConstantManager* const_mgr = context->get_constant_mgr();
  2088. const analysis::Type* type =
  2089. type_mgr->GetType(feeding_shuffle_inst->type_id());
  2090. const analysis::Constant* null_const = const_mgr->GetConstant(type, {});
  2091. new_feeder_id =
  2092. const_mgr->GetDefiningInstruction(null_const, 0)->result_id();
  2093. }
  2094. if (feeder_is_op0) {
  2095. // If the size of the first vector operand changed then the indices
  2096. // referring to the second operand need to be adjusted.
  2097. Instruction* new_feeder_inst = def_use_mgr->GetDef(new_feeder_id);
  2098. analysis::Type* new_feeder_type =
  2099. type_mgr->GetType(new_feeder_inst->type_id());
  2100. uint32_t new_op0_size = new_feeder_type->AsVector()->element_count();
  2101. int32_t adjustment = op0_length - new_op0_size;
  2102. if (adjustment != 0) {
  2103. for (uint32_t i = 2; i < new_operands.size(); i++) {
  2104. if (inst->GetSingleWordInOperand(i) >= op0_length) {
  2105. new_operands[i].words[0] -= adjustment;
  2106. }
  2107. }
  2108. }
  2109. new_operands[0].words[0] = new_feeder_id;
  2110. new_operands[1] = inst->GetInOperand(1);
  2111. } else {
  2112. new_operands[1].words[0] = new_feeder_id;
  2113. new_operands[0] = inst->GetInOperand(0);
  2114. }
  2115. inst->SetInOperands(std::move(new_operands));
  2116. return true;
  2117. };
  2118. }
  2119. // Removes duplicate ids from the interface list of an OpEntryPoint
  2120. // instruction.
  2121. FoldingRule RemoveRedundantOperands() {
  2122. return [](IRContext*, Instruction* inst,
  2123. const std::vector<const analysis::Constant*>&) {
  2124. assert(inst->opcode() == SpvOpEntryPoint &&
  2125. "Wrong opcode. Should be OpEntryPoint.");
  2126. bool has_redundant_operand = false;
  2127. std::unordered_set<uint32_t> seen_operands;
  2128. std::vector<Operand> new_operands;
  2129. new_operands.emplace_back(inst->GetOperand(0));
  2130. new_operands.emplace_back(inst->GetOperand(1));
  2131. new_operands.emplace_back(inst->GetOperand(2));
  2132. for (uint32_t i = 3; i < inst->NumOperands(); ++i) {
  2133. if (seen_operands.insert(inst->GetSingleWordOperand(i)).second) {
  2134. new_operands.emplace_back(inst->GetOperand(i));
  2135. } else {
  2136. has_redundant_operand = true;
  2137. }
  2138. }
  2139. if (!has_redundant_operand) {
  2140. return false;
  2141. }
  2142. inst->SetInOperands(std::move(new_operands));
  2143. return true;
  2144. };
  2145. }
  2146. // If an image instruction's operand is a constant, updates the image operand
  2147. // flag from Offset to ConstOffset.
  2148. FoldingRule UpdateImageOperands() {
  2149. return [](IRContext*, Instruction* inst,
  2150. const std::vector<const analysis::Constant*>& constants) {
  2151. const auto opcode = inst->opcode();
  2152. (void)opcode;
  2153. assert((opcode == SpvOpImageSampleImplicitLod ||
  2154. opcode == SpvOpImageSampleExplicitLod ||
  2155. opcode == SpvOpImageSampleDrefImplicitLod ||
  2156. opcode == SpvOpImageSampleDrefExplicitLod ||
  2157. opcode == SpvOpImageSampleProjImplicitLod ||
  2158. opcode == SpvOpImageSampleProjExplicitLod ||
  2159. opcode == SpvOpImageSampleProjDrefImplicitLod ||
  2160. opcode == SpvOpImageSampleProjDrefExplicitLod ||
  2161. opcode == SpvOpImageFetch || opcode == SpvOpImageGather ||
  2162. opcode == SpvOpImageDrefGather || opcode == SpvOpImageRead ||
  2163. opcode == SpvOpImageWrite ||
  2164. opcode == SpvOpImageSparseSampleImplicitLod ||
  2165. opcode == SpvOpImageSparseSampleExplicitLod ||
  2166. opcode == SpvOpImageSparseSampleDrefImplicitLod ||
  2167. opcode == SpvOpImageSparseSampleDrefExplicitLod ||
  2168. opcode == SpvOpImageSparseSampleProjImplicitLod ||
  2169. opcode == SpvOpImageSparseSampleProjExplicitLod ||
  2170. opcode == SpvOpImageSparseSampleProjDrefImplicitLod ||
  2171. opcode == SpvOpImageSparseSampleProjDrefExplicitLod ||
  2172. opcode == SpvOpImageSparseFetch ||
  2173. opcode == SpvOpImageSparseGather ||
  2174. opcode == SpvOpImageSparseDrefGather ||
  2175. opcode == SpvOpImageSparseRead) &&
  2176. "Wrong opcode. Should be an image instruction.");
  2177. int32_t operand_index = ImageOperandsMaskInOperandIndex(inst);
  2178. if (operand_index >= 0) {
  2179. auto image_operands = inst->GetSingleWordInOperand(operand_index);
  2180. if (image_operands & SpvImageOperandsOffsetMask) {
  2181. uint32_t offset_operand_index = operand_index + 1;
  2182. if (image_operands & SpvImageOperandsBiasMask) offset_operand_index++;
  2183. if (image_operands & SpvImageOperandsLodMask) offset_operand_index++;
  2184. if (image_operands & SpvImageOperandsGradMask)
  2185. offset_operand_index += 2;
  2186. assert(((image_operands & SpvImageOperandsConstOffsetMask) == 0) &&
  2187. "Offset and ConstOffset may not be used together");
  2188. if (offset_operand_index < inst->NumOperands()) {
  2189. if (constants[offset_operand_index]) {
  2190. image_operands = image_operands | SpvImageOperandsConstOffsetMask;
  2191. image_operands = image_operands & ~SpvImageOperandsOffsetMask;
  2192. inst->SetInOperand(operand_index, {image_operands});
  2193. return true;
  2194. }
  2195. }
  2196. }
  2197. }
  2198. return false;
  2199. };
  2200. }
  2201. } // namespace
  2202. void FoldingRules::AddFoldingRules() {
  2203. // Add all folding rules to the list for the opcodes to which they apply.
  2204. // Note that the order in which rules are added to the list matters. If a rule
  2205. // applies to the instruction, the rest of the rules will not be attempted.
  2206. // Take that into consideration.
  2207. rules_[SpvOpBitcast].push_back(BitCastScalarOrVector());
  2208. rules_[SpvOpCompositeConstruct].push_back(CompositeExtractFeedingConstruct);
  2209. rules_[SpvOpCompositeExtract].push_back(InsertFeedingExtract());
  2210. rules_[SpvOpCompositeExtract].push_back(CompositeConstructFeedingExtract());
  2211. rules_[SpvOpCompositeExtract].push_back(VectorShuffleFeedingExtract());
  2212. rules_[SpvOpCompositeExtract].push_back(FMixFeedingExtract());
  2213. rules_[SpvOpDot].push_back(DotProductDoingExtract());
  2214. rules_[SpvOpEntryPoint].push_back(RemoveRedundantOperands());
  2215. rules_[SpvOpFAdd].push_back(RedundantFAdd());
  2216. rules_[SpvOpFAdd].push_back(MergeAddNegateArithmetic());
  2217. rules_[SpvOpFAdd].push_back(MergeAddAddArithmetic());
  2218. rules_[SpvOpFAdd].push_back(MergeAddSubArithmetic());
  2219. rules_[SpvOpFAdd].push_back(MergeGenericAddSubArithmetic());
  2220. rules_[SpvOpFAdd].push_back(FactorAddMuls());
  2221. rules_[SpvOpFDiv].push_back(RedundantFDiv());
  2222. rules_[SpvOpFDiv].push_back(ReciprocalFDiv());
  2223. rules_[SpvOpFDiv].push_back(MergeDivDivArithmetic());
  2224. rules_[SpvOpFDiv].push_back(MergeDivMulArithmetic());
  2225. rules_[SpvOpFDiv].push_back(MergeDivNegateArithmetic());
  2226. rules_[SpvOpFMul].push_back(RedundantFMul());
  2227. rules_[SpvOpFMul].push_back(MergeMulMulArithmetic());
  2228. rules_[SpvOpFMul].push_back(MergeMulDivArithmetic());
  2229. rules_[SpvOpFMul].push_back(MergeMulNegateArithmetic());
  2230. rules_[SpvOpFNegate].push_back(MergeNegateArithmetic());
  2231. rules_[SpvOpFNegate].push_back(MergeNegateAddSubArithmetic());
  2232. rules_[SpvOpFNegate].push_back(MergeNegateMulDivArithmetic());
  2233. rules_[SpvOpFSub].push_back(RedundantFSub());
  2234. rules_[SpvOpFSub].push_back(MergeSubNegateArithmetic());
  2235. rules_[SpvOpFSub].push_back(MergeSubAddArithmetic());
  2236. rules_[SpvOpFSub].push_back(MergeSubSubArithmetic());
  2237. rules_[SpvOpIAdd].push_back(RedundantIAdd());
  2238. rules_[SpvOpIAdd].push_back(MergeAddNegateArithmetic());
  2239. rules_[SpvOpIAdd].push_back(MergeAddAddArithmetic());
  2240. rules_[SpvOpIAdd].push_back(MergeAddSubArithmetic());
  2241. rules_[SpvOpIAdd].push_back(MergeGenericAddSubArithmetic());
  2242. rules_[SpvOpIAdd].push_back(FactorAddMuls());
  2243. rules_[SpvOpIMul].push_back(IntMultipleBy1());
  2244. rules_[SpvOpIMul].push_back(MergeMulMulArithmetic());
  2245. rules_[SpvOpIMul].push_back(MergeMulNegateArithmetic());
  2246. rules_[SpvOpISub].push_back(MergeSubNegateArithmetic());
  2247. rules_[SpvOpISub].push_back(MergeSubAddArithmetic());
  2248. rules_[SpvOpISub].push_back(MergeSubSubArithmetic());
  2249. rules_[SpvOpPhi].push_back(RedundantPhi());
  2250. rules_[SpvOpSDiv].push_back(MergeDivNegateArithmetic());
  2251. rules_[SpvOpSNegate].push_back(MergeNegateArithmetic());
  2252. rules_[SpvOpSNegate].push_back(MergeNegateMulDivArithmetic());
  2253. rules_[SpvOpSNegate].push_back(MergeNegateAddSubArithmetic());
  2254. rules_[SpvOpSelect].push_back(RedundantSelect());
  2255. rules_[SpvOpStore].push_back(StoringUndef());
  2256. rules_[SpvOpVectorShuffle].push_back(VectorShuffleFeedingShuffle());
  2257. rules_[SpvOpImageSampleImplicitLod].push_back(UpdateImageOperands());
  2258. rules_[SpvOpImageSampleExplicitLod].push_back(UpdateImageOperands());
  2259. rules_[SpvOpImageSampleDrefImplicitLod].push_back(UpdateImageOperands());
  2260. rules_[SpvOpImageSampleDrefExplicitLod].push_back(UpdateImageOperands());
  2261. rules_[SpvOpImageSampleProjImplicitLod].push_back(UpdateImageOperands());
  2262. rules_[SpvOpImageSampleProjExplicitLod].push_back(UpdateImageOperands());
  2263. rules_[SpvOpImageSampleProjDrefImplicitLod].push_back(UpdateImageOperands());
  2264. rules_[SpvOpImageSampleProjDrefExplicitLod].push_back(UpdateImageOperands());
  2265. rules_[SpvOpImageFetch].push_back(UpdateImageOperands());
  2266. rules_[SpvOpImageGather].push_back(UpdateImageOperands());
  2267. rules_[SpvOpImageDrefGather].push_back(UpdateImageOperands());
  2268. rules_[SpvOpImageRead].push_back(UpdateImageOperands());
  2269. rules_[SpvOpImageWrite].push_back(UpdateImageOperands());
  2270. rules_[SpvOpImageSparseSampleImplicitLod].push_back(UpdateImageOperands());
  2271. rules_[SpvOpImageSparseSampleExplicitLod].push_back(UpdateImageOperands());
  2272. rules_[SpvOpImageSparseSampleDrefImplicitLod].push_back(
  2273. UpdateImageOperands());
  2274. rules_[SpvOpImageSparseSampleDrefExplicitLod].push_back(
  2275. UpdateImageOperands());
  2276. rules_[SpvOpImageSparseSampleProjImplicitLod].push_back(
  2277. UpdateImageOperands());
  2278. rules_[SpvOpImageSparseSampleProjExplicitLod].push_back(
  2279. UpdateImageOperands());
  2280. rules_[SpvOpImageSparseSampleProjDrefImplicitLod].push_back(
  2281. UpdateImageOperands());
  2282. rules_[SpvOpImageSparseSampleProjDrefExplicitLod].push_back(
  2283. UpdateImageOperands());
  2284. rules_[SpvOpImageSparseFetch].push_back(UpdateImageOperands());
  2285. rules_[SpvOpImageSparseGather].push_back(UpdateImageOperands());
  2286. rules_[SpvOpImageSparseDrefGather].push_back(UpdateImageOperands());
  2287. rules_[SpvOpImageSparseRead].push_back(UpdateImageOperands());
  2288. FeatureManager* feature_manager = context_->get_feature_mgr();
  2289. // Add rules for GLSLstd450
  2290. uint32_t ext_inst_glslstd450_id =
  2291. feature_manager->GetExtInstImportId_GLSLstd450();
  2292. if (ext_inst_glslstd450_id != 0) {
  2293. ext_rules_[{ext_inst_glslstd450_id, GLSLstd450FMix}].push_back(
  2294. RedundantFMix());
  2295. }
  2296. }
  2297. } // namespace opt
  2298. } // namespace spvtools