CFG.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. //===- CFG.h ----------------------------------------------------*- 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. /// \file
  9. ///
  10. /// This file provides various utilities for inspecting and working with the
  11. /// control flow graph in LLVM IR. This includes generic facilities for
  12. /// iterating successors and predecessors of basic blocks, the successors of
  13. /// specific terminator instructions, etc. It also defines specializations of
  14. /// GraphTraits that allow Function and BasicBlock graphs to be treated as
  15. /// proper graphs for generic algorithms.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_CFG_H
  19. #define LLVM_IR_CFG_H
  20. #include "llvm/ADT/GraphTraits.h"
  21. #include "llvm/ADT/iterator.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/Value.h"
  25. #include "llvm/Support/Casting.h"
  26. #include <cassert>
  27. #include <cstddef>
  28. #include <iterator>
  29. namespace llvm {
  30. class BasicBlock;
  31. class Instruction;
  32. class Use;
  33. //===----------------------------------------------------------------------===//
  34. // BasicBlock pred_iterator definition
  35. //===----------------------------------------------------------------------===//
  36. template <class Ptr, class USE_iterator> // Predecessor Iterator
  37. class PredIterator {
  38. public:
  39. using iterator_category = std::forward_iterator_tag;
  40. using value_type = Ptr;
  41. using difference_type = std::ptrdiff_t;
  42. using pointer = Ptr *;
  43. using reference = Ptr *;
  44. private:
  45. using Self = PredIterator<Ptr, USE_iterator>;
  46. USE_iterator It;
  47. inline void advancePastNonTerminators() {
  48. // Loop to ignore non-terminator uses (for example BlockAddresses).
  49. while (!It.atEnd()) {
  50. if (auto *Inst = dyn_cast<Instruction>(*It))
  51. if (Inst->isTerminator())
  52. break;
  53. ++It;
  54. }
  55. }
  56. public:
  57. PredIterator() = default;
  58. explicit inline PredIterator(Ptr *bb) : It(bb->user_begin()) {
  59. advancePastNonTerminators();
  60. }
  61. inline PredIterator(Ptr *bb, bool) : It(bb->user_end()) {}
  62. inline bool operator==(const Self& x) const { return It == x.It; }
  63. inline bool operator!=(const Self& x) const { return !operator==(x); }
  64. inline reference operator*() const {
  65. assert(!It.atEnd() && "pred_iterator out of range!");
  66. return cast<Instruction>(*It)->getParent();
  67. }
  68. inline pointer *operator->() const { return &operator*(); }
  69. inline Self& operator++() { // Preincrement
  70. assert(!It.atEnd() && "pred_iterator out of range!");
  71. ++It; advancePastNonTerminators();
  72. return *this;
  73. }
  74. inline Self operator++(int) { // Postincrement
  75. Self tmp = *this; ++*this; return tmp;
  76. }
  77. /// getOperandNo - Return the operand number in the predecessor's
  78. /// terminator of the successor.
  79. unsigned getOperandNo() const {
  80. return It.getOperandNo();
  81. }
  82. /// getUse - Return the operand Use in the predecessor's terminator
  83. /// of the successor.
  84. Use &getUse() const {
  85. return It.getUse();
  86. }
  87. };
  88. using pred_iterator = PredIterator<BasicBlock, Value::user_iterator>;
  89. using const_pred_iterator =
  90. PredIterator<const BasicBlock, Value::const_user_iterator>;
  91. using pred_range = iterator_range<pred_iterator>;
  92. using const_pred_range = iterator_range<const_pred_iterator>;
  93. inline pred_iterator pred_begin(BasicBlock *BB) { return pred_iterator(BB); }
  94. inline const_pred_iterator pred_begin(const BasicBlock *BB) {
  95. return const_pred_iterator(BB);
  96. }
  97. inline pred_iterator pred_end(BasicBlock *BB) { return pred_iterator(BB, true);}
  98. inline const_pred_iterator pred_end(const BasicBlock *BB) {
  99. return const_pred_iterator(BB, true);
  100. }
  101. inline bool pred_empty(const BasicBlock *BB) {
  102. return pred_begin(BB) == pred_end(BB);
  103. }
  104. /// Get the number of predecessors of \p BB. This is a linear time operation.
  105. /// Use \ref BasicBlock::hasNPredecessors() or hasNPredecessorsOrMore if able.
  106. inline unsigned pred_size(const BasicBlock *BB) {
  107. return std::distance(pred_begin(BB), pred_end(BB));
  108. }
  109. inline pred_range predecessors(BasicBlock *BB) {
  110. return pred_range(pred_begin(BB), pred_end(BB));
  111. }
  112. inline const_pred_range predecessors(const BasicBlock *BB) {
  113. return const_pred_range(pred_begin(BB), pred_end(BB));
  114. }
  115. //===----------------------------------------------------------------------===//
  116. // Instruction and BasicBlock succ_iterator helpers
  117. //===----------------------------------------------------------------------===//
  118. template <class InstructionT, class BlockT>
  119. class SuccIterator
  120. : public iterator_facade_base<SuccIterator<InstructionT, BlockT>,
  121. std::random_access_iterator_tag, BlockT, int,
  122. BlockT *, BlockT *> {
  123. public:
  124. using difference_type = int;
  125. using pointer = BlockT *;
  126. using reference = BlockT *;
  127. private:
  128. InstructionT *Inst;
  129. int Idx;
  130. using Self = SuccIterator<InstructionT, BlockT>;
  131. inline bool index_is_valid(int Idx) {
  132. // Note that we specially support the index of zero being valid even in the
  133. // face of a null instruction.
  134. return Idx >= 0 && (Idx == 0 || Idx <= (int)Inst->getNumSuccessors());
  135. }
  136. /// Proxy object to allow write access in operator[]
  137. class SuccessorProxy {
  138. Self It;
  139. public:
  140. explicit SuccessorProxy(const Self &It) : It(It) {}
  141. SuccessorProxy(const SuccessorProxy &) = default;
  142. SuccessorProxy &operator=(SuccessorProxy RHS) {
  143. *this = reference(RHS);
  144. return *this;
  145. }
  146. SuccessorProxy &operator=(reference RHS) {
  147. It.Inst->setSuccessor(It.Idx, RHS);
  148. return *this;
  149. }
  150. operator reference() const { return *It; }
  151. };
  152. public:
  153. // begin iterator
  154. explicit inline SuccIterator(InstructionT *Inst) : Inst(Inst), Idx(0) {}
  155. // end iterator
  156. inline SuccIterator(InstructionT *Inst, bool) : Inst(Inst) {
  157. if (Inst)
  158. Idx = Inst->getNumSuccessors();
  159. else
  160. // Inst == NULL happens, if a basic block is not fully constructed and
  161. // consequently getTerminator() returns NULL. In this case we construct
  162. // a SuccIterator which describes a basic block that has zero
  163. // successors.
  164. // Defining SuccIterator for incomplete and malformed CFGs is especially
  165. // useful for debugging.
  166. Idx = 0;
  167. }
  168. /// This is used to interface between code that wants to
  169. /// operate on terminator instructions directly.
  170. int getSuccessorIndex() const { return Idx; }
  171. inline bool operator==(const Self &x) const { return Idx == x.Idx; }
  172. inline BlockT *operator*() const { return Inst->getSuccessor(Idx); }
  173. // We use the basic block pointer directly for operator->.
  174. inline BlockT *operator->() const { return operator*(); }
  175. inline bool operator<(const Self &RHS) const {
  176. assert(Inst == RHS.Inst && "Cannot compare iterators of different blocks!");
  177. return Idx < RHS.Idx;
  178. }
  179. int operator-(const Self &RHS) const {
  180. assert(Inst == RHS.Inst && "Cannot compare iterators of different blocks!");
  181. return Idx - RHS.Idx;
  182. }
  183. inline Self &operator+=(int RHS) {
  184. int NewIdx = Idx + RHS;
  185. assert(index_is_valid(NewIdx) && "Iterator index out of bound");
  186. Idx = NewIdx;
  187. return *this;
  188. }
  189. inline Self &operator-=(int RHS) { return operator+=(-RHS); }
  190. // Specially implement the [] operation using a proxy object to support
  191. // assignment.
  192. inline SuccessorProxy operator[](int Offset) {
  193. Self TmpIt = *this;
  194. TmpIt += Offset;
  195. return SuccessorProxy(TmpIt);
  196. }
  197. /// Get the source BlockT of this iterator.
  198. inline BlockT *getSource() {
  199. assert(Inst && "Source not available, if basic block was malformed");
  200. return Inst->getParent();
  201. }
  202. };
  203. using succ_iterator = SuccIterator<Instruction, BasicBlock>;
  204. using const_succ_iterator = SuccIterator<const Instruction, const BasicBlock>;
  205. using succ_range = iterator_range<succ_iterator>;
  206. using const_succ_range = iterator_range<const_succ_iterator>;
  207. inline succ_iterator succ_begin(Instruction *I) { return succ_iterator(I); }
  208. inline const_succ_iterator succ_begin(const Instruction *I) {
  209. return const_succ_iterator(I);
  210. }
  211. inline succ_iterator succ_end(Instruction *I) { return succ_iterator(I, true); }
  212. inline const_succ_iterator succ_end(const Instruction *I) {
  213. return const_succ_iterator(I, true);
  214. }
  215. inline bool succ_empty(const Instruction *I) {
  216. return succ_begin(I) == succ_end(I);
  217. }
  218. inline unsigned succ_size(const Instruction *I) {
  219. return std::distance(succ_begin(I), succ_end(I));
  220. }
  221. inline succ_range successors(Instruction *I) {
  222. return succ_range(succ_begin(I), succ_end(I));
  223. }
  224. inline const_succ_range successors(const Instruction *I) {
  225. return const_succ_range(succ_begin(I), succ_end(I));
  226. }
  227. inline succ_iterator succ_begin(BasicBlock *BB) {
  228. return succ_iterator(BB->getTerminator());
  229. }
  230. inline const_succ_iterator succ_begin(const BasicBlock *BB) {
  231. return const_succ_iterator(BB->getTerminator());
  232. }
  233. inline succ_iterator succ_end(BasicBlock *BB) {
  234. return succ_iterator(BB->getTerminator(), true);
  235. }
  236. inline const_succ_iterator succ_end(const BasicBlock *BB) {
  237. return const_succ_iterator(BB->getTerminator(), true);
  238. }
  239. inline bool succ_empty(const BasicBlock *BB) {
  240. return succ_begin(BB) == succ_end(BB);
  241. }
  242. inline unsigned succ_size(const BasicBlock *BB) {
  243. return std::distance(succ_begin(BB), succ_end(BB));
  244. }
  245. inline succ_range successors(BasicBlock *BB) {
  246. return succ_range(succ_begin(BB), succ_end(BB));
  247. }
  248. inline const_succ_range successors(const BasicBlock *BB) {
  249. return const_succ_range(succ_begin(BB), succ_end(BB));
  250. }
  251. //===--------------------------------------------------------------------===//
  252. // GraphTraits specializations for basic block graphs (CFGs)
  253. //===--------------------------------------------------------------------===//
  254. // Provide specializations of GraphTraits to be able to treat a function as a
  255. // graph of basic blocks...
  256. template <> struct GraphTraits<BasicBlock*> {
  257. using NodeRef = BasicBlock *;
  258. using ChildIteratorType = succ_iterator;
  259. static NodeRef getEntryNode(BasicBlock *BB) { return BB; }
  260. static ChildIteratorType child_begin(NodeRef N) { return succ_begin(N); }
  261. static ChildIteratorType child_end(NodeRef N) { return succ_end(N); }
  262. };
  263. template <> struct GraphTraits<const BasicBlock*> {
  264. using NodeRef = const BasicBlock *;
  265. using ChildIteratorType = const_succ_iterator;
  266. static NodeRef getEntryNode(const BasicBlock *BB) { return BB; }
  267. static ChildIteratorType child_begin(NodeRef N) { return succ_begin(N); }
  268. static ChildIteratorType child_end(NodeRef N) { return succ_end(N); }
  269. };
  270. // Provide specializations of GraphTraits to be able to treat a function as a
  271. // graph of basic blocks... and to walk it in inverse order. Inverse order for
  272. // a function is considered to be when traversing the predecessor edges of a BB
  273. // instead of the successor edges.
  274. //
  275. template <> struct GraphTraits<Inverse<BasicBlock*>> {
  276. using NodeRef = BasicBlock *;
  277. using ChildIteratorType = pred_iterator;
  278. static NodeRef getEntryNode(Inverse<BasicBlock *> G) { return G.Graph; }
  279. static ChildIteratorType child_begin(NodeRef N) { return pred_begin(N); }
  280. static ChildIteratorType child_end(NodeRef N) { return pred_end(N); }
  281. };
  282. template <> struct GraphTraits<Inverse<const BasicBlock*>> {
  283. using NodeRef = const BasicBlock *;
  284. using ChildIteratorType = const_pred_iterator;
  285. static NodeRef getEntryNode(Inverse<const BasicBlock *> G) { return G.Graph; }
  286. static ChildIteratorType child_begin(NodeRef N) { return pred_begin(N); }
  287. static ChildIteratorType child_end(NodeRef N) { return pred_end(N); }
  288. };
  289. //===--------------------------------------------------------------------===//
  290. // GraphTraits specializations for function basic block graphs (CFGs)
  291. //===--------------------------------------------------------------------===//
  292. // Provide specializations of GraphTraits to be able to treat a function as a
  293. // graph of basic blocks... these are the same as the basic block iterators,
  294. // except that the root node is implicitly the first node of the function.
  295. //
  296. template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> {
  297. static NodeRef getEntryNode(Function *F) { return &F->getEntryBlock(); }
  298. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  299. using nodes_iterator = pointer_iterator<Function::iterator>;
  300. static nodes_iterator nodes_begin(Function *F) {
  301. return nodes_iterator(F->begin());
  302. }
  303. static nodes_iterator nodes_end(Function *F) {
  304. return nodes_iterator(F->end());
  305. }
  306. static size_t size(Function *F) { return F->size(); }
  307. };
  308. template <> struct GraphTraits<const Function*> :
  309. public GraphTraits<const BasicBlock*> {
  310. static NodeRef getEntryNode(const Function *F) { return &F->getEntryBlock(); }
  311. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  312. using nodes_iterator = pointer_iterator<Function::const_iterator>;
  313. static nodes_iterator nodes_begin(const Function *F) {
  314. return nodes_iterator(F->begin());
  315. }
  316. static nodes_iterator nodes_end(const Function *F) {
  317. return nodes_iterator(F->end());
  318. }
  319. static size_t size(const Function *F) { return F->size(); }
  320. };
  321. // Provide specializations of GraphTraits to be able to treat a function as a
  322. // graph of basic blocks... and to walk it in inverse order. Inverse order for
  323. // a function is considered to be when traversing the predecessor edges of a BB
  324. // instead of the successor edges.
  325. //
  326. template <> struct GraphTraits<Inverse<Function*>> :
  327. public GraphTraits<Inverse<BasicBlock*>> {
  328. static NodeRef getEntryNode(Inverse<Function *> G) {
  329. return &G.Graph->getEntryBlock();
  330. }
  331. };
  332. template <> struct GraphTraits<Inverse<const Function*>> :
  333. public GraphTraits<Inverse<const BasicBlock*>> {
  334. static NodeRef getEntryNode(Inverse<const Function *> G) {
  335. return &G.Graph->getEntryBlock();
  336. }
  337. };
  338. } // end namespace llvm
  339. #endif // LLVM_IR_CFG_H