cfa.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. // Copyright (c) 2015-2016 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef SOURCE_CFA_H_
  15. #define SOURCE_CFA_H_
  16. #include <algorithm>
  17. #include <cassert>
  18. #include <cstdint>
  19. #include <functional>
  20. #include <map>
  21. #include <unordered_map>
  22. #include <unordered_set>
  23. #include <utility>
  24. #include <vector>
  25. namespace spvtools {
  26. // Control Flow Analysis of control flow graphs of basic block nodes |BB|.
  27. template <class BB>
  28. class CFA {
  29. using bb_ptr = BB*;
  30. using cbb_ptr = const BB*;
  31. using bb_iter = typename std::vector<BB*>::const_iterator;
  32. using get_blocks_func = std::function<const std::vector<BB*>*(const BB*)>;
  33. struct block_info {
  34. cbb_ptr block; ///< pointer to the block
  35. bb_iter iter; ///< Iterator to the current child node being processed
  36. };
  37. /// Returns true if a block with @p id is found in the @p work_list vector
  38. ///
  39. /// @param[in] work_list Set of blocks visited in the depth first
  40. /// traversal
  41. /// of the CFG
  42. /// @param[in] id The ID of the block being checked
  43. ///
  44. /// @return true if the edge work_list.back().block->id() => id is a back-edge
  45. static bool FindInWorkList(const std::vector<block_info>& work_list,
  46. uint32_t id);
  47. public:
  48. /// @brief Depth first traversal starting from the \p entry BasicBlock
  49. ///
  50. /// This function performs a depth first traversal from the \p entry
  51. /// BasicBlock and calls the pre/postorder functions when it needs to process
  52. /// the node in pre order, post order.
  53. ///
  54. /// @param[in] entry The root BasicBlock of a CFG
  55. /// @param[in] successor_func A function which will return a pointer to the
  56. /// successor nodes
  57. /// @param[in] preorder A function that will be called for every block in a
  58. /// CFG following preorder traversal semantics
  59. /// @param[in] postorder A function that will be called for every block in a
  60. /// CFG following postorder traversal semantics
  61. /// @param[in] terminal A function that will be called to determine if the
  62. /// search should stop at the given node.
  63. /// NOTE: The @p successor_func and predecessor_func each return a pointer to
  64. /// a collection such that iterators to that collection remain valid for the
  65. /// lifetime of the algorithm.
  66. static void DepthFirstTraversal(const BB* entry,
  67. get_blocks_func successor_func,
  68. std::function<void(cbb_ptr)> preorder,
  69. std::function<void(cbb_ptr)> postorder,
  70. std::function<bool(cbb_ptr)> terminal);
  71. /// @brief Depth first traversal starting from the \p entry BasicBlock
  72. ///
  73. /// This function performs a depth first traversal from the \p entry
  74. /// BasicBlock and calls the pre/postorder functions when it needs to process
  75. /// the node in pre order, post order. It also calls the backedge function
  76. /// when a back edge is encountered. The backedge function can be empty. The
  77. /// runtime of the algorithm is improved if backedge is empty.
  78. ///
  79. /// @param[in] entry The root BasicBlock of a CFG
  80. /// @param[in] successor_func A function which will return a pointer to the
  81. /// successor nodes
  82. /// @param[in] preorder A function that will be called for every block in a
  83. /// CFG following preorder traversal semantics
  84. /// @param[in] postorder A function that will be called for every block in a
  85. /// CFG following postorder traversal semantics
  86. /// @param[in] backedge A function that will be called when a backedge is
  87. /// encountered during a traversal.
  88. /// @param[in] terminal A function that will be called to determine if the
  89. /// search should stop at the given node.
  90. /// NOTE: The @p successor_func and predecessor_func each return a pointer to
  91. /// a collection such that iterators to that collection remain valid for the
  92. /// lifetime of the algorithm.
  93. static void DepthFirstTraversal(
  94. const BB* entry, get_blocks_func successor_func,
  95. std::function<void(cbb_ptr)> preorder,
  96. std::function<void(cbb_ptr)> postorder,
  97. std::function<void(cbb_ptr, cbb_ptr)> backedge,
  98. std::function<bool(cbb_ptr)> terminal);
  99. /// @brief Calculates dominator edges for a set of blocks
  100. ///
  101. /// Computes dominators using the algorithm of Cooper, Harvey, and Kennedy
  102. /// "A Simple, Fast Dominance Algorithm", 2001.
  103. ///
  104. /// The algorithm assumes there is a unique root node (a node without
  105. /// predecessors), and it is therefore at the end of the postorder vector.
  106. ///
  107. /// This function calculates the dominator edges for a set of blocks in the
  108. /// CFG.
  109. /// Uses the dominator algorithm by Cooper et al.
  110. ///
  111. /// @param[in] postorder A vector of blocks in post order traversal
  112. /// order
  113. /// in a CFG
  114. /// @param[in] predecessor_func Function used to get the predecessor nodes of
  115. /// a
  116. /// block
  117. ///
  118. /// @return the dominator tree of the graph, as a vector of pairs of nodes.
  119. /// The first node in the pair is a node in the graph. The second node in the
  120. /// pair is its immediate dominator in the sense of Cooper et.al., where a
  121. /// block
  122. /// without predecessors (such as the root node) is its own immediate
  123. /// dominator.
  124. static std::vector<std::pair<BB*, BB*>> CalculateDominators(
  125. const std::vector<cbb_ptr>& postorder, get_blocks_func predecessor_func);
  126. // Computes a minimal set of root nodes required to traverse, in the forward
  127. // direction, the CFG represented by the given vector of blocks, and successor
  128. // and predecessor functions. When considering adding two nodes, each having
  129. // predecessors, favour using the one that appears earlier on the input blocks
  130. // list.
  131. static std::vector<BB*> TraversalRoots(const std::vector<BB*>& blocks,
  132. get_blocks_func succ_func,
  133. get_blocks_func pred_func);
  134. static void ComputeAugmentedCFG(
  135. std::vector<BB*>& ordered_blocks, BB* pseudo_entry_block,
  136. BB* pseudo_exit_block,
  137. std::unordered_map<const BB*, std::vector<BB*>>* augmented_successors_map,
  138. std::unordered_map<const BB*, std::vector<BB*>>*
  139. augmented_predecessors_map,
  140. get_blocks_func succ_func, get_blocks_func pred_func);
  141. };
  142. template <class BB>
  143. bool CFA<BB>::FindInWorkList(const std::vector<block_info>& work_list,
  144. uint32_t id) {
  145. for (const auto& b : work_list) {
  146. if (b.block->id() == id) return true;
  147. }
  148. return false;
  149. }
  150. template <class BB>
  151. void CFA<BB>::DepthFirstTraversal(const BB* entry,
  152. get_blocks_func successor_func,
  153. std::function<void(cbb_ptr)> preorder,
  154. std::function<void(cbb_ptr)> postorder,
  155. std::function<bool(cbb_ptr)> terminal) {
  156. DepthFirstTraversal(entry, successor_func, preorder, postorder,
  157. /* backedge = */ {}, terminal);
  158. }
  159. template <class BB>
  160. void CFA<BB>::DepthFirstTraversal(
  161. const BB* entry, get_blocks_func successor_func,
  162. std::function<void(cbb_ptr)> preorder,
  163. std::function<void(cbb_ptr)> postorder,
  164. std::function<void(cbb_ptr, cbb_ptr)> backedge,
  165. std::function<bool(cbb_ptr)> terminal) {
  166. assert(successor_func && "The successor function cannot be empty.");
  167. assert(preorder && "The preorder function cannot be empty.");
  168. assert(postorder && "The postorder function cannot be empty.");
  169. assert(terminal && "The terminal function cannot be empty.");
  170. std::unordered_set<uint32_t> processed;
  171. /// NOTE: work_list is the sequence of nodes from the root node to the node
  172. /// being processed in the traversal
  173. std::vector<block_info> work_list;
  174. work_list.reserve(10);
  175. work_list.push_back({entry, std::begin(*successor_func(entry))});
  176. preorder(entry);
  177. processed.insert(entry->id());
  178. while (!work_list.empty()) {
  179. block_info& top = work_list.back();
  180. if (terminal(top.block) || top.iter == end(*successor_func(top.block))) {
  181. postorder(top.block);
  182. work_list.pop_back();
  183. } else {
  184. BB* child = *top.iter;
  185. top.iter++;
  186. if (backedge && FindInWorkList(work_list, child->id())) {
  187. backedge(top.block, child);
  188. }
  189. if (processed.count(child->id()) == 0) {
  190. preorder(child);
  191. work_list.emplace_back(
  192. block_info{child, std::begin(*successor_func(child))});
  193. processed.insert(child->id());
  194. }
  195. }
  196. }
  197. }
  198. template <class BB>
  199. std::vector<std::pair<BB*, BB*>> CFA<BB>::CalculateDominators(
  200. const std::vector<cbb_ptr>& postorder, get_blocks_func predecessor_func) {
  201. struct block_detail {
  202. size_t dominator; ///< The index of blocks's dominator in post order array
  203. size_t postorder_index; ///< The index of the block in the post order array
  204. };
  205. const size_t undefined_dom = postorder.size();
  206. std::unordered_map<cbb_ptr, block_detail> idoms;
  207. for (size_t i = 0; i < postorder.size(); i++) {
  208. idoms[postorder[i]] = {undefined_dom, i};
  209. }
  210. idoms[postorder.back()].dominator = idoms[postorder.back()].postorder_index;
  211. bool changed = true;
  212. while (changed) {
  213. changed = false;
  214. for (auto b = postorder.rbegin() + 1; b != postorder.rend(); ++b) {
  215. const std::vector<BB*>& predecessors = *predecessor_func(*b);
  216. // Find the first processed/reachable predecessor that is reachable
  217. // in the forward traversal.
  218. auto res = std::find_if(std::begin(predecessors), std::end(predecessors),
  219. [&idoms, undefined_dom](BB* pred) {
  220. return idoms.count(pred) &&
  221. idoms[pred].dominator != undefined_dom;
  222. });
  223. if (res == end(predecessors)) continue;
  224. const BB* idom = *res;
  225. size_t idom_idx = idoms[idom].postorder_index;
  226. // all other predecessors
  227. for (const auto* p : predecessors) {
  228. if (idom == p) continue;
  229. // Only consider nodes reachable in the forward traversal.
  230. // Otherwise the intersection doesn't make sense and will never
  231. // terminate.
  232. if (!idoms.count(p)) continue;
  233. if (idoms[p].dominator != undefined_dom) {
  234. size_t finger1 = idoms[p].postorder_index;
  235. size_t finger2 = idom_idx;
  236. while (finger1 != finger2) {
  237. while (finger1 < finger2) {
  238. finger1 = idoms[postorder[finger1]].dominator;
  239. }
  240. while (finger2 < finger1) {
  241. finger2 = idoms[postorder[finger2]].dominator;
  242. }
  243. }
  244. idom_idx = finger1;
  245. }
  246. }
  247. if (idoms[*b].dominator != idom_idx) {
  248. idoms[*b].dominator = idom_idx;
  249. changed = true;
  250. }
  251. }
  252. }
  253. std::vector<std::pair<bb_ptr, bb_ptr>> out;
  254. for (auto idom : idoms) {
  255. // At this point if there is no dominator for the node, just make it
  256. // reflexive.
  257. auto dominator = std::get<1>(idom).dominator;
  258. if (dominator == undefined_dom) {
  259. dominator = std::get<1>(idom).postorder_index;
  260. }
  261. // NOTE: performing a const cast for convenient usage with
  262. // UpdateImmediateDominators
  263. out.push_back({const_cast<BB*>(std::get<0>(idom)),
  264. const_cast<BB*>(postorder[dominator])});
  265. }
  266. // Sort by postorder index to generate a deterministic ordering of edges.
  267. std::sort(
  268. out.begin(), out.end(),
  269. [&idoms](const std::pair<bb_ptr, bb_ptr>& lhs,
  270. const std::pair<bb_ptr, bb_ptr>& rhs) {
  271. assert(lhs.first);
  272. assert(lhs.second);
  273. assert(rhs.first);
  274. assert(rhs.second);
  275. auto lhs_indices = std::make_pair(idoms[lhs.first].postorder_index,
  276. idoms[lhs.second].postorder_index);
  277. auto rhs_indices = std::make_pair(idoms[rhs.first].postorder_index,
  278. idoms[rhs.second].postorder_index);
  279. return lhs_indices < rhs_indices;
  280. });
  281. return out;
  282. }
  283. template <class BB>
  284. std::vector<BB*> CFA<BB>::TraversalRoots(const std::vector<BB*>& blocks,
  285. get_blocks_func succ_func,
  286. get_blocks_func pred_func) {
  287. // The set of nodes which have been visited from any of the roots so far.
  288. std::unordered_set<const BB*> visited;
  289. auto mark_visited = [&visited](const BB* b) { visited.insert(b); };
  290. auto ignore_block = [](const BB*) {};
  291. auto no_terminal_blocks = [](const BB*) { return false; };
  292. auto traverse_from_root = [&mark_visited, &succ_func, &ignore_block,
  293. &no_terminal_blocks](const BB* entry) {
  294. DepthFirstTraversal(entry, succ_func, mark_visited, ignore_block,
  295. no_terminal_blocks);
  296. };
  297. std::vector<BB*> result;
  298. // First collect nodes without predecessors.
  299. for (auto block : blocks) {
  300. if (pred_func(block)->empty()) {
  301. assert(visited.count(block) == 0 && "Malformed graph!");
  302. result.push_back(block);
  303. traverse_from_root(block);
  304. }
  305. }
  306. // Now collect other stranded nodes. These must be in unreachable cycles.
  307. for (auto block : blocks) {
  308. if (visited.count(block) == 0) {
  309. result.push_back(block);
  310. traverse_from_root(block);
  311. }
  312. }
  313. return result;
  314. }
  315. template <class BB>
  316. void CFA<BB>::ComputeAugmentedCFG(
  317. std::vector<BB*>& ordered_blocks, BB* pseudo_entry_block,
  318. BB* pseudo_exit_block,
  319. std::unordered_map<const BB*, std::vector<BB*>>* augmented_successors_map,
  320. std::unordered_map<const BB*, std::vector<BB*>>* augmented_predecessors_map,
  321. get_blocks_func succ_func, get_blocks_func pred_func) {
  322. // Compute the successors of the pseudo-entry block, and
  323. // the predecessors of the pseudo exit block.
  324. auto sources = TraversalRoots(ordered_blocks, succ_func, pred_func);
  325. // For the predecessor traversals, reverse the order of blocks. This
  326. // will affect the post-dominance calculation as follows:
  327. // - Suppose you have blocks A and B, with A appearing before B in
  328. // the list of blocks.
  329. // - Also, A branches only to B, and B branches only to A.
  330. // - We want to compute A as dominating B, and B as post-dominating B.
  331. // By using reversed blocks for predecessor traversal roots discovery,
  332. // we'll add an edge from B to the pseudo-exit node, rather than from A.
  333. // All this is needed to correctly process the dominance/post-dominance
  334. // constraint when A is a loop header that points to itself as its
  335. // own continue target, and B is the latch block for the loop.
  336. std::vector<BB*> reversed_blocks(ordered_blocks.rbegin(),
  337. ordered_blocks.rend());
  338. auto sinks = TraversalRoots(reversed_blocks, pred_func, succ_func);
  339. // Wire up the pseudo entry block.
  340. (*augmented_successors_map)[pseudo_entry_block] = sources;
  341. for (auto block : sources) {
  342. auto& augmented_preds = (*augmented_predecessors_map)[block];
  343. const auto preds = pred_func(block);
  344. augmented_preds.reserve(1 + preds->size());
  345. augmented_preds.push_back(pseudo_entry_block);
  346. augmented_preds.insert(augmented_preds.end(), preds->begin(), preds->end());
  347. }
  348. // Wire up the pseudo exit block.
  349. (*augmented_predecessors_map)[pseudo_exit_block] = sinks;
  350. for (auto block : sinks) {
  351. auto& augmented_succ = (*augmented_successors_map)[block];
  352. const auto succ = succ_func(block);
  353. augmented_succ.reserve(1 + succ->size());
  354. augmented_succ.push_back(pseudo_exit_block);
  355. augmented_succ.insert(augmented_succ.end(), succ->begin(), succ->end());
  356. }
  357. }
  358. } // namespace spvtools
  359. #endif // SOURCE_CFA_H_