DepthFirstIterator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/DepthFirstIterator.h - Depth First iterator -----*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file builds on the ADT/GraphTraits.h file to build generic depth
  16. /// first graph iterator. This file exposes the following functions/types:
  17. ///
  18. /// df_begin/df_end/df_iterator
  19. /// * Normal depth-first iteration - visit a node and then all of its
  20. /// children.
  21. ///
  22. /// idf_begin/idf_end/idf_iterator
  23. /// * Depth-first iteration on the 'inverse' graph.
  24. ///
  25. /// df_ext_begin/df_ext_end/df_ext_iterator
  26. /// * Normal depth-first iteration - visit a node and then all of its
  27. /// children. This iterator stores the 'visited' set in an external set,
  28. /// which allows it to be more efficient, and allows external clients to
  29. /// use the set for other purposes.
  30. ///
  31. /// idf_ext_begin/idf_ext_end/idf_ext_iterator
  32. /// * Depth-first iteration on the 'inverse' graph.
  33. /// This iterator stores the 'visited' set in an external set, which
  34. /// allows it to be more efficient, and allows external clients to use
  35. /// the set for other purposes.
  36. ///
  37. //===----------------------------------------------------------------------===//
  38. #ifndef LLVM_ADT_DEPTHFIRSTITERATOR_H
  39. #define LLVM_ADT_DEPTHFIRSTITERATOR_H
  40. #include "llvm/ADT/GraphTraits.h"
  41. #include "llvm/ADT/None.h"
  42. #include "llvm/ADT/Optional.h"
  43. #include "llvm/ADT/SmallPtrSet.h"
  44. #include "llvm/ADT/iterator_range.h"
  45. #include <iterator>
  46. #include <utility>
  47. #include <vector>
  48. namespace llvm {
  49. // df_iterator_storage - A private class which is used to figure out where to
  50. // store the visited set.
  51. template<class SetType, bool External> // Non-external set
  52. class df_iterator_storage {
  53. public:
  54. SetType Visited;
  55. };
  56. template<class SetType>
  57. class df_iterator_storage<SetType, true> {
  58. public:
  59. df_iterator_storage(SetType &VSet) : Visited(VSet) {}
  60. df_iterator_storage(const df_iterator_storage &S) : Visited(S.Visited) {}
  61. SetType &Visited;
  62. };
  63. // The visited stated for the iteration is a simple set augmented with
  64. // one more method, completed, which is invoked when all children of a
  65. // node have been processed. It is intended to distinguish of back and
  66. // cross edges in the spanning tree but is not used in the common case.
  67. template <typename NodeRef, unsigned SmallSize=8>
  68. struct df_iterator_default_set : public SmallPtrSet<NodeRef, SmallSize> {
  69. using BaseSet = SmallPtrSet<NodeRef, SmallSize>;
  70. using iterator = typename BaseSet::iterator;
  71. std::pair<iterator,bool> insert(NodeRef N) { return BaseSet::insert(N); }
  72. template <typename IterT>
  73. void insert(IterT Begin, IterT End) { BaseSet::insert(Begin,End); }
  74. void completed(NodeRef) {}
  75. };
  76. // Generic Depth First Iterator
  77. template <class GraphT,
  78. class SetType =
  79. df_iterator_default_set<typename GraphTraits<GraphT>::NodeRef>,
  80. bool ExtStorage = false, class GT = GraphTraits<GraphT>>
  81. class df_iterator : public df_iterator_storage<SetType, ExtStorage> {
  82. public:
  83. using iterator_category = std::forward_iterator_tag;
  84. using value_type = typename GT::NodeRef;
  85. using difference_type = std::ptrdiff_t;
  86. using pointer = value_type *;
  87. using reference = value_type &;
  88. private:
  89. using NodeRef = typename GT::NodeRef;
  90. using ChildItTy = typename GT::ChildIteratorType;
  91. // First element is node reference, second is the 'next child' to visit.
  92. // The second child is initialized lazily to pick up graph changes during the
  93. // DFS.
  94. using StackElement = std::pair<NodeRef, Optional<ChildItTy>>;
  95. // VisitStack - Used to maintain the ordering. Top = current block
  96. std::vector<StackElement> VisitStack;
  97. inline df_iterator(NodeRef Node) {
  98. this->Visited.insert(Node);
  99. VisitStack.push_back(StackElement(Node, None));
  100. }
  101. inline df_iterator() = default; // End is when stack is empty
  102. inline df_iterator(NodeRef Node, SetType &S)
  103. : df_iterator_storage<SetType, ExtStorage>(S) {
  104. if (this->Visited.insert(Node).second)
  105. VisitStack.push_back(StackElement(Node, None));
  106. }
  107. inline df_iterator(SetType &S)
  108. : df_iterator_storage<SetType, ExtStorage>(S) {
  109. // End is when stack is empty
  110. }
  111. inline void toNext() {
  112. do {
  113. NodeRef Node = VisitStack.back().first;
  114. Optional<ChildItTy> &Opt = VisitStack.back().second;
  115. if (!Opt)
  116. Opt.emplace(GT::child_begin(Node));
  117. // Notice that we directly mutate *Opt here, so that
  118. // VisitStack.back().second actually gets updated as the iterator
  119. // increases.
  120. while (*Opt != GT::child_end(Node)) {
  121. NodeRef Next = *(*Opt)++;
  122. // Has our next sibling been visited?
  123. if (this->Visited.insert(Next).second) {
  124. // No, do it now.
  125. VisitStack.push_back(StackElement(Next, None));
  126. return;
  127. }
  128. }
  129. this->Visited.completed(Node);
  130. // Oops, ran out of successors... go up a level on the stack.
  131. VisitStack.pop_back();
  132. } while (!VisitStack.empty());
  133. }
  134. public:
  135. // Provide static begin and end methods as our public "constructors"
  136. static df_iterator begin(const GraphT &G) {
  137. return df_iterator(GT::getEntryNode(G));
  138. }
  139. static df_iterator end(const GraphT &G) { return df_iterator(); }
  140. // Static begin and end methods as our public ctors for external iterators
  141. static df_iterator begin(const GraphT &G, SetType &S) {
  142. return df_iterator(GT::getEntryNode(G), S);
  143. }
  144. static df_iterator end(const GraphT &G, SetType &S) { return df_iterator(S); }
  145. bool operator==(const df_iterator &x) const {
  146. return VisitStack == x.VisitStack;
  147. }
  148. bool operator!=(const df_iterator &x) const { return !(*this == x); }
  149. const NodeRef &operator*() const { return VisitStack.back().first; }
  150. // This is a nonstandard operator-> that dereferences the pointer an extra
  151. // time... so that you can actually call methods ON the Node, because
  152. // the contained type is a pointer. This allows BBIt->getTerminator() f.e.
  153. //
  154. NodeRef operator->() const { return **this; }
  155. df_iterator &operator++() { // Preincrement
  156. toNext();
  157. return *this;
  158. }
  159. /// Skips all children of the current node and traverses to next node
  160. ///
  161. /// Note: This function takes care of incrementing the iterator. If you
  162. /// always increment and call this function, you risk walking off the end.
  163. df_iterator &skipChildren() {
  164. VisitStack.pop_back();
  165. if (!VisitStack.empty())
  166. toNext();
  167. return *this;
  168. }
  169. df_iterator operator++(int) { // Postincrement
  170. df_iterator tmp = *this;
  171. ++*this;
  172. return tmp;
  173. }
  174. // nodeVisited - return true if this iterator has already visited the
  175. // specified node. This is public, and will probably be used to iterate over
  176. // nodes that a depth first iteration did not find: ie unreachable nodes.
  177. //
  178. bool nodeVisited(NodeRef Node) const {
  179. return this->Visited.contains(Node);
  180. }
  181. /// getPathLength - Return the length of the path from the entry node to the
  182. /// current node, counting both nodes.
  183. unsigned getPathLength() const { return VisitStack.size(); }
  184. /// getPath - Return the n'th node in the path from the entry node to the
  185. /// current node.
  186. NodeRef getPath(unsigned n) const { return VisitStack[n].first; }
  187. };
  188. // Provide global constructors that automatically figure out correct types...
  189. //
  190. template <class T>
  191. df_iterator<T> df_begin(const T& G) {
  192. return df_iterator<T>::begin(G);
  193. }
  194. template <class T>
  195. df_iterator<T> df_end(const T& G) {
  196. return df_iterator<T>::end(G);
  197. }
  198. // Provide an accessor method to use them in range-based patterns.
  199. template <class T>
  200. iterator_range<df_iterator<T>> depth_first(const T& G) {
  201. return make_range(df_begin(G), df_end(G));
  202. }
  203. // Provide global definitions of external depth first iterators...
  204. template <class T, class SetTy = df_iterator_default_set<typename GraphTraits<T>::NodeRef>>
  205. struct df_ext_iterator : public df_iterator<T, SetTy, true> {
  206. df_ext_iterator(const df_iterator<T, SetTy, true> &V)
  207. : df_iterator<T, SetTy, true>(V) {}
  208. };
  209. template <class T, class SetTy>
  210. df_ext_iterator<T, SetTy> df_ext_begin(const T& G, SetTy &S) {
  211. return df_ext_iterator<T, SetTy>::begin(G, S);
  212. }
  213. template <class T, class SetTy>
  214. df_ext_iterator<T, SetTy> df_ext_end(const T& G, SetTy &S) {
  215. return df_ext_iterator<T, SetTy>::end(G, S);
  216. }
  217. template <class T, class SetTy>
  218. iterator_range<df_ext_iterator<T, SetTy>> depth_first_ext(const T& G,
  219. SetTy &S) {
  220. return make_range(df_ext_begin(G, S), df_ext_end(G, S));
  221. }
  222. // Provide global definitions of inverse depth first iterators...
  223. template <class T,
  224. class SetTy =
  225. df_iterator_default_set<typename GraphTraits<T>::NodeRef>,
  226. bool External = false>
  227. struct idf_iterator : public df_iterator<Inverse<T>, SetTy, External> {
  228. idf_iterator(const df_iterator<Inverse<T>, SetTy, External> &V)
  229. : df_iterator<Inverse<T>, SetTy, External>(V) {}
  230. };
  231. template <class T>
  232. idf_iterator<T> idf_begin(const T& G) {
  233. return idf_iterator<T>::begin(Inverse<T>(G));
  234. }
  235. template <class T>
  236. idf_iterator<T> idf_end(const T& G){
  237. return idf_iterator<T>::end(Inverse<T>(G));
  238. }
  239. // Provide an accessor method to use them in range-based patterns.
  240. template <class T>
  241. iterator_range<idf_iterator<T>> inverse_depth_first(const T& G) {
  242. return make_range(idf_begin(G), idf_end(G));
  243. }
  244. // Provide global definitions of external inverse depth first iterators...
  245. template <class T, class SetTy = df_iterator_default_set<typename GraphTraits<T>::NodeRef>>
  246. struct idf_ext_iterator : public idf_iterator<T, SetTy, true> {
  247. idf_ext_iterator(const idf_iterator<T, SetTy, true> &V)
  248. : idf_iterator<T, SetTy, true>(V) {}
  249. idf_ext_iterator(const df_iterator<Inverse<T>, SetTy, true> &V)
  250. : idf_iterator<T, SetTy, true>(V) {}
  251. };
  252. template <class T, class SetTy>
  253. idf_ext_iterator<T, SetTy> idf_ext_begin(const T& G, SetTy &S) {
  254. return idf_ext_iterator<T, SetTy>::begin(Inverse<T>(G), S);
  255. }
  256. template <class T, class SetTy>
  257. idf_ext_iterator<T, SetTy> idf_ext_end(const T& G, SetTy &S) {
  258. return idf_ext_iterator<T, SetTy>::end(Inverse<T>(G), S);
  259. }
  260. template <class T, class SetTy>
  261. iterator_range<idf_ext_iterator<T, SetTy>> inverse_depth_first_ext(const T& G,
  262. SetTy &S) {
  263. return make_range(idf_ext_begin(G, S), idf_ext_end(G, S));
  264. }
  265. } // end namespace llvm
  266. #endif // LLVM_ADT_DEPTHFIRSTITERATOR_H
  267. #ifdef __GNUC__
  268. #pragma GCC diagnostic pop
  269. #endif