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