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