1 //===-- Support/SCCIterator.h - Strongly Connected Comp. Iter. --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected
11 // components (SCCs) of a graph in O(N+E) time using Tarjan's DFS algorithm.
13 // The SCC iterator has the important property that if a node in SCC S1 has an
14 // edge to a node in SCC S2, then it visits S1 *after* S2.
16 // To visit S1 *before* S2, use the scc_iterator on the Inverse graph.
17 // (NOTE: This requires some simple wrappers and is not supported yet.)
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ADT_SCCITERATOR_H
22 #define LLVM_ADT_SCCITERATOR_H
24 #include "llvm/ADT/GraphTraits.h"
25 #include "llvm/ADT/iterator"
31 //===----------------------------------------------------------------------===//
33 /// scc_iterator - Enumerate the SCCs of a directed graph, in
34 /// reverse topological order of the SCC DAG.
36 template<class GraphT, class GT = GraphTraits<GraphT> >
38 : public forward_iterator<std::vector<typename GT::NodeType>, ptrdiff_t> {
39 typedef typename GT::NodeType NodeType;
40 typedef typename GT::ChildIteratorType ChildItTy;
41 typedef std::vector<NodeType*> SccTy;
42 typedef forward_iterator<SccTy, ptrdiff_t> super;
43 typedef typename super::reference reference;
44 typedef typename super::pointer pointer;
46 // The visit counters used to detect when a complete SCC is on the stack.
47 // visitNum is the global counter.
48 // nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
50 std::map<NodeType *, unsigned> nodeVisitNumbers;
52 // SCCNodeStack - Stack holding nodes of the SCC.
53 std::vector<NodeType *> SCCNodeStack;
55 // CurrentSCC - The current SCC, retrieved using operator*().
58 // VisitStack - Used to maintain the ordering. Top = current block
59 // First element is basic block pointer, second is the 'next child' to visit
60 std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
62 // MinVistNumStack - Stack holding the "min" values for each node in the DFS.
63 // This is used to track the minimum uplink values for all children of
64 // the corresponding node on the VisitStack.
65 std::vector<unsigned> MinVisitNumStack;
67 // A single "visit" within the non-recursive DFS traversal.
68 void DFSVisitOne(NodeType* N) {
69 ++visitNum; // Global counter for the visit order
70 nodeVisitNumbers[N] = visitNum;
71 SCCNodeStack.push_back(N);
72 MinVisitNumStack.push_back(visitNum);
73 VisitStack.push_back(std::make_pair(N, GT::child_begin(N)));
74 //DEBUG(std::cerr << "TarjanSCC: Node " << N <<
75 // " : visitNum = " << visitNum << "\n");
78 // The stack-based DFS traversal; defined below.
79 void DFSVisitChildren() {
80 assert(!VisitStack.empty());
81 while (VisitStack.back().second != GT::child_end(VisitStack.back().first)) {
82 // TOS has at least one more child so continue DFS
83 NodeType *childN = *VisitStack.back().second++;
84 if (!nodeVisitNumbers.count(childN)) {
85 // this node has never been seen
88 unsigned childNum = nodeVisitNumbers[childN];
89 if (MinVisitNumStack.back() > childNum)
90 MinVisitNumStack.back() = childNum;
95 // Compute the next SCC using the DFS traversal.
97 assert(VisitStack.size() == MinVisitNumStack.size());
98 CurrentSCC.clear(); // Prepare to compute the next SCC
99 while (!VisitStack.empty()) {
101 assert(VisitStack.back().second ==GT::child_end(VisitStack.back().first));
102 NodeType* visitingN = VisitStack.back().first;
103 unsigned minVisitNum = MinVisitNumStack.back();
104 VisitStack.pop_back();
105 MinVisitNumStack.pop_back();
106 if (!MinVisitNumStack.empty() && MinVisitNumStack.back() > minVisitNum)
107 MinVisitNumStack.back() = minVisitNum;
109 //DEBUG(std::cerr << "TarjanSCC: Popped node " << visitingN <<
110 // " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
111 // nodeVisitNumbers[visitingN] << "\n");
113 if (minVisitNum == nodeVisitNumbers[visitingN]) {
114 // A full SCC is on the SCCNodeStack! It includes all nodes below
115 // visitingN on the stack. Copy those nodes to CurrentSCC,
116 // reset their minVisit values, and return (this suspends
117 // the DFS traversal till the next ++).
119 CurrentSCC.push_back(SCCNodeStack.back());
120 SCCNodeStack.pop_back();
121 nodeVisitNumbers[CurrentSCC.back()] = ~0U;
122 } while (CurrentSCC.back() != visitingN);
128 inline scc_iterator(NodeType *entryN) : visitNum(0) {
132 inline scc_iterator() { /* End is when DFS stack is empty */ }
135 typedef scc_iterator<GraphT, GT> _Self;
137 // Provide static "constructors"...
138 static inline _Self begin(GraphT& G) { return _Self(GT::getEntryNode(G)); }
139 static inline _Self end (GraphT& G) { return _Self(); }
141 // Direct loop termination test (I.fini() is more efficient than I == end())
142 inline bool fini() const {
143 assert(!CurrentSCC.empty() || VisitStack.empty());
144 return CurrentSCC.empty();
147 inline bool operator==(const _Self& x) const {
148 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
150 inline bool operator!=(const _Self& x) const { return !operator==(x); }
152 // Iterator traversal: forward iteration only
153 inline _Self& operator++() { // Preincrement
157 inline _Self operator++(int) { // Postincrement
158 _Self tmp = *this; ++*this; return tmp;
161 // Retrieve a reference to the current SCC
162 inline const SccTy &operator*() const {
163 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
166 inline SccTy &operator*() {
167 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
171 // hasLoop() -- Test if the current SCC has a loop. If it has more than one
172 // node, this is trivially true. If not, it may still contain a loop if the
173 // node has an edge back to itself.
174 bool hasLoop() const {
175 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
176 if (CurrentSCC.size() > 1) return true;
177 NodeType *N = CurrentSCC.front();
178 for (ChildItTy CI = GT::child_begin(N), CE=GT::child_end(N); CI != CE; ++CI)
186 // Global constructor for the SCC iterator.
188 scc_iterator<T> scc_begin(T G) {
189 return scc_iterator<T>::begin(G);
193 scc_iterator<T> scc_end(T G) {
194 return scc_iterator<T>::end(G);
197 } // End llvm namespace