1 //===---- ADT/SCCIterator.h - Strongly Connected Comp. Iter. ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This builds on the llvm/ADT/GraphTraits.h file to find the strongly
12 /// connected components (SCCs) of a graph in O(N+E) time using Tarjan's DFS
15 /// The SCC iterator has the important property that if a node in SCC S1 has an
16 /// edge to a node in SCC S2, then it visits S1 *after* S2.
18 /// To visit S1 *before* S2, use the scc_iterator on the Inverse graph. (NOTE:
19 /// This requires some simple wrappers and is not supported yet.)
21 //===----------------------------------------------------------------------===//
23 #ifndef LLVM_ADT_SCCITERATOR_H
24 #define LLVM_ADT_SCCITERATOR_H
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/GraphTraits.h"
32 /// \brief Enumerate the SCCs of a directed graph in reverse topological order
35 /// This is implemented using Tarjan's DFS algorithm using an internal stack to
36 /// build up a vector of nodes in a particular SCC. Note that it is a forward
37 /// iterator and thus you cannot backtrack or re-visit nodes.
38 template <class GraphT, class GT = GraphTraits<GraphT>>
40 : public std::iterator<std::forward_iterator_tag,
41 const std::vector<typename GT::NodeType>,
43 typedef typename GT::NodeType NodeType;
44 typedef typename GT::ChildIteratorType ChildItTy;
45 typedef std::vector<NodeType *> SccTy;
46 typedef std::iterator<std::forward_iterator_tag,
47 const std::vector<typename GT::NodeType>,
49 typedef typename super::reference reference;
50 typedef typename super::pointer pointer;
52 /// Element of VisitStack during DFS.
54 NodeType *Node; ///< The current node pointer.
55 ChildItTy NextChild; ///< The next child, modified inplace during DFS.
56 unsigned MinVisited; ///< Minimum uplink value of all children of Node.
58 StackElement(NodeType *Node, const ChildItTy &Child, unsigned Min)
59 : Node(Node), NextChild(Child), MinVisited(Min) {}
61 bool operator==(const StackElement &Other) const {
62 return Node == Other.Node &&
63 NextChild == Other.NextChild &&
64 MinVisited == Other.MinVisited;
68 /// The visit counters used to detect when a complete SCC is on the stack.
69 /// visitNum is the global counter.
71 /// nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
73 DenseMap<NodeType *, unsigned> nodeVisitNumbers;
75 /// Stack holding nodes of the SCC.
76 std::vector<NodeType *> SCCNodeStack;
78 /// The current SCC, retrieved using operator*().
81 /// DFS stack, Used to maintain the ordering. The top contains the current
82 /// node, the next child to visit, and the minimum uplink value of all child
83 std::vector<StackElement> VisitStack;
85 /// A single "visit" within the non-recursive DFS traversal.
86 void DFSVisitOne(NodeType *N);
88 /// The stack-based DFS traversal; defined below.
89 void DFSVisitChildren();
91 /// Compute the next SCC using the DFS traversal.
94 scc_iterator(NodeType *entryN) : visitNum(0) {
99 /// End is when the DFS stack is empty.
103 static scc_iterator begin(const GraphT &G) {
104 return scc_iterator(GT::getEntryNode(G));
106 static scc_iterator end(const GraphT &) { return scc_iterator(); }
108 /// \brief Direct loop termination test which is more efficient than
109 /// comparison with \c end().
110 bool isAtEnd() const {
111 assert(!CurrentSCC.empty() || VisitStack.empty());
112 return CurrentSCC.empty();
115 bool operator==(const scc_iterator &x) const {
116 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
118 bool operator!=(const scc_iterator &x) const { return !operator==(x); }
120 scc_iterator &operator++() {
124 scc_iterator operator++(int) {
125 scc_iterator tmp = *this;
130 const SccTy &operator*() const {
131 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
135 /// \brief Test if the current SCC has a loop.
137 /// If the SCC has more than one node, this is trivially true. If not, it may
138 /// still contain a loop if the node has an edge back to itself.
139 bool hasLoop() const;
141 /// This informs the \c scc_iterator that the specified \c Old node
142 /// has been deleted, and \c New is to be used in its place.
143 void ReplaceNode(NodeType *Old, NodeType *New) {
144 assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
145 nodeVisitNumbers[New] = nodeVisitNumbers[Old];
146 nodeVisitNumbers.erase(Old);
150 template <class GraphT, class GT>
151 void scc_iterator<GraphT, GT>::DFSVisitOne(NodeType *N) {
153 nodeVisitNumbers[N] = visitNum;
154 SCCNodeStack.push_back(N);
155 VisitStack.push_back(StackElement(N, GT::child_begin(N), visitNum));
156 #if 0 // Enable if needed when debugging.
157 dbgs() << "TarjanSCC: Node " << N <<
158 " : visitNum = " << visitNum << "\n";
162 template <class GraphT, class GT>
163 void scc_iterator<GraphT, GT>::DFSVisitChildren() {
164 assert(!VisitStack.empty());
165 while (VisitStack.back().NextChild != GT::child_end(VisitStack.back().Node)) {
166 // TOS has at least one more child so continue DFS
167 NodeType *childN = *VisitStack.back().NextChild++;
168 typename DenseMap<NodeType *, unsigned>::iterator Visited =
169 nodeVisitNumbers.find(childN);
170 if (Visited == nodeVisitNumbers.end()) {
171 // this node has never been seen.
176 unsigned childNum = Visited->second;
177 if (VisitStack.back().MinVisited > childNum)
178 VisitStack.back().MinVisited = childNum;
182 template <class GraphT, class GT> void scc_iterator<GraphT, GT>::GetNextSCC() {
183 CurrentSCC.clear(); // Prepare to compute the next SCC
184 while (!VisitStack.empty()) {
187 // Pop the leaf on top of the VisitStack.
188 NodeType *visitingN = VisitStack.back().Node;
189 unsigned minVisitNum = VisitStack.back().MinVisited;
190 assert(VisitStack.back().NextChild == GT::child_end(visitingN));
191 VisitStack.pop_back();
193 // Propagate MinVisitNum to parent so we can detect the SCC starting node.
194 if (!VisitStack.empty() && VisitStack.back().MinVisited > minVisitNum)
195 VisitStack.back().MinVisited = minVisitNum;
197 #if 0 // Enable if needed when debugging.
198 dbgs() << "TarjanSCC: Popped node " << visitingN <<
199 " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
200 nodeVisitNumbers[visitingN] << "\n";
203 if (minVisitNum != nodeVisitNumbers[visitingN])
206 // A full SCC is on the SCCNodeStack! It includes all nodes below
207 // visitingN on the stack. Copy those nodes to CurrentSCC,
208 // reset their minVisit values, and return (this suspends
209 // the DFS traversal till the next ++).
211 CurrentSCC.push_back(SCCNodeStack.back());
212 SCCNodeStack.pop_back();
213 nodeVisitNumbers[CurrentSCC.back()] = ~0U;
214 } while (CurrentSCC.back() != visitingN);
219 template <class GraphT, class GT>
220 bool scc_iterator<GraphT, GT>::hasLoop() const {
221 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
222 if (CurrentSCC.size() > 1)
224 NodeType *N = CurrentSCC.front();
225 for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
232 /// \brief Construct the begin iterator for a deduced graph type T.
233 template <class T> scc_iterator<T> scc_begin(const T &G) {
234 return scc_iterator<T>::begin(G);
237 /// \brief Construct the end iterator for a deduced graph type T.
238 template <class T> scc_iterator<T> scc_end(const T &G) {
239 return scc_iterator<T>::end(G);
242 /// \brief Construct the begin iterator for a deduced graph type T's Inverse<T>.
243 template <class T> scc_iterator<Inverse<T> > scc_begin(const Inverse<T> &G) {
244 return scc_iterator<Inverse<T> >::begin(G);
247 /// \brief Construct the end iterator for a deduced graph type T's Inverse<T>.
248 template <class T> scc_iterator<Inverse<T> > scc_end(const Inverse<T> &G) {
249 return scc_iterator<Inverse<T> >::end(G);
252 } // End llvm namespace