SCCIterator.h 8.0 KB

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