cfa.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 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. It also calls the backedge function
  53. /// when a back edge is encountered.
  54. ///
  55. /// @param[in] entry The root BasicBlock of a CFG
  56. /// @param[in] successor_func A function which will return a pointer to the
  57. /// successor nodes
  58. /// @param[in] preorder A function that will be called for every block in a
  59. /// CFG following preorder traversal semantics
  60. /// @param[in] postorder A function that will be called for every block in a
  61. /// CFG following postorder traversal semantics
  62. /// @param[in] backedge A function that will be called when a backedge is
  63. /// encountered during a traversal
  64. /// NOTE: The @p successor_func and predecessor_func each return a pointer to
  65. /// a
  66. /// collection such that iterators to that collection remain valid for the
  67. /// lifetime of the algorithm.
  68. static void DepthFirstTraversal(
  69. const BB* entry, get_blocks_func successor_func,
  70. std::function<void(cbb_ptr)> preorder,
  71. std::function<void(cbb_ptr)> postorder,
  72. std::function<void(cbb_ptr, cbb_ptr)> backedge);
  73. /// @brief Calculates dominator edges for a set of blocks
  74. ///
  75. /// Computes dominators using the algorithm of Cooper, Harvey, and Kennedy
  76. /// "A Simple, Fast Dominance Algorithm", 2001.
  77. ///
  78. /// The algorithm assumes there is a unique root node (a node without
  79. /// predecessors), and it is therefore at the end of the postorder vector.
  80. ///
  81. /// This function calculates the dominator edges for a set of blocks in the
  82. /// CFG.
  83. /// Uses the dominator algorithm by Cooper et al.
  84. ///
  85. /// @param[in] postorder A vector of blocks in post order traversal
  86. /// order
  87. /// in a CFG
  88. /// @param[in] predecessor_func Function used to get the predecessor nodes of
  89. /// a
  90. /// block
  91. ///
  92. /// @return the dominator tree of the graph, as a vector of pairs of nodes.
  93. /// The first node in the pair is a node in the graph. The second node in the
  94. /// pair is its immediate dominator in the sense of Cooper et.al., where a
  95. /// block
  96. /// without predecessors (such as the root node) is its own immediate
  97. /// dominator.
  98. static std::vector<std::pair<BB*, BB*>> CalculateDominators(
  99. const std::vector<cbb_ptr>& postorder, get_blocks_func predecessor_func);
  100. // Computes a minimal set of root nodes required to traverse, in the forward
  101. // direction, the CFG represented by the given vector of blocks, and successor
  102. // and predecessor functions. When considering adding two nodes, each having
  103. // predecessors, favour using the one that appears earlier on the input blocks
  104. // list.
  105. static std::vector<BB*> TraversalRoots(const std::vector<BB*>& blocks,
  106. get_blocks_func succ_func,
  107. get_blocks_func pred_func);
  108. static void ComputeAugmentedCFG(
  109. std::vector<BB*>& ordered_blocks, BB* pseudo_entry_block,
  110. BB* pseudo_exit_block,
  111. std::unordered_map<const BB*, std::vector<BB*>>* augmented_successors_map,
  112. std::unordered_map<const BB*, std::vector<BB*>>*
  113. augmented_predecessors_map,
  114. get_blocks_func succ_func, get_blocks_func pred_func);
  115. };
  116. template <class BB>
  117. bool CFA<BB>::FindInWorkList(const std::vector<block_info>& work_list,
  118. uint32_t id) {
  119. for (const auto b : work_list) {
  120. if (b.block->id() == id) return true;
  121. }
  122. return false;
  123. }
  124. template <class BB>
  125. void CFA<BB>::DepthFirstTraversal(
  126. const BB* entry, get_blocks_func successor_func,
  127. std::function<void(cbb_ptr)> preorder,
  128. std::function<void(cbb_ptr)> postorder,
  129. std::function<void(cbb_ptr, cbb_ptr)> backedge) {
  130. std::unordered_set<uint32_t> processed;
  131. /// NOTE: work_list is the sequence of nodes from the root node to the node
  132. /// being processed in the traversal
  133. std::vector<block_info> work_list;
  134. work_list.reserve(10);
  135. work_list.push_back({entry, std::begin(*successor_func(entry))});
  136. preorder(entry);
  137. processed.insert(entry->id());
  138. while (!work_list.empty()) {
  139. block_info& top = work_list.back();
  140. if (top.iter == end(*successor_func(top.block))) {
  141. postorder(top.block);
  142. work_list.pop_back();
  143. } else {
  144. BB* child = *top.iter;
  145. top.iter++;
  146. if (FindInWorkList(work_list, child->id())) {
  147. backedge(top.block, child);
  148. }
  149. if (processed.count(child->id()) == 0) {
  150. preorder(child);
  151. work_list.emplace_back(
  152. block_info{child, std::begin(*successor_func(child))});
  153. processed.insert(child->id());
  154. }
  155. }
  156. }
  157. }
  158. template <class BB>
  159. std::vector<std::pair<BB*, BB*>> CFA<BB>::CalculateDominators(
  160. const std::vector<cbb_ptr>& postorder, get_blocks_func predecessor_func) {
  161. struct block_detail {
  162. size_t dominator; ///< The index of blocks's dominator in post order array
  163. size_t postorder_index; ///< The index of the block in the post order array
  164. };
  165. const size_t undefined_dom = postorder.size();
  166. std::unordered_map<cbb_ptr, block_detail> idoms;
  167. for (size_t i = 0; i < postorder.size(); i++) {
  168. idoms[postorder[i]] = {undefined_dom, i};
  169. }
  170. idoms[postorder.back()].dominator = idoms[postorder.back()].postorder_index;
  171. bool changed = true;
  172. while (changed) {
  173. changed = false;
  174. for (auto b = postorder.rbegin() + 1; b != postorder.rend(); ++b) {
  175. const std::vector<BB*>& predecessors = *predecessor_func(*b);
  176. // Find the first processed/reachable predecessor that is reachable
  177. // in the forward traversal.
  178. auto res = std::find_if(std::begin(predecessors), std::end(predecessors),
  179. [&idoms, undefined_dom](BB* pred) {
  180. return idoms.count(pred) &&
  181. idoms[pred].dominator != undefined_dom;
  182. });
  183. if (res == end(predecessors)) continue;
  184. const BB* idom = *res;
  185. size_t idom_idx = idoms[idom].postorder_index;
  186. // all other predecessors
  187. for (const auto* p : predecessors) {
  188. if (idom == p) continue;
  189. // Only consider nodes reachable in the forward traversal.
  190. // Otherwise the intersection doesn't make sense and will never
  191. // terminate.
  192. if (!idoms.count(p)) continue;
  193. if (idoms[p].dominator != undefined_dom) {
  194. size_t finger1 = idoms[p].postorder_index;
  195. size_t finger2 = idom_idx;
  196. while (finger1 != finger2) {
  197. while (finger1 < finger2) {
  198. finger1 = idoms[postorder[finger1]].dominator;
  199. }
  200. while (finger2 < finger1) {
  201. finger2 = idoms[postorder[finger2]].dominator;
  202. }
  203. }
  204. idom_idx = finger1;
  205. }
  206. }
  207. if (idoms[*b].dominator != idom_idx) {
  208. idoms[*b].dominator = idom_idx;
  209. changed = true;
  210. }
  211. }
  212. }
  213. std::vector<std::pair<bb_ptr, bb_ptr>> out;
  214. for (auto idom : idoms) {
  215. // NOTE: performing a const cast for convenient usage with
  216. // UpdateImmediateDominators
  217. out.push_back({const_cast<BB*>(std::get<0>(idom)),
  218. const_cast<BB*>(postorder[std::get<1>(idom).dominator])});
  219. }
  220. // Sort by postorder index to generate a deterministic ordering of edges.
  221. std::sort(
  222. out.begin(), out.end(),
  223. [&idoms](const std::pair<bb_ptr, bb_ptr>& lhs,
  224. const std::pair<bb_ptr, bb_ptr>& rhs) {
  225. assert(lhs.first);
  226. assert(lhs.second);
  227. assert(rhs.first);
  228. assert(rhs.second);
  229. auto lhs_indices = std::make_pair(idoms[lhs.first].postorder_index,
  230. idoms[lhs.second].postorder_index);
  231. auto rhs_indices = std::make_pair(idoms[rhs.first].postorder_index,
  232. idoms[rhs.second].postorder_index);
  233. return lhs_indices < rhs_indices;
  234. });
  235. return out;
  236. }
  237. template <class BB>
  238. std::vector<BB*> CFA<BB>::TraversalRoots(const std::vector<BB*>& blocks,
  239. get_blocks_func succ_func,
  240. get_blocks_func pred_func) {
  241. // The set of nodes which have been visited from any of the roots so far.
  242. std::unordered_set<const BB*> visited;
  243. auto mark_visited = [&visited](const BB* b) { visited.insert(b); };
  244. auto ignore_block = [](const BB*) {};
  245. auto ignore_blocks = [](const BB*, const BB*) {};
  246. auto traverse_from_root = [&mark_visited, &succ_func, &ignore_block,
  247. &ignore_blocks](const BB* entry) {
  248. DepthFirstTraversal(entry, succ_func, mark_visited, ignore_block,
  249. ignore_blocks);
  250. };
  251. std::vector<BB*> result;
  252. // First collect nodes without predecessors.
  253. for (auto block : blocks) {
  254. if (pred_func(block)->empty()) {
  255. assert(visited.count(block) == 0 && "Malformed graph!");
  256. result.push_back(block);
  257. traverse_from_root(block);
  258. }
  259. }
  260. // Now collect other stranded nodes. These must be in unreachable cycles.
  261. for (auto block : blocks) {
  262. if (visited.count(block) == 0) {
  263. result.push_back(block);
  264. traverse_from_root(block);
  265. }
  266. }
  267. return result;
  268. }
  269. template <class BB>
  270. void CFA<BB>::ComputeAugmentedCFG(
  271. std::vector<BB*>& ordered_blocks, BB* pseudo_entry_block,
  272. BB* pseudo_exit_block,
  273. std::unordered_map<const BB*, std::vector<BB*>>* augmented_successors_map,
  274. std::unordered_map<const BB*, std::vector<BB*>>* augmented_predecessors_map,
  275. get_blocks_func succ_func, get_blocks_func pred_func) {
  276. // Compute the successors of the pseudo-entry block, and
  277. // the predecessors of the pseudo exit block.
  278. auto sources = TraversalRoots(ordered_blocks, succ_func, pred_func);
  279. // For the predecessor traversals, reverse the order of blocks. This
  280. // will affect the post-dominance calculation as follows:
  281. // - Suppose you have blocks A and B, with A appearing before B in
  282. // the list of blocks.
  283. // - Also, A branches only to B, and B branches only to A.
  284. // - We want to compute A as dominating B, and B as post-dominating B.
  285. // By using reversed blocks for predecessor traversal roots discovery,
  286. // we'll add an edge from B to the pseudo-exit node, rather than from A.
  287. // All this is needed to correctly process the dominance/post-dominance
  288. // constraint when A is a loop header that points to itself as its
  289. // own continue target, and B is the latch block for the loop.
  290. std::vector<BB*> reversed_blocks(ordered_blocks.rbegin(),
  291. ordered_blocks.rend());
  292. auto sinks = TraversalRoots(reversed_blocks, pred_func, succ_func);
  293. // Wire up the pseudo entry block.
  294. (*augmented_successors_map)[pseudo_entry_block] = sources;
  295. for (auto block : sources) {
  296. auto& augmented_preds = (*augmented_predecessors_map)[block];
  297. const auto preds = pred_func(block);
  298. augmented_preds.reserve(1 + preds->size());
  299. augmented_preds.push_back(pseudo_entry_block);
  300. augmented_preds.insert(augmented_preds.end(), preds->begin(), preds->end());
  301. }
  302. // Wire up the pseudo exit block.
  303. (*augmented_predecessors_map)[pseudo_exit_block] = sinks;
  304. for (auto block : sinks) {
  305. auto& augmented_succ = (*augmented_successors_map)[block];
  306. const auto succ = succ_func(block);
  307. augmented_succ.reserve(1 + succ->size());
  308. augmented_succ.push_back(pseudo_exit_block);
  309. augmented_succ.insert(augmented_succ.end(), succ->begin(), succ->end());
  310. }
  311. }
  312. } // namespace spvtools
  313. #endif // SOURCE_CFA_H_