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 std::vector<typename GT::NodeType>, ptrdiff_t> {
42 typedef typename GT::NodeType NodeType;
43 typedef typename GT::ChildIteratorType ChildItTy;
44 typedef std::vector<NodeType *> SccTy;
45 typedef std::iterator<std::forward_iterator_tag,
46 std::vector<typename GT::NodeType>, ptrdiff_t> super;
47 typedef typename super::reference reference;
48 typedef typename super::pointer pointer;
50 /// Element of VisitStack during DFS.
52 NodeType *Node; ///< The current node pointer.
53 ChildItTy NextChild; ///< The next child, modified inplace during DFS.
54 unsigned MinVisited; ///< Minimum uplink value of all children of Node.
56 StackElement(NodeType *Node, const ChildItTy &Child, unsigned Min)
57 : Node(Node), NextChild(Child), MinVisited(Min) {}
59 bool operator==(const StackElement &Other) const {
60 return Node == Other.Node &&
61 NextChild == Other.NextChild &&
62 MinVisited == Other.MinVisited;
66 /// The visit counters used to detect when a complete SCC is on the stack.
67 /// visitNum is the global counter.
69 /// nodeVisitNumbers are per-node visit numbers, also used as DFS flags.
71 DenseMap<NodeType *, unsigned> nodeVisitNumbers;
73 /// Stack holding nodes of the SCC.
74 std::vector<NodeType *> SCCNodeStack;
76 /// The current SCC, retrieved using operator*().
79 /// DFS stack, Used to maintain the ordering. The top contains the current
80 /// node, the next child to visit, and the minimum uplink value of all child
81 std::vector<StackElement> VisitStack;
83 /// A single "visit" within the non-recursive DFS traversal.
84 void DFSVisitOne(NodeType *N);
86 /// The stack-based DFS traversal; defined below.
87 void DFSVisitChildren();
89 /// Compute the next SCC using the DFS traversal.
92 scc_iterator(NodeType *entryN) : visitNum(0) {
97 /// End is when the DFS stack is empty.
101 static scc_iterator begin(const GraphT &G) {
102 return scc_iterator(GT::getEntryNode(G));
104 static scc_iterator end(const GraphT &) { return scc_iterator(); }
106 /// \brief Direct loop termination test which is more efficient than
107 /// comparison with \c end().
108 bool isAtEnd() const {
109 assert(!CurrentSCC.empty() || VisitStack.empty());
110 return CurrentSCC.empty();
113 bool operator==(const scc_iterator &x) const {
114 return VisitStack == x.VisitStack && CurrentSCC == x.CurrentSCC;
116 bool operator!=(const scc_iterator &x) const { return !operator==(x); }
118 scc_iterator &operator++() {
122 scc_iterator operator++(int) {
123 scc_iterator tmp = *this;
128 const SccTy &operator*() const {
129 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
133 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
137 /// \brief Test if the current SCC has a loop.
139 /// If the SCC has more than one node, this is trivially true. If not, it may
140 /// still contain a loop if the node has an edge back to itself.
141 bool hasLoop() const;
143 /// This informs the \c scc_iterator that the specified \c Old node
144 /// has been deleted, and \c New is to be used in its place.
145 void ReplaceNode(NodeType *Old, NodeType *New) {
146 assert(nodeVisitNumbers.count(Old) && "Old not in scc_iterator?");
147 nodeVisitNumbers[New] = nodeVisitNumbers[Old];
148 nodeVisitNumbers.erase(Old);
152 template <class GraphT, class GT>
153 void scc_iterator<GraphT, GT>::DFSVisitOne(NodeType *N) {
155 nodeVisitNumbers[N] = visitNum;
156 SCCNodeStack.push_back(N);
157 VisitStack.push_back(StackElement(N, GT::child_begin(N), visitNum));
158 #if 0 // Enable if needed when debugging.
159 dbgs() << "TarjanSCC: Node " << N <<
160 " : visitNum = " << visitNum << "\n";
164 template <class GraphT, class GT>
165 void scc_iterator<GraphT, GT>::DFSVisitChildren() {
166 assert(!VisitStack.empty());
167 while (VisitStack.back().NextChild != GT::child_end(VisitStack.back().Node)) {
168 // TOS has at least one more child so continue DFS
169 NodeType *childN = *VisitStack.back().NextChild++;
170 typename DenseMap<NodeType *, unsigned>::iterator Visited =
171 nodeVisitNumbers.find(childN);
172 if (Visited == nodeVisitNumbers.end()) {
173 // this node has never been seen.
178 unsigned childNum = Visited->second;
179 if (VisitStack.back().MinVisited > childNum)
180 VisitStack.back().MinVisited = childNum;
184 template <class GraphT, class GT> void scc_iterator<GraphT, GT>::GetNextSCC() {
185 CurrentSCC.clear(); // Prepare to compute the next SCC
186 while (!VisitStack.empty()) {
189 // Pop the leaf on top of the VisitStack.
190 NodeType *visitingN = VisitStack.back().Node;
191 unsigned minVisitNum = VisitStack.back().MinVisited;
192 assert(VisitStack.back().NextChild == GT::child_end(visitingN));
193 VisitStack.pop_back();
195 // Propagate MinVisitNum to parent so we can detect the SCC starting node.
196 if (!VisitStack.empty() && VisitStack.back().MinVisited > minVisitNum)
197 VisitStack.back().MinVisited = minVisitNum;
199 #if 0 // Enable if needed when debugging.
200 dbgs() << "TarjanSCC: Popped node " << visitingN <<
201 " : minVisitNum = " << minVisitNum << "; Node visit num = " <<
202 nodeVisitNumbers[visitingN] << "\n";
205 if (minVisitNum != nodeVisitNumbers[visitingN])
208 // A full SCC is on the SCCNodeStack! It includes all nodes below
209 // visitingN on the stack. Copy those nodes to CurrentSCC,
210 // reset their minVisit values, and return (this suspends
211 // the DFS traversal till the next ++).
213 CurrentSCC.push_back(SCCNodeStack.back());
214 SCCNodeStack.pop_back();
215 nodeVisitNumbers[CurrentSCC.back()] = ~0U;
216 } while (CurrentSCC.back() != visitingN);
221 template <class GraphT, class GT>
222 bool scc_iterator<GraphT, GT>::hasLoop() const {
223 assert(!CurrentSCC.empty() && "Dereferencing END SCC iterator!");
224 if (CurrentSCC.size() > 1)
226 NodeType *N = CurrentSCC.front();
227 for (ChildItTy CI = GT::child_begin(N), CE = GT::child_end(N); CI != CE;
234 /// \brief Construct the begin iterator for a deduced graph type T.
235 template <class T> scc_iterator<T> scc_begin(const T &G) {
236 return scc_iterator<T>::begin(G);
239 /// \brief Construct the end iterator for a deduced graph type T.
240 template <class T> scc_iterator<T> scc_end(const T &G) {
241 return scc_iterator<T>::end(G);
244 /// \brief Construct the begin iterator for a deduced graph type T's Inverse<T>.
245 template <class T> scc_iterator<Inverse<T> > scc_begin(const Inverse<T> &G) {
246 return scc_iterator<Inverse<T> >::begin(G);
249 /// \brief Construct the end iterator for a deduced graph type T's Inverse<T>.
250 template <class T> scc_iterator<Inverse<T> > scc_end(const Inverse<T> &G) {
251 return scc_iterator<Inverse<T> >::end(G);
254 } // End llvm namespace