constant_propagation_pass.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <functional>
  5. #include <tuple>
  6. #include <type_traits>
  7. #include "common/bit_cast.h"
  8. #include "shader_recompiler/environment.h"
  9. #include "shader_recompiler/exception.h"
  10. #include "shader_recompiler/frontend/ir/ir_emitter.h"
  11. #include "shader_recompiler/frontend/ir/modifiers.h"
  12. #include "shader_recompiler/frontend/ir/value.h"
  13. #include "shader_recompiler/ir_opt/passes.h"
  14. namespace Shader::Optimization {
  15. namespace {
  16. // Metaprogramming stuff to get arguments information out of a lambda
  17. template <typename Func>
  18. struct LambdaTraits : LambdaTraits<decltype(&std::remove_reference_t<Func>::operator())> {};
  19. template <typename ReturnType, typename LambdaType, typename... Args>
  20. struct LambdaTraits<ReturnType (LambdaType::*)(Args...) const> {
  21. template <size_t I>
  22. using ArgType = std::tuple_element_t<I, std::tuple<Args...>>;
  23. static constexpr size_t NUM_ARGS{sizeof...(Args)};
  24. };
  25. template <typename T>
  26. [[nodiscard]] T Arg(const IR::Value& value) {
  27. if constexpr (std::is_same_v<T, bool>) {
  28. return value.U1();
  29. } else if constexpr (std::is_same_v<T, u32>) {
  30. return value.U32();
  31. } else if constexpr (std::is_same_v<T, s32>) {
  32. return static_cast<s32>(value.U32());
  33. } else if constexpr (std::is_same_v<T, f32>) {
  34. return value.F32();
  35. } else if constexpr (std::is_same_v<T, u64>) {
  36. return value.U64();
  37. }
  38. }
  39. template <typename T, typename ImmFn>
  40. bool FoldCommutative(IR::Inst& inst, ImmFn&& imm_fn) {
  41. const IR::Value lhs{inst.Arg(0)};
  42. const IR::Value rhs{inst.Arg(1)};
  43. const bool is_lhs_immediate{lhs.IsImmediate()};
  44. const bool is_rhs_immediate{rhs.IsImmediate()};
  45. if (is_lhs_immediate && is_rhs_immediate) {
  46. const auto result{imm_fn(Arg<T>(lhs), Arg<T>(rhs))};
  47. inst.ReplaceUsesWith(IR::Value{result});
  48. return false;
  49. }
  50. if (is_lhs_immediate && !is_rhs_immediate) {
  51. IR::Inst* const rhs_inst{rhs.InstRecursive()};
  52. if (rhs_inst->GetOpcode() == inst.GetOpcode() && rhs_inst->Arg(1).IsImmediate()) {
  53. const auto combined{imm_fn(Arg<T>(lhs), Arg<T>(rhs_inst->Arg(1)))};
  54. inst.SetArg(0, rhs_inst->Arg(0));
  55. inst.SetArg(1, IR::Value{combined});
  56. } else {
  57. // Normalize
  58. inst.SetArg(0, rhs);
  59. inst.SetArg(1, lhs);
  60. }
  61. }
  62. if (!is_lhs_immediate && is_rhs_immediate) {
  63. const IR::Inst* const lhs_inst{lhs.InstRecursive()};
  64. if (lhs_inst->GetOpcode() == inst.GetOpcode() && lhs_inst->Arg(1).IsImmediate()) {
  65. const auto combined{imm_fn(Arg<T>(rhs), Arg<T>(lhs_inst->Arg(1)))};
  66. inst.SetArg(0, lhs_inst->Arg(0));
  67. inst.SetArg(1, IR::Value{combined});
  68. }
  69. }
  70. return true;
  71. }
  72. template <typename Func>
  73. bool FoldWhenAllImmediates(IR::Inst& inst, Func&& func) {
  74. if (!inst.AreAllArgsImmediates() || inst.HasAssociatedPseudoOperation()) {
  75. return false;
  76. }
  77. using Indices = std::make_index_sequence<LambdaTraits<decltype(func)>::NUM_ARGS>;
  78. inst.ReplaceUsesWith(EvalImmediates(inst, func, Indices{}));
  79. return true;
  80. }
  81. /// Return true when all values in a range are equal
  82. template <typename Range>
  83. bool AreEqual(const Range& range) {
  84. auto resolver{[](const auto& value) { return value.Resolve(); }};
  85. auto equal{[](const IR::Value& lhs, const IR::Value& rhs) {
  86. if (lhs == rhs) {
  87. return true;
  88. }
  89. // Not equal, but try to match if they read the same constant buffer
  90. if (!lhs.IsImmediate() && !rhs.IsImmediate() &&
  91. lhs.Inst()->GetOpcode() == IR::Opcode::GetCbufU32 &&
  92. rhs.Inst()->GetOpcode() == IR::Opcode::GetCbufU32 &&
  93. lhs.Inst()->Arg(0) == rhs.Inst()->Arg(0) && lhs.Inst()->Arg(1) == rhs.Inst()->Arg(1)) {
  94. return true;
  95. }
  96. return false;
  97. }};
  98. return std::ranges::adjacent_find(range, std::not_fn(equal), resolver) == std::end(range);
  99. }
  100. void FoldGetRegister(IR::Inst& inst) {
  101. if (inst.Arg(0).Reg() == IR::Reg::RZ) {
  102. inst.ReplaceUsesWith(IR::Value{u32{0}});
  103. }
  104. }
  105. void FoldGetPred(IR::Inst& inst) {
  106. if (inst.Arg(0).Pred() == IR::Pred::PT) {
  107. inst.ReplaceUsesWith(IR::Value{true});
  108. }
  109. }
  110. /// Replaces the XMAD pattern generated by an integer FMA
  111. bool FoldXmadMultiplyAdd(IR::Block& block, IR::Inst& inst) {
  112. /*
  113. * We are looking for this specific pattern:
  114. * %6 = BitFieldUExtract %op_b, #0, #16
  115. * %7 = BitFieldUExtract %op_a', #16, #16
  116. * %8 = IMul32 %6, %7
  117. * %10 = BitFieldUExtract %op_a', #0, #16
  118. * %11 = BitFieldInsert %8, %10, #16, #16
  119. * %15 = BitFieldUExtract %op_b, #0, #16
  120. * %16 = BitFieldUExtract %op_a, #0, #16
  121. * %17 = IMul32 %15, %16
  122. * %18 = IAdd32 %17, %op_c
  123. * %22 = BitFieldUExtract %op_b, #16, #16
  124. * %23 = BitFieldUExtract %11, #16, #16
  125. * %24 = IMul32 %22, %23
  126. * %25 = ShiftLeftLogical32 %24, #16
  127. * %26 = ShiftLeftLogical32 %11, #16
  128. * %27 = IAdd32 %26, %18
  129. * %result = IAdd32 %25, %27
  130. *
  131. * And replace it with:
  132. * %temp = IMul32 %op_a, %op_b
  133. * %result = IAdd32 %temp, %op_c
  134. *
  135. * This optimization has been proven safe by Nvidia's compiler logic being reversed.
  136. * (If Nvidia generates this code from 'fma(a, b, c)', we can do the same in the reverse order.)
  137. */
  138. const IR::Value zero{0u};
  139. const IR::Value sixteen{16u};
  140. IR::Inst* const _25{inst.Arg(0).TryInstRecursive()};
  141. IR::Inst* const _27{inst.Arg(1).TryInstRecursive()};
  142. if (!_25 || !_27) {
  143. return false;
  144. }
  145. if (_27->GetOpcode() != IR::Opcode::IAdd32) {
  146. return false;
  147. }
  148. if (_25->GetOpcode() != IR::Opcode::ShiftLeftLogical32 || _25->Arg(1) != sixteen) {
  149. return false;
  150. }
  151. IR::Inst* const _24{_25->Arg(0).TryInstRecursive()};
  152. if (!_24 || _24->GetOpcode() != IR::Opcode::IMul32) {
  153. return false;
  154. }
  155. IR::Inst* const _22{_24->Arg(0).TryInstRecursive()};
  156. IR::Inst* const _23{_24->Arg(1).TryInstRecursive()};
  157. if (!_22 || !_23) {
  158. return false;
  159. }
  160. if (_22->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  161. return false;
  162. }
  163. if (_23->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  164. return false;
  165. }
  166. if (_22->Arg(1) != sixteen || _22->Arg(2) != sixteen) {
  167. return false;
  168. }
  169. if (_23->Arg(1) != sixteen || _23->Arg(2) != sixteen) {
  170. return false;
  171. }
  172. IR::Inst* const _11{_23->Arg(0).TryInstRecursive()};
  173. if (!_11 || _11->GetOpcode() != IR::Opcode::BitFieldInsert) {
  174. return false;
  175. }
  176. if (_11->Arg(2) != sixteen || _11->Arg(3) != sixteen) {
  177. return false;
  178. }
  179. IR::Inst* const _8{_11->Arg(0).TryInstRecursive()};
  180. IR::Inst* const _10{_11->Arg(1).TryInstRecursive()};
  181. if (!_8 || !_10) {
  182. return false;
  183. }
  184. if (_8->GetOpcode() != IR::Opcode::IMul32) {
  185. return false;
  186. }
  187. if (_10->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  188. return false;
  189. }
  190. IR::Inst* const _6{_8->Arg(0).TryInstRecursive()};
  191. IR::Inst* const _7{_8->Arg(1).TryInstRecursive()};
  192. if (!_6 || !_7) {
  193. return false;
  194. }
  195. if (_6->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  196. return false;
  197. }
  198. if (_7->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  199. return false;
  200. }
  201. if (_6->Arg(1) != zero || _6->Arg(2) != sixteen) {
  202. return false;
  203. }
  204. if (_7->Arg(1) != sixteen || _7->Arg(2) != sixteen) {
  205. return false;
  206. }
  207. IR::Inst* const _26{_27->Arg(0).TryInstRecursive()};
  208. IR::Inst* const _18{_27->Arg(1).TryInstRecursive()};
  209. if (!_26 || !_18) {
  210. return false;
  211. }
  212. if (_26->GetOpcode() != IR::Opcode::ShiftLeftLogical32 || _26->Arg(1) != sixteen) {
  213. return false;
  214. }
  215. if (_26->Arg(0).InstRecursive() != _11) {
  216. return false;
  217. }
  218. if (_18->GetOpcode() != IR::Opcode::IAdd32) {
  219. return false;
  220. }
  221. IR::Inst* const _17{_18->Arg(0).TryInstRecursive()};
  222. if (!_17 || _17->GetOpcode() != IR::Opcode::IMul32) {
  223. return false;
  224. }
  225. IR::Inst* const _15{_17->Arg(0).TryInstRecursive()};
  226. IR::Inst* const _16{_17->Arg(1).TryInstRecursive()};
  227. if (!_15 || !_16) {
  228. return false;
  229. }
  230. if (_15->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  231. return false;
  232. }
  233. if (_16->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  234. return false;
  235. }
  236. if (_15->Arg(1) != zero || _16->Arg(1) != zero || _10->Arg(1) != zero) {
  237. return false;
  238. }
  239. if (_15->Arg(2) != sixteen || _16->Arg(2) != sixteen || _10->Arg(2) != sixteen) {
  240. return false;
  241. }
  242. const std::array<IR::Value, 3> op_as{
  243. _7->Arg(0).Resolve(),
  244. _16->Arg(0).Resolve(),
  245. _10->Arg(0).Resolve(),
  246. };
  247. const std::array<IR::Value, 3> op_bs{
  248. _22->Arg(0).Resolve(),
  249. _6->Arg(0).Resolve(),
  250. _15->Arg(0).Resolve(),
  251. };
  252. const IR::U32 op_c{_18->Arg(1)};
  253. if (!AreEqual(op_as) || !AreEqual(op_bs)) {
  254. return false;
  255. }
  256. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  257. inst.ReplaceUsesWith(ir.IAdd(ir.IMul(IR::U32{op_as[0]}, IR::U32{op_bs[1]}), op_c));
  258. return true;
  259. }
  260. /// Replaces the pattern generated by two XMAD multiplications
  261. bool FoldXmadMultiply(IR::Block& block, IR::Inst& inst) {
  262. /*
  263. * We are looking for this pattern:
  264. * %rhs_bfe = BitFieldUExtract %factor_a, #0, #16
  265. * %rhs_mul = IMul32 %rhs_bfe, %factor_b
  266. * %lhs_bfe = BitFieldUExtract %factor_a, #16, #16
  267. * %rhs_mul = IMul32 %lhs_bfe, %factor_b
  268. * %lhs_shl = ShiftLeftLogical32 %rhs_mul, #16
  269. * %result = IAdd32 %lhs_shl, %rhs_mul
  270. *
  271. * And replacing it with
  272. * %result = IMul32 %factor_a, %factor_b
  273. *
  274. * This optimization has been proven safe by LLVM and MSVC.
  275. */
  276. IR::Inst* const lhs_shl{inst.Arg(0).TryInstRecursive()};
  277. IR::Inst* const rhs_mul{inst.Arg(1).TryInstRecursive()};
  278. if (!lhs_shl || !rhs_mul) {
  279. return false;
  280. }
  281. if (lhs_shl->GetOpcode() != IR::Opcode::ShiftLeftLogical32 ||
  282. lhs_shl->Arg(1) != IR::Value{16U}) {
  283. return false;
  284. }
  285. IR::Inst* const lhs_mul{lhs_shl->Arg(0).TryInstRecursive()};
  286. if (!lhs_mul) {
  287. return false;
  288. }
  289. if (lhs_mul->GetOpcode() != IR::Opcode::IMul32 || rhs_mul->GetOpcode() != IR::Opcode::IMul32) {
  290. return false;
  291. }
  292. const IR::U32 factor_b{lhs_mul->Arg(1)};
  293. if (factor_b.Resolve() != rhs_mul->Arg(1).Resolve()) {
  294. return false;
  295. }
  296. IR::Inst* const lhs_bfe{lhs_mul->Arg(0).TryInstRecursive()};
  297. IR::Inst* const rhs_bfe{rhs_mul->Arg(0).TryInstRecursive()};
  298. if (!lhs_bfe || !rhs_bfe) {
  299. return false;
  300. }
  301. if (lhs_bfe->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  302. return false;
  303. }
  304. if (rhs_bfe->GetOpcode() != IR::Opcode::BitFieldUExtract) {
  305. return false;
  306. }
  307. if (lhs_bfe->Arg(1) != IR::Value{16U} || lhs_bfe->Arg(2) != IR::Value{16U}) {
  308. return false;
  309. }
  310. if (rhs_bfe->Arg(1) != IR::Value{0U} || rhs_bfe->Arg(2) != IR::Value{16U}) {
  311. return false;
  312. }
  313. const IR::U32 factor_a{lhs_bfe->Arg(0)};
  314. if (factor_a.Resolve() != rhs_bfe->Arg(0).Resolve()) {
  315. return false;
  316. }
  317. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  318. inst.ReplaceUsesWith(ir.IMul(factor_a, factor_b));
  319. return true;
  320. }
  321. template <typename T>
  322. void FoldAdd(IR::Block& block, IR::Inst& inst) {
  323. if (inst.HasAssociatedPseudoOperation()) {
  324. return;
  325. }
  326. if (!FoldCommutative<T>(inst, [](T a, T b) { return a + b; })) {
  327. return;
  328. }
  329. const IR::Value rhs{inst.Arg(1)};
  330. if (rhs.IsImmediate() && Arg<T>(rhs) == 0) {
  331. inst.ReplaceUsesWith(inst.Arg(0));
  332. return;
  333. }
  334. if constexpr (std::is_same_v<T, u32>) {
  335. if (FoldXmadMultiply(block, inst)) {
  336. return;
  337. }
  338. if (FoldXmadMultiplyAdd(block, inst)) {
  339. return;
  340. }
  341. }
  342. }
  343. void FoldISub32(IR::Inst& inst) {
  344. if (FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a - b; })) {
  345. return;
  346. }
  347. if (inst.Arg(0).IsImmediate() || inst.Arg(1).IsImmediate()) {
  348. return;
  349. }
  350. // ISub32 is generally used to subtract two constant buffers, compare and replace this with
  351. // zero if they equal.
  352. const auto equal_cbuf{[](IR::Inst* a, IR::Inst* b) {
  353. return a->GetOpcode() == IR::Opcode::GetCbufU32 &&
  354. b->GetOpcode() == IR::Opcode::GetCbufU32 && a->Arg(0) == b->Arg(0) &&
  355. a->Arg(1) == b->Arg(1);
  356. }};
  357. IR::Inst* op_a{inst.Arg(0).InstRecursive()};
  358. IR::Inst* op_b{inst.Arg(1).InstRecursive()};
  359. if (equal_cbuf(op_a, op_b)) {
  360. inst.ReplaceUsesWith(IR::Value{u32{0}});
  361. return;
  362. }
  363. // It's also possible a value is being added to a cbuf and then subtracted
  364. if (op_b->GetOpcode() == IR::Opcode::IAdd32) {
  365. // Canonicalize local variables to simplify the following logic
  366. std::swap(op_a, op_b);
  367. }
  368. if (op_b->GetOpcode() != IR::Opcode::GetCbufU32) {
  369. return;
  370. }
  371. IR::Inst* const inst_cbuf{op_b};
  372. if (op_a->GetOpcode() != IR::Opcode::IAdd32) {
  373. return;
  374. }
  375. IR::Value add_op_a{op_a->Arg(0)};
  376. IR::Value add_op_b{op_a->Arg(1)};
  377. if (add_op_b.IsImmediate()) {
  378. // Canonicalize
  379. std::swap(add_op_a, add_op_b);
  380. }
  381. if (add_op_b.IsImmediate()) {
  382. return;
  383. }
  384. IR::Inst* const add_cbuf{add_op_b.InstRecursive()};
  385. if (equal_cbuf(add_cbuf, inst_cbuf)) {
  386. inst.ReplaceUsesWith(add_op_a);
  387. }
  388. }
  389. void FoldSelect(IR::Inst& inst) {
  390. const IR::Value cond{inst.Arg(0)};
  391. if (cond.IsImmediate()) {
  392. inst.ReplaceUsesWith(cond.U1() ? inst.Arg(1) : inst.Arg(2));
  393. }
  394. }
  395. void FoldFPAdd32(IR::Inst& inst) {
  396. if (FoldWhenAllImmediates(inst, [](f32 a, f32 b) { return a + b; })) {
  397. return;
  398. }
  399. const IR::Value lhs_value{inst.Arg(0)};
  400. const IR::Value rhs_value{inst.Arg(1)};
  401. const auto check_neutral = [](const IR::Value& one_operand) {
  402. return one_operand.IsImmediate() && std::abs(one_operand.F32()) == 0.0f;
  403. };
  404. if (check_neutral(lhs_value)) {
  405. inst.ReplaceUsesWith(rhs_value);
  406. }
  407. if (check_neutral(rhs_value)) {
  408. inst.ReplaceUsesWith(lhs_value);
  409. }
  410. }
  411. bool FoldDerivativeYFromCorrection(IR::Inst& inst) {
  412. const IR::Value lhs_value{inst.Arg(0)};
  413. const IR::Value rhs_value{inst.Arg(1)};
  414. IR::Inst* const lhs_op{lhs_value.InstRecursive()};
  415. IR::Inst* const rhs_op{rhs_value.InstRecursive()};
  416. if (lhs_op->GetOpcode() == IR::Opcode::YDirection) {
  417. if (rhs_op->GetOpcode() != IR::Opcode::DPdyFine) {
  418. return false;
  419. }
  420. inst.ReplaceUsesWith(rhs_value);
  421. return true;
  422. }
  423. if (rhs_op->GetOpcode() != IR::Opcode::YDirection) {
  424. return false;
  425. }
  426. if (lhs_op->GetOpcode() != IR::Opcode::DPdyFine) {
  427. return false;
  428. }
  429. inst.ReplaceUsesWith(lhs_value);
  430. return true;
  431. }
  432. void FoldFPMul32(IR::Inst& inst) {
  433. if (FoldWhenAllImmediates(inst, [](f32 a, f32 b) { return a * b; })) {
  434. return;
  435. }
  436. const auto control{inst.Flags<IR::FpControl>()};
  437. if (control.no_contraction) {
  438. return;
  439. }
  440. // Fold interpolation operations
  441. const IR::Value lhs_value{inst.Arg(0)};
  442. const IR::Value rhs_value{inst.Arg(1)};
  443. if (lhs_value.IsImmediate() || rhs_value.IsImmediate()) {
  444. return;
  445. }
  446. if (FoldDerivativeYFromCorrection(inst)) {
  447. return;
  448. }
  449. IR::Inst* const lhs_op{lhs_value.InstRecursive()};
  450. IR::Inst* const rhs_op{rhs_value.InstRecursive()};
  451. if (lhs_op->GetOpcode() != IR::Opcode::FPMul32 ||
  452. rhs_op->GetOpcode() != IR::Opcode::FPRecip32) {
  453. return;
  454. }
  455. const IR::Value recip_source{rhs_op->Arg(0)};
  456. const IR::Value lhs_mul_source{lhs_op->Arg(1).Resolve()};
  457. if (recip_source.IsImmediate() || lhs_mul_source.IsImmediate()) {
  458. return;
  459. }
  460. IR::Inst* const attr_a{recip_source.InstRecursive()};
  461. IR::Inst* const attr_b{lhs_mul_source.InstRecursive()};
  462. if (attr_a->GetOpcode() != IR::Opcode::GetAttribute ||
  463. attr_b->GetOpcode() != IR::Opcode::GetAttribute) {
  464. return;
  465. }
  466. if (attr_a->Arg(0).Attribute() == attr_b->Arg(0).Attribute()) {
  467. inst.ReplaceUsesWith(lhs_op->Arg(0));
  468. }
  469. }
  470. void FoldLogicalAnd(IR::Inst& inst) {
  471. if (!FoldCommutative<bool>(inst, [](bool a, bool b) { return a && b; })) {
  472. return;
  473. }
  474. const IR::Value rhs{inst.Arg(1)};
  475. if (rhs.IsImmediate()) {
  476. if (rhs.U1()) {
  477. inst.ReplaceUsesWith(inst.Arg(0));
  478. } else {
  479. inst.ReplaceUsesWith(IR::Value{false});
  480. }
  481. }
  482. }
  483. void FoldLogicalOr(IR::Inst& inst) {
  484. if (!FoldCommutative<bool>(inst, [](bool a, bool b) { return a || b; })) {
  485. return;
  486. }
  487. const IR::Value rhs{inst.Arg(1)};
  488. if (rhs.IsImmediate()) {
  489. if (rhs.U1()) {
  490. inst.ReplaceUsesWith(IR::Value{true});
  491. } else {
  492. inst.ReplaceUsesWith(inst.Arg(0));
  493. }
  494. }
  495. }
  496. void FoldLogicalNot(IR::Inst& inst) {
  497. const IR::U1 value{inst.Arg(0)};
  498. if (value.IsImmediate()) {
  499. inst.ReplaceUsesWith(IR::Value{!value.U1()});
  500. return;
  501. }
  502. IR::Inst* const arg{value.InstRecursive()};
  503. if (arg->GetOpcode() == IR::Opcode::LogicalNot) {
  504. inst.ReplaceUsesWith(arg->Arg(0));
  505. }
  506. }
  507. template <IR::Opcode op, typename Dest, typename Source>
  508. void FoldBitCast(IR::Inst& inst, IR::Opcode reverse) {
  509. const IR::Value value{inst.Arg(0)};
  510. if (value.IsImmediate()) {
  511. inst.ReplaceUsesWith(IR::Value{Common::BitCast<Dest>(Arg<Source>(value))});
  512. return;
  513. }
  514. IR::Inst* const arg_inst{value.InstRecursive()};
  515. if (arg_inst->GetOpcode() == reverse) {
  516. inst.ReplaceUsesWith(arg_inst->Arg(0));
  517. return;
  518. }
  519. if constexpr (op == IR::Opcode::BitCastF32U32) {
  520. if (arg_inst->GetOpcode() == IR::Opcode::GetCbufU32) {
  521. // Replace the bitcast with a typed constant buffer read
  522. inst.ReplaceOpcode(IR::Opcode::GetCbufF32);
  523. inst.SetArg(0, arg_inst->Arg(0));
  524. inst.SetArg(1, arg_inst->Arg(1));
  525. return;
  526. }
  527. }
  528. if constexpr (op == IR::Opcode::BitCastU32F32) {
  529. // Workaround for new NVIDIA driver bug, where:
  530. // uint attr = ftou(itof(gl_InstanceID));
  531. // always returned 0.
  532. // We can instead manually optimize this and work around the driver bug:
  533. // uint attr = uint(gl_InstanceID);
  534. if (arg_inst->GetOpcode() == IR::Opcode::GetAttribute) {
  535. const IR::Attribute attr{arg_inst->Arg(0).Attribute()};
  536. switch (attr) {
  537. case IR::Attribute::PrimitiveId:
  538. case IR::Attribute::InstanceId:
  539. case IR::Attribute::VertexId:
  540. case IR::Attribute::BaseVertex:
  541. case IR::Attribute::BaseInstance:
  542. case IR::Attribute::DrawID:
  543. break;
  544. default:
  545. return;
  546. }
  547. // Replace the bitcasts with an integer attribute get
  548. inst.ReplaceOpcode(IR::Opcode::GetAttributeU32);
  549. inst.SetArg(0, arg_inst->Arg(0));
  550. inst.SetArg(1, arg_inst->Arg(1));
  551. return;
  552. }
  553. }
  554. }
  555. void FoldInverseFunc(IR::Inst& inst, IR::Opcode reverse) {
  556. const IR::Value value{inst.Arg(0)};
  557. if (value.IsImmediate()) {
  558. return;
  559. }
  560. IR::Inst* const arg_inst{value.InstRecursive()};
  561. if (arg_inst->GetOpcode() == reverse) {
  562. inst.ReplaceUsesWith(arg_inst->Arg(0));
  563. return;
  564. }
  565. }
  566. template <typename Func, size_t... I>
  567. IR::Value EvalImmediates(const IR::Inst& inst, Func&& func, std::index_sequence<I...>) {
  568. using Traits = LambdaTraits<decltype(func)>;
  569. return IR::Value{func(Arg<typename Traits::template ArgType<I>>(inst.Arg(I))...)};
  570. }
  571. std::optional<IR::Value> FoldCompositeExtractImpl(IR::Value inst_value, IR::Opcode insert,
  572. IR::Opcode construct, u32 first_index) {
  573. IR::Inst* const inst{inst_value.InstRecursive()};
  574. if (inst->GetOpcode() == construct) {
  575. return inst->Arg(first_index);
  576. }
  577. if (inst->GetOpcode() != insert) {
  578. return std::nullopt;
  579. }
  580. IR::Value value_index{inst->Arg(2)};
  581. if (!value_index.IsImmediate()) {
  582. return std::nullopt;
  583. }
  584. const u32 second_index{value_index.U32()};
  585. if (first_index != second_index) {
  586. IR::Value value_composite{inst->Arg(0)};
  587. if (value_composite.IsImmediate()) {
  588. return std::nullopt;
  589. }
  590. return FoldCompositeExtractImpl(value_composite, insert, construct, first_index);
  591. }
  592. return inst->Arg(1);
  593. }
  594. void FoldCompositeExtract(IR::Inst& inst, IR::Opcode construct, IR::Opcode insert) {
  595. const IR::Value value_1{inst.Arg(0)};
  596. const IR::Value value_2{inst.Arg(1)};
  597. if (value_1.IsImmediate()) {
  598. return;
  599. }
  600. if (!value_2.IsImmediate()) {
  601. return;
  602. }
  603. const u32 first_index{value_2.U32()};
  604. const std::optional result{FoldCompositeExtractImpl(value_1, insert, construct, first_index)};
  605. if (!result) {
  606. return;
  607. }
  608. inst.ReplaceUsesWith(*result);
  609. }
  610. IR::Value GetThroughCast(IR::Value value, IR::Opcode expected_cast) {
  611. if (value.IsImmediate()) {
  612. return value;
  613. }
  614. IR::Inst* const inst{value.InstRecursive()};
  615. if (inst->GetOpcode() == expected_cast) {
  616. return inst->Arg(0).Resolve();
  617. }
  618. return value;
  619. }
  620. void FoldFSwizzleAdd(IR::Block& block, IR::Inst& inst) {
  621. const IR::Value swizzle{inst.Arg(2)};
  622. if (!swizzle.IsImmediate()) {
  623. return;
  624. }
  625. const IR::Value value_1{GetThroughCast(inst.Arg(0).Resolve(), IR::Opcode::BitCastF32U32)};
  626. const IR::Value value_2{GetThroughCast(inst.Arg(1).Resolve(), IR::Opcode::BitCastF32U32)};
  627. if (value_1.IsImmediate()) {
  628. return;
  629. }
  630. const u32 swizzle_value{swizzle.U32()};
  631. if (swizzle_value != 0x99 && swizzle_value != 0xA5) {
  632. return;
  633. }
  634. IR::Inst* const inst2{value_1.InstRecursive()};
  635. if (inst2->GetOpcode() != IR::Opcode::ShuffleButterfly) {
  636. return;
  637. }
  638. const IR::Value value_3{GetThroughCast(inst2->Arg(0).Resolve(), IR::Opcode::BitCastU32F32)};
  639. if (value_2 != value_3) {
  640. if (!value_2.IsImmediate() || !value_3.IsImmediate()) {
  641. return;
  642. }
  643. if (Common::BitCast<u32>(value_2.F32()) != value_3.U32()) {
  644. return;
  645. }
  646. }
  647. const IR::Value index{inst2->Arg(1)};
  648. const IR::Value clamp{inst2->Arg(2)};
  649. const IR::Value segmentation_mask{inst2->Arg(3)};
  650. if (!index.IsImmediate() || !clamp.IsImmediate() || !segmentation_mask.IsImmediate()) {
  651. return;
  652. }
  653. if (clamp.U32() != 3 || segmentation_mask.U32() != 28) {
  654. return;
  655. }
  656. if (swizzle_value == 0x99) {
  657. // DPdxFine
  658. if (index.U32() == 1) {
  659. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  660. inst.ReplaceUsesWith(ir.DPdxFine(IR::F32{inst.Arg(1)}));
  661. }
  662. } else if (swizzle_value == 0xA5) {
  663. // DPdyFine
  664. if (index.U32() == 2) {
  665. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  666. inst.ReplaceUsesWith(ir.DPdyFine(IR::F32{inst.Arg(1)}));
  667. }
  668. }
  669. }
  670. bool FindGradient3DDerivatives(std::array<IR::Value, 3>& results, IR::Value coord) {
  671. if (coord.IsImmediate()) {
  672. return false;
  673. }
  674. const auto check_through_shuffle = [](IR::Value input, IR::Value& result) {
  675. const IR::Value value_1{GetThroughCast(input.Resolve(), IR::Opcode::BitCastF32U32)};
  676. IR::Inst* const inst2{value_1.InstRecursive()};
  677. if (inst2->GetOpcode() != IR::Opcode::ShuffleIndex) {
  678. return false;
  679. }
  680. const IR::Value index{inst2->Arg(1).Resolve()};
  681. const IR::Value clamp{inst2->Arg(2).Resolve()};
  682. const IR::Value segmentation_mask{inst2->Arg(3).Resolve()};
  683. if (!index.IsImmediate() || !clamp.IsImmediate() || !segmentation_mask.IsImmediate()) {
  684. return false;
  685. }
  686. if (index.U32() != 3 && clamp.U32() != 3) {
  687. return false;
  688. }
  689. result = GetThroughCast(inst2->Arg(0).Resolve(), IR::Opcode::BitCastU32F32);
  690. return true;
  691. };
  692. IR::Inst* const inst = coord.InstRecursive();
  693. if (inst->GetOpcode() != IR::Opcode::FSwizzleAdd) {
  694. return false;
  695. }
  696. std::array<IR::Value, 3> temporary_values;
  697. IR::Value value_1 = inst->Arg(0).Resolve();
  698. IR::Value value_2 = inst->Arg(1).Resolve();
  699. IR::Value value_3 = inst->Arg(2).Resolve();
  700. std::array<u32, 4> swizzles_mask_a{};
  701. std::array<u32, 4> swizzles_mask_b{};
  702. const auto resolve_mask = [](std::array<u32, 4>& mask_results, IR::Value mask) {
  703. u32 value = mask.U32();
  704. for (size_t i = 0; i < 4; i++) {
  705. mask_results[i] = (value >> (i * 2)) & 0x3;
  706. }
  707. };
  708. resolve_mask(swizzles_mask_a, value_3);
  709. size_t coordinate_index = 0;
  710. const auto resolve_pending = [&](IR::Value resolve_v) {
  711. IR::Inst* const inst_r = resolve_v.InstRecursive();
  712. if (inst_r->GetOpcode() != IR::Opcode::FSwizzleAdd) {
  713. return false;
  714. }
  715. if (!check_through_shuffle(inst_r->Arg(0).Resolve(), temporary_values[1])) {
  716. return false;
  717. }
  718. if (!check_through_shuffle(inst_r->Arg(1).Resolve(), temporary_values[2])) {
  719. return false;
  720. }
  721. resolve_mask(swizzles_mask_b, inst_r->Arg(2).Resolve());
  722. return true;
  723. };
  724. if (value_1.IsImmediate() || value_2.IsImmediate()) {
  725. return false;
  726. }
  727. bool should_continue = false;
  728. if (resolve_pending(value_1)) {
  729. should_continue = check_through_shuffle(value_2, temporary_values[0]);
  730. coordinate_index = 0;
  731. }
  732. if (resolve_pending(value_2)) {
  733. should_continue = check_through_shuffle(value_1, temporary_values[0]);
  734. coordinate_index = 2;
  735. }
  736. if (!should_continue) {
  737. return false;
  738. }
  739. // figure which is which
  740. size_t zero_mask_a = 0;
  741. size_t zero_mask_b = 0;
  742. for (size_t i = 0; i < 4; i++) {
  743. if (swizzles_mask_a[i] == 2 || swizzles_mask_b[i] == 2) {
  744. // last operand can be inversed, we cannot determine a result.
  745. return false;
  746. }
  747. zero_mask_a |= static_cast<size_t>(swizzles_mask_a[i] == 3 ? 1 : 0) << i;
  748. zero_mask_b |= static_cast<size_t>(swizzles_mask_b[i] == 3 ? 1 : 0) << i;
  749. }
  750. static constexpr size_t ddx_pattern = 0b1010;
  751. static constexpr size_t ddx_pattern_inv = ~ddx_pattern & 0b00001111;
  752. if (std::popcount(zero_mask_a) != 2) {
  753. return false;
  754. }
  755. if (std::popcount(zero_mask_b) != 2) {
  756. return false;
  757. }
  758. if (zero_mask_a == zero_mask_b) {
  759. return false;
  760. }
  761. results[0] = temporary_values[coordinate_index];
  762. if (coordinate_index == 0) {
  763. if (zero_mask_b == ddx_pattern || zero_mask_b == ddx_pattern_inv) {
  764. results[1] = temporary_values[1];
  765. results[2] = temporary_values[2];
  766. return true;
  767. }
  768. results[2] = temporary_values[1];
  769. results[1] = temporary_values[2];
  770. } else {
  771. const auto assign_result = [&results](IR::Value temporary_value, size_t mask) {
  772. if (mask == ddx_pattern || mask == ddx_pattern_inv) {
  773. results[1] = temporary_value;
  774. return;
  775. }
  776. results[2] = temporary_value;
  777. };
  778. assign_result(temporary_values[1], zero_mask_b);
  779. assign_result(temporary_values[0], zero_mask_a);
  780. }
  781. return true;
  782. }
  783. void FoldImageSampleImplicitLod(IR::Block& block, IR::Inst& inst) {
  784. IR::TextureInstInfo info = inst.Flags<IR::TextureInstInfo>();
  785. auto orig_opcode = inst.GetOpcode();
  786. if (info.ndv_is_active == 0) {
  787. return;
  788. }
  789. if (info.type != TextureType::Color3D) {
  790. return;
  791. }
  792. const IR::Value handle{inst.Arg(0)};
  793. const IR::Value coords{inst.Arg(1)};
  794. const IR::Value bias_lc{inst.Arg(2)};
  795. const IR::Value offset{inst.Arg(3)};
  796. if (!offset.IsImmediate()) {
  797. return;
  798. }
  799. IR::Inst* const inst2 = coords.InstRecursive();
  800. std::array<std::array<IR::Value, 3>, 3> results_matrix;
  801. for (size_t i = 0; i < 3; i++) {
  802. if (!FindGradient3DDerivatives(results_matrix[i], inst2->Arg(i).Resolve())) {
  803. return;
  804. }
  805. }
  806. IR::F32 lod_clamp{};
  807. if (info.has_lod_clamp != 0) {
  808. if (!bias_lc.IsImmediate()) {
  809. lod_clamp = IR::F32{bias_lc.InstRecursive()->Arg(1).Resolve()};
  810. } else {
  811. lod_clamp = IR::F32{bias_lc};
  812. }
  813. }
  814. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  815. IR::Value new_coords =
  816. ir.CompositeConstruct(results_matrix[0][0], results_matrix[1][0], results_matrix[2][0]);
  817. IR::Value derivatives_1 = ir.CompositeConstruct(results_matrix[0][1], results_matrix[0][2],
  818. results_matrix[1][1], results_matrix[1][2]);
  819. IR::Value derivatives_2 = ir.CompositeConstruct(results_matrix[2][1], results_matrix[2][2]);
  820. info.num_derivatives.Assign(3);
  821. IR::Value new_gradient_instruction =
  822. ir.ImageGradient(handle, new_coords, derivatives_1, derivatives_2, lod_clamp, info);
  823. IR::Inst* const new_inst = new_gradient_instruction.InstRecursive();
  824. if (orig_opcode == IR::Opcode::ImageSampleImplicitLod) {
  825. new_inst->ReplaceOpcode(IR::Opcode::ImageGradient);
  826. }
  827. inst.ReplaceUsesWith(new_gradient_instruction);
  828. }
  829. void FoldConstBuffer(Environment& env, IR::Block& block, IR::Inst& inst) {
  830. const IR::Value bank{inst.Arg(0)};
  831. const IR::Value offset{inst.Arg(1)};
  832. if (!bank.IsImmediate() || !offset.IsImmediate()) {
  833. return;
  834. }
  835. const auto bank_value = bank.U32();
  836. const auto offset_value = offset.U32();
  837. auto replacement = env.GetReplaceConstBuffer(bank_value, offset_value);
  838. if (!replacement) {
  839. return;
  840. }
  841. const auto new_attribute = [replacement]() {
  842. switch (*replacement) {
  843. case ReplaceConstant::BaseInstance:
  844. return IR::Attribute::BaseInstance;
  845. case ReplaceConstant::BaseVertex:
  846. return IR::Attribute::BaseVertex;
  847. case ReplaceConstant::DrawID:
  848. return IR::Attribute::DrawID;
  849. default:
  850. throw NotImplementedException("Not implemented replacement variable {}", *replacement);
  851. }
  852. }();
  853. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  854. if (inst.GetOpcode() == IR::Opcode::GetCbufU32) {
  855. inst.ReplaceUsesWith(ir.GetAttributeU32(new_attribute));
  856. } else {
  857. inst.ReplaceUsesWith(ir.GetAttribute(new_attribute));
  858. }
  859. }
  860. void FoldDriverConstBuffer(Environment& env, IR::Block& block, IR::Inst& inst, u32 which_bank,
  861. u32 offset_start = 0, u32 offset_end = std::numeric_limits<u16>::max()) {
  862. const IR::Value bank{inst.Arg(0)};
  863. const IR::Value offset{inst.Arg(1)};
  864. if (!bank.IsImmediate() || !offset.IsImmediate()) {
  865. return;
  866. }
  867. const auto bank_value = bank.U32();
  868. if (bank_value != which_bank) {
  869. return;
  870. }
  871. const auto offset_value = offset.U32();
  872. if (offset_value < offset_start || offset_value >= offset_end) {
  873. return;
  874. }
  875. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  876. if (inst.GetOpcode() == IR::Opcode::GetCbufU32) {
  877. inst.ReplaceUsesWith(IR::Value{env.ReadCbufValue(bank_value, offset_value)});
  878. } else {
  879. inst.ReplaceUsesWith(
  880. IR::Value{Common::BitCast<f32>(env.ReadCbufValue(bank_value, offset_value))});
  881. }
  882. }
  883. void ConstantPropagation(Environment& env, IR::Block& block, IR::Inst& inst) {
  884. switch (inst.GetOpcode()) {
  885. case IR::Opcode::GetRegister:
  886. return FoldGetRegister(inst);
  887. case IR::Opcode::GetPred:
  888. return FoldGetPred(inst);
  889. case IR::Opcode::IAdd32:
  890. return FoldAdd<u32>(block, inst);
  891. case IR::Opcode::ISub32:
  892. return FoldISub32(inst);
  893. case IR::Opcode::IMul32:
  894. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a * b; });
  895. return;
  896. case IR::Opcode::ShiftRightArithmetic32:
  897. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return static_cast<u32>(a >> b); });
  898. return;
  899. case IR::Opcode::BitCastF32U32:
  900. return FoldBitCast<IR::Opcode::BitCastF32U32, f32, u32>(inst, IR::Opcode::BitCastU32F32);
  901. case IR::Opcode::BitCastU32F32:
  902. return FoldBitCast<IR::Opcode::BitCastU32F32, u32, f32>(inst, IR::Opcode::BitCastF32U32);
  903. case IR::Opcode::IAdd64:
  904. return FoldAdd<u64>(block, inst);
  905. case IR::Opcode::PackHalf2x16:
  906. return FoldInverseFunc(inst, IR::Opcode::UnpackHalf2x16);
  907. case IR::Opcode::UnpackHalf2x16:
  908. return FoldInverseFunc(inst, IR::Opcode::PackHalf2x16);
  909. case IR::Opcode::PackFloat2x16:
  910. return FoldInverseFunc(inst, IR::Opcode::UnpackFloat2x16);
  911. case IR::Opcode::UnpackFloat2x16:
  912. return FoldInverseFunc(inst, IR::Opcode::PackFloat2x16);
  913. case IR::Opcode::SelectU1:
  914. case IR::Opcode::SelectU8:
  915. case IR::Opcode::SelectU16:
  916. case IR::Opcode::SelectU32:
  917. case IR::Opcode::SelectU64:
  918. case IR::Opcode::SelectF16:
  919. case IR::Opcode::SelectF32:
  920. case IR::Opcode::SelectF64:
  921. return FoldSelect(inst);
  922. case IR::Opcode::FPNeg32:
  923. FoldWhenAllImmediates(inst, [](f32 a) { return -a; });
  924. return;
  925. case IR::Opcode::FPAdd32:
  926. FoldFPAdd32(inst);
  927. return;
  928. case IR::Opcode::FPMul32:
  929. return FoldFPMul32(inst);
  930. case IR::Opcode::LogicalAnd:
  931. return FoldLogicalAnd(inst);
  932. case IR::Opcode::LogicalOr:
  933. return FoldLogicalOr(inst);
  934. case IR::Opcode::LogicalNot:
  935. return FoldLogicalNot(inst);
  936. case IR::Opcode::SLessThan:
  937. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a < b; });
  938. return;
  939. case IR::Opcode::ULessThan:
  940. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a < b; });
  941. return;
  942. case IR::Opcode::SLessThanEqual:
  943. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a <= b; });
  944. return;
  945. case IR::Opcode::ULessThanEqual:
  946. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a <= b; });
  947. return;
  948. case IR::Opcode::SGreaterThan:
  949. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a > b; });
  950. return;
  951. case IR::Opcode::UGreaterThan:
  952. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a > b; });
  953. return;
  954. case IR::Opcode::SGreaterThanEqual:
  955. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a >= b; });
  956. return;
  957. case IR::Opcode::UGreaterThanEqual:
  958. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a >= b; });
  959. return;
  960. case IR::Opcode::IEqual:
  961. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a == b; });
  962. return;
  963. case IR::Opcode::INotEqual:
  964. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a != b; });
  965. return;
  966. case IR::Opcode::BitwiseAnd32:
  967. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a & b; });
  968. return;
  969. case IR::Opcode::BitwiseOr32:
  970. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a | b; });
  971. return;
  972. case IR::Opcode::BitwiseXor32:
  973. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a ^ b; });
  974. return;
  975. case IR::Opcode::BitFieldUExtract:
  976. FoldWhenAllImmediates(inst, [](u32 base, u32 shift, u32 count) {
  977. if (static_cast<size_t>(shift) + static_cast<size_t>(count) > 32) {
  978. throw LogicError("Undefined result in {}({}, {}, {})", IR::Opcode::BitFieldUExtract,
  979. base, shift, count);
  980. }
  981. return (base >> shift) & ((1U << count) - 1);
  982. });
  983. return;
  984. case IR::Opcode::BitFieldSExtract:
  985. FoldWhenAllImmediates(inst, [](s32 base, u32 shift, u32 count) {
  986. const size_t back_shift{static_cast<size_t>(shift) + static_cast<size_t>(count)};
  987. const size_t left_shift{32 - back_shift};
  988. const size_t right_shift{static_cast<size_t>(32 - count)};
  989. if (back_shift > 32 || left_shift >= 32 || right_shift >= 32) {
  990. throw LogicError("Undefined result in {}({}, {}, {})", IR::Opcode::BitFieldSExtract,
  991. base, shift, count);
  992. }
  993. return static_cast<u32>((base << left_shift) >> right_shift);
  994. });
  995. return;
  996. case IR::Opcode::BitFieldInsert:
  997. FoldWhenAllImmediates(inst, [](u32 base, u32 insert, u32 offset, u32 bits) {
  998. if (bits >= 32 || offset >= 32) {
  999. throw LogicError("Undefined result in {}({}, {}, {}, {})",
  1000. IR::Opcode::BitFieldInsert, base, insert, offset, bits);
  1001. }
  1002. return (base & ~(~(~0u << bits) << offset)) | (insert << offset);
  1003. });
  1004. return;
  1005. case IR::Opcode::CompositeExtractU32x2:
  1006. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructU32x2,
  1007. IR::Opcode::CompositeInsertU32x2);
  1008. case IR::Opcode::CompositeExtractU32x3:
  1009. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructU32x3,
  1010. IR::Opcode::CompositeInsertU32x3);
  1011. case IR::Opcode::CompositeExtractU32x4:
  1012. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructU32x4,
  1013. IR::Opcode::CompositeInsertU32x4);
  1014. case IR::Opcode::CompositeExtractF32x2:
  1015. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF32x2,
  1016. IR::Opcode::CompositeInsertF32x2);
  1017. case IR::Opcode::CompositeExtractF32x3:
  1018. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF32x3,
  1019. IR::Opcode::CompositeInsertF32x3);
  1020. case IR::Opcode::CompositeExtractF32x4:
  1021. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF32x4,
  1022. IR::Opcode::CompositeInsertF32x4);
  1023. case IR::Opcode::CompositeExtractF16x2:
  1024. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF16x2,
  1025. IR::Opcode::CompositeInsertF16x2);
  1026. case IR::Opcode::CompositeExtractF16x3:
  1027. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF16x3,
  1028. IR::Opcode::CompositeInsertF16x3);
  1029. case IR::Opcode::CompositeExtractF16x4:
  1030. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF16x4,
  1031. IR::Opcode::CompositeInsertF16x4);
  1032. case IR::Opcode::FSwizzleAdd:
  1033. return FoldFSwizzleAdd(block, inst);
  1034. case IR::Opcode::GetCbufF32:
  1035. case IR::Opcode::GetCbufU32:
  1036. if (env.HasHLEMacroState()) {
  1037. FoldConstBuffer(env, block, inst);
  1038. }
  1039. if (env.IsPropietaryDriver()) {
  1040. FoldDriverConstBuffer(env, block, inst, 1);
  1041. }
  1042. break;
  1043. case IR::Opcode::BindlessImageSampleImplicitLod:
  1044. case IR::Opcode::BoundImageSampleImplicitLod:
  1045. case IR::Opcode::ImageSampleImplicitLod:
  1046. FoldImageSampleImplicitLod(block, inst);
  1047. break;
  1048. default:
  1049. break;
  1050. }
  1051. }
  1052. } // Anonymous namespace
  1053. void ConstantPropagationPass(Environment& env, IR::Program& program) {
  1054. const auto end{program.post_order_blocks.rend()};
  1055. for (auto it = program.post_order_blocks.rbegin(); it != end; ++it) {
  1056. IR::Block* const block{*it};
  1057. for (IR::Inst& inst : block->Instructions()) {
  1058. ConstantPropagation(env, *block, inst);
  1059. }
  1060. }
  1061. }
  1062. } // namespace Shader::Optimization