1 //===-- Support/SCCIterator.h - SCC iterator --------------------*- C++ -*-===//
3 // This builds on the Support/GraphTraits.h file to find the strongly connected
4 // components (SCCs) of a graph in O(N+E) time using Tarjan's DFS algorithm.
6 // The SCC iterator has the important property that if a node in SCC S1 has an
7 // edge to a node in SCC S2, then it visits S1 *after* S2.
9 // To visit S1 *before* S2, use the scc_iterator on the Inverse graph.
10 // (NOTE: This requires some simple wrappers and is not supported yet.)
12 //===----------------------------------------------------------------------===//
14 #ifndef SUPPORT_SCCITERATOR_H
15 #define SUPPORT_SCCITERATOR_H
17 #include "Support/GraphTraits.h"
18 #include "Support/iterator"
22 //===----------------------------------------------------------------------===//
24 /// scc_iterator - Enumerate the SCCs of a directed graph, in
25 /// reverse topological order of the SCC DAG.
27 template<class GraphT, class GT = GraphTraits<GraphT> >
29 : public forward_iterator<std::vector<typename GT::NodeType>, ptrdiff_t> {
30 typedef typename GT::NodeType NodeType;
31 typedef typename GT::ChildIteratorType ChildItTy;
32 typedef std::vector<NodeType*> SccTy;
33 typedef forward_iterator<SccTy, ptrdiff_t> super;
34 typedef typename super::reference reference;
35 typedef typename super::pointer pointer;
37 // The visit counters used to detect when a complete SCC is on the stack.
38 // visitNum is the global counter.
39 // nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
41 std::map<NodeType *, unsigned> nodeVisitNumbers;
43 // SCCNodeStack - Stack holding nodes of the SCC.
44 std::vector<NodeType *> SCCNodeStack;
46 // CurrentSCC - The current SCC, retrieved using operator*().
49 // VisitStack - Used to maintain the ordering. Top = current block
50 // First element is basic block pointer, second is the 'next child' to visit
51 std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
53 // MinVistNumStack - Stack holding the "min" values for each node in the DFS.
54 // This is used to track the minimum uplink values for all children of
55 // the corresponding node on the VisitStack.
56 std::vector<unsigned> MinVisitNumStack;
58 // A single "visit" within the non-recursive DFS traversal.
59 void DFSVisitOne(NodeType* N) {
60 ++visitNum; // Global counter for the visit order
61 nodeVisitNumbers[N] = visitNum;
62 SCCNodeStack.push_back(N);
63 MinVisitNumStack.push_back(visitNum);
64 VisitStack.push_back(make_pair(N, GT::child_begin(N)));
65 //DEBUG(std::cerr << "TarjanSCC: Node " << N <<
66 // " : visitNum = " << visitNum << "\n");
69 // The stack-based DFS traversal; defined below.
70 void DFSVisitChildren() {
71 assert(!VisitStack.empty());
72 while (VisitStack.back().second != GT::child_end(VisitStack.back().first))
73 { // TOS has at least one more child so continue DFS
74 NodeType *childN = *VisitStack.back().second++;
75 if (nodeVisitNumbers.find(childN) == nodeVisitNumbers.end())
76 { // this node has never been seen
81 unsigned childNum = nodeVisitNumbers[childN];
82 if (MinVisitNumStack.back() > childNum)
83 MinVisitNumStack.back() = childNum;
88 // Compute the next SCC using the DFS traversal.
90 assert(VisitStack.size() == MinVisitNumStack.size());
91 CurrentSCC.clear(); // Prepare to compute the next SCC
92 while (! VisitStack.empty())
96 assert(VisitStack.back().second ==
97 GT::child_end(VisitStack.back().first));
98 NodeType* visitingN = VisitStack.back().first;
99 unsigned minVisitNum = MinVisitNumStack.back();
100 VisitStack.pop_back();
101 MinVisitNumStack.pop_back();
102 if (! MinVisitNumStack.empty() && MinVisitNumStack.back() > minVisitNum)
103 MinVisitNumStack.back() = minVisitNum;
105 //DEBUG(std::cerr << "TarjanSCC: Popped node " << visitingN <<
106 // " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
107 // nodeVisitNumbers[visitingN] << "\n");
109 if (minVisitNum == nodeVisitNumbers[visitingN])
110 { // A full SCC is on the SCCNodeStack! It includes all nodes below
111 // visitingN on the stack. Copy those nodes to CurrentSCC,
112 // reset their minVisit values, and return (this suspends
113 // the DFS traversal till the next ++).
115 CurrentSCC.push_back(SCCNodeStack.back());
116 SCCNodeStack.pop_back();
117 nodeVisitNumbers[CurrentSCC.back()] = ~0UL;
118 } while (CurrentSCC.back() != visitingN);
124 inline scc_iterator(NodeType *entryN) : visitNum(0) {
128 inline scc_iterator() { /* End is when DFS stack is empty */ }
131 typedef scc_iterator<GraphT, GT> _Self;
133 // Provide static "constructors"...
134 static inline _Self begin(GraphT& G) { return _Self(GT::getEntryNode(G)); }
135 static inline _Self end (GraphT& G) { return _Self(); }
137 // Direct loop termination test (I.fini() is more efficient than I == end())
138 inline bool fini() const {
139 assert(!CurrentSCC.empty() || VisitStack.empty());
140 return CurrentSCC.empty();
143 inline bool operator==(const _Self& x) const {
144 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
146 inline bool operator!=(const _Self& x) const { return !operator==(x); }
148 // Iterator traversal: forward iteration only
149 inline _Self& operator++() { // Preincrement
153 inline _Self operator++(int) { // Postincrement
154 _Self tmp = *this; ++*this; return tmp;
157 // Retrieve a reference to the current SCC
158 inline const SccTy &operator*() const {
159 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
162 inline SccTy &operator*() {
163 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
167 // hasLoop() -- Test if the current SCC has a loop. If it has more than one
168 // node, this is trivially true. If not, it may still contain a loop if the
169 // node has an edge back to itself.
170 bool hasLoop() const {
171 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
172 if (CurrentSCC.size() > 1) return true;
173 NodeType *N = CurrentSCC.front();
174 for (ChildItTy CI = GT::child_begin(N), CE=GT::child_end(N); CI != CE; ++CI)
182 // Global constructor for the SCC iterator.
184 scc_iterator<T> scc_begin(T G) {
185 return scc_iterator<T>::begin(G);
189 scc_iterator<T> scc_end(T G) {
190 return scc_iterator<T>::end(G);