fa337e9efb897b79c3a90705419f30ec619a847c
[oota-llvm.git] / include / llvm / ADT / PostOrderIterator.h
1 //===- llvm/ADT/PostOrderIterator.h - PostOrder iterator --------*- 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 file builds on the ADT/GraphTraits.h file to build a generic graph
11 // post order iterator.  This should work over any graph type that has a
12 // GraphTraits specialization.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_ADT_POSTORDERITERATOR_H
17 #define LLVM_ADT_POSTORDERITERATOR_H
18
19 #include "llvm/ADT/GraphTraits.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include <set>
22 #include <vector>
23
24 namespace llvm {
25
26 // The po_iterator_storage template provides access to the set of already
27 // visited nodes during the po_iterator's depth-first traversal.
28 //
29 // The default implementation simply contains a set of visited nodes, while
30 // the Extended=true version uses a reference to an external set.
31 //
32 // It is possible to prune the depth-first traversal in several ways:
33 //
34 // - When providing an external set that already contains some graph nodes,
35 //   those nodes won't be visited again. This is useful for restarting a
36 //   post-order traversal on a graph with nodes that aren't dominated by a
37 //   single node.
38 //
39 // - By providing a custom SetType class, unwanted graph nodes can be excluded
40 //   by having the insert() function return false. This could for example
41 //   confine a CFG traversal to blocks in a specific loop.
42 //
43 // - Finally, by specializing the po_iterator_storage template itself, graph
44 //   edges can be pruned by returning false in the insertEdge() function. This
45 //   could be used to remove loop back-edges from the CFG seen by po_iterator.
46 //
47 // A specialized po_iterator_storage class can observe both the pre-order and
48 // the post-order. The insertEdge() function is called in a pre-order, while
49 // the finishPostorder() function is called just before the po_iterator moves
50 // on to the next node.
51
52 /// Default po_iterator_storage implementation with an internal set object.
53 template<class SetType, bool External>
54 class po_iterator_storage {
55   SetType Visited;
56 public:
57   // Return true if edge destination should be visited.
58   template<typename NodeType>
59   bool insertEdge(NodeType *From, NodeType *To) {
60     return Visited.insert(To).second;
61   }
62
63   // Called after all children of BB have been visited.
64   template<typename NodeType>
65   void finishPostorder(NodeType *BB) {}
66 };
67
68 /// Specialization of po_iterator_storage that references an external set.
69 template<class SetType>
70 class po_iterator_storage<SetType, true> {
71   SetType &Visited;
72 public:
73   po_iterator_storage(SetType &VSet) : Visited(VSet) {}
74   po_iterator_storage(const po_iterator_storage &S) : Visited(S.Visited) {}
75
76   // Return true if edge destination should be visited, called with From = 0 for
77   // the root node.
78   // Graph edges can be pruned by specializing this function.
79   template <class NodeType> bool insertEdge(NodeType *From, NodeType *To) {
80     return Visited.insert(To).second;
81   }
82
83   // Called after all children of BB have been visited.
84   template<class NodeType>
85   void finishPostorder(NodeType *BB) {}
86 };
87
88 template<class GraphT,
89   class SetType = llvm::SmallPtrSet<typename GraphTraits<GraphT>::NodeType*, 8>,
90   bool ExtStorage = false,
91   class GT = GraphTraits<GraphT> >
92 class po_iterator : public std::iterator<std::forward_iterator_tag,
93                                          typename GT::NodeType, ptrdiff_t>,
94                     public po_iterator_storage<SetType, ExtStorage> {
95   typedef std::iterator<std::forward_iterator_tag,
96                         typename GT::NodeType, ptrdiff_t> super;
97   typedef typename GT::NodeType          NodeType;
98   typedef typename GT::ChildIteratorType ChildItTy;
99
100   // VisitStack - Used to maintain the ordering.  Top = current block
101   // First element is basic block pointer, second is the 'next child' to visit
102   std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
103
104   void traverseChild() {
105     while (VisitStack.back().second != GT::child_end(VisitStack.back().first)) {
106       NodeType *BB = *VisitStack.back().second++;
107       if (this->insertEdge(VisitStack.back().first, BB)) {
108         // If the block is not visited...
109         VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
110       }
111     }
112   }
113
114   po_iterator(NodeType *BB) {
115     this->insertEdge((NodeType*)nullptr, BB);
116     VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
117     traverseChild();
118   }
119   po_iterator() {} // End is when stack is empty.
120
121   po_iterator(NodeType *BB, SetType &S)
122       : po_iterator_storage<SetType, ExtStorage>(S) {
123     if (this->insertEdge((NodeType*)nullptr, BB)) {
124       VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
125       traverseChild();
126     }
127   }
128
129   po_iterator(SetType &S)
130       : po_iterator_storage<SetType, ExtStorage>(S) {
131   } // End is when stack is empty.
132 public:
133   typedef typename super::pointer pointer;
134
135   // Provide static "constructors"...
136   static po_iterator begin(GraphT G) {
137     return po_iterator(GT::getEntryNode(G));
138   }
139   static po_iterator end(GraphT G) { return po_iterator(); }
140
141   static po_iterator begin(GraphT G, SetType &S) {
142     return po_iterator(GT::getEntryNode(G), S);
143   }
144   static po_iterator end(GraphT G, SetType &S) { return po_iterator(S); }
145
146   bool operator==(const po_iterator &x) const {
147     return VisitStack == x.VisitStack;
148   }
149   bool operator!=(const po_iterator &x) const { return !(*this == x); }
150
151   pointer operator*() const { return VisitStack.back().first; }
152
153   // This is a nonstandard operator-> that dereferences the pointer an extra
154   // time... so that you can actually call methods ON the BasicBlock, because
155   // the contained type is a pointer.  This allows BBIt->getTerminator() f.e.
156   //
157   NodeType *operator->() const { return **this; }
158
159   po_iterator &operator++() { // Preincrement
160     this->finishPostorder(VisitStack.back().first);
161     VisitStack.pop_back();
162     if (!VisitStack.empty())
163       traverseChild();
164     return *this;
165   }
166
167   po_iterator operator++(int) { // Postincrement
168     po_iterator tmp = *this;
169     ++*this;
170     return tmp;
171   }
172 };
173
174 // Provide global constructors that automatically figure out correct types...
175 //
176 template <class T>
177 po_iterator<T> po_begin(T G) { return po_iterator<T>::begin(G); }
178 template <class T>
179 po_iterator<T> po_end  (T G) { return po_iterator<T>::end(G); }
180
181 // Provide global definitions of external postorder iterators...
182 template<class T, class SetType=std::set<typename GraphTraits<T>::NodeType*> >
183 struct po_ext_iterator : public po_iterator<T, SetType, true> {
184   po_ext_iterator(const po_iterator<T, SetType, true> &V) :
185   po_iterator<T, SetType, true>(V) {}
186 };
187
188 template<class T, class SetType>
189 po_ext_iterator<T, SetType> po_ext_begin(T G, SetType &S) {
190   return po_ext_iterator<T, SetType>::begin(G, S);
191 }
192
193 template<class T, class SetType>
194 po_ext_iterator<T, SetType> po_ext_end(T G, SetType &S) {
195   return po_ext_iterator<T, SetType>::end(G, S);
196 }
197
198 // Provide global definitions of inverse post order iterators...
199 template <class T,
200           class SetType = std::set<typename GraphTraits<T>::NodeType*>,
201           bool External = false>
202 struct ipo_iterator : public po_iterator<Inverse<T>, SetType, External > {
203   ipo_iterator(const po_iterator<Inverse<T>, SetType, External> &V) :
204      po_iterator<Inverse<T>, SetType, External> (V) {}
205 };
206
207 template <class T>
208 ipo_iterator<T> ipo_begin(T G, bool Reverse = false) {
209   return ipo_iterator<T>::begin(G, Reverse);
210 }
211
212 template <class T>
213 ipo_iterator<T> ipo_end(T G){
214   return ipo_iterator<T>::end(G);
215 }
216
217 // Provide global definitions of external inverse postorder iterators...
218 template <class T,
219           class SetType = std::set<typename GraphTraits<T>::NodeType*> >
220 struct ipo_ext_iterator : public ipo_iterator<T, SetType, true> {
221   ipo_ext_iterator(const ipo_iterator<T, SetType, true> &V) :
222     ipo_iterator<T, SetType, true>(V) {}
223   ipo_ext_iterator(const po_iterator<Inverse<T>, SetType, true> &V) :
224     ipo_iterator<T, SetType, true>(V) {}
225 };
226
227 template <class T, class SetType>
228 ipo_ext_iterator<T, SetType> ipo_ext_begin(T G, SetType &S) {
229   return ipo_ext_iterator<T, SetType>::begin(G, S);
230 }
231
232 template <class T, class SetType>
233 ipo_ext_iterator<T, SetType> ipo_ext_end(T G, SetType &S) {
234   return ipo_ext_iterator<T, SetType>::end(G, S);
235 }
236
237 //===--------------------------------------------------------------------===//
238 // Reverse Post Order CFG iterator code
239 //===--------------------------------------------------------------------===//
240 //
241 // This is used to visit basic blocks in a method in reverse post order.  This
242 // class is awkward to use because I don't know a good incremental algorithm to
243 // computer RPO from a graph.  Because of this, the construction of the
244 // ReversePostOrderTraversal object is expensive (it must walk the entire graph
245 // with a postorder iterator to build the data structures).  The moral of this
246 // story is: Don't create more ReversePostOrderTraversal classes than necessary.
247 //
248 // This class should be used like this:
249 // {
250 //   ReversePostOrderTraversal<Function*> RPOT(FuncPtr); // Expensive to create
251 //   for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
252 //      ...
253 //   }
254 //   for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
255 //      ...
256 //   }
257 // }
258 //
259
260 template<class GraphT, class GT = GraphTraits<GraphT> >
261 class ReversePostOrderTraversal {
262   typedef typename GT::NodeType NodeType;
263   std::vector<NodeType*> Blocks;       // Block list in normal PO order
264   void Initialize(NodeType *BB) {
265     std::copy(po_begin(BB), po_end(BB), std::back_inserter(Blocks));
266   }
267 public:
268   typedef typename std::vector<NodeType*>::reverse_iterator rpo_iterator;
269
270   ReversePostOrderTraversal(GraphT G) { Initialize(GT::getEntryNode(G)); }
271
272   // Because we want a reverse post order, use reverse iterators from the vector
273   rpo_iterator begin() { return Blocks.rbegin(); }
274   rpo_iterator end() { return Blocks.rend(); }
275 };
276
277 } // End llvm namespace
278
279 #endif