SSABuildingPass.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. * Copyright (c) 2023, Dan Klishch <danilklishch@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Enumerate.h>
  7. #include <AK/Queue.h>
  8. #include "AST/AST.h"
  9. #include "Compiler/GenericASTPass.h"
  10. #include "Compiler/Passes/SSABuildingPass.h"
  11. #include "Function.h"
  12. namespace JSSpecCompiler {
  13. void SSABuildingPass::process_function()
  14. {
  15. m_dtree_timer = 0;
  16. m_order.clear();
  17. m_mark_version = 1;
  18. m_def_stack.clear();
  19. m_next_id.clear();
  20. m_undo_vector.clear();
  21. m_graph = m_function->m_cfg;
  22. with_graph(m_graph->blocks_count(), [&] {
  23. compute_dominator_tree();
  24. compute_dominance_frontiers();
  25. place_phi_nodes();
  26. rename_variables();
  27. });
  28. }
  29. // ===== compute_dominator_tree =====
  30. namespace {
  31. class DSU {
  32. struct NodeData {
  33. size_t sdom;
  34. size_t parent;
  35. };
  36. public:
  37. DSU(size_t n)
  38. : n(n)
  39. {
  40. m_nodes.resize(n);
  41. for (size_t i = 0; i < n; ++i)
  42. m_nodes[i] = { i, i };
  43. }
  44. NodeData get(size_t u)
  45. {
  46. if (m_nodes[u].parent == u)
  47. return { n, u };
  48. auto [sdom, root] = get(m_nodes[u].parent);
  49. sdom = min(sdom, m_nodes[u].sdom);
  50. return m_nodes[u] = { sdom, root };
  51. }
  52. void merge(size_t u, size_t v, size_t v_sdom)
  53. {
  54. m_nodes[v] = { v_sdom, u };
  55. }
  56. private:
  57. size_t n;
  58. Vector<NodeData> m_nodes;
  59. };
  60. }
  61. void SSABuildingPass::compute_order(BasicBlockRef u, Vertex parent)
  62. {
  63. if (m_nodes[u->m_index].is_used)
  64. return;
  65. m_nodes[u->m_index].is_used = true;
  66. Vertex reordered_u = m_order.size();
  67. m_order.append(RefPtr<BasicBlock>(u).release_nonnull());
  68. reordered_u->parent = parent;
  69. for (auto* v : u->m_continuation->references())
  70. compute_order(*v, reordered_u);
  71. }
  72. void SSABuildingPass::compute_dominator_tree()
  73. {
  74. size_t n = m_graph->blocks_count();
  75. m_nodes.resize(n);
  76. // Algorithm is from https://tanujkhattar.wordpress.com/2016/01/11/dominator-tree-of-a-directed-graph/ ,
  77. // an author writes awful CP-style write-only code, but the explanation is pretty good.
  78. // Step 1
  79. compute_order(m_graph->start_block);
  80. VERIFY(m_order.size() == n);
  81. for (size_t i = 0; i < n; ++i)
  82. m_order[i]->m_index = i;
  83. m_graph->blocks = m_order;
  84. for (size_t i = 0; i < n; ++i) {
  85. Vertex u = i;
  86. for (auto* reference : u.block()->m_continuation->references()) {
  87. Vertex v { *reference };
  88. v->incoming_edges.append(u);
  89. u->outgoing_edges.append(v);
  90. }
  91. }
  92. // Steps 2 & 3
  93. DSU dsu(n);
  94. for (size_t i = n - 1; i > 0; --i) {
  95. Vertex u = i;
  96. Vertex& current_sdom = u->semi_dominator;
  97. current_sdom = n;
  98. for (Vertex v : u->incoming_edges) {
  99. if (v < u)
  100. current_sdom = min(current_sdom, v);
  101. else
  102. current_sdom = min(current_sdom, dsu.get(v).sdom);
  103. }
  104. current_sdom->buckets.append(u);
  105. for (Vertex w : u->buckets) {
  106. Vertex v = dsu.get(w).sdom;
  107. if (v->semi_dominator == w->semi_dominator)
  108. w->immediate_dominator = v->semi_dominator;
  109. else
  110. w->immediate_dominator = v;
  111. }
  112. dsu.merge(u->parent, u, current_sdom);
  113. }
  114. m_nodes[0].immediate_dominator = invalid_node;
  115. for (size_t i = 1; i < n; ++i) {
  116. Vertex u = i;
  117. if (u->immediate_dominator.is_invalid())
  118. u->immediate_dominator = 0;
  119. else if (u->immediate_dominator != u->semi_dominator)
  120. u->immediate_dominator = u->immediate_dominator->immediate_dominator;
  121. }
  122. // Populate dtree_children & BasicBlock::immediate_dominator
  123. for (size_t i = 0; i < n; ++i) {
  124. Vertex u = i;
  125. if (i != 0) {
  126. u.block()->m_immediate_dominator = u->immediate_dominator.block();
  127. u->immediate_dominator->dtree_children.append(u);
  128. } else {
  129. u.block()->m_immediate_dominator = nullptr;
  130. }
  131. }
  132. }
  133. // ===== compute_dominance_frontiers =====
  134. template<typename... Args>
  135. Vector<SSABuildingPass::Vertex> SSABuildingPass::unique(Args const&... args)
  136. {
  137. ++m_mark_version;
  138. Vector<Vertex> result;
  139. (([&](auto const& list) {
  140. for (Vertex u : list) {
  141. if (u->mark != m_mark_version) {
  142. u->mark = m_mark_version;
  143. result.append(u);
  144. }
  145. }
  146. })(args),
  147. ...);
  148. return result;
  149. }
  150. void SSABuildingPass::compute_dtree_tin_tout(Vertex u)
  151. {
  152. u->tin = m_dtree_timer++;
  153. for (Vertex v : u->dtree_children)
  154. compute_dtree_tin_tout(v);
  155. u->tout = m_dtree_timer++;
  156. }
  157. bool SSABuildingPass::is_strictly_dominating(Vertex u, Vertex v)
  158. {
  159. return u != v && u->tin <= v->tin && v->tout <= u->tout;
  160. }
  161. void SSABuildingPass::compute_dominance_frontiers()
  162. {
  163. compute_dtree_tin_tout(0);
  164. // Algorithm from https://en.wikipedia.org/wiki/Static_single-assignment_form#Converting%20to%20SSA:~:text=their%20paper%20titled-,A%20Simple%2C%20Fast%20Dominance%20Algorithm,-%3A%5B13%5D .
  165. // DF(u) = {w : !(u sdom w) /\ (\exists v \in incoming_edges(v) : u dom v)}
  166. for (size_t wi = 0; wi < m_nodes.size(); ++wi) {
  167. Vertex w = wi;
  168. for (Vertex v : w->incoming_edges) {
  169. Vertex u = v;
  170. while (u != invalid_node && !is_strictly_dominating(u, w)) {
  171. u->d_frontier.append(w);
  172. u = u->immediate_dominator;
  173. }
  174. }
  175. }
  176. for (size_t i = 0; i < m_nodes.size(); ++i) {
  177. Vertex u = i;
  178. u->d_frontier = unique(u->d_frontier);
  179. }
  180. }
  181. // ===== place_phi_nodes =====
  182. namespace {
  183. class VariableAssignmentCollector : private RecursiveASTVisitor {
  184. public:
  185. VariableAssignmentCollector(OrderedHashMap<NamedVariableDeclarationRef, Vector<BasicBlockRef>>& declarations)
  186. : m_declarations(declarations)
  187. {
  188. }
  189. void run(BasicBlockRef block)
  190. {
  191. m_current_block = block;
  192. for (auto& expression : block->m_expressions)
  193. run_in_subtree(expression);
  194. run_in_const_subtree(block->m_continuation);
  195. }
  196. protected:
  197. RecursionDecision on_entry(Tree tree) override
  198. {
  199. if (tree->is_statement())
  200. TODO();
  201. return RecursionDecision::Recurse;
  202. }
  203. void on_leave(Tree tree) override
  204. {
  205. if (auto binary_operation = as<BinaryOperation>(tree); binary_operation) {
  206. if (binary_operation->m_operation != BinaryOperator::Assignment)
  207. return;
  208. if (auto variable = as<Variable>(binary_operation->m_left); variable) {
  209. auto& vector = m_declarations.get(variable->m_name).value();
  210. if (vector.is_empty() || vector.last() != m_current_block)
  211. vector.append(m_current_block);
  212. }
  213. }
  214. }
  215. private:
  216. BasicBlockRef m_current_block;
  217. OrderedHashMap<NamedVariableDeclarationRef, Vector<BasicBlockRef>>& m_declarations;
  218. };
  219. }
  220. void SSABuildingPass::add_phi_node(BasicBlockRef block, NamedVariableDeclarationRef decl)
  221. {
  222. BasicBlock::PhiNode node { .var = make_ref_counted<Variable>(decl) };
  223. for (Vertex incoming : Vertex(block)->incoming_edges) {
  224. BasicBlockRef incoming_block = incoming.block();
  225. auto value = make_ref_counted<Variable>(decl);
  226. node.branches.append({ .block = incoming_block, .value = value });
  227. }
  228. block->m_phi_nodes.append(move(node));
  229. }
  230. void SSABuildingPass::place_phi_nodes()
  231. {
  232. // Entry block has implicit declarations of all variables.
  233. OrderedHashMap<NamedVariableDeclarationRef, Vector<BasicBlockRef>> m_declarations;
  234. for (auto const& [name, var_decl] : m_function->m_local_variables)
  235. m_declarations.set(var_decl, { m_order[0] });
  236. m_declarations.set(m_function->m_named_return_value, { m_order[0] });
  237. VariableAssignmentCollector collector(m_declarations);
  238. for (auto const& block : m_order)
  239. collector.run(block);
  240. for (auto const& [decl, blocks] : m_declarations) {
  241. ++m_mark_version;
  242. Queue<BasicBlockRef> queue;
  243. for (auto const& block : blocks)
  244. queue.enqueue(block);
  245. while (!queue.is_empty()) {
  246. Vertex u(queue.dequeue());
  247. for (Vertex frontier : u->d_frontier) {
  248. if (frontier->mark == m_mark_version)
  249. continue;
  250. frontier->mark = m_mark_version;
  251. add_phi_node(frontier.block(), decl);
  252. }
  253. }
  254. }
  255. }
  256. // ===== rename_variables =====
  257. namespace {
  258. template<typename CreateSSAVariableFunc, typename RenameVariableFunc>
  259. class VariableRenamer : private RecursiveASTVisitor {
  260. public:
  261. VariableRenamer(CreateSSAVariableFunc create, RenameVariableFunc rename)
  262. : m_create(create)
  263. , m_rename(rename)
  264. {
  265. }
  266. void run(BasicBlockRef block)
  267. {
  268. for (auto& expression : block->m_expressions)
  269. run_in_subtree(expression);
  270. run_in_const_subtree(block->m_continuation);
  271. }
  272. protected:
  273. RecursionDecision on_entry(Tree tree) override
  274. {
  275. if (tree->is_statement())
  276. TODO();
  277. auto binary_operation = as<BinaryOperation>(tree);
  278. if (binary_operation && binary_operation->m_operation == BinaryOperator::Assignment) {
  279. run_in_subtree(binary_operation->m_right);
  280. if (auto variable = as<Variable>(binary_operation->m_left); variable) {
  281. m_create(variable->m_name);
  282. m_rename(variable.release_nonnull());
  283. } else {
  284. run_in_subtree(binary_operation->m_left);
  285. }
  286. return RecursionDecision::Continue;
  287. }
  288. if (auto variable = as<Variable>(tree); variable) {
  289. m_rename(variable.release_nonnull());
  290. return RecursionDecision::Continue;
  291. }
  292. return RecursionDecision::Recurse;
  293. }
  294. private:
  295. CreateSSAVariableFunc m_create;
  296. RenameVariableFunc m_rename;
  297. };
  298. }
  299. void SSABuildingPass::make_new_ssa_variable_for(NamedVariableDeclarationRef var)
  300. {
  301. m_undo_vector.append(var);
  302. u64 id = 0;
  303. if (auto it = m_next_id.find(var); it == m_next_id.end())
  304. m_next_id.set(var, 1);
  305. else
  306. id = it->value++;
  307. auto ssa_decl = make_ref_counted<SSAVariableDeclaration>(id);
  308. m_function->m_local_ssa_variables.append(ssa_decl);
  309. if (auto it = m_def_stack.find(var); it == m_def_stack.end())
  310. m_def_stack.set(var, { ssa_decl });
  311. else
  312. it->value.append(ssa_decl);
  313. }
  314. void SSABuildingPass::rename_variable(VariableRef var)
  315. {
  316. var->m_ssa = m_def_stack.get(var->m_name).value().last();
  317. }
  318. void SSABuildingPass::rename_variables(Vertex u, Vertex from)
  319. {
  320. size_t rollback_point = m_undo_vector.size();
  321. for (auto& phi_node : u.block()->m_phi_nodes) {
  322. // TODO: Find the right branch index without iterating through all of the branches.
  323. bool found = false;
  324. for (auto& branch : phi_node.branches) {
  325. if (branch.block->m_index == from) {
  326. rename_variable(branch.value);
  327. found = true;
  328. break;
  329. }
  330. }
  331. VERIFY(found);
  332. }
  333. if (u->mark == m_mark_version)
  334. return;
  335. u->mark = m_mark_version;
  336. for (auto& phi_node : u.block()->m_phi_nodes) {
  337. make_new_ssa_variable_for(phi_node.var->m_name);
  338. rename_variable(phi_node.var);
  339. }
  340. VariableRenamer renamer(
  341. [&](NamedVariableDeclarationRef decl) {
  342. make_new_ssa_variable_for(move(decl));
  343. },
  344. [&](VariableRef var) {
  345. rename_variable(move(var));
  346. });
  347. renamer.run(u.block());
  348. if (auto function_return = as<ControlFlowFunctionReturn>(u.block()->m_continuation); function_return) {
  349. // CFG should have exactly one ControlFlowFunctionReturn.
  350. VERIFY(m_function->m_return_value == nullptr);
  351. m_function->m_return_value = function_return->m_return_value->m_ssa;
  352. }
  353. for (size_t j : u->outgoing_edges)
  354. rename_variables(j, u);
  355. while (m_undo_vector.size() > rollback_point)
  356. (void)m_def_stack.get(m_undo_vector.take_last()).value().take_last();
  357. }
  358. void SSABuildingPass::rename_variables()
  359. {
  360. HashMap<StringView, size_t> argument_index_by_name;
  361. for (auto [i, argument] : enumerate(m_function->arguments()))
  362. argument_index_by_name.set(argument.name, i);
  363. m_function->m_ssa_arguments.resize(m_function->arguments().size());
  364. for (auto const& [name, var_decl] : m_function->m_local_variables) {
  365. make_new_ssa_variable_for(var_decl);
  366. if (auto maybe_index = argument_index_by_name.get(name); maybe_index.has_value()) {
  367. size_t index = maybe_index.value();
  368. m_function->m_ssa_arguments[index] = m_def_stack.get(var_decl).value()[0];
  369. }
  370. }
  371. make_new_ssa_variable_for(m_function->m_named_return_value);
  372. ++m_mark_version;
  373. rename_variables(0);
  374. VERIFY(m_function->m_return_value);
  375. m_function->reindex_ssa_variables();
  376. }
  377. }