1 //===-- Support/TarjanSCCIterator.h - Tarjan SCC iterator -------*- C++ -*-===//
3 // This builds on the Support/GraphTraits.h file to find the strongly
4 // connected components (SCCs) of a graph in O(N+E) time using
5 // Tarjan's DFS algorithm.
7 // The SCC iterator has the important property that if a node in SCC S1
8 // has an edge to a node in SCC S2, then it visits S1 *after* S2.
10 // To visit S1 *before* S2, use the TarjanSCCIterator on the Inverse graph.
11 // (NOTE: This requires some simple wrappers and is not supported yet.)
13 //===----------------------------------------------------------------------===//
15 #ifndef SUPPORT_TARJANSCCITERATOR_H
16 #define SUPPORT_TARJANSCCITERATOR_H
18 #include "Support/GraphTraits.h"
19 #include "Support/iterator"
23 //--------------------------------------------------------------------------
24 // class SCC - A simple representation of an SCC in a generic Graph.
25 //--------------------------------------------------------------------------
27 template<class GraphT, class GT = GraphTraits<GraphT> >
28 struct SCC : public std::vector<typename GT::NodeType*> {
30 typedef typename GT::NodeType NodeType;
31 typedef typename GT::ChildIteratorType ChildItTy;
33 typedef std::vector<typename GT::NodeType*> super;
34 typedef typename super::iterator iterator;
35 typedef typename super::const_iterator const_iterator;
36 typedef typename super::reverse_iterator reverse_iterator;
37 typedef typename super::const_reverse_iterator const_reverse_iterator;
39 // HasLoop() -- Test if this SCC has a loop. If it has more than one
40 // node, this is trivially true. If not, it may still contain a loop
41 // if the node has an edge back to itself.
42 bool HasLoop() const {
43 if (size() > 1) return true;
44 NodeType* N = front();
45 for (ChildItTy CI = GT::child_begin(N), CE=GT::child_end(N); CI != CE; ++CI)
52 //--------------------------------------------------------------------------
53 // class TarjanSCC_iterator: Enumerate the SCCs of a directed graph, in
54 // reverse topological order of the SCC DAG.
55 //--------------------------------------------------------------------------
57 template<class GraphT, class GT = GraphTraits<GraphT> >
58 class TarjanSCC_iterator : public forward_iterator<SCC<GraphT, GT>, ptrdiff_t> {
59 typedef SCC<GraphT, GT> SccTy;
60 typedef forward_iterator<SccTy, ptrdiff_t> super;
61 typedef typename super::reference reference;
62 typedef typename super::pointer pointer;
63 typedef typename GT::NodeType NodeType;
64 typedef typename GT::ChildIteratorType ChildItTy;
66 // The visit counters used to detect when a complete SCC is on the stack.
67 // visitNum is the global counter.
68 // nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
70 std::map<NodeType *, unsigned> nodeVisitNumbers;
72 // SCCNodeStack - Stack holding nodes of the SCC.
73 std::vector<NodeType *> SCCNodeStack;
75 // CurrentSCC - The current SCC, retrieved using operator*().
78 // VisitStack - Used to maintain the ordering. Top = current block
79 // First element is basic block pointer, second is the 'next child' to visit
80 std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
82 // MinVistNumStack - Stack holding the "min" values for each node in the DFS.
83 // This is used to track the minimum uplink values for all children of
84 // the corresponding node on the VisitStack.
85 std::vector<unsigned> MinVisitNumStack;
87 // A single "visit" within the non-recursive DFS traversal.
88 void DFSVisitOne(NodeType* N) {
89 ++visitNum; // Global counter for the visit order
90 nodeVisitNumbers[N] = visitNum;
91 SCCNodeStack.push_back(N);
92 MinVisitNumStack.push_back(visitNum);
93 VisitStack.push_back(make_pair(N, GT::child_begin(N)));
94 //DEBUG(std::cerr << "TarjanSCC: Node " << N <<
95 // " : visitNum = " << visitNum << "\n");
98 // The stack-based DFS traversal; defined below.
99 void DFSVisitChildren() {
100 assert(!VisitStack.empty());
101 while (VisitStack.back().second != GT::child_end(VisitStack.back().first))
102 { // TOS has at least one more child so continue DFS
103 NodeType *childN = *VisitStack.back().second++;
104 if (nodeVisitNumbers.find(childN) == nodeVisitNumbers.end())
105 { // this node has never been seen
110 unsigned childNum = nodeVisitNumbers[childN];
111 if (MinVisitNumStack.back() > childNum)
112 MinVisitNumStack.back() = childNum;
117 // Compute the next SCC using the DFS traversal.
119 assert(VisitStack.size() == MinVisitNumStack.size());
120 CurrentSCC.clear(); // Prepare to compute the next SCC
121 while (! VisitStack.empty())
125 assert(VisitStack.back().second ==
126 GT::child_end(VisitStack.back().first));
127 NodeType* visitingN = VisitStack.back().first;
128 unsigned minVisitNum = MinVisitNumStack.back();
129 VisitStack.pop_back();
130 MinVisitNumStack.pop_back();
131 if (! MinVisitNumStack.empty() && MinVisitNumStack.back() > minVisitNum)
132 MinVisitNumStack.back() = minVisitNum;
134 //DEBUG(std::cerr << "TarjanSCC: Popped node " << visitingN <<
135 // " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
136 // nodeVisitNumbers[visitingN] << "\n");
138 if (minVisitNum == nodeVisitNumbers[visitingN])
139 { // A full SCC is on the SCCNodeStack! It includes all nodes below
140 // visitingN on the stack. Copy those nodes to CurrentSCC,
141 // reset their minVisit values, and return (this suspends
142 // the DFS traversal till the next ++).
144 CurrentSCC.push_back(SCCNodeStack.back());
145 SCCNodeStack.pop_back();
146 nodeVisitNumbers[CurrentSCC.back()] = ~0UL;
147 } while (CurrentSCC.back() != visitingN);
153 inline TarjanSCC_iterator(NodeType *entryN) : visitNum(0) {
157 inline TarjanSCC_iterator() { /* End is when DFS stack is empty */ }
160 typedef TarjanSCC_iterator<GraphT, GT> _Self;
162 // Provide static "constructors"...
163 static inline _Self begin(GraphT& G) { return _Self(GT::getEntryNode(G)); }
164 static inline _Self end (GraphT& G) { return _Self(); }
166 // Direct loop termination test (I.fini() is more efficient than I == end())
167 inline bool fini() const {
168 assert(!CurrentSCC.empty() || VisitStack.empty());
169 return CurrentSCC.empty();
172 inline bool operator==(const _Self& x) const {
173 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
175 inline bool operator!=(const _Self& x) const { return !operator==(x); }
177 // Iterator traversal: forward iteration only
178 inline _Self& operator++() { // Preincrement
182 inline _Self operator++(int) { // Postincrement
183 _Self tmp = *this; ++*this; return tmp;
186 // Retrieve a reference to the current SCC
187 inline const SccTy &operator*() const {
188 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
191 inline SccTy &operator*() {
192 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
198 // Global constructor for the Tarjan SCC iterator.
200 TarjanSCC_iterator<T> tarj_begin(T G) {
201 return TarjanSCC_iterator<T>::begin(G);
205 TarjanSCC_iterator<T> tarj_end(T G) {
206 return TarjanSCC_iterator<T>::end(G);