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