9ca0f1c00e753ed484eb1e9ddde0adb65302302a
[oota-llvm.git] / include / llvm / ADT / SCCIterator.h
1 //===-- Support/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 //
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.
12 //
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.
15 //
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.)
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_ADT_SCCITERATOR_H
22 #define LLVM_ADT_SCCITERATOR_H
23
24 #include "llvm/ADT/GraphTraits.h"
25 #include <map>
26 #include <vector>
27
28 namespace llvm {
29
30 //===----------------------------------------------------------------------===//
31 ///
32 /// scc_iterator - Enumerate the SCCs of a directed graph, in
33 /// reverse topological order of the SCC DAG.
34 ///
35 template<class GraphT, class GT = GraphTraits<GraphT> >
36 class scc_iterator
37   : public std::iterator<std::forward_iterator_tag, std::vector<typename GT::NodeType>, ptrdiff_t> {
38   typedef typename GT::NodeType          NodeType;
39   typedef typename GT::ChildIteratorType ChildItTy;
40   typedef std::vector<NodeType*> SccTy;
41   typedef std::iterator<std::forward_iterator_tag, std::vector<typename GT::NodeType>, ptrdiff_t> super;
42   typedef typename super::reference reference;
43   typedef typename super::pointer pointer;
44
45   // The visit counters used to detect when a complete SCC is on the stack.
46   // visitNum is the global counter.
47   // nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
48   unsigned visitNum;
49   std::map<NodeType *, unsigned> nodeVisitNumbers;
50
51   // SCCNodeStack - Stack holding nodes of the SCC.
52   std::vector<NodeType *> SCCNodeStack;
53
54   // CurrentSCC - The current SCC, retrieved using operator*().
55   SccTy CurrentSCC;
56
57   // VisitStack - Used to maintain the ordering.  Top = current block
58   // First element is basic block pointer, second is the 'next child' to visit
59   std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
60
61   // MinVistNumStack - Stack holding the "min" values for each node in the DFS.
62   // This is used to track the minimum uplink values for all children of
63   // the corresponding node on the VisitStack.
64   std::vector<unsigned> MinVisitNumStack;
65
66   // A single "visit" within the non-recursive DFS traversal.
67   void DFSVisitOne(NodeType* N) {
68     ++visitNum;                         // Global counter for the visit order
69     nodeVisitNumbers[N] = visitNum;
70     SCCNodeStack.push_back(N);
71     MinVisitNumStack.push_back(visitNum);
72     VisitStack.push_back(std::make_pair(N, GT::child_begin(N)));
73     //errs() << "TarjanSCC: Node " << N <<
74     //      " : visitNum = " << visitNum << "\n";
75   }
76
77   // The stack-based DFS traversal; defined below.
78   void DFSVisitChildren() {
79     assert(!VisitStack.empty());
80     while (VisitStack.back().second != GT::child_end(VisitStack.back().first)) {
81       // TOS has at least one more child so continue DFS
82       NodeType *childN = *VisitStack.back().second++;
83       if (!nodeVisitNumbers.count(childN)) {
84         // this node has never been seen
85         DFSVisitOne(childN);
86       } else {
87         unsigned childNum = nodeVisitNumbers[childN];
88         if (MinVisitNumStack.back() > childNum)
89           MinVisitNumStack.back() = childNum;
90       }
91     }
92   }
93
94   // Compute the next SCC using the DFS traversal.
95   void GetNextSCC() {
96     assert(VisitStack.size() == MinVisitNumStack.size());
97     CurrentSCC.clear();                 // Prepare to compute the next SCC
98     while (!VisitStack.empty()) {
99       DFSVisitChildren();
100       assert(VisitStack.back().second ==GT::child_end(VisitStack.back().first));
101       NodeType* visitingN = VisitStack.back().first;
102       unsigned minVisitNum = MinVisitNumStack.back();
103       VisitStack.pop_back();
104       MinVisitNumStack.pop_back();
105       if (!MinVisitNumStack.empty() && MinVisitNumStack.back() > minVisitNum)
106         MinVisitNumStack.back() = minVisitNum;
107
108       //errs() << "TarjanSCC: Popped node " << visitingN <<
109       //      " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
110       //      nodeVisitNumbers[visitingN] << "\n";
111
112       if (minVisitNum == nodeVisitNumbers[visitingN]) {
113         // A full SCC is on the SCCNodeStack!  It includes all nodes below
114           // visitingN on the stack.  Copy those nodes to CurrentSCC,
115           // reset their minVisit values, and return (this suspends
116           // the DFS traversal till the next ++).
117           do {
118             CurrentSCC.push_back(SCCNodeStack.back());
119             SCCNodeStack.pop_back();
120             nodeVisitNumbers[CurrentSCC.back()] = ~0U;
121           } while (CurrentSCC.back() != visitingN);
122           return;
123         }
124     }
125   }
126
127   inline scc_iterator(NodeType *entryN) : visitNum(0) {
128     DFSVisitOne(entryN);
129     GetNextSCC();
130   }
131   inline scc_iterator() { /* End is when DFS stack is empty */ }
132
133 public:
134   typedef scc_iterator<GraphT, GT> _Self;
135
136   // Provide static "constructors"...
137   static inline _Self begin(GraphT& G) { return _Self(GT::getEntryNode(G)); }
138   static inline _Self end  (GraphT& G) { return _Self(); }
139
140   // Direct loop termination test (I.fini() is more efficient than I == end())
141   inline bool fini() const {
142     assert(!CurrentSCC.empty() || VisitStack.empty());
143     return CurrentSCC.empty();
144   }
145
146   inline bool operator==(const _Self& x) const {
147     return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
148   }
149   inline bool operator!=(const _Self& x) const { return !operator==(x); }
150
151   // Iterator traversal: forward iteration only
152   inline _Self& operator++() {          // Preincrement
153     GetNextSCC();
154     return *this;
155   }
156   inline _Self operator++(int) {        // Postincrement
157     _Self tmp = *this; ++*this; return tmp;
158   }
159
160   // Retrieve a reference to the current SCC
161   inline const SccTy &operator*() const {
162     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
163     return CurrentSCC;
164   }
165   inline SccTy &operator*() {
166     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
167     return CurrentSCC;
168   }
169
170   // hasLoop() -- Test if the current SCC has a loop.  If it has more than one
171   // node, this is trivially true.  If not, it may still contain a loop if the
172   // node has an edge back to itself.
173   bool hasLoop() const {
174     assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
175     if (CurrentSCC.size() > 1) return true;
176     NodeType *N = CurrentSCC.front();
177     for (ChildItTy CI = GT::child_begin(N), CE=GT::child_end(N); CI != CE; ++CI)
178       if (*CI == N)
179         return true;
180     return false;
181   }
182 };
183
184
185 // Global constructor for the SCC iterator.
186 template <class T>
187 scc_iterator<T> scc_begin(T G) {
188   return scc_iterator<T>::begin(G);
189 }
190
191 template <class T>
192 scc_iterator<T> scc_end(T G) {
193   return scc_iterator<T>::end(G);
194 }
195
196 } // End llvm namespace
197
198 #endif