GenericDomTreeConstruction.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //===- GenericDomTreeConstruction.h - Dominator Calculation ------*- C++ -*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. ///
  11. /// Generic dominator tree construction - This file provides routines to
  12. /// construct immediate dominator information for a flow-graph based on the
  13. /// algorithm described in this document:
  14. ///
  15. /// A Fast Algorithm for Finding Dominators in a Flowgraph
  16. /// T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
  17. ///
  18. /// This implements the O(n*log(n)) versions of EVAL and LINK, because it turns
  19. /// out that the theoretically slower O(n*log(n)) implementation is actually
  20. /// faster than the almost-linear O(n*alpha(n)) version, even for large CFGs.
  21. ///
  22. //===----------------------------------------------------------------------===//
  23. #ifndef LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
  24. #define LLVM_SUPPORT_GENERICDOMTREECONSTRUCTION_H
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/Support/GenericDomTree.h"
  27. namespace llvm {
  28. template<class GraphT>
  29. unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
  30. typename GraphT::NodeType* V, unsigned N) {
  31. // This is more understandable as a recursive algorithm, but we can't use the
  32. // recursive algorithm due to stack depth issues. Keep it here for
  33. // documentation purposes.
  34. #if 0
  35. InfoRec &VInfo = DT.Info[DT.Roots[i]];
  36. VInfo.DFSNum = VInfo.Semi = ++N;
  37. VInfo.Label = V;
  38. Vertex.push_back(V); // Vertex[n] = V;
  39. for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
  40. InfoRec &SuccVInfo = DT.Info[*SI];
  41. if (SuccVInfo.Semi == 0) {
  42. SuccVInfo.Parent = V;
  43. N = DTDFSPass(DT, *SI, N);
  44. }
  45. }
  46. #else
  47. bool IsChildOfArtificialExit = (N != 0);
  48. SmallVector<std::pair<typename GraphT::NodeType*,
  49. typename GraphT::ChildIteratorType>, 32> Worklist;
  50. Worklist.push_back(std::make_pair(V, GraphT::child_begin(V)));
  51. while (!Worklist.empty()) {
  52. typename GraphT::NodeType* BB = Worklist.back().first;
  53. typename GraphT::ChildIteratorType NextSucc = Worklist.back().second;
  54. typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
  55. DT.Info[BB];
  56. // First time we visited this BB?
  57. if (NextSucc == GraphT::child_begin(BB)) {
  58. BBInfo.DFSNum = BBInfo.Semi = ++N;
  59. BBInfo.Label = BB;
  60. DT.Vertex.push_back(BB); // Vertex[n] = V;
  61. if (IsChildOfArtificialExit)
  62. BBInfo.Parent = 1;
  63. IsChildOfArtificialExit = false;
  64. }
  65. // store the DFS number of the current BB - the reference to BBInfo might
  66. // get invalidated when processing the successors.
  67. unsigned BBDFSNum = BBInfo.DFSNum;
  68. // If we are done with this block, remove it from the worklist.
  69. if (NextSucc == GraphT::child_end(BB)) {
  70. Worklist.pop_back();
  71. continue;
  72. }
  73. // Increment the successor number for the next time we get to it.
  74. ++Worklist.back().second;
  75. // Visit the successor next, if it isn't already visited.
  76. typename GraphT::NodeType* Succ = *NextSucc;
  77. typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &SuccVInfo =
  78. DT.Info[Succ];
  79. if (SuccVInfo.Semi == 0) {
  80. SuccVInfo.Parent = BBDFSNum;
  81. Worklist.push_back(std::make_pair(Succ, GraphT::child_begin(Succ)));
  82. }
  83. }
  84. #endif
  85. return N;
  86. }
  87. template<class GraphT>
  88. typename GraphT::NodeType*
  89. Eval(DominatorTreeBase<typename GraphT::NodeType>& DT,
  90. typename GraphT::NodeType *VIn, unsigned LastLinked) {
  91. typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInInfo =
  92. DT.Info[VIn];
  93. if (VInInfo.DFSNum < LastLinked)
  94. return VIn;
  95. SmallVector<typename GraphT::NodeType*, 32> Work;
  96. SmallPtrSet<typename GraphT::NodeType*, 32> Visited;
  97. if (VInInfo.Parent >= LastLinked)
  98. Work.push_back(VIn);
  99. while (!Work.empty()) {
  100. typename GraphT::NodeType* V = Work.back();
  101. typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VInfo =
  102. DT.Info[V];
  103. typename GraphT::NodeType* VAncestor = DT.Vertex[VInfo.Parent];
  104. // Process Ancestor first
  105. if (Visited.insert(VAncestor).second && VInfo.Parent >= LastLinked) {
  106. Work.push_back(VAncestor);
  107. continue;
  108. }
  109. Work.pop_back();
  110. // Update VInfo based on Ancestor info
  111. if (VInfo.Parent < LastLinked)
  112. continue;
  113. typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &VAInfo =
  114. DT.Info[VAncestor];
  115. typename GraphT::NodeType* VAncestorLabel = VAInfo.Label;
  116. typename GraphT::NodeType* VLabel = VInfo.Label;
  117. if (DT.Info[VAncestorLabel].Semi < DT.Info[VLabel].Semi)
  118. VInfo.Label = VAncestorLabel;
  119. VInfo.Parent = VAInfo.Parent;
  120. }
  121. return VInInfo.Label;
  122. }
  123. template<class FuncT, class NodeT>
  124. void Calculate(DominatorTreeBase<typename GraphTraits<NodeT>::NodeType>& DT,
  125. FuncT& F) {
  126. typedef GraphTraits<NodeT> GraphT;
  127. unsigned N = 0;
  128. bool MultipleRoots = (DT.Roots.size() > 1);
  129. if (MultipleRoots) {
  130. typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &BBInfo =
  131. DT.Info[nullptr];
  132. BBInfo.DFSNum = BBInfo.Semi = ++N;
  133. BBInfo.Label = nullptr;
  134. DT.Vertex.push_back(nullptr); // Vertex[n] = V;
  135. }
  136. // Step #1: Number blocks in depth-first order and initialize variables used
  137. // in later stages of the algorithm.
  138. for (unsigned i = 0, e = static_cast<unsigned>(DT.Roots.size());
  139. i != e; ++i)
  140. N = DFSPass<GraphT>(DT, DT.Roots[i], N);
  141. // it might be that some blocks did not get a DFS number (e.g., blocks of
  142. // infinite loops). In these cases an artificial exit node is required.
  143. MultipleRoots |= (DT.isPostDominator() && N != GraphTraits<FuncT*>::size(&F));
  144. // When naively implemented, the Lengauer-Tarjan algorithm requires a separate
  145. // bucket for each vertex. However, this is unnecessary, because each vertex
  146. // is only placed into a single bucket (that of its semidominator), and each
  147. // vertex's bucket is processed before it is added to any bucket itself.
  148. //
  149. // Instead of using a bucket per vertex, we use a single array Buckets that
  150. // has two purposes. Before the vertex V with preorder number i is processed,
  151. // Buckets[i] stores the index of the first element in V's bucket. After V's
  152. // bucket is processed, Buckets[i] stores the index of the next element in the
  153. // bucket containing V, if any.
  154. SmallVector<unsigned, 32> Buckets;
  155. Buckets.resize(N + 1);
  156. for (unsigned i = 1; i <= N; ++i)
  157. Buckets[i] = i;
  158. for (unsigned i = N; i >= 2; --i) {
  159. typename GraphT::NodeType* W = DT.Vertex[i];
  160. typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo =
  161. DT.Info[W];
  162. // Step #2: Implicitly define the immediate dominator of vertices
  163. for (unsigned j = i; Buckets[j] != i; j = Buckets[j]) {
  164. typename GraphT::NodeType* V = DT.Vertex[Buckets[j]];
  165. typename GraphT::NodeType* U = Eval<GraphT>(DT, V, i + 1);
  166. DT.IDoms[V] = DT.Info[U].Semi < i ? U : W;
  167. }
  168. // Step #3: Calculate the semidominators of all vertices
  169. // initialize the semi dominator to point to the parent node
  170. WInfo.Semi = WInfo.Parent;
  171. typedef GraphTraits<Inverse<NodeT> > InvTraits;
  172. for (typename InvTraits::ChildIteratorType CI =
  173. InvTraits::child_begin(W),
  174. E = InvTraits::child_end(W); CI != E; ++CI) {
  175. typename InvTraits::NodeType *N = *CI;
  176. if (DT.Info.count(N)) { // Only if this predecessor is reachable!
  177. unsigned SemiU = DT.Info[Eval<GraphT>(DT, N, i + 1)].Semi;
  178. if (SemiU < WInfo.Semi)
  179. WInfo.Semi = SemiU;
  180. }
  181. }
  182. // If V is a non-root vertex and sdom(V) = parent(V), then idom(V) is
  183. // necessarily parent(V). In this case, set idom(V) here and avoid placing
  184. // V into a bucket.
  185. if (WInfo.Semi == WInfo.Parent) {
  186. DT.IDoms[W] = DT.Vertex[WInfo.Parent];
  187. } else {
  188. Buckets[i] = Buckets[WInfo.Semi];
  189. Buckets[WInfo.Semi] = i;
  190. }
  191. }
  192. if (N >= 1) {
  193. typename GraphT::NodeType* Root = DT.Vertex[1];
  194. for (unsigned j = 1; Buckets[j] != 1; j = Buckets[j]) {
  195. typename GraphT::NodeType* V = DT.Vertex[Buckets[j]];
  196. DT.IDoms[V] = Root;
  197. }
  198. }
  199. // Step #4: Explicitly define the immediate dominator of each vertex
  200. for (unsigned i = 2; i <= N; ++i) {
  201. typename GraphT::NodeType* W = DT.Vertex[i];
  202. typename GraphT::NodeType*& WIDom = DT.IDoms[W];
  203. if (WIDom != DT.Vertex[DT.Info[W].Semi])
  204. WIDom = DT.IDoms[WIDom];
  205. }
  206. if (DT.Roots.empty()) return;
  207. // Add a node for the root. This node might be the actual root, if there is
  208. // one exit block, or it may be the virtual exit (denoted by (BasicBlock *)0)
  209. // which postdominates all real exits if there are multiple exit blocks, or
  210. // an infinite loop.
  211. typename GraphT::NodeType* Root = !MultipleRoots ? DT.Roots[0] : nullptr;
  212. DT.RootNode =
  213. (DT.DomTreeNodes[Root] =
  214. llvm::make_unique<DomTreeNodeBase<typename GraphT::NodeType>>(
  215. Root, nullptr)).get();
  216. // Loop over all of the reachable blocks in the function...
  217. for (unsigned i = 2; i <= N; ++i) {
  218. typename GraphT::NodeType* W = DT.Vertex[i];
  219. // Don't replace this with 'count', the insertion side effect is important
  220. if (DT.DomTreeNodes[W])
  221. continue; // Haven't calculated this node yet?
  222. typename GraphT::NodeType* ImmDom = DT.getIDom(W);
  223. assert(ImmDom || DT.DomTreeNodes[nullptr]);
  224. // Get or calculate the node for the immediate dominator
  225. DomTreeNodeBase<typename GraphT::NodeType> *IDomNode =
  226. DT.getNodeForBlock(ImmDom);
  227. // Add a new tree node for this BasicBlock, and link it as a child of
  228. // IDomNode
  229. DT.DomTreeNodes[W] = IDomNode->addChild(
  230. llvm::make_unique<DomTreeNodeBase<typename GraphT::NodeType>>(
  231. W, IDomNode));
  232. }
  233. // Free temporary memory used to construct idom's
  234. DT.IDoms.clear();
  235. DT.Info.clear();
  236. DT.Vertex.clear();
  237. DT.Vertex.shrink_to_fit();
  238. DT.updateDFSNumbers();
  239. }
  240. }
  241. #endif