1193323Sed//===- llvm/ADT/PostOrderIterator.h - PostOrder iterator --------*- C++ -*-===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file builds on the ADT/GraphTraits.h file to build a generic graph
11193323Sed// post order iterator.  This should work over any graph type that has a
12193323Sed// GraphTraits specialization.
13193323Sed//
14193323Sed//===----------------------------------------------------------------------===//
15193323Sed
16193323Sed#ifndef LLVM_ADT_POSTORDERITERATOR_H
17193323Sed#define LLVM_ADT_POSTORDERITERATOR_H
18193323Sed
19193323Sed#include "llvm/ADT/GraphTraits.h"
20194612Sed#include "llvm/ADT/SmallPtrSet.h"
21193323Sed#include <set>
22193323Sed#include <vector>
23193323Sed
24193323Sednamespace llvm {
25193323Sed
26239462Sdim// The po_iterator_storage template provides access to the set of already
27239462Sdim// visited nodes during the po_iterator's depth-first traversal.
28239462Sdim//
29239462Sdim// The default implementation simply contains a set of visited nodes, while
30239462Sdim// the Extended=true version uses a reference to an external set.
31239462Sdim//
32239462Sdim// It is possible to prune the depth-first traversal in several ways:
33239462Sdim//
34239462Sdim// - When providing an external set that already contains some graph nodes,
35239462Sdim//   those nodes won't be visited again. This is useful for restarting a
36239462Sdim//   post-order traversal on a graph with nodes that aren't dominated by a
37239462Sdim//   single node.
38239462Sdim//
39239462Sdim// - By providing a custom SetType class, unwanted graph nodes can be excluded
40239462Sdim//   by having the insert() function return false. This could for example
41239462Sdim//   confine a CFG traversal to blocks in a specific loop.
42239462Sdim//
43239462Sdim// - Finally, by specializing the po_iterator_storage template itself, graph
44239462Sdim//   edges can be pruned by returning false in the insertEdge() function. This
45239462Sdim//   could be used to remove loop back-edges from the CFG seen by po_iterator.
46239462Sdim//
47239462Sdim// A specialized po_iterator_storage class can observe both the pre-order and
48239462Sdim// the post-order. The insertEdge() function is called in a pre-order, while
49239462Sdim// the finishPostorder() function is called just before the po_iterator moves
50239462Sdim// on to the next node.
51239462Sdim
52239462Sdim/// Default po_iterator_storage implementation with an internal set object.
53239462Sdimtemplate<class SetType, bool External>
54193323Sedclass po_iterator_storage {
55239462Sdim  SetType Visited;
56193323Sedpublic:
57239462Sdim  // Return true if edge destination should be visited.
58239462Sdim  template<typename NodeType>
59239462Sdim  bool insertEdge(NodeType *From, NodeType *To) {
60239462Sdim    return Visited.insert(To);
61239462Sdim  }
62193323Sed
63239462Sdim  // Called after all children of BB have been visited.
64239462Sdim  template<typename NodeType>
65239462Sdim  void finishPostorder(NodeType *BB) {}
66226633Sdim};
67226633Sdim
68239462Sdim/// Specialization of po_iterator_storage that references an external set.
69226633Sdimtemplate<class SetType>
70193323Sedclass po_iterator_storage<SetType, true> {
71239462Sdim  SetType &Visited;
72193323Sedpublic:
73193323Sed  po_iterator_storage(SetType &VSet) : Visited(VSet) {}
74193323Sed  po_iterator_storage(const po_iterator_storage &S) : Visited(S.Visited) {}
75239462Sdim
76239462Sdim  // Return true if edge destination should be visited, called with From = 0 for
77239462Sdim  // the root node.
78239462Sdim  // Graph edges can be pruned by specializing this function.
79239462Sdim  template<class NodeType>
80239462Sdim  bool insertEdge(NodeType *From, NodeType *To) { return Visited.insert(To); }
81239462Sdim
82239462Sdim  // Called after all children of BB have been visited.
83239462Sdim  template<class NodeType>
84239462Sdim  void finishPostorder(NodeType *BB) {}
85193323Sed};
86193323Sed
87193323Sedtemplate<class GraphT,
88194612Sed  class SetType = llvm::SmallPtrSet<typename GraphTraits<GraphT>::NodeType*, 8>,
89194612Sed  bool ExtStorage = false,
90194612Sed  class GT = GraphTraits<GraphT> >
91198090Srdivackyclass po_iterator : public std::iterator<std::forward_iterator_tag,
92198090Srdivacky                                         typename GT::NodeType, ptrdiff_t>,
93193323Sed                    public po_iterator_storage<SetType, ExtStorage> {
94198090Srdivacky  typedef std::iterator<std::forward_iterator_tag,
95198090Srdivacky                        typename GT::NodeType, ptrdiff_t> super;
96193323Sed  typedef typename GT::NodeType          NodeType;
97193323Sed  typedef typename GT::ChildIteratorType ChildItTy;
98193323Sed
99193323Sed  // VisitStack - Used to maintain the ordering.  Top = current block
100193323Sed  // First element is basic block pointer, second is the 'next child' to visit
101210299Sed  std::vector<std::pair<NodeType *, ChildItTy> > VisitStack;
102193323Sed
103193323Sed  void traverseChild() {
104210299Sed    while (VisitStack.back().second != GT::child_end(VisitStack.back().first)) {
105210299Sed      NodeType *BB = *VisitStack.back().second++;
106239462Sdim      if (this->insertEdge(VisitStack.back().first, BB)) {
107239462Sdim        // If the block is not visited...
108210299Sed        VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
109193323Sed      }
110193323Sed    }
111193323Sed  }
112193323Sed
113193323Sed  inline po_iterator(NodeType *BB) {
114239462Sdim    this->insertEdge((NodeType*)0, BB);
115210299Sed    VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
116193323Sed    traverseChild();
117193323Sed  }
118193323Sed  inline po_iterator() {} // End is when stack is empty.
119193323Sed
120193323Sed  inline po_iterator(NodeType *BB, SetType &S) :
121198090Srdivacky    po_iterator_storage<SetType, ExtStorage>(S) {
122239462Sdim    if (this->insertEdge((NodeType*)0, BB)) {
123210299Sed      VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
124193323Sed      traverseChild();
125193323Sed    }
126193323Sed  }
127193323Sed
128193323Sed  inline po_iterator(SetType &S) :
129198090Srdivacky      po_iterator_storage<SetType, ExtStorage>(S) {
130193323Sed  } // End is when stack is empty.
131193323Sedpublic:
132193323Sed  typedef typename super::pointer pointer;
133193323Sed  typedef po_iterator<GraphT, SetType, ExtStorage, GT> _Self;
134193323Sed
135193323Sed  // Provide static "constructors"...
136193323Sed  static inline _Self begin(GraphT G) { return _Self(GT::getEntryNode(G)); }
137193323Sed  static inline _Self end  (GraphT G) { return _Self(); }
138193323Sed
139193323Sed  static inline _Self begin(GraphT G, SetType &S) {
140193323Sed    return _Self(GT::getEntryNode(G), S);
141193323Sed  }
142193323Sed  static inline _Self end  (GraphT G, SetType &S) { return _Self(S); }
143193323Sed
144193323Sed  inline bool operator==(const _Self& x) const {
145193323Sed    return VisitStack == x.VisitStack;
146193323Sed  }
147193323Sed  inline bool operator!=(const _Self& x) const { return !operator==(x); }
148193323Sed
149193323Sed  inline pointer operator*() const {
150210299Sed    return VisitStack.back().first;
151193323Sed  }
152193323Sed
153193323Sed  // This is a nonstandard operator-> that dereferences the pointer an extra
154193323Sed  // time... so that you can actually call methods ON the BasicBlock, because
155193323Sed  // the contained type is a pointer.  This allows BBIt->getTerminator() f.e.
156193323Sed  //
157193323Sed  inline NodeType *operator->() const { return operator*(); }
158193323Sed
159193323Sed  inline _Self& operator++() {   // Preincrement
160239462Sdim    this->finishPostorder(VisitStack.back().first);
161210299Sed    VisitStack.pop_back();
162193323Sed    if (!VisitStack.empty())
163193323Sed      traverseChild();
164193323Sed    return *this;
165193323Sed  }
166193323Sed
167193323Sed  inline _Self operator++(int) { // Postincrement
168193323Sed    _Self tmp = *this; ++*this; return tmp;
169193323Sed  }
170193323Sed};
171193323Sed
172193323Sed// Provide global constructors that automatically figure out correct types...
173193323Sed//
174193323Sedtemplate <class T>
175193323Sedpo_iterator<T> po_begin(T G) { return po_iterator<T>::begin(G); }
176193323Sedtemplate <class T>
177193323Sedpo_iterator<T> po_end  (T G) { return po_iterator<T>::end(G); }
178193323Sed
179193323Sed// Provide global definitions of external postorder iterators...
180193323Sedtemplate<class T, class SetType=std::set<typename GraphTraits<T>::NodeType*> >
181193323Sedstruct po_ext_iterator : public po_iterator<T, SetType, true> {
182193323Sed  po_ext_iterator(const po_iterator<T, SetType, true> &V) :
183193323Sed  po_iterator<T, SetType, true>(V) {}
184193323Sed};
185193323Sed
186193323Sedtemplate<class T, class SetType>
187193323Sedpo_ext_iterator<T, SetType> po_ext_begin(T G, SetType &S) {
188193323Sed  return po_ext_iterator<T, SetType>::begin(G, S);
189193323Sed}
190193323Sed
191193323Sedtemplate<class T, class SetType>
192193323Sedpo_ext_iterator<T, SetType> po_ext_end(T G, SetType &S) {
193193323Sed  return po_ext_iterator<T, SetType>::end(G, S);
194193323Sed}
195193323Sed
196193323Sed// Provide global definitions of inverse post order iterators...
197193323Sedtemplate <class T,
198193323Sed          class SetType = std::set<typename GraphTraits<T>::NodeType*>,
199193323Sed          bool External = false>
200193323Sedstruct ipo_iterator : public po_iterator<Inverse<T>, SetType, External > {
201193323Sed  ipo_iterator(const po_iterator<Inverse<T>, SetType, External> &V) :
202193323Sed     po_iterator<Inverse<T>, SetType, External> (V) {}
203193323Sed};
204193323Sed
205193323Sedtemplate <class T>
206193323Sedipo_iterator<T> ipo_begin(T G, bool Reverse = false) {
207193323Sed  return ipo_iterator<T>::begin(G, Reverse);
208193323Sed}
209193323Sed
210193323Sedtemplate <class T>
211193323Sedipo_iterator<T> ipo_end(T G){
212193323Sed  return ipo_iterator<T>::end(G);
213193323Sed}
214193323Sed
215239462Sdim// Provide global definitions of external inverse postorder iterators...
216193323Sedtemplate <class T,
217193323Sed          class SetType = std::set<typename GraphTraits<T>::NodeType*> >
218193323Sedstruct ipo_ext_iterator : public ipo_iterator<T, SetType, true> {
219193323Sed  ipo_ext_iterator(const ipo_iterator<T, SetType, true> &V) :
220239462Sdim    ipo_iterator<T, SetType, true>(V) {}
221193323Sed  ipo_ext_iterator(const po_iterator<Inverse<T>, SetType, true> &V) :
222239462Sdim    ipo_iterator<T, SetType, true>(V) {}
223193323Sed};
224193323Sed
225193323Sedtemplate <class T, class SetType>
226193323Sedipo_ext_iterator<T, SetType> ipo_ext_begin(T G, SetType &S) {
227193323Sed  return ipo_ext_iterator<T, SetType>::begin(G, S);
228193323Sed}
229193323Sed
230193323Sedtemplate <class T, class SetType>
231193323Sedipo_ext_iterator<T, SetType> ipo_ext_end(T G, SetType &S) {
232193323Sed  return ipo_ext_iterator<T, SetType>::end(G, S);
233193323Sed}
234193323Sed
235193323Sed//===--------------------------------------------------------------------===//
236193323Sed// Reverse Post Order CFG iterator code
237193323Sed//===--------------------------------------------------------------------===//
238193323Sed//
239193323Sed// This is used to visit basic blocks in a method in reverse post order.  This
240193323Sed// class is awkward to use because I don't know a good incremental algorithm to
241193323Sed// computer RPO from a graph.  Because of this, the construction of the
242193323Sed// ReversePostOrderTraversal object is expensive (it must walk the entire graph
243193323Sed// with a postorder iterator to build the data structures).  The moral of this
244193323Sed// story is: Don't create more ReversePostOrderTraversal classes than necessary.
245193323Sed//
246193323Sed// This class should be used like this:
247193323Sed// {
248193323Sed//   ReversePostOrderTraversal<Function*> RPOT(FuncPtr); // Expensive to create
249193323Sed//   for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
250193323Sed//      ...
251193323Sed//   }
252193323Sed//   for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
253193323Sed//      ...
254193323Sed//   }
255193323Sed// }
256193323Sed//
257193323Sed
258193323Sedtemplate<class GraphT, class GT = GraphTraits<GraphT> >
259193323Sedclass ReversePostOrderTraversal {
260193323Sed  typedef typename GT::NodeType NodeType;
261193323Sed  std::vector<NodeType*> Blocks;       // Block list in normal PO order
262193323Sed  inline void Initialize(NodeType *BB) {
263249423Sdim    std::copy(po_begin(BB), po_end(BB), std::back_inserter(Blocks));
264193323Sed  }
265193323Sedpublic:
266193323Sed  typedef typename std::vector<NodeType*>::reverse_iterator rpo_iterator;
267193323Sed
268193323Sed  inline ReversePostOrderTraversal(GraphT G) {
269193323Sed    Initialize(GT::getEntryNode(G));
270193323Sed  }
271193323Sed
272193323Sed  // Because we want a reverse post order, use reverse iterators from the vector
273193323Sed  inline rpo_iterator begin() { return Blocks.rbegin(); }
274193323Sed  inline rpo_iterator end()   { return Blocks.rend(); }
275193323Sed};
276193323Sed
277193323Sed} // End llvm namespace
278193323Sed
279193323Sed#endif
280