structured_control_flow.cpp 39 KB

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