ssa_rewrite_pass.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. // This file implements the SSA rewriting algorithm proposed in
  5. //
  6. // Simple and Efficient Construction of Static Single Assignment Form.
  7. // Braun M., Buchwald S., Hack S., Leiba R., Mallon C., Zwinkau A. (2013)
  8. // In: Jhala R., De Bosschere K. (eds)
  9. // Compiler Construction. CC 2013.
  10. // Lecture Notes in Computer Science, vol 7791.
  11. // Springer, Berlin, Heidelberg
  12. //
  13. // https://link.springer.com/chapter/10.1007/978-3-642-37051-9_6
  14. //
  15. #include <ranges>
  16. #include <span>
  17. #include <variant>
  18. #include <vector>
  19. #include <boost/container/flat_map.hpp>
  20. #include <boost/container/flat_set.hpp>
  21. #include "shader_recompiler/frontend/ir/basic_block.h"
  22. #include "shader_recompiler/frontend/ir/opcodes.h"
  23. #include "shader_recompiler/frontend/ir/pred.h"
  24. #include "shader_recompiler/frontend/ir/reg.h"
  25. #include "shader_recompiler/frontend/ir/value.h"
  26. #include "shader_recompiler/ir_opt/passes.h"
  27. namespace Shader::Optimization {
  28. namespace {
  29. struct FlagTag {
  30. auto operator<=>(const FlagTag&) const noexcept = default;
  31. };
  32. struct ZeroFlagTag : FlagTag {};
  33. struct SignFlagTag : FlagTag {};
  34. struct CarryFlagTag : FlagTag {};
  35. struct OverflowFlagTag : FlagTag {};
  36. struct GotoVariable : FlagTag {
  37. GotoVariable() = default;
  38. explicit GotoVariable(u32 index_) : index{index_} {}
  39. auto operator<=>(const GotoVariable&) const noexcept = default;
  40. u32 index;
  41. };
  42. struct IndirectBranchVariable {
  43. auto operator<=>(const IndirectBranchVariable&) const noexcept = default;
  44. };
  45. using Variant = std::variant<IR::Reg, IR::Pred, ZeroFlagTag, SignFlagTag, CarryFlagTag,
  46. OverflowFlagTag, GotoVariable, IndirectBranchVariable>;
  47. using ValueMap = boost::container::flat_map<IR::Block*, IR::Value>;
  48. struct DefTable {
  49. const IR::Value& Def(IR::Block* block, IR::Reg variable) {
  50. return block->SsaRegValue(variable);
  51. }
  52. void SetDef(IR::Block* block, IR::Reg variable, const IR::Value& value) {
  53. block->SetSsaRegValue(variable, value);
  54. }
  55. const IR::Value& Def(IR::Block* block, IR::Pred variable) {
  56. return preds[IR::PredIndex(variable)][block];
  57. }
  58. void SetDef(IR::Block* block, IR::Pred variable, const IR::Value& value) {
  59. preds[IR::PredIndex(variable)].insert_or_assign(block, value);
  60. }
  61. const IR::Value& Def(IR::Block* block, GotoVariable variable) {
  62. return goto_vars[variable.index][block];
  63. }
  64. void SetDef(IR::Block* block, GotoVariable variable, const IR::Value& value) {
  65. goto_vars[variable.index].insert_or_assign(block, value);
  66. }
  67. const IR::Value& Def(IR::Block* block, IndirectBranchVariable) {
  68. return indirect_branch_var[block];
  69. }
  70. void SetDef(IR::Block* block, IndirectBranchVariable, const IR::Value& value) {
  71. indirect_branch_var.insert_or_assign(block, value);
  72. }
  73. const IR::Value& Def(IR::Block* block, ZeroFlagTag) {
  74. return zero_flag[block];
  75. }
  76. void SetDef(IR::Block* block, ZeroFlagTag, const IR::Value& value) {
  77. zero_flag.insert_or_assign(block, value);
  78. }
  79. const IR::Value& Def(IR::Block* block, SignFlagTag) {
  80. return sign_flag[block];
  81. }
  82. void SetDef(IR::Block* block, SignFlagTag, const IR::Value& value) {
  83. sign_flag.insert_or_assign(block, value);
  84. }
  85. const IR::Value& Def(IR::Block* block, CarryFlagTag) {
  86. return carry_flag[block];
  87. }
  88. void SetDef(IR::Block* block, CarryFlagTag, const IR::Value& value) {
  89. carry_flag.insert_or_assign(block, value);
  90. }
  91. const IR::Value& Def(IR::Block* block, OverflowFlagTag) {
  92. return overflow_flag[block];
  93. }
  94. void SetDef(IR::Block* block, OverflowFlagTag, const IR::Value& value) {
  95. overflow_flag.insert_or_assign(block, value);
  96. }
  97. std::array<ValueMap, IR::NUM_USER_PREDS> preds;
  98. boost::container::flat_map<u32, ValueMap> goto_vars;
  99. ValueMap indirect_branch_var;
  100. ValueMap zero_flag;
  101. ValueMap sign_flag;
  102. ValueMap carry_flag;
  103. ValueMap overflow_flag;
  104. };
  105. IR::Opcode UndefOpcode(IR::Reg) noexcept {
  106. return IR::Opcode::UndefU32;
  107. }
  108. IR::Opcode UndefOpcode(IR::Pred) noexcept {
  109. return IR::Opcode::UndefU1;
  110. }
  111. IR::Opcode UndefOpcode(const FlagTag&) noexcept {
  112. return IR::Opcode::UndefU1;
  113. }
  114. IR::Opcode UndefOpcode(IndirectBranchVariable) noexcept {
  115. return IR::Opcode::UndefU32;
  116. }
  117. enum class Status {
  118. Start,
  119. SetValue,
  120. PreparePhiArgument,
  121. PushPhiArgument,
  122. };
  123. template <typename Type>
  124. struct ReadState {
  125. ReadState(IR::Block* block_) : block{block_} {}
  126. ReadState() = default;
  127. IR::Block* block{};
  128. IR::Value result{};
  129. IR::Inst* phi{};
  130. IR::Block* const* pred_it{};
  131. IR::Block* const* pred_end{};
  132. Status pc{Status::Start};
  133. };
  134. class Pass {
  135. public:
  136. template <typename Type>
  137. void WriteVariable(Type variable, IR::Block* block, const IR::Value& value) {
  138. current_def.SetDef(block, variable, value);
  139. }
  140. template <typename Type>
  141. IR::Value ReadVariable(Type variable, IR::Block* root_block) {
  142. boost::container::small_vector<ReadState<Type>, 64> stack{
  143. ReadState<Type>(nullptr),
  144. ReadState<Type>(root_block),
  145. };
  146. const auto prepare_phi_operand{[&] {
  147. if (stack.back().pred_it == stack.back().pred_end) {
  148. IR::Inst* const phi{stack.back().phi};
  149. IR::Block* const block{stack.back().block};
  150. const IR::Value result{TryRemoveTrivialPhi(*phi, block, UndefOpcode(variable))};
  151. stack.pop_back();
  152. stack.back().result = result;
  153. WriteVariable(variable, block, result);
  154. } else {
  155. IR::Block* const imm_pred{*stack.back().pred_it};
  156. stack.back().pc = Status::PushPhiArgument;
  157. stack.emplace_back(imm_pred);
  158. }
  159. }};
  160. do {
  161. IR::Block* const block{stack.back().block};
  162. switch (stack.back().pc) {
  163. case Status::Start: {
  164. if (const IR::Value& def = current_def.Def(block, variable); !def.IsEmpty()) {
  165. stack.back().result = def;
  166. } else if (!block->IsSsaSealed()) {
  167. // Incomplete CFG
  168. IR::Inst* phi{&*block->PrependNewInst(block->begin(), IR::Opcode::Phi)};
  169. phi->SetFlags(IR::TypeOf(UndefOpcode(variable)));
  170. incomplete_phis[block].insert_or_assign(variable, phi);
  171. stack.back().result = IR::Value{&*phi};
  172. } else if (const std::span imm_preds = block->ImmPredecessors();
  173. imm_preds.size() == 1) {
  174. // Optimize the common case of one predecessor: no phi needed
  175. stack.back().pc = Status::SetValue;
  176. stack.emplace_back(imm_preds.front());
  177. break;
  178. } else {
  179. // Break potential cycles with operandless phi
  180. IR::Inst* const phi{&*block->PrependNewInst(block->begin(), IR::Opcode::Phi)};
  181. phi->SetFlags(IR::TypeOf(UndefOpcode(variable)));
  182. WriteVariable(variable, block, IR::Value{phi});
  183. stack.back().phi = phi;
  184. stack.back().pred_it = imm_preds.data();
  185. stack.back().pred_end = imm_preds.data() + imm_preds.size();
  186. prepare_phi_operand();
  187. break;
  188. }
  189. }
  190. [[fallthrough]];
  191. case Status::SetValue: {
  192. const IR::Value result{stack.back().result};
  193. WriteVariable(variable, block, result);
  194. stack.pop_back();
  195. stack.back().result = result;
  196. break;
  197. }
  198. case Status::PushPhiArgument: {
  199. IR::Inst* const phi{stack.back().phi};
  200. phi->AddPhiOperand(*stack.back().pred_it, stack.back().result);
  201. ++stack.back().pred_it;
  202. }
  203. [[fallthrough]];
  204. case Status::PreparePhiArgument:
  205. prepare_phi_operand();
  206. break;
  207. }
  208. } while (stack.size() > 1);
  209. return stack.back().result;
  210. }
  211. void SealBlock(IR::Block* block) {
  212. const auto it{incomplete_phis.find(block)};
  213. if (it != incomplete_phis.end()) {
  214. for (auto& [variant, phi] : it->second) {
  215. std::visit([&](auto& variable) { AddPhiOperands(variable, *phi, block); }, variant);
  216. }
  217. }
  218. block->SsaSeal();
  219. }
  220. private:
  221. template <typename Type>
  222. IR::Value AddPhiOperands(Type variable, IR::Inst& phi, IR::Block* block) {
  223. for (IR::Block* const imm_pred : block->ImmPredecessors()) {
  224. phi.AddPhiOperand(imm_pred, ReadVariable(variable, imm_pred));
  225. }
  226. return TryRemoveTrivialPhi(phi, block, UndefOpcode(variable));
  227. }
  228. IR::Value TryRemoveTrivialPhi(IR::Inst& phi, IR::Block* block, IR::Opcode undef_opcode) {
  229. IR::Value same;
  230. const size_t num_args{phi.NumArgs()};
  231. for (size_t arg_index = 0; arg_index < num_args; ++arg_index) {
  232. const IR::Value& op{phi.Arg(arg_index)};
  233. if (op.Resolve() == same.Resolve() || op == IR::Value{&phi}) {
  234. // Unique value or self-reference
  235. continue;
  236. }
  237. if (!same.IsEmpty()) {
  238. // The phi merges at least two values: not trivial
  239. return IR::Value{&phi};
  240. }
  241. same = op;
  242. }
  243. // Remove the phi node from the block, it will be reinserted
  244. IR::Block::InstructionList& list{block->Instructions()};
  245. list.erase(IR::Block::InstructionList::s_iterator_to(phi));
  246. // Find the first non-phi instruction and use it as an insertion point
  247. IR::Block::iterator reinsert_point{std::ranges::find_if_not(list, IR::IsPhi)};
  248. if (same.IsEmpty()) {
  249. // The phi is unreachable or in the start block
  250. // Insert an undefined instruction and make it the phi node replacement
  251. // The "phi" node reinsertion point is specified after this instruction
  252. reinsert_point = block->PrependNewInst(reinsert_point, undef_opcode);
  253. same = IR::Value{&*reinsert_point};
  254. ++reinsert_point;
  255. }
  256. // Reinsert the phi node and reroute all its uses to the "same" value
  257. list.insert(reinsert_point, phi);
  258. phi.ReplaceUsesWith(same);
  259. // TODO: Try to recursively remove all phi users, which might have become trivial
  260. return same;
  261. }
  262. boost::container::flat_map<IR::Block*, boost::container::flat_map<Variant, IR::Inst*>>
  263. incomplete_phis;
  264. DefTable current_def;
  265. };
  266. void VisitInst(Pass& pass, IR::Block* block, IR::Inst& inst) {
  267. switch (inst.GetOpcode()) {
  268. case IR::Opcode::SetRegister:
  269. if (const IR::Reg reg{inst.Arg(0).Reg()}; reg != IR::Reg::RZ) {
  270. pass.WriteVariable(reg, block, inst.Arg(1));
  271. }
  272. break;
  273. case IR::Opcode::SetPred:
  274. if (const IR::Pred pred{inst.Arg(0).Pred()}; pred != IR::Pred::PT) {
  275. pass.WriteVariable(pred, block, inst.Arg(1));
  276. }
  277. break;
  278. case IR::Opcode::SetGotoVariable:
  279. pass.WriteVariable(GotoVariable{inst.Arg(0).U32()}, block, inst.Arg(1));
  280. break;
  281. case IR::Opcode::SetIndirectBranchVariable:
  282. pass.WriteVariable(IndirectBranchVariable{}, block, inst.Arg(0));
  283. break;
  284. case IR::Opcode::SetZFlag:
  285. pass.WriteVariable(ZeroFlagTag{}, block, inst.Arg(0));
  286. break;
  287. case IR::Opcode::SetSFlag:
  288. pass.WriteVariable(SignFlagTag{}, block, inst.Arg(0));
  289. break;
  290. case IR::Opcode::SetCFlag:
  291. pass.WriteVariable(CarryFlagTag{}, block, inst.Arg(0));
  292. break;
  293. case IR::Opcode::SetOFlag:
  294. pass.WriteVariable(OverflowFlagTag{}, block, inst.Arg(0));
  295. break;
  296. case IR::Opcode::GetRegister:
  297. if (const IR::Reg reg{inst.Arg(0).Reg()}; reg != IR::Reg::RZ) {
  298. inst.ReplaceUsesWith(pass.ReadVariable(reg, block));
  299. }
  300. break;
  301. case IR::Opcode::GetPred:
  302. if (const IR::Pred pred{inst.Arg(0).Pred()}; pred != IR::Pred::PT) {
  303. inst.ReplaceUsesWith(pass.ReadVariable(pred, block));
  304. }
  305. break;
  306. case IR::Opcode::GetGotoVariable:
  307. inst.ReplaceUsesWith(pass.ReadVariable(GotoVariable{inst.Arg(0).U32()}, block));
  308. break;
  309. case IR::Opcode::GetIndirectBranchVariable:
  310. inst.ReplaceUsesWith(pass.ReadVariable(IndirectBranchVariable{}, block));
  311. break;
  312. case IR::Opcode::GetZFlag:
  313. inst.ReplaceUsesWith(pass.ReadVariable(ZeroFlagTag{}, block));
  314. break;
  315. case IR::Opcode::GetSFlag:
  316. inst.ReplaceUsesWith(pass.ReadVariable(SignFlagTag{}, block));
  317. break;
  318. case IR::Opcode::GetCFlag:
  319. inst.ReplaceUsesWith(pass.ReadVariable(CarryFlagTag{}, block));
  320. break;
  321. case IR::Opcode::GetOFlag:
  322. inst.ReplaceUsesWith(pass.ReadVariable(OverflowFlagTag{}, block));
  323. break;
  324. default:
  325. break;
  326. }
  327. }
  328. void VisitBlock(Pass& pass, IR::Block* block) {
  329. for (IR::Inst& inst : block->Instructions()) {
  330. VisitInst(pass, block, inst);
  331. }
  332. pass.SealBlock(block);
  333. }
  334. } // Anonymous namespace
  335. void SsaRewritePass(IR::Program& program) {
  336. Pass pass;
  337. for (IR::Block* const block : program.post_order_blocks | std::views::reverse) {
  338. VisitBlock(pass, block);
  339. }
  340. }
  341. } // namespace Shader::Optimization