SCCIterator.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //===---- ADT/SCCIterator.h - Strongly Connected Comp. Iter. ----*- 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. /// This builds on the llvm/ADT/GraphTraits.h file to find the strongly
  12. /// connected components (SCCs) of a graph in O(N+E) time using Tarjan's DFS
  13. /// algorithm.
  14. ///
  15. /// The SCC iterator has the important property that if a node in SCC S1 has an
  16. /// edge to a node in SCC S2, then it visits S1 *after* S2.
  17. ///
  18. /// To visit S1 *before* S2, use the scc_iterator on the Inverse graph. (NOTE:
  19. /// This requires some simple wrappers and is not supported yet.)
  20. ///
  21. //===----------------------------------------------------------------------===//
  22. #ifndef LLVM_ADT_SCCITERATOR_H
  23. #define LLVM_ADT_SCCITERATOR_H
  24. #include "llvm/ADT/DenseMap.h"
  25. #include "llvm/ADT/GraphTraits.h"
  26. #include "llvm/ADT/iterator.h"
  27. #include <vector>
  28. namespace llvm {
  29. /// \brief Enumerate the SCCs of a directed graph in reverse topological order
  30. /// of the SCC DAG.
  31. ///
  32. /// This is implemented using Tarjan's DFS algorithm using an internal stack to
  33. /// build up a vector of nodes in a particular SCC. Note that it is a forward
  34. /// iterator and thus you cannot backtrack or re-visit nodes.
  35. template <class GraphT, class GT = GraphTraits<GraphT>>
  36. class scc_iterator
  37. : public iterator_facade_base<
  38. scc_iterator<GraphT, GT>, std::forward_iterator_tag,
  39. const std::vector<typename GT::NodeType *>, ptrdiff_t> {
  40. typedef typename GT::NodeType NodeType;
  41. typedef typename GT::ChildIteratorType ChildItTy;
  42. typedef std::vector<NodeType *> SccTy;
  43. typedef typename scc_iterator::reference reference;
  44. /// Element of VisitStack during DFS.
  45. struct StackElement {
  46. NodeType *Node; ///< The current node pointer.
  47. ChildItTy NextChild; ///< The next child, modified inplace during DFS.
  48. unsigned MinVisited; ///< Minimum uplink value of all children of Node.
  49. StackElement(NodeType *Node, const ChildItTy &Child, unsigned Min)
  50. : Node(Node), NextChild(Child), MinVisited(Min) {}
  51. bool operator==(const StackElement &Other) const {
  52. return Node == Other.Node &&
  53. NextChild == Other.NextChild &&
  54. MinVisited == Other.MinVisited;
  55. }
  56. };
  57. /// The visit counters used to detect when a complete SCC is on the stack.
  58. /// visitNum is the global counter.
  59. ///
  60. /// nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
  61. unsigned visitNum;
  62. DenseMap<NodeType *, unsigned> nodeVisitNumbers;
  63. /// Stack holding nodes of the SCC.
  64. std::vector<NodeType *> SCCNodeStack;
  65. /// The current SCC, retrieved using operator*().
  66. SccTy CurrentSCC;
  67. /// DFS stack, Used to maintain the ordering. The top contains the current
  68. /// node, the next child to visit, and the minimum uplink value of all child
  69. std::vector<StackElement> VisitStack;
  70. /// A single "visit" within the non-recursive DFS traversal.
  71. void DFSVisitOne(NodeType *N);
  72. /// The stack-based DFS traversal; defined below.
  73. void DFSVisitChildren();
  74. /// Compute the next SCC using the DFS traversal.
  75. void GetNextSCC();
  76. scc_iterator(NodeType *entryN) : visitNum(0) {
  77. DFSVisitOne(entryN);
  78. GetNextSCC();
  79. }
  80. /// End is when the DFS stack is empty.
  81. scc_iterator() {}
  82. public:
  83. static scc_iterator begin(const GraphT &G) {
  84. return scc_iterator(GT::getEntryNode(G));
  85. }
  86. static scc_iterator end(const GraphT &) { return scc_iterator(); }
  87. /// \brief Direct loop termination test which is more efficient than
  88. /// comparison with \c end().
  89. bool isAtEnd() const {
  90. assert(!CurrentSCC.empty() || VisitStack.empty());
  91. return CurrentSCC.empty();
  92. }
  93. bool operator==(const scc_iterator &x) const {
  94. return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
  95. }
  96. scc_iterator &operator++() {
  97. GetNextSCC();
  98. return *this;
  99. }
  100. reference operator*() const {
  101. assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
  102. return CurrentSCC;
  103. }
  104. /// \brief Test if the current SCC has a loop.
  105. ///
  106. /// If the SCC has more than one node, this is trivially true. If not, it may
  107. /// still contain a loop if the node has an edge back to itself.
  108. bool hasLoop() const;
  109. /// This informs the \c scc_iterator that the specified \c Old node
  110. /// has been deleted, and \c New is to be used in its place.
  111. void ReplaceNode(NodeType *Old, NodeType *New) {
  112. assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
  113. nodeVisitNumbers[New] = nodeVisitNumbers[Old];
  114. nodeVisitNumbers.erase(Old);
  115. }
  116. };
  117. template <class GraphT, class GT>
  118. void scc_iterator<GraphT, GT>::DFSVisitOne(NodeType *N) {
  119. ++visitNum;
  120. nodeVisitNumbers[N] = visitNum;
  121. SCCNodeStack.push_back(N);
  122. VisitStack.push_back(StackElement(N, GT::child_begin(N), visitNum));
  123. #if 0 // Enable if needed when debugging.
  124. dbgs() << "TarjanSCC: Node " << N <<
  125. " : visitNum = " << visitNum << "\n";
  126. #endif
  127. }
  128. template <class GraphT, class GT>
  129. void scc_iterator<GraphT, GT>::DFSVisitChildren() {
  130. assert(!VisitStack.empty());
  131. while (VisitStack.back().NextChild != GT::child_end(VisitStack.back().Node)) {
  132. // TOS has at least one more child so continue DFS
  133. NodeType *childN = *VisitStack.back().NextChild++;
  134. typename DenseMap<NodeType *, unsigned>::iterator Visited =
  135. nodeVisitNumbers.find(childN);
  136. if (Visited == nodeVisitNumbers.end()) {
  137. // this node has never been seen.
  138. DFSVisitOne(childN);
  139. continue;
  140. }
  141. unsigned childNum = Visited->second;
  142. if (VisitStack.back().MinVisited > childNum)
  143. VisitStack.back().MinVisited = childNum;
  144. }
  145. }
  146. template <class GraphT, class GT> void scc_iterator<GraphT, GT>::GetNextSCC() {
  147. CurrentSCC.clear(); // Prepare to compute the next SCC
  148. while (!VisitStack.empty()) {
  149. DFSVisitChildren();
  150. // Pop the leaf on top of the VisitStack.
  151. NodeType *visitingN = VisitStack.back().Node;
  152. unsigned minVisitNum = VisitStack.back().MinVisited;
  153. assert(VisitStack.back().NextChild == GT::child_end(visitingN));
  154. VisitStack.pop_back();
  155. // Propagate MinVisitNum to parent so we can detect the SCC starting node.
  156. if (!VisitStack.empty() && VisitStack.back().MinVisited > minVisitNum)
  157. VisitStack.back().MinVisited = minVisitNum;
  158. #if 0 // Enable if needed when debugging.
  159. dbgs() << "TarjanSCC: Popped node " << visitingN <<
  160. " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
  161. nodeVisitNumbers[visitingN] << "\n";
  162. #endif
  163. if (minVisitNum != nodeVisitNumbers[visitingN])
  164. continue;
  165. // A full SCC is on the SCCNodeStack! It includes all nodes below
  166. // visitingN on the stack. Copy those nodes to CurrentSCC,
  167. // reset their minVisit values, and return (this suspends
  168. // the DFS traversal till the next ++).
  169. do {
  170. CurrentSCC.push_back(SCCNodeStack.back());
  171. SCCNodeStack.pop_back();
  172. nodeVisitNumbers[CurrentSCC.back()] = ~0U;
  173. } while (CurrentSCC.back() != visitingN);
  174. return;
  175. }
  176. }
  177. template <class GraphT, class GT>
  178. bool scc_iterator<GraphT, GT>::hasLoop() const {
  179. assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
  180. if (CurrentSCC.size() > 1)
  181. return true;
  182. NodeType *N = CurrentSCC.front();
  183. for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
  184. ++CI)
  185. if (*CI == N)
  186. return true;
  187. return false;
  188. }
  189. /// \brief Construct the begin iterator for a deduced graph type T.
  190. template <class T> scc_iterator<T> scc_begin(const T &G) {
  191. return scc_iterator<T>::begin(G);
  192. }
  193. /// \brief Construct the end iterator for a deduced graph type T.
  194. template <class T> scc_iterator<T> scc_end(const T &G) {
  195. return scc_iterator<T>::end(G);
  196. }
  197. /// \brief Construct the begin iterator for a deduced graph type T's Inverse<T>.
  198. template <class T> scc_iterator<Inverse<T> > scc_begin(const Inverse<T> &G) {
  199. return scc_iterator<Inverse<T> >::begin(G);
  200. }
  201. /// \brief Construct the end iterator for a deduced graph type T's Inverse<T>.
  202. template <class T> scc_iterator<Inverse<T> > scc_end(const Inverse<T> &G) {
  203. return scc_iterator<Inverse<T> >::end(G);
  204. }
  205. } // End llvm namespace
  206. #endif