PostOrderIterator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. //===- llvm/ADT/PostOrderIterator.h - PostOrder iterator --------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file builds on the ADT/GraphTraits.h file to build a generic graph
  10. // post order iterator. This should work over any graph type that has a
  11. // GraphTraits specialization.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_ADT_POSTORDERITERATOR_H
  15. #define LLVM_ADT_POSTORDERITERATOR_H
  16. #include "llvm/ADT/GraphTraits.h"
  17. #include "llvm/ADT/Optional.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/iterator_range.h"
  21. #include <iterator>
  22. #include <set>
  23. #include <utility>
  24. #include <vector>
  25. namespace llvm {
  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 External=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. /// Default po_iterator_storage implementation with an internal set object.
  52. template<class SetType, bool External>
  53. class po_iterator_storage {
  54. SetType Visited;
  55. public:
  56. // Return true if edge destination should be visited.
  57. template <typename NodeRef>
  58. bool insertEdge(Optional<NodeRef> From, NodeRef To) {
  59. return Visited.insert(To).second;
  60. }
  61. // Called after all children of BB have been visited.
  62. template <typename NodeRef> void finishPostorder(NodeRef BB) {}
  63. };
  64. /// Specialization of po_iterator_storage that references an external set.
  65. template<class SetType>
  66. class po_iterator_storage<SetType, true> {
  67. SetType &Visited;
  68. public:
  69. po_iterator_storage(SetType &VSet) : Visited(VSet) {}
  70. po_iterator_storage(const po_iterator_storage &S) : Visited(S.Visited) {}
  71. // Return true if edge destination should be visited, called with From = 0 for
  72. // the root node.
  73. // Graph edges can be pruned by specializing this function.
  74. template <class NodeRef> bool insertEdge(Optional<NodeRef> From, NodeRef To) {
  75. return Visited.insert(To).second;
  76. }
  77. // Called after all children of BB have been visited.
  78. template <class NodeRef> void finishPostorder(NodeRef BB) {}
  79. };
  80. template <class GraphT,
  81. class SetType = SmallPtrSet<typename GraphTraits<GraphT>::NodeRef, 8>,
  82. bool ExtStorage = false, class GT = GraphTraits<GraphT>>
  83. class po_iterator : public po_iterator_storage<SetType, ExtStorage> {
  84. public:
  85. using iterator_category = std::forward_iterator_tag;
  86. using value_type = typename GT::NodeRef;
  87. using difference_type = std::ptrdiff_t;
  88. using pointer = value_type *;
  89. using reference = value_type &;
  90. private:
  91. using NodeRef = typename GT::NodeRef;
  92. using ChildItTy = typename GT::ChildIteratorType;
  93. // VisitStack - Used to maintain the ordering. Top = current block
  94. // First element is basic block pointer, second is the 'next child' to visit
  95. SmallVector<std::pair<NodeRef, ChildItTy>, 8> VisitStack;
  96. po_iterator(NodeRef BB) {
  97. this->insertEdge(Optional<NodeRef>(), BB);
  98. VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
  99. traverseChild();
  100. }
  101. po_iterator() = default; // End is when stack is empty.
  102. po_iterator(NodeRef BB, SetType &S)
  103. : po_iterator_storage<SetType, ExtStorage>(S) {
  104. if (this->insertEdge(Optional<NodeRef>(), BB)) {
  105. VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
  106. traverseChild();
  107. }
  108. }
  109. po_iterator(SetType &S)
  110. : po_iterator_storage<SetType, ExtStorage>(S) {
  111. } // End is when stack is empty.
  112. void traverseChild() {
  113. while (VisitStack.back().second != GT::child_end(VisitStack.back().first)) {
  114. NodeRef BB = *VisitStack.back().second++;
  115. if (this->insertEdge(Optional<NodeRef>(VisitStack.back().first), BB)) {
  116. // If the block is not visited...
  117. VisitStack.push_back(std::make_pair(BB, GT::child_begin(BB)));
  118. }
  119. }
  120. }
  121. public:
  122. // Provide static "constructors"...
  123. static po_iterator begin(const GraphT &G) {
  124. return po_iterator(GT::getEntryNode(G));
  125. }
  126. static po_iterator end(const GraphT &G) { return po_iterator(); }
  127. static po_iterator begin(const GraphT &G, SetType &S) {
  128. return po_iterator(GT::getEntryNode(G), S);
  129. }
  130. static po_iterator end(const GraphT &G, SetType &S) { return po_iterator(S); }
  131. bool operator==(const po_iterator &x) const {
  132. return VisitStack == x.VisitStack;
  133. }
  134. bool operator!=(const po_iterator &x) const { return !(*this == x); }
  135. const NodeRef &operator*() const { return VisitStack.back().first; }
  136. // This is a nonstandard operator-> that dereferences the pointer an extra
  137. // time... so that you can actually call methods ON the BasicBlock, because
  138. // the contained type is a pointer. This allows BBIt->getTerminator() f.e.
  139. //
  140. NodeRef operator->() const { return **this; }
  141. po_iterator &operator++() { // Preincrement
  142. this->finishPostorder(VisitStack.back().first);
  143. VisitStack.pop_back();
  144. if (!VisitStack.empty())
  145. traverseChild();
  146. return *this;
  147. }
  148. po_iterator operator++(int) { // Postincrement
  149. po_iterator tmp = *this;
  150. ++*this;
  151. return tmp;
  152. }
  153. };
  154. // Provide global constructors that automatically figure out correct types...
  155. //
  156. template <class T>
  157. po_iterator<T> po_begin(const T &G) { return po_iterator<T>::begin(G); }
  158. template <class T>
  159. po_iterator<T> po_end (const T &G) { return po_iterator<T>::end(G); }
  160. template <class T> iterator_range<po_iterator<T>> post_order(const T &G) {
  161. return make_range(po_begin(G), po_end(G));
  162. }
  163. // Provide global definitions of external postorder iterators...
  164. template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>>
  165. struct po_ext_iterator : public po_iterator<T, SetType, true> {
  166. po_ext_iterator(const po_iterator<T, SetType, true> &V) :
  167. po_iterator<T, SetType, true>(V) {}
  168. };
  169. template<class T, class SetType>
  170. po_ext_iterator<T, SetType> po_ext_begin(T G, SetType &S) {
  171. return po_ext_iterator<T, SetType>::begin(G, S);
  172. }
  173. template<class T, class SetType>
  174. po_ext_iterator<T, SetType> po_ext_end(T G, SetType &S) {
  175. return po_ext_iterator<T, SetType>::end(G, S);
  176. }
  177. template <class T, class SetType>
  178. iterator_range<po_ext_iterator<T, SetType>> post_order_ext(const T &G, SetType &S) {
  179. return make_range(po_ext_begin(G, S), po_ext_end(G, S));
  180. }
  181. // Provide global definitions of inverse post order iterators...
  182. template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>,
  183. bool External = false>
  184. struct ipo_iterator : public po_iterator<Inverse<T>, SetType, External> {
  185. ipo_iterator(const po_iterator<Inverse<T>, SetType, External> &V) :
  186. po_iterator<Inverse<T>, SetType, External> (V) {}
  187. };
  188. template <class T>
  189. ipo_iterator<T> ipo_begin(const T &G) {
  190. return ipo_iterator<T>::begin(G);
  191. }
  192. template <class T>
  193. ipo_iterator<T> ipo_end(const T &G){
  194. return ipo_iterator<T>::end(G);
  195. }
  196. template <class T>
  197. iterator_range<ipo_iterator<T>> inverse_post_order(const T &G) {
  198. return make_range(ipo_begin(G), ipo_end(G));
  199. }
  200. // Provide global definitions of external inverse postorder iterators...
  201. template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>>
  202. struct ipo_ext_iterator : public ipo_iterator<T, SetType, true> {
  203. ipo_ext_iterator(const ipo_iterator<T, SetType, true> &V) :
  204. ipo_iterator<T, SetType, true>(V) {}
  205. ipo_ext_iterator(const po_iterator<Inverse<T>, SetType, true> &V) :
  206. ipo_iterator<T, SetType, true>(V) {}
  207. };
  208. template <class T, class SetType>
  209. ipo_ext_iterator<T, SetType> ipo_ext_begin(const T &G, SetType &S) {
  210. return ipo_ext_iterator<T, SetType>::begin(G, S);
  211. }
  212. template <class T, class SetType>
  213. ipo_ext_iterator<T, SetType> ipo_ext_end(const T &G, SetType &S) {
  214. return ipo_ext_iterator<T, SetType>::end(G, S);
  215. }
  216. template <class T, class SetType>
  217. iterator_range<ipo_ext_iterator<T, SetType>>
  218. inverse_post_order_ext(const T &G, SetType &S) {
  219. return make_range(ipo_ext_begin(G, S), ipo_ext_end(G, S));
  220. }
  221. //===--------------------------------------------------------------------===//
  222. // Reverse Post Order CFG iterator code
  223. //===--------------------------------------------------------------------===//
  224. //
  225. // This is used to visit basic blocks in a method in reverse post order. This
  226. // class is awkward to use because I don't know a good incremental algorithm to
  227. // computer RPO from a graph. Because of this, the construction of the
  228. // ReversePostOrderTraversal object is expensive (it must walk the entire graph
  229. // with a postorder iterator to build the data structures). The moral of this
  230. // story is: Don't create more ReversePostOrderTraversal classes than necessary.
  231. //
  232. // Because it does the traversal in its constructor, it won't invalidate when
  233. // BasicBlocks are removed, *but* it may contain erased blocks. Some places
  234. // rely on this behavior (i.e. GVN).
  235. //
  236. // This class should be used like this:
  237. // {
  238. // ReversePostOrderTraversal<Function*> RPOT(FuncPtr); // Expensive to create
  239. // for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
  240. // ...
  241. // }
  242. // for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) {
  243. // ...
  244. // }
  245. // }
  246. //
  247. template<class GraphT, class GT = GraphTraits<GraphT>>
  248. class ReversePostOrderTraversal {
  249. using NodeRef = typename GT::NodeRef;
  250. std::vector<NodeRef> Blocks; // Block list in normal PO order
  251. void Initialize(const GraphT &G) {
  252. std::copy(po_begin(G), po_end(G), std::back_inserter(Blocks));
  253. }
  254. public:
  255. using rpo_iterator = typename std::vector<NodeRef>::reverse_iterator;
  256. using const_rpo_iterator = typename std::vector<NodeRef>::const_reverse_iterator;
  257. ReversePostOrderTraversal(const GraphT &G) { Initialize(G); }
  258. // Because we want a reverse post order, use reverse iterators from the vector
  259. rpo_iterator begin() { return Blocks.rbegin(); }
  260. const_rpo_iterator begin() const { return Blocks.crbegin(); }
  261. rpo_iterator end() { return Blocks.rend(); }
  262. const_rpo_iterator end() const { return Blocks.crend(); }
  263. };
  264. } // end namespace llvm
  265. #endif // LLVM_ADT_POSTORDERITERATOR_H