DepthFirstIterator.h 11 KB

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