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 /// \file 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/SmallVector.h" 22 #include "llvm/ADT/iterator_range.h" 23 #include <iterator> 24 #include <optional> 25 #include <set> 26 #include <utility> 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(std::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> 85 bool insertEdge(std::optional<NodeRef> From, NodeRef To) { 86 return Visited.insert(To).second; 87 } 88 89 // Called after all children of BB have been visited. 90 template <class NodeRef> void finishPostorder(NodeRef BB) {} 91 }; 92 93 template <class GraphT, 94 class SetType = SmallPtrSet<typename GraphTraits<GraphT>::NodeRef, 8>, 95 bool ExtStorage = false, class GT = GraphTraits<GraphT>> 96 class po_iterator : public po_iterator_storage<SetType, ExtStorage> { 97 public: 98 using iterator_category = std::forward_iterator_tag; 99 using value_type = typename GT::NodeRef; 100 using difference_type = std::ptrdiff_t; 101 using pointer = value_type *; 102 using reference = const value_type &; 103 104 private: 105 using NodeRef = typename GT::NodeRef; 106 using ChildItTy = typename GT::ChildIteratorType; 107 108 /// Used to maintain the ordering. 109 /// First element is basic block pointer, second is iterator for the next 110 /// child to visit, third is the end iterator. 111 SmallVector<std::tuple<NodeRef, ChildItTy, ChildItTy>, 8> VisitStack; 112 113 po_iterator(NodeRef BB) { 114 this->insertEdge(std::optional<NodeRef>(), BB); 115 VisitStack.emplace_back(BB, GT::child_begin(BB), GT::child_end(BB)); 116 traverseChild(); 117 } 118 119 po_iterator() = default; // End is when stack is empty. 120 121 po_iterator(NodeRef BB, SetType &S) 122 : po_iterator_storage<SetType, ExtStorage>(S) { 123 if (this->insertEdge(std::optional<NodeRef>(), BB)) { 124 VisitStack.emplace_back(BB, GT::child_begin(BB), GT::child_end(BB)); 125 traverseChild(); 126 } 127 } 128 129 po_iterator(SetType &S) 130 : po_iterator_storage<SetType, ExtStorage>(S) { 131 } // End is when stack is empty. 132 133 void traverseChild() { 134 while (true) { 135 auto &Entry = VisitStack.back(); 136 if (std::get<1>(Entry) == std::get<2>(Entry)) 137 break; 138 NodeRef BB = *std::get<1>(Entry)++; 139 if (this->insertEdge(std::optional<NodeRef>(std::get<0>(Entry)), BB)) { 140 // If the block is not visited... 141 VisitStack.emplace_back(BB, GT::child_begin(BB), GT::child_end(BB)); 142 } 143 } 144 } 145 146 public: 147 // Provide static "constructors"... 148 static po_iterator begin(const GraphT &G) { 149 return po_iterator(GT::getEntryNode(G)); 150 } 151 static po_iterator end(const GraphT &G) { return po_iterator(); } 152 153 static po_iterator begin(const GraphT &G, SetType &S) { 154 return po_iterator(GT::getEntryNode(G), S); 155 } 156 static po_iterator end(const GraphT &G, SetType &S) { return po_iterator(S); } 157 158 bool operator==(const po_iterator &x) const { 159 return VisitStack == x.VisitStack; 160 } 161 bool operator!=(const po_iterator &x) const { return !(*this == x); } 162 163 reference operator*() const { return std::get<0>(VisitStack.back()); } 164 165 // This is a nonstandard operator-> that dereferences the pointer an extra 166 // time... so that you can actually call methods ON the BasicBlock, because 167 // the contained type is a pointer. This allows BBIt->getTerminator() f.e. 168 // 169 NodeRef operator->() const { return **this; } 170 171 po_iterator &operator++() { // Preincrement 172 this->finishPostorder(std::get<0>(VisitStack.back())); 173 VisitStack.pop_back(); 174 if (!VisitStack.empty()) 175 traverseChild(); 176 return *this; 177 } 178 179 po_iterator operator++(int) { // Postincrement 180 po_iterator tmp = *this; 181 ++*this; 182 return tmp; 183 } 184 }; 185 186 // Provide global constructors that automatically figure out correct types... 187 // 188 template <class T> 189 po_iterator<T> po_begin(const T &G) { return po_iterator<T>::begin(G); } 190 template <class T> 191 po_iterator<T> po_end (const T &G) { return po_iterator<T>::end(G); } 192 193 template <class T> iterator_range<po_iterator<T>> post_order(const T &G) { 194 return make_range(po_begin(G), po_end(G)); 195 } 196 197 // Provide global definitions of external postorder iterators... 198 template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>> 199 struct po_ext_iterator : public po_iterator<T, SetType, true> { 200 po_ext_iterator(const po_iterator<T, SetType, true> &V) : 201 po_iterator<T, SetType, true>(V) {} 202 }; 203 204 template<class T, class SetType> 205 po_ext_iterator<T, SetType> po_ext_begin(T G, SetType &S) { 206 return po_ext_iterator<T, SetType>::begin(G, S); 207 } 208 209 template<class T, class SetType> 210 po_ext_iterator<T, SetType> po_ext_end(T G, SetType &S) { 211 return po_ext_iterator<T, SetType>::end(G, S); 212 } 213 214 template <class T, class SetType> 215 iterator_range<po_ext_iterator<T, SetType>> post_order_ext(const T &G, SetType &S) { 216 return make_range(po_ext_begin(G, S), po_ext_end(G, S)); 217 } 218 219 // Provide global definitions of inverse post order iterators... 220 template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>, 221 bool External = false> 222 struct ipo_iterator : public po_iterator<Inverse<T>, SetType, External> { 223 ipo_iterator(const po_iterator<Inverse<T>, SetType, External> &V) : 224 po_iterator<Inverse<T>, SetType, External> (V) {} 225 }; 226 227 template <class T> 228 ipo_iterator<T> ipo_begin(const T &G) { 229 return ipo_iterator<T>::begin(G); 230 } 231 232 template <class T> 233 ipo_iterator<T> ipo_end(const T &G){ 234 return ipo_iterator<T>::end(G); 235 } 236 237 template <class T> 238 iterator_range<ipo_iterator<T>> inverse_post_order(const T &G) { 239 return make_range(ipo_begin(G), ipo_end(G)); 240 } 241 242 // Provide global definitions of external inverse postorder iterators... 243 template <class T, class SetType = std::set<typename GraphTraits<T>::NodeRef>> 244 struct ipo_ext_iterator : public ipo_iterator<T, SetType, true> { 245 ipo_ext_iterator(const ipo_iterator<T, SetType, true> &V) : 246 ipo_iterator<T, SetType, true>(V) {} 247 ipo_ext_iterator(const po_iterator<Inverse<T>, SetType, true> &V) : 248 ipo_iterator<T, SetType, true>(V) {} 249 }; 250 251 template <class T, class SetType> 252 ipo_ext_iterator<T, SetType> ipo_ext_begin(const T &G, SetType &S) { 253 return ipo_ext_iterator<T, SetType>::begin(G, S); 254 } 255 256 template <class T, class SetType> 257 ipo_ext_iterator<T, SetType> ipo_ext_end(const T &G, SetType &S) { 258 return ipo_ext_iterator<T, SetType>::end(G, S); 259 } 260 261 template <class T, class SetType> 262 iterator_range<ipo_ext_iterator<T, SetType>> 263 inverse_post_order_ext(const T &G, SetType &S) { 264 return make_range(ipo_ext_begin(G, S), ipo_ext_end(G, S)); 265 } 266 267 //===--------------------------------------------------------------------===// 268 // Reverse Post Order CFG iterator code 269 //===--------------------------------------------------------------------===// 270 // 271 // This is used to visit basic blocks in a method in reverse post order. This 272 // class is awkward to use because I don't know a good incremental algorithm to 273 // computer RPO from a graph. Because of this, the construction of the 274 // ReversePostOrderTraversal object is expensive (it must walk the entire graph 275 // with a postorder iterator to build the data structures). The moral of this 276 // story is: Don't create more ReversePostOrderTraversal classes than necessary. 277 // 278 // Because it does the traversal in its constructor, it won't invalidate when 279 // BasicBlocks are removed, *but* it may contain erased blocks. Some places 280 // rely on this behavior (i.e. GVN). 281 // 282 // This class should be used like this: 283 // { 284 // ReversePostOrderTraversal<Function*> RPOT(FuncPtr); // Expensive to create 285 // for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) { 286 // ... 287 // } 288 // for (rpo_iterator I = RPOT.begin(); I != RPOT.end(); ++I) { 289 // ... 290 // } 291 // } 292 // 293 294 template<class GraphT, class GT = GraphTraits<GraphT>> 295 class ReversePostOrderTraversal { 296 using NodeRef = typename GT::NodeRef; 297 298 using VecTy = SmallVector<NodeRef, 8>; 299 VecTy Blocks; // Block list in normal PO order 300 301 void Initialize(const GraphT &G) { 302 std::copy(po_begin(G), po_end(G), std::back_inserter(Blocks)); 303 } 304 305 public: 306 using rpo_iterator = typename VecTy::reverse_iterator; 307 using const_rpo_iterator = typename VecTy::const_reverse_iterator; 308 309 ReversePostOrderTraversal(const GraphT &G) { Initialize(G); } 310 311 // Because we want a reverse post order, use reverse iterators from the vector 312 rpo_iterator begin() { return Blocks.rbegin(); } 313 const_rpo_iterator begin() const { return Blocks.rbegin(); } 314 rpo_iterator end() { return Blocks.rend(); } 315 const_rpo_iterator end() const { return Blocks.rend(); } 316 }; 317 318 } // end namespace llvm 319 320 #endif // LLVM_ADT_POSTORDERITERATOR_H 321