constant_propagation_pass.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <functional>
  6. #include <tuple>
  7. #include <type_traits>
  8. #include "common/bit_cast.h"
  9. #include "common/bit_util.h"
  10. #include "shader_recompiler/exception.h"
  11. #include "shader_recompiler/frontend/ir/ir_emitter.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 FoldFPMul32(IR::Inst& inst) {
  396. const auto control{inst.Flags<IR::FpControl>()};
  397. if (control.no_contraction) {
  398. return;
  399. }
  400. // Fold interpolation operations
  401. const IR::Value lhs_value{inst.Arg(0)};
  402. const IR::Value rhs_value{inst.Arg(1)};
  403. if (lhs_value.IsImmediate() || rhs_value.IsImmediate()) {
  404. return;
  405. }
  406. IR::Inst* const lhs_op{lhs_value.InstRecursive()};
  407. IR::Inst* const rhs_op{rhs_value.InstRecursive()};
  408. if (lhs_op->GetOpcode() != IR::Opcode::FPMul32 ||
  409. rhs_op->GetOpcode() != IR::Opcode::FPRecip32) {
  410. return;
  411. }
  412. const IR::Value recip_source{rhs_op->Arg(0)};
  413. const IR::Value lhs_mul_source{lhs_op->Arg(1).Resolve()};
  414. if (recip_source.IsImmediate() || lhs_mul_source.IsImmediate()) {
  415. return;
  416. }
  417. IR::Inst* const attr_a{recip_source.InstRecursive()};
  418. IR::Inst* const attr_b{lhs_mul_source.InstRecursive()};
  419. if (attr_a->GetOpcode() != IR::Opcode::GetAttribute ||
  420. attr_b->GetOpcode() != IR::Opcode::GetAttribute) {
  421. return;
  422. }
  423. if (attr_a->Arg(0).Attribute() == attr_b->Arg(0).Attribute()) {
  424. inst.ReplaceUsesWith(lhs_op->Arg(0));
  425. }
  426. }
  427. void FoldLogicalAnd(IR::Inst& inst) {
  428. if (!FoldCommutative<bool>(inst, [](bool a, bool b) { return a && b; })) {
  429. return;
  430. }
  431. const IR::Value rhs{inst.Arg(1)};
  432. if (rhs.IsImmediate()) {
  433. if (rhs.U1()) {
  434. inst.ReplaceUsesWith(inst.Arg(0));
  435. } else {
  436. inst.ReplaceUsesWith(IR::Value{false});
  437. }
  438. }
  439. }
  440. void FoldLogicalOr(IR::Inst& inst) {
  441. if (!FoldCommutative<bool>(inst, [](bool a, bool b) { return a || b; })) {
  442. return;
  443. }
  444. const IR::Value rhs{inst.Arg(1)};
  445. if (rhs.IsImmediate()) {
  446. if (rhs.U1()) {
  447. inst.ReplaceUsesWith(IR::Value{true});
  448. } else {
  449. inst.ReplaceUsesWith(inst.Arg(0));
  450. }
  451. }
  452. }
  453. void FoldLogicalNot(IR::Inst& inst) {
  454. const IR::U1 value{inst.Arg(0)};
  455. if (value.IsImmediate()) {
  456. inst.ReplaceUsesWith(IR::Value{!value.U1()});
  457. return;
  458. }
  459. IR::Inst* const arg{value.InstRecursive()};
  460. if (arg->GetOpcode() == IR::Opcode::LogicalNot) {
  461. inst.ReplaceUsesWith(arg->Arg(0));
  462. }
  463. }
  464. template <IR::Opcode op, typename Dest, typename Source>
  465. void FoldBitCast(IR::Inst& inst, IR::Opcode reverse) {
  466. const IR::Value value{inst.Arg(0)};
  467. if (value.IsImmediate()) {
  468. inst.ReplaceUsesWith(IR::Value{Common::BitCast<Dest>(Arg<Source>(value))});
  469. return;
  470. }
  471. IR::Inst* const arg_inst{value.InstRecursive()};
  472. if (arg_inst->GetOpcode() == reverse) {
  473. inst.ReplaceUsesWith(arg_inst->Arg(0));
  474. return;
  475. }
  476. if constexpr (op == IR::Opcode::BitCastF32U32) {
  477. if (arg_inst->GetOpcode() == IR::Opcode::GetCbufU32) {
  478. // Replace the bitcast with a typed constant buffer read
  479. inst.ReplaceOpcode(IR::Opcode::GetCbufF32);
  480. inst.SetArg(0, arg_inst->Arg(0));
  481. inst.SetArg(1, arg_inst->Arg(1));
  482. return;
  483. }
  484. }
  485. }
  486. void FoldInverseFunc(IR::Inst& inst, IR::Opcode reverse) {
  487. const IR::Value value{inst.Arg(0)};
  488. if (value.IsImmediate()) {
  489. return;
  490. }
  491. IR::Inst* const arg_inst{value.InstRecursive()};
  492. if (arg_inst->GetOpcode() == reverse) {
  493. inst.ReplaceUsesWith(arg_inst->Arg(0));
  494. return;
  495. }
  496. }
  497. template <typename Func, size_t... I>
  498. IR::Value EvalImmediates(const IR::Inst& inst, Func&& func, std::index_sequence<I...>) {
  499. using Traits = LambdaTraits<decltype(func)>;
  500. return IR::Value{func(Arg<typename Traits::template ArgType<I>>(inst.Arg(I))...)};
  501. }
  502. std::optional<IR::Value> FoldCompositeExtractImpl(IR::Value inst_value, IR::Opcode insert,
  503. IR::Opcode construct, u32 first_index) {
  504. IR::Inst* const inst{inst_value.InstRecursive()};
  505. if (inst->GetOpcode() == construct) {
  506. return inst->Arg(first_index);
  507. }
  508. if (inst->GetOpcode() != insert) {
  509. return std::nullopt;
  510. }
  511. IR::Value value_index{inst->Arg(2)};
  512. if (!value_index.IsImmediate()) {
  513. return std::nullopt;
  514. }
  515. const u32 second_index{value_index.U32()};
  516. if (first_index != second_index) {
  517. IR::Value value_composite{inst->Arg(0)};
  518. if (value_composite.IsImmediate()) {
  519. return std::nullopt;
  520. }
  521. return FoldCompositeExtractImpl(value_composite, insert, construct, first_index);
  522. }
  523. return inst->Arg(1);
  524. }
  525. void FoldCompositeExtract(IR::Inst& inst, IR::Opcode construct, IR::Opcode insert) {
  526. const IR::Value value_1{inst.Arg(0)};
  527. const IR::Value value_2{inst.Arg(1)};
  528. if (value_1.IsImmediate()) {
  529. return;
  530. }
  531. if (!value_2.IsImmediate()) {
  532. return;
  533. }
  534. const u32 first_index{value_2.U32()};
  535. const std::optional result{FoldCompositeExtractImpl(value_1, insert, construct, first_index)};
  536. if (!result) {
  537. return;
  538. }
  539. inst.ReplaceUsesWith(*result);
  540. }
  541. IR::Value GetThroughCast(IR::Value value, IR::Opcode expected_cast) {
  542. if (value.IsImmediate()) {
  543. return value;
  544. }
  545. IR::Inst* const inst{value.InstRecursive()};
  546. if (inst->GetOpcode() == expected_cast) {
  547. return inst->Arg(0).Resolve();
  548. }
  549. return value;
  550. }
  551. void FoldFSwizzleAdd(IR::Block& block, IR::Inst& inst) {
  552. const IR::Value swizzle{inst.Arg(2)};
  553. if (!swizzle.IsImmediate()) {
  554. return;
  555. }
  556. const IR::Value value_1{GetThroughCast(inst.Arg(0).Resolve(), IR::Opcode::BitCastF32U32)};
  557. const IR::Value value_2{GetThroughCast(inst.Arg(1).Resolve(), IR::Opcode::BitCastF32U32)};
  558. if (value_1.IsImmediate()) {
  559. return;
  560. }
  561. const u32 swizzle_value{swizzle.U32()};
  562. if (swizzle_value != 0x99 && swizzle_value != 0xA5) {
  563. return;
  564. }
  565. IR::Inst* const inst2{value_1.InstRecursive()};
  566. if (inst2->GetOpcode() != IR::Opcode::ShuffleButterfly) {
  567. return;
  568. }
  569. const IR::Value value_3{GetThroughCast(inst2->Arg(0).Resolve(), IR::Opcode::BitCastU32F32)};
  570. if (value_2 != value_3) {
  571. return;
  572. }
  573. const IR::Value index{inst2->Arg(1)};
  574. const IR::Value clamp{inst2->Arg(2)};
  575. const IR::Value segmentation_mask{inst2->Arg(3)};
  576. if (!index.IsImmediate() || !clamp.IsImmediate() || !segmentation_mask.IsImmediate()) {
  577. return;
  578. }
  579. if (clamp.U32() != 3 || segmentation_mask.U32() != 28) {
  580. return;
  581. }
  582. if (swizzle_value == 0x99) {
  583. // DPdxFine
  584. if (index.U32() == 1) {
  585. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  586. inst.ReplaceUsesWith(ir.DPdxFine(IR::F32{inst.Arg(1)}));
  587. }
  588. } else if (swizzle_value == 0xA5) {
  589. // DPdyFine
  590. if (index.U32() == 2) {
  591. IR::IREmitter ir{block, IR::Block::InstructionList::s_iterator_to(inst)};
  592. inst.ReplaceUsesWith(ir.DPdyFine(IR::F32{inst.Arg(1)}));
  593. }
  594. }
  595. }
  596. void ConstantPropagation(IR::Block& block, IR::Inst& inst) {
  597. switch (inst.GetOpcode()) {
  598. case IR::Opcode::GetRegister:
  599. return FoldGetRegister(inst);
  600. case IR::Opcode::GetPred:
  601. return FoldGetPred(inst);
  602. case IR::Opcode::IAdd32:
  603. return FoldAdd<u32>(block, inst);
  604. case IR::Opcode::ISub32:
  605. return FoldISub32(inst);
  606. case IR::Opcode::IMul32:
  607. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a * b; });
  608. return;
  609. case IR::Opcode::ShiftRightArithmetic32:
  610. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return static_cast<u32>(a >> b); });
  611. return;
  612. case IR::Opcode::BitCastF32U32:
  613. return FoldBitCast<IR::Opcode::BitCastF32U32, f32, u32>(inst, IR::Opcode::BitCastU32F32);
  614. case IR::Opcode::BitCastU32F32:
  615. return FoldBitCast<IR::Opcode::BitCastU32F32, u32, f32>(inst, IR::Opcode::BitCastF32U32);
  616. case IR::Opcode::IAdd64:
  617. return FoldAdd<u64>(block, inst);
  618. case IR::Opcode::PackHalf2x16:
  619. return FoldInverseFunc(inst, IR::Opcode::UnpackHalf2x16);
  620. case IR::Opcode::UnpackHalf2x16:
  621. return FoldInverseFunc(inst, IR::Opcode::PackHalf2x16);
  622. case IR::Opcode::PackFloat2x16:
  623. return FoldInverseFunc(inst, IR::Opcode::UnpackFloat2x16);
  624. case IR::Opcode::UnpackFloat2x16:
  625. return FoldInverseFunc(inst, IR::Opcode::PackFloat2x16);
  626. case IR::Opcode::SelectU1:
  627. case IR::Opcode::SelectU8:
  628. case IR::Opcode::SelectU16:
  629. case IR::Opcode::SelectU32:
  630. case IR::Opcode::SelectU64:
  631. case IR::Opcode::SelectF16:
  632. case IR::Opcode::SelectF32:
  633. case IR::Opcode::SelectF64:
  634. return FoldSelect(inst);
  635. case IR::Opcode::FPMul32:
  636. return FoldFPMul32(inst);
  637. case IR::Opcode::LogicalAnd:
  638. return FoldLogicalAnd(inst);
  639. case IR::Opcode::LogicalOr:
  640. return FoldLogicalOr(inst);
  641. case IR::Opcode::LogicalNot:
  642. return FoldLogicalNot(inst);
  643. case IR::Opcode::SLessThan:
  644. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a < b; });
  645. return;
  646. case IR::Opcode::ULessThan:
  647. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a < b; });
  648. return;
  649. case IR::Opcode::SLessThanEqual:
  650. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a <= b; });
  651. return;
  652. case IR::Opcode::ULessThanEqual:
  653. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a <= b; });
  654. return;
  655. case IR::Opcode::SGreaterThan:
  656. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a > b; });
  657. return;
  658. case IR::Opcode::UGreaterThan:
  659. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a > b; });
  660. return;
  661. case IR::Opcode::SGreaterThanEqual:
  662. FoldWhenAllImmediates(inst, [](s32 a, s32 b) { return a >= b; });
  663. return;
  664. case IR::Opcode::UGreaterThanEqual:
  665. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a >= b; });
  666. return;
  667. case IR::Opcode::IEqual:
  668. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a == b; });
  669. return;
  670. case IR::Opcode::INotEqual:
  671. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a != b; });
  672. return;
  673. case IR::Opcode::BitwiseAnd32:
  674. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a & b; });
  675. return;
  676. case IR::Opcode::BitwiseOr32:
  677. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a | b; });
  678. return;
  679. case IR::Opcode::BitwiseXor32:
  680. FoldWhenAllImmediates(inst, [](u32 a, u32 b) { return a ^ b; });
  681. return;
  682. case IR::Opcode::BitFieldUExtract:
  683. FoldWhenAllImmediates(inst, [](u32 base, u32 shift, u32 count) {
  684. if (static_cast<size_t>(shift) + static_cast<size_t>(count) > 32) {
  685. throw LogicError("Undefined result in {}({}, {}, {})", IR::Opcode::BitFieldUExtract,
  686. base, shift, count);
  687. }
  688. return (base >> shift) & ((1U << count) - 1);
  689. });
  690. return;
  691. case IR::Opcode::BitFieldSExtract:
  692. FoldWhenAllImmediates(inst, [](s32 base, u32 shift, u32 count) {
  693. const size_t back_shift{static_cast<size_t>(shift) + static_cast<size_t>(count)};
  694. const size_t left_shift{32 - back_shift};
  695. const size_t right_shift{static_cast<size_t>(32 - count)};
  696. if (back_shift > 32 || left_shift >= 32 || right_shift >= 32) {
  697. throw LogicError("Undefined result in {}({}, {}, {})", IR::Opcode::BitFieldSExtract,
  698. base, shift, count);
  699. }
  700. return static_cast<u32>((base << left_shift) >> right_shift);
  701. });
  702. return;
  703. case IR::Opcode::BitFieldInsert:
  704. FoldWhenAllImmediates(inst, [](u32 base, u32 insert, u32 offset, u32 bits) {
  705. if (bits >= 32 || offset >= 32) {
  706. throw LogicError("Undefined result in {}({}, {}, {}, {})",
  707. IR::Opcode::BitFieldInsert, base, insert, offset, bits);
  708. }
  709. return (base & ~(~(~0u << bits) << offset)) | (insert << offset);
  710. });
  711. return;
  712. case IR::Opcode::CompositeExtractU32x2:
  713. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructU32x2,
  714. IR::Opcode::CompositeInsertU32x2);
  715. case IR::Opcode::CompositeExtractU32x3:
  716. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructU32x3,
  717. IR::Opcode::CompositeInsertU32x3);
  718. case IR::Opcode::CompositeExtractU32x4:
  719. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructU32x4,
  720. IR::Opcode::CompositeInsertU32x4);
  721. case IR::Opcode::CompositeExtractF32x2:
  722. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF32x2,
  723. IR::Opcode::CompositeInsertF32x2);
  724. case IR::Opcode::CompositeExtractF32x3:
  725. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF32x3,
  726. IR::Opcode::CompositeInsertF32x3);
  727. case IR::Opcode::CompositeExtractF32x4:
  728. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF32x4,
  729. IR::Opcode::CompositeInsertF32x4);
  730. case IR::Opcode::CompositeExtractF16x2:
  731. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF16x2,
  732. IR::Opcode::CompositeInsertF16x2);
  733. case IR::Opcode::CompositeExtractF16x3:
  734. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF16x3,
  735. IR::Opcode::CompositeInsertF16x3);
  736. case IR::Opcode::CompositeExtractF16x4:
  737. return FoldCompositeExtract(inst, IR::Opcode::CompositeConstructF16x4,
  738. IR::Opcode::CompositeInsertF16x4);
  739. case IR::Opcode::FSwizzleAdd:
  740. return FoldFSwizzleAdd(block, inst);
  741. default:
  742. break;
  743. }
  744. }
  745. } // Anonymous namespace
  746. void ConstantPropagationPass(IR::Program& program) {
  747. const auto end{program.post_order_blocks.rend()};
  748. for (auto it = program.post_order_blocks.rbegin(); it != end; ++it) {
  749. IR::Block* const block{*it};
  750. for (IR::Inst& inst : block->Instructions()) {
  751. ConstantPropagation(*block, inst);
  752. }
  753. }
  754. }
  755. } // namespace Shader::Optimization