structured_control_flow.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <memory>
  5. #include <string>
  6. #include <unordered_map>
  7. #include <utility>
  8. #include <vector>
  9. #include <fmt/format.h>
  10. #include <boost/intrusive/list.hpp>
  11. #include "common/polyfill_ranges.h"
  12. #include "shader_recompiler/environment.h"
  13. #include "shader_recompiler/frontend/ir/basic_block.h"
  14. #include "shader_recompiler/frontend/ir/ir_emitter.h"
  15. #include "shader_recompiler/frontend/maxwell/structured_control_flow.h"
  16. #include "shader_recompiler/frontend/maxwell/translate/translate.h"
  17. #include "shader_recompiler/host_translate_info.h"
  18. #include "shader_recompiler/object_pool.h"
  19. namespace Shader::Maxwell {
  20. namespace {
  21. struct Statement;
  22. // Use normal_link because we are not guaranteed to destroy the tree in order
  23. using ListBaseHook =
  24. boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>>;
  25. using Tree = boost::intrusive::list<Statement,
  26. // Allow using Statement without a definition
  27. boost::intrusive::base_hook<ListBaseHook>,
  28. // Avoid linear complexity on splice, size is never called
  29. boost::intrusive::constant_time_size<false>>;
  30. using Node = Tree::iterator;
  31. enum class StatementType {
  32. Code,
  33. Goto,
  34. Label,
  35. If,
  36. Loop,
  37. Break,
  38. Return,
  39. Kill,
  40. Unreachable,
  41. Function,
  42. Identity,
  43. Not,
  44. Or,
  45. SetVariable,
  46. SetIndirectBranchVariable,
  47. Variable,
  48. IndirectBranchCond,
  49. };
  50. bool HasChildren(StatementType type) {
  51. switch (type) {
  52. case StatementType::If:
  53. case StatementType::Loop:
  54. case StatementType::Function:
  55. return true;
  56. default:
  57. return false;
  58. }
  59. }
  60. struct Goto {};
  61. struct Label {};
  62. struct If {};
  63. struct Loop {};
  64. struct Break {};
  65. struct Return {};
  66. struct Kill {};
  67. struct Unreachable {};
  68. struct FunctionTag {};
  69. struct Identity {};
  70. struct Not {};
  71. struct Or {};
  72. struct SetVariable {};
  73. struct SetIndirectBranchVariable {};
  74. struct Variable {};
  75. struct IndirectBranchCond {};
  76. #ifdef _MSC_VER
  77. #pragma warning(push)
  78. #pragma warning(disable : 26495) // Always initialize a member variable, expected in Statement
  79. #endif
  80. struct Statement : ListBaseHook {
  81. Statement(const Flow::Block* block_, Statement* up_)
  82. : block{block_}, up{up_}, type{StatementType::Code} {}
  83. Statement(Goto, Statement* cond_, Node label_, Statement* up_)
  84. : label{label_}, cond{cond_}, up{up_}, type{StatementType::Goto} {}
  85. Statement(Label, u32 id_, Statement* up_) : id{id_}, up{up_}, type{StatementType::Label} {}
  86. Statement(If, Statement* cond_, Tree&& children_, Statement* up_)
  87. : children{std::move(children_)}, cond{cond_}, up{up_}, type{StatementType::If} {}
  88. Statement(Loop, Statement* cond_, Tree&& children_, Statement* up_)
  89. : children{std::move(children_)}, cond{cond_}, up{up_}, type{StatementType::Loop} {}
  90. Statement(Break, Statement* cond_, Statement* up_)
  91. : cond{cond_}, up{up_}, type{StatementType::Break} {}
  92. Statement(Return, Statement* up_) : up{up_}, type{StatementType::Return} {}
  93. Statement(Kill, Statement* up_) : up{up_}, type{StatementType::Kill} {}
  94. Statement(Unreachable, Statement* up_) : up{up_}, type{StatementType::Unreachable} {}
  95. Statement(FunctionTag) : children{}, type{StatementType::Function} {}
  96. Statement(Identity, IR::Condition cond_, Statement* up_)
  97. : guest_cond{cond_}, up{up_}, type{StatementType::Identity} {}
  98. Statement(Not, Statement* op_, Statement* up_) : op{op_}, up{up_}, type{StatementType::Not} {}
  99. Statement(Or, Statement* op_a_, Statement* op_b_, Statement* up_)
  100. : op_a{op_a_}, op_b{op_b_}, up{up_}, type{StatementType::Or} {}
  101. Statement(SetVariable, u32 id_, Statement* op_, Statement* up_)
  102. : op{op_}, id{id_}, up{up_}, type{StatementType::SetVariable} {}
  103. Statement(SetIndirectBranchVariable, IR::Reg branch_reg_, s32 branch_offset_, Statement* up_)
  104. : branch_offset{branch_offset_}, branch_reg{branch_reg_}, up{up_},
  105. type{StatementType::SetIndirectBranchVariable} {}
  106. Statement(Variable, u32 id_, Statement* up_)
  107. : id{id_}, up{up_}, type{StatementType::Variable} {}
  108. Statement(IndirectBranchCond, u32 location_, Statement* up_)
  109. : location{location_}, up{up_}, type{StatementType::IndirectBranchCond} {}
  110. ~Statement() {
  111. if (HasChildren(type)) {
  112. std::destroy_at(&children);
  113. }
  114. }
  115. union {
  116. const Flow::Block* block;
  117. Node label;
  118. Tree children;
  119. IR::Condition guest_cond;
  120. Statement* op;
  121. Statement* op_a;
  122. u32 location;
  123. s32 branch_offset;
  124. };
  125. union {
  126. Statement* cond;
  127. Statement* op_b;
  128. u32 id;
  129. IR::Reg branch_reg;
  130. };
  131. Statement* up{};
  132. StatementType type;
  133. };
  134. #ifdef _MSC_VER
  135. #pragma warning(pop)
  136. #endif
  137. std::string DumpExpr(const Statement* stmt) {
  138. switch (stmt->type) {
  139. case StatementType::Identity:
  140. return fmt::format("{}", stmt->guest_cond);
  141. case StatementType::Not:
  142. return fmt::format("!{}", DumpExpr(stmt->op));
  143. case StatementType::Or:
  144. return fmt::format("{} || {}", DumpExpr(stmt->op_a), DumpExpr(stmt->op_b));
  145. case StatementType::Variable:
  146. return fmt::format("goto_L{}", stmt->id);
  147. case StatementType::IndirectBranchCond:
  148. return fmt::format("(indirect_branch == {:x})", stmt->location);
  149. default:
  150. return "<invalid type>";
  151. }
  152. }
  153. [[maybe_unused]] std::string DumpTree(const Tree& tree, u32 indentation = 0) {
  154. std::string ret;
  155. std::string indent(indentation, ' ');
  156. for (auto stmt = tree.begin(); stmt != tree.end(); ++stmt) {
  157. switch (stmt->type) {
  158. case StatementType::Code:
  159. ret += fmt::format("{} Block {:04x} -> {:04x} (0x{:016x});\n", indent,
  160. stmt->block->begin.Offset(), stmt->block->end.Offset(),
  161. reinterpret_cast<uintptr_t>(stmt->block));
  162. break;
  163. case StatementType::Goto:
  164. ret += fmt::format("{} if ({}) goto L{};\n", indent, DumpExpr(stmt->cond),
  165. stmt->label->id);
  166. break;
  167. case StatementType::Label:
  168. ret += fmt::format("{}L{}:\n", indent, stmt->id);
  169. break;
  170. case StatementType::If:
  171. ret += fmt::format("{} if ({}) {{\n", indent, DumpExpr(stmt->cond));
  172. ret += DumpTree(stmt->children, indentation + 4);
  173. ret += fmt::format("{} }}\n", indent);
  174. break;
  175. case StatementType::Loop:
  176. ret += fmt::format("{} do {{\n", indent);
  177. ret += DumpTree(stmt->children, indentation + 4);
  178. ret += fmt::format("{} }} while ({});\n", indent, DumpExpr(stmt->cond));
  179. break;
  180. case StatementType::Break:
  181. ret += fmt::format("{} if ({}) break;\n", indent, DumpExpr(stmt->cond));
  182. break;
  183. case StatementType::Return:
  184. ret += fmt::format("{} return;\n", indent);
  185. break;
  186. case StatementType::Kill:
  187. ret += fmt::format("{} kill;\n", indent);
  188. break;
  189. case StatementType::Unreachable:
  190. ret += fmt::format("{} unreachable;\n", indent);
  191. break;
  192. case StatementType::SetVariable:
  193. ret += fmt::format("{} goto_L{} = {};\n", indent, stmt->id, DumpExpr(stmt->op));
  194. break;
  195. case StatementType::SetIndirectBranchVariable:
  196. ret += fmt::format("{} indirect_branch = {} + {};\n", indent, stmt->branch_reg,
  197. stmt->branch_offset);
  198. break;
  199. case StatementType::Function:
  200. case StatementType::Identity:
  201. case StatementType::Not:
  202. case StatementType::Or:
  203. case StatementType::Variable:
  204. case StatementType::IndirectBranchCond:
  205. throw LogicError("Statement can't be printed");
  206. }
  207. }
  208. return ret;
  209. }
  210. void SanitizeNoBreaks(const Tree& tree) {
  211. if (std::ranges::find(tree, StatementType::Break, &Statement::type) != tree.end()) {
  212. throw NotImplementedException("Capturing statement with break nodes");
  213. }
  214. }
  215. size_t Level(Node stmt) {
  216. size_t level{0};
  217. Statement* node{stmt->up};
  218. while (node) {
  219. ++level;
  220. node = node->up;
  221. }
  222. return level;
  223. }
  224. bool IsDirectlyRelated(Node goto_stmt, Node label_stmt) {
  225. const size_t goto_level{Level(goto_stmt)};
  226. const size_t label_level{Level(label_stmt)};
  227. size_t min_level;
  228. size_t max_level;
  229. Node min;
  230. Node max;
  231. if (label_level < goto_level) {
  232. min_level = label_level;
  233. max_level = goto_level;
  234. min = label_stmt;
  235. max = goto_stmt;
  236. } else { // goto_level < label_level
  237. min_level = goto_level;
  238. max_level = label_level;
  239. min = goto_stmt;
  240. max = label_stmt;
  241. }
  242. while (max_level > min_level) {
  243. --max_level;
  244. max = max->up;
  245. }
  246. return min->up == max->up;
  247. }
  248. bool IsIndirectlyRelated(Node goto_stmt, Node label_stmt) {
  249. return goto_stmt->up != label_stmt->up && !IsDirectlyRelated(goto_stmt, label_stmt);
  250. }
  251. [[maybe_unused]] bool AreSiblings(Node goto_stmt, Node label_stmt) noexcept {
  252. Node it{goto_stmt};
  253. do {
  254. if (it == label_stmt) {
  255. return true;
  256. }
  257. --it;
  258. } while (it != goto_stmt->up->children.begin());
  259. while (it != goto_stmt->up->children.end()) {
  260. if (it == label_stmt) {
  261. return true;
  262. }
  263. ++it;
  264. }
  265. return false;
  266. }
  267. Node SiblingFromNephew(Node uncle, Node nephew) noexcept {
  268. Statement* const parent{uncle->up};
  269. Statement* it{&*nephew};
  270. while (it->up != parent) {
  271. it = it->up;
  272. }
  273. return Tree::s_iterator_to(*it);
  274. }
  275. bool AreOrdered(Node left_sibling, Node right_sibling) noexcept {
  276. const Node end{right_sibling->up->children.end()};
  277. for (auto it = right_sibling; it != end; ++it) {
  278. if (it == left_sibling) {
  279. return false;
  280. }
  281. }
  282. return true;
  283. }
  284. bool NeedsLift(Node goto_stmt, Node label_stmt) noexcept {
  285. const Node sibling{SiblingFromNephew(goto_stmt, label_stmt)};
  286. return AreOrdered(sibling, goto_stmt);
  287. }
  288. class GotoPass {
  289. public:
  290. explicit GotoPass(Flow::CFG& cfg, ObjectPool<Statement>& stmt_pool) : pool{stmt_pool} {
  291. std::vector gotos{BuildTree(cfg)};
  292. const auto end{gotos.rend()};
  293. for (auto goto_stmt = gotos.rbegin(); goto_stmt != end; ++goto_stmt) {
  294. RemoveGoto(*goto_stmt);
  295. }
  296. }
  297. Statement& RootStatement() noexcept {
  298. return root_stmt;
  299. }
  300. private:
  301. void RemoveGoto(Node goto_stmt) {
  302. // Force goto_stmt and label_stmt to be directly related
  303. const Node label_stmt{goto_stmt->label};
  304. if (IsIndirectlyRelated(goto_stmt, label_stmt)) {
  305. // Move goto_stmt out using outward-movement transformation until it becomes
  306. // directly related to label_stmt
  307. while (!IsDirectlyRelated(goto_stmt, label_stmt)) {
  308. goto_stmt = MoveOutward(goto_stmt);
  309. }
  310. }
  311. // Force goto_stmt and label_stmt to be siblings
  312. if (IsDirectlyRelated(goto_stmt, label_stmt)) {
  313. const size_t label_level{Level(label_stmt)};
  314. size_t goto_level{Level(goto_stmt)};
  315. if (goto_level > label_level) {
  316. // Move goto_stmt out of its level using outward-movement transformations
  317. while (goto_level > label_level) {
  318. goto_stmt = MoveOutward(goto_stmt);
  319. --goto_level;
  320. }
  321. } else { // Level(goto_stmt) < Level(label_stmt)
  322. if (NeedsLift(goto_stmt, label_stmt)) {
  323. // Lift goto_stmt to above stmt containing label_stmt using goto-lifting
  324. // transformations
  325. goto_stmt = Lift(goto_stmt);
  326. }
  327. // Move goto_stmt into label_stmt's level using inward-movement transformation
  328. while (goto_level < label_level) {
  329. goto_stmt = MoveInward(goto_stmt);
  330. ++goto_level;
  331. }
  332. }
  333. }
  334. // Expensive operation:
  335. // if (!AreSiblings(goto_stmt, label_stmt)) {
  336. // throw LogicError("Goto is not a sibling with the label");
  337. // }
  338. // goto_stmt and label_stmt are guaranteed to be siblings, eliminate
  339. if (std::next(goto_stmt) == label_stmt) {
  340. // Simply eliminate the goto if the label is next to it
  341. goto_stmt->up->children.erase(goto_stmt);
  342. } else if (AreOrdered(goto_stmt, label_stmt)) {
  343. // Eliminate goto_stmt with a conditional
  344. EliminateAsConditional(goto_stmt, label_stmt);
  345. } else {
  346. // Eliminate goto_stmt with a loop
  347. EliminateAsLoop(goto_stmt, label_stmt);
  348. }
  349. }
  350. std::vector<Node> BuildTree(Flow::CFG& cfg) {
  351. u32 label_id{0};
  352. std::vector<Node> gotos;
  353. Flow::Function& first_function{cfg.Functions().front()};
  354. BuildTree(cfg, first_function, label_id, gotos, root_stmt.children.end(), std::nullopt);
  355. return gotos;
  356. }
  357. void BuildTree(Flow::CFG& cfg, Flow::Function& function, u32& label_id,
  358. std::vector<Node>& gotos, Node function_insert_point,
  359. std::optional<Node> return_label) {
  360. Statement* const false_stmt{pool.Create(Identity{}, IR::Condition{false}, &root_stmt)};
  361. Tree& root{root_stmt.children};
  362. std::unordered_map<Flow::Block*, Node> local_labels;
  363. local_labels.reserve(function.blocks.size());
  364. for (Flow::Block& block : function.blocks) {
  365. Statement* const label{pool.Create(Label{}, label_id, &root_stmt)};
  366. const Node label_it{root.insert(function_insert_point, *label)};
  367. local_labels.emplace(&block, label_it);
  368. ++label_id;
  369. }
  370. for (Flow::Block& block : function.blocks) {
  371. const Node label{local_labels.at(&block)};
  372. // Insertion point
  373. const Node ip{std::next(label)};
  374. // Reset goto variables before the first block and after its respective label
  375. const auto make_reset_variable{[&]() -> Statement& {
  376. return *pool.Create(SetVariable{}, label->id, false_stmt, &root_stmt);
  377. }};
  378. root.push_front(make_reset_variable());
  379. root.insert(ip, make_reset_variable());
  380. root.insert(ip, *pool.Create(&block, &root_stmt));
  381. switch (block.end_class) {
  382. case Flow::EndClass::Branch: {
  383. Statement* const always_cond{
  384. pool.Create(Identity{}, IR::Condition{true}, &root_stmt)};
  385. if (block.cond == IR::Condition{true}) {
  386. const Node true_label{local_labels.at(block.branch_true)};
  387. gotos.push_back(
  388. root.insert(ip, *pool.Create(Goto{}, always_cond, true_label, &root_stmt)));
  389. } else if (block.cond == IR::Condition{false}) {
  390. const Node false_label{local_labels.at(block.branch_false)};
  391. gotos.push_back(root.insert(
  392. ip, *pool.Create(Goto{}, always_cond, false_label, &root_stmt)));
  393. } else {
  394. const Node true_label{local_labels.at(block.branch_true)};
  395. const Node false_label{local_labels.at(block.branch_false)};
  396. Statement* const true_cond{pool.Create(Identity{}, block.cond, &root_stmt)};
  397. gotos.push_back(
  398. root.insert(ip, *pool.Create(Goto{}, true_cond, true_label, &root_stmt)));
  399. gotos.push_back(root.insert(
  400. ip, *pool.Create(Goto{}, always_cond, false_label, &root_stmt)));
  401. }
  402. break;
  403. }
  404. case Flow::EndClass::IndirectBranch:
  405. root.insert(ip, *pool.Create(SetIndirectBranchVariable{}, block.branch_reg,
  406. block.branch_offset, &root_stmt));
  407. for (const Flow::IndirectBranch& indirect : block.indirect_branches) {
  408. const Node indirect_label{local_labels.at(indirect.block)};
  409. Statement* cond{
  410. pool.Create(IndirectBranchCond{}, indirect.address, &root_stmt)};
  411. Statement* goto_stmt{pool.Create(Goto{}, cond, indirect_label, &root_stmt)};
  412. gotos.push_back(root.insert(ip, *goto_stmt));
  413. }
  414. root.insert(ip, *pool.Create(Unreachable{}, &root_stmt));
  415. break;
  416. case Flow::EndClass::Call: {
  417. Flow::Function& call{cfg.Functions()[block.function_call]};
  418. const Node call_return_label{local_labels.at(block.return_block)};
  419. BuildTree(cfg, call, label_id, gotos, ip, call_return_label);
  420. break;
  421. }
  422. case Flow::EndClass::Exit:
  423. root.insert(ip, *pool.Create(Return{}, &root_stmt));
  424. break;
  425. case Flow::EndClass::Return: {
  426. Statement* const always_cond{pool.Create(Identity{}, block.cond, &root_stmt)};
  427. auto goto_stmt{pool.Create(Goto{}, always_cond, return_label.value(), &root_stmt)};
  428. gotos.push_back(root.insert(ip, *goto_stmt));
  429. break;
  430. }
  431. case Flow::EndClass::Kill:
  432. root.insert(ip, *pool.Create(Kill{}, &root_stmt));
  433. break;
  434. }
  435. }
  436. }
  437. void UpdateTreeUp(Statement* tree) {
  438. for (Statement& stmt : tree->children) {
  439. stmt.up = tree;
  440. }
  441. }
  442. void EliminateAsConditional(Node goto_stmt, Node label_stmt) {
  443. Tree& body{goto_stmt->up->children};
  444. Tree if_body;
  445. if_body.splice(if_body.begin(), body, std::next(goto_stmt), label_stmt);
  446. Statement* const cond{pool.Create(Not{}, goto_stmt->cond, &root_stmt)};
  447. Statement* const if_stmt{pool.Create(If{}, cond, std::move(if_body), goto_stmt->up)};
  448. UpdateTreeUp(if_stmt);
  449. body.insert(goto_stmt, *if_stmt);
  450. body.erase(goto_stmt);
  451. }
  452. void EliminateAsLoop(Node goto_stmt, Node label_stmt) {
  453. Tree& body{goto_stmt->up->children};
  454. Tree loop_body;
  455. loop_body.splice(loop_body.begin(), body, label_stmt, goto_stmt);
  456. Statement* const cond{goto_stmt->cond};
  457. Statement* const loop{pool.Create(Loop{}, cond, std::move(loop_body), goto_stmt->up)};
  458. UpdateTreeUp(loop);
  459. body.insert(goto_stmt, *loop);
  460. body.erase(goto_stmt);
  461. }
  462. [[nodiscard]] Node MoveOutward(Node goto_stmt) {
  463. switch (goto_stmt->up->type) {
  464. case StatementType::If:
  465. return MoveOutwardIf(goto_stmt);
  466. case StatementType::Loop:
  467. return MoveOutwardLoop(goto_stmt);
  468. default:
  469. throw LogicError("Invalid outward movement");
  470. }
  471. }
  472. [[nodiscard]] Node MoveInward(Node goto_stmt) {
  473. Statement* const parent{goto_stmt->up};
  474. Tree& body{parent->children};
  475. const Node label{goto_stmt->label};
  476. const Node label_nested_stmt{SiblingFromNephew(goto_stmt, label)};
  477. const u32 label_id{label->id};
  478. Statement* const goto_cond{goto_stmt->cond};
  479. Statement* const set_var{pool.Create(SetVariable{}, label_id, goto_cond, parent)};
  480. body.insert(goto_stmt, *set_var);
  481. Tree if_body;
  482. if_body.splice(if_body.begin(), body, std::next(goto_stmt), label_nested_stmt);
  483. Statement* const variable{pool.Create(Variable{}, label_id, &root_stmt)};
  484. Statement* const neg_var{pool.Create(Not{}, variable, &root_stmt)};
  485. if (!if_body.empty()) {
  486. Statement* const if_stmt{pool.Create(If{}, neg_var, std::move(if_body), parent)};
  487. UpdateTreeUp(if_stmt);
  488. body.insert(goto_stmt, *if_stmt);
  489. }
  490. body.erase(goto_stmt);
  491. switch (label_nested_stmt->type) {
  492. case StatementType::If:
  493. // Update nested if condition
  494. label_nested_stmt->cond =
  495. pool.Create(Or{}, variable, label_nested_stmt->cond, &root_stmt);
  496. break;
  497. case StatementType::Loop:
  498. break;
  499. default:
  500. throw LogicError("Invalid inward movement");
  501. }
  502. Tree& nested_tree{label_nested_stmt->children};
  503. Statement* const new_goto{pool.Create(Goto{}, variable, label, &*label_nested_stmt)};
  504. return nested_tree.insert(nested_tree.begin(), *new_goto);
  505. }
  506. [[nodiscard]] Node Lift(Node goto_stmt) {
  507. Statement* const parent{goto_stmt->up};
  508. Tree& body{parent->children};
  509. const Node label{goto_stmt->label};
  510. const u32 label_id{label->id};
  511. const Node label_nested_stmt{SiblingFromNephew(goto_stmt, label)};
  512. Tree loop_body;
  513. loop_body.splice(loop_body.begin(), body, label_nested_stmt, goto_stmt);
  514. SanitizeNoBreaks(loop_body);
  515. Statement* const variable{pool.Create(Variable{}, label_id, &root_stmt)};
  516. Statement* const loop_stmt{pool.Create(Loop{}, variable, std::move(loop_body), parent)};
  517. UpdateTreeUp(loop_stmt);
  518. body.insert(goto_stmt, *loop_stmt);
  519. Statement* const new_goto{pool.Create(Goto{}, variable, label, loop_stmt)};
  520. loop_stmt->children.push_front(*new_goto);
  521. const Node new_goto_node{loop_stmt->children.begin()};
  522. Statement* const set_var{pool.Create(SetVariable{}, label_id, goto_stmt->cond, loop_stmt)};
  523. loop_stmt->children.push_back(*set_var);
  524. body.erase(goto_stmt);
  525. return new_goto_node;
  526. }
  527. Node MoveOutwardIf(Node goto_stmt) {
  528. const Node parent{Tree::s_iterator_to(*goto_stmt->up)};
  529. Tree& body{parent->children};
  530. const u32 label_id{goto_stmt->label->id};
  531. Statement* const goto_cond{goto_stmt->cond};
  532. Statement* const set_goto_var{pool.Create(SetVariable{}, label_id, goto_cond, &*parent)};
  533. body.insert(goto_stmt, *set_goto_var);
  534. Tree if_body;
  535. if_body.splice(if_body.begin(), body, std::next(goto_stmt), body.end());
  536. if_body.pop_front();
  537. Statement* const cond{pool.Create(Variable{}, label_id, &root_stmt)};
  538. Statement* const neg_cond{pool.Create(Not{}, cond, &root_stmt)};
  539. Statement* const if_stmt{pool.Create(If{}, neg_cond, std::move(if_body), &*parent)};
  540. UpdateTreeUp(if_stmt);
  541. body.insert(goto_stmt, *if_stmt);
  542. body.erase(goto_stmt);
  543. Statement* const new_cond{pool.Create(Variable{}, label_id, &root_stmt)};
  544. Statement* const new_goto{pool.Create(Goto{}, new_cond, goto_stmt->label, parent->up)};
  545. Tree& parent_tree{parent->up->children};
  546. return parent_tree.insert(std::next(parent), *new_goto);
  547. }
  548. Node MoveOutwardLoop(Node goto_stmt) {
  549. Statement* const parent{goto_stmt->up};
  550. Tree& body{parent->children};
  551. const u32 label_id{goto_stmt->label->id};
  552. Statement* const goto_cond{goto_stmt->cond};
  553. Statement* const set_goto_var{pool.Create(SetVariable{}, label_id, goto_cond, parent)};
  554. Statement* const cond{pool.Create(Variable{}, label_id, &root_stmt)};
  555. Statement* const break_stmt{pool.Create(Break{}, cond, parent)};
  556. body.insert(goto_stmt, *set_goto_var);
  557. body.insert(goto_stmt, *break_stmt);
  558. body.erase(goto_stmt);
  559. const Node loop{Tree::s_iterator_to(*goto_stmt->up)};
  560. Statement* const new_goto_cond{pool.Create(Variable{}, label_id, &root_stmt)};
  561. Statement* const new_goto{pool.Create(Goto{}, new_goto_cond, goto_stmt->label, loop->up)};
  562. Tree& parent_tree{loop->up->children};
  563. return parent_tree.insert(std::next(loop), *new_goto);
  564. }
  565. ObjectPool<Statement>& pool;
  566. Statement root_stmt{FunctionTag{}};
  567. };
  568. [[nodiscard]] Statement* TryFindForwardBlock(Statement& stmt) {
  569. Tree& tree{stmt.up->children};
  570. const Node end{tree.end()};
  571. Node forward_node{std::next(Tree::s_iterator_to(stmt))};
  572. while (forward_node != end && !HasChildren(forward_node->type)) {
  573. if (forward_node->type == StatementType::Code) {
  574. return &*forward_node;
  575. }
  576. ++forward_node;
  577. }
  578. return nullptr;
  579. }
  580. [[nodiscard]] IR::U1 VisitExpr(IR::IREmitter& ir, const Statement& stmt) {
  581. switch (stmt.type) {
  582. case StatementType::Identity:
  583. return ir.Condition(stmt.guest_cond);
  584. case StatementType::Not:
  585. return ir.LogicalNot(IR::U1{VisitExpr(ir, *stmt.op)});
  586. case StatementType::Or:
  587. return ir.LogicalOr(VisitExpr(ir, *stmt.op_a), VisitExpr(ir, *stmt.op_b));
  588. case StatementType::Variable:
  589. return ir.GetGotoVariable(stmt.id);
  590. case StatementType::IndirectBranchCond:
  591. return ir.IEqual(ir.GetIndirectBranchVariable(), ir.Imm32(stmt.location));
  592. default:
  593. throw NotImplementedException("Statement type {}", stmt.type);
  594. }
  595. }
  596. class TranslatePass {
  597. public:
  598. TranslatePass(ObjectPool<IR::Inst>& inst_pool_, ObjectPool<IR::Block>& block_pool_,
  599. ObjectPool<Statement>& stmt_pool_, Environment& env_, Statement& root_stmt,
  600. IR::AbstractSyntaxList& syntax_list_, const HostTranslateInfo& host_info)
  601. : stmt_pool{stmt_pool_}, inst_pool{inst_pool_}, block_pool{block_pool_}, env{env_},
  602. syntax_list{syntax_list_} {
  603. Visit(root_stmt, nullptr, nullptr);
  604. IR::Block& first_block{*syntax_list.front().data.block};
  605. IR::IREmitter ir(first_block, first_block.begin());
  606. ir.Prologue();
  607. if (uses_demote_to_helper && host_info.needs_demote_reorder) {
  608. DemoteCombinationPass();
  609. }
  610. }
  611. private:
  612. void Visit(Statement& parent, IR::Block* break_block, IR::Block* fallthrough_block) {
  613. IR::Block* current_block{};
  614. const auto ensure_block{[&] {
  615. if (current_block) {
  616. return;
  617. }
  618. current_block = block_pool.Create(inst_pool);
  619. auto& node{syntax_list.emplace_back()};
  620. node.type = IR::AbstractSyntaxNode::Type::Block;
  621. node.data.block = current_block;
  622. }};
  623. Tree& tree{parent.children};
  624. for (auto it = tree.begin(); it != tree.end(); ++it) {
  625. Statement& stmt{*it};
  626. switch (stmt.type) {
  627. case StatementType::Label:
  628. // Labels can be ignored
  629. break;
  630. case StatementType::Code: {
  631. ensure_block();
  632. Translate(env, current_block, stmt.block->begin.Offset(), stmt.block->end.Offset());
  633. break;
  634. }
  635. case StatementType::SetVariable: {
  636. ensure_block();
  637. IR::IREmitter ir{*current_block};
  638. ir.SetGotoVariable(stmt.id, VisitExpr(ir, *stmt.op));
  639. break;
  640. }
  641. case StatementType::SetIndirectBranchVariable: {
  642. ensure_block();
  643. IR::IREmitter ir{*current_block};
  644. IR::U32 address{ir.IAdd(ir.GetReg(stmt.branch_reg), ir.Imm32(stmt.branch_offset))};
  645. ir.SetIndirectBranchVariable(address);
  646. break;
  647. }
  648. case StatementType::If: {
  649. ensure_block();
  650. IR::Block* const merge_block{MergeBlock(parent, stmt)};
  651. // Implement if header block
  652. IR::IREmitter ir{*current_block};
  653. const IR::U1 cond{ir.ConditionRef(VisitExpr(ir, *stmt.cond))};
  654. const size_t if_node_index{syntax_list.size()};
  655. syntax_list.emplace_back();
  656. // Visit children
  657. const size_t then_block_index{syntax_list.size()};
  658. Visit(stmt, break_block, merge_block);
  659. IR::Block* const then_block{syntax_list.at(then_block_index).data.block};
  660. current_block->AddBranch(then_block);
  661. current_block->AddBranch(merge_block);
  662. current_block = merge_block;
  663. auto& if_node{syntax_list[if_node_index]};
  664. if_node.type = IR::AbstractSyntaxNode::Type::If;
  665. if_node.data.if_node.cond = cond;
  666. if_node.data.if_node.body = then_block;
  667. if_node.data.if_node.merge = merge_block;
  668. auto& endif_node{syntax_list.emplace_back()};
  669. endif_node.type = IR::AbstractSyntaxNode::Type::EndIf;
  670. endif_node.data.end_if.merge = merge_block;
  671. auto& merge{syntax_list.emplace_back()};
  672. merge.type = IR::AbstractSyntaxNode::Type::Block;
  673. merge.data.block = merge_block;
  674. break;
  675. }
  676. case StatementType::Loop: {
  677. IR::Block* const loop_header_block{block_pool.Create(inst_pool)};
  678. if (current_block) {
  679. current_block->AddBranch(loop_header_block);
  680. }
  681. auto& header_node{syntax_list.emplace_back()};
  682. header_node.type = IR::AbstractSyntaxNode::Type::Block;
  683. header_node.data.block = loop_header_block;
  684. IR::Block* const continue_block{block_pool.Create(inst_pool)};
  685. IR::Block* const merge_block{MergeBlock(parent, stmt)};
  686. const size_t loop_node_index{syntax_list.size()};
  687. syntax_list.emplace_back();
  688. // Visit children
  689. const size_t body_block_index{syntax_list.size()};
  690. Visit(stmt, merge_block, continue_block);
  691. // The continue block is located at the end of the loop
  692. IR::IREmitter ir{*continue_block};
  693. const IR::U1 cond{ir.ConditionRef(VisitExpr(ir, *stmt.cond))};
  694. IR::Block* const body_block{syntax_list.at(body_block_index).data.block};
  695. loop_header_block->AddBranch(body_block);
  696. continue_block->AddBranch(loop_header_block);
  697. continue_block->AddBranch(merge_block);
  698. current_block = merge_block;
  699. auto& loop{syntax_list[loop_node_index]};
  700. loop.type = IR::AbstractSyntaxNode::Type::Loop;
  701. loop.data.loop.body = body_block;
  702. loop.data.loop.continue_block = continue_block;
  703. loop.data.loop.merge = merge_block;
  704. auto& continue_block_node{syntax_list.emplace_back()};
  705. continue_block_node.type = IR::AbstractSyntaxNode::Type::Block;
  706. continue_block_node.data.block = continue_block;
  707. auto& repeat{syntax_list.emplace_back()};
  708. repeat.type = IR::AbstractSyntaxNode::Type::Repeat;
  709. repeat.data.repeat.cond = cond;
  710. repeat.data.repeat.loop_header = loop_header_block;
  711. repeat.data.repeat.merge = merge_block;
  712. auto& merge{syntax_list.emplace_back()};
  713. merge.type = IR::AbstractSyntaxNode::Type::Block;
  714. merge.data.block = merge_block;
  715. break;
  716. }
  717. case StatementType::Break: {
  718. ensure_block();
  719. IR::Block* const skip_block{MergeBlock(parent, stmt)};
  720. IR::IREmitter ir{*current_block};
  721. const IR::U1 cond{ir.ConditionRef(VisitExpr(ir, *stmt.cond))};
  722. current_block->AddBranch(break_block);
  723. current_block->AddBranch(skip_block);
  724. current_block = skip_block;
  725. auto& break_node{syntax_list.emplace_back()};
  726. break_node.type = IR::AbstractSyntaxNode::Type::Break;
  727. break_node.data.break_node.cond = cond;
  728. break_node.data.break_node.merge = break_block;
  729. break_node.data.break_node.skip = skip_block;
  730. auto& merge{syntax_list.emplace_back()};
  731. merge.type = IR::AbstractSyntaxNode::Type::Block;
  732. merge.data.block = skip_block;
  733. break;
  734. }
  735. case StatementType::Return: {
  736. ensure_block();
  737. IR::Block* return_block{block_pool.Create(inst_pool)};
  738. IR::IREmitter{*return_block}.Epilogue();
  739. current_block->AddBranch(return_block);
  740. auto& merge{syntax_list.emplace_back()};
  741. merge.type = IR::AbstractSyntaxNode::Type::Block;
  742. merge.data.block = return_block;
  743. current_block = nullptr;
  744. syntax_list.emplace_back().type = IR::AbstractSyntaxNode::Type::Return;
  745. break;
  746. }
  747. case StatementType::Kill: {
  748. ensure_block();
  749. IR::Block* demote_block{MergeBlock(parent, stmt)};
  750. IR::IREmitter{*current_block}.DemoteToHelperInvocation();
  751. current_block->AddBranch(demote_block);
  752. current_block = demote_block;
  753. auto& merge{syntax_list.emplace_back()};
  754. merge.type = IR::AbstractSyntaxNode::Type::Block;
  755. merge.data.block = demote_block;
  756. uses_demote_to_helper = true;
  757. break;
  758. }
  759. case StatementType::Unreachable: {
  760. ensure_block();
  761. current_block = nullptr;
  762. syntax_list.emplace_back().type = IR::AbstractSyntaxNode::Type::Unreachable;
  763. break;
  764. }
  765. default:
  766. throw NotImplementedException("Statement type {}", stmt.type);
  767. }
  768. }
  769. if (current_block) {
  770. if (fallthrough_block) {
  771. current_block->AddBranch(fallthrough_block);
  772. } else {
  773. syntax_list.emplace_back().type = IR::AbstractSyntaxNode::Type::Unreachable;
  774. }
  775. }
  776. }
  777. IR::Block* MergeBlock(Statement& parent, Statement& stmt) {
  778. Statement* merge_stmt{TryFindForwardBlock(stmt)};
  779. if (!merge_stmt) {
  780. // Create a merge block we can visit later
  781. merge_stmt = stmt_pool.Create(&dummy_flow_block, &parent);
  782. parent.children.insert(std::next(Tree::s_iterator_to(stmt)), *merge_stmt);
  783. }
  784. return block_pool.Create(inst_pool);
  785. }
  786. void DemoteCombinationPass() {
  787. using Type = IR::AbstractSyntaxNode::Type;
  788. std::vector<IR::Block*> demote_blocks;
  789. std::vector<IR::U1> demote_conds;
  790. u32 num_epilogues{};
  791. u32 branch_depth{};
  792. for (const IR::AbstractSyntaxNode& node : syntax_list) {
  793. if (node.type == Type::If) {
  794. ++branch_depth;
  795. }
  796. if (node.type == Type::EndIf) {
  797. --branch_depth;
  798. }
  799. if (node.type != Type::Block) {
  800. continue;
  801. }
  802. if (branch_depth > 1) {
  803. // Skip reordering nested demote branches.
  804. continue;
  805. }
  806. for (const IR::Inst& inst : node.data.block->Instructions()) {
  807. const IR::Opcode op{inst.GetOpcode()};
  808. if (op == IR::Opcode::DemoteToHelperInvocation) {
  809. demote_blocks.push_back(node.data.block);
  810. break;
  811. }
  812. if (op == IR::Opcode::Epilogue) {
  813. ++num_epilogues;
  814. }
  815. }
  816. }
  817. if (demote_blocks.size() == 0) {
  818. return;
  819. }
  820. if (num_epilogues > 1) {
  821. LOG_DEBUG(Shader, "Combining demotes with more than one return is not implemented.");
  822. return;
  823. }
  824. s64 last_iterator_offset{};
  825. auto& asl{syntax_list};
  826. for (const IR::Block* demote_block : demote_blocks) {
  827. const auto start_it{asl.begin() + last_iterator_offset};
  828. auto asl_it{std::find_if(start_it, asl.end(), [&](const IR::AbstractSyntaxNode& asn) {
  829. return asn.type == Type::If && asn.data.if_node.body == demote_block;
  830. })};
  831. if (asl_it == asl.end()) {
  832. // Demote without a conditional branch.
  833. // No need to proceed since all fragment instances will be demoted regardless.
  834. return;
  835. }
  836. const IR::Block* const end_if = asl_it->data.if_node.merge;
  837. demote_conds.push_back(asl_it->data.if_node.cond);
  838. last_iterator_offset = std::distance(asl.begin(), asl_it);
  839. asl_it = asl.erase(asl_it);
  840. asl_it = std::find_if(asl_it, asl.end(), [&](const IR::AbstractSyntaxNode& asn) {
  841. return asn.type == Type::Block && asn.data.block == demote_block;
  842. });
  843. asl_it = asl.erase(asl_it);
  844. asl_it = std::find_if(asl_it, asl.end(), [&](const IR::AbstractSyntaxNode& asn) {
  845. return asn.type == Type::EndIf && asn.data.end_if.merge == end_if;
  846. });
  847. asl_it = asl.erase(asl_it);
  848. }
  849. const auto epilogue_func{[](const IR::AbstractSyntaxNode& asn) {
  850. if (asn.type != Type::Block) {
  851. return false;
  852. }
  853. for (const auto& inst : asn.data.block->Instructions()) {
  854. if (inst.GetOpcode() == IR::Opcode::Epilogue) {
  855. return true;
  856. }
  857. }
  858. return false;
  859. }};
  860. const auto reverse_it{std::find_if(asl.rbegin(), asl.rend(), epilogue_func)};
  861. const auto return_block_it{(reverse_it + 1).base()};
  862. IR::IREmitter ir{*(return_block_it - 1)->data.block};
  863. IR::U1 cond(IR::Value(false));
  864. for (const auto& demote_cond : demote_conds) {
  865. cond = ir.LogicalOr(cond, demote_cond);
  866. }
  867. cond.Inst()->DestructiveAddUsage(1);
  868. IR::AbstractSyntaxNode demote_if_node{};
  869. demote_if_node.type = Type::If;
  870. demote_if_node.data.if_node.cond = cond;
  871. demote_if_node.data.if_node.body = demote_blocks[0];
  872. demote_if_node.data.if_node.merge = return_block_it->data.block;
  873. IR::AbstractSyntaxNode demote_node{};
  874. demote_node.type = Type::Block;
  875. demote_node.data.block = demote_blocks[0];
  876. IR::AbstractSyntaxNode demote_endif_node{};
  877. demote_endif_node.type = Type::EndIf;
  878. demote_endif_node.data.end_if.merge = return_block_it->data.block;
  879. const auto next_it_1 = asl.insert(return_block_it, demote_endif_node);
  880. const auto next_it_2 = asl.insert(next_it_1, demote_node);
  881. asl.insert(next_it_2, demote_if_node);
  882. }
  883. ObjectPool<Statement>& stmt_pool;
  884. ObjectPool<IR::Inst>& inst_pool;
  885. ObjectPool<IR::Block>& block_pool;
  886. Environment& env;
  887. IR::AbstractSyntaxList& syntax_list;
  888. bool uses_demote_to_helper{};
  889. const Flow::Block dummy_flow_block;
  890. };
  891. } // Anonymous namespace
  892. IR::AbstractSyntaxList BuildASL(ObjectPool<IR::Inst>& inst_pool, ObjectPool<IR::Block>& block_pool,
  893. Environment& env, Flow::CFG& cfg,
  894. const HostTranslateInfo& host_info) {
  895. ObjectPool<Statement> stmt_pool{64};
  896. GotoPass goto_pass{cfg, stmt_pool};
  897. Statement& root{goto_pass.RootStatement()};
  898. IR::AbstractSyntaxList syntax_list;
  899. TranslatePass{inst_pool, block_pool, stmt_pool, env, root, syntax_list, host_info};
  900. return syntax_list;
  901. }
  902. } // namespace Shader::Maxwell