CFG.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. //===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
  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 family of functions performs analyses on basic blocks, and instructions
  10. // contained within basic blocks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/CFG.h"
  14. #include "llvm/Analysis/LoopInfo.h"
  15. #include "llvm/IR/Dominators.h"
  16. #include "llvm/Support/CommandLine.h"
  17. using namespace llvm;
  18. // The max number of basic blocks explored during reachability analysis between
  19. // two basic blocks. This is kept reasonably small to limit compile time when
  20. // repeatedly used by clients of this analysis (such as captureTracking).
  21. static cl::opt<unsigned> DefaultMaxBBsToExplore(
  22. "dom-tree-reachability-max-bbs-to-explore", cl::Hidden,
  23. cl::desc("Max number of BBs to explore for reachability analysis"),
  24. cl::init(32));
  25. /// FindFunctionBackedges - Analyze the specified function to find all of the
  26. /// loop backedges in the function and return them. This is a relatively cheap
  27. /// (compared to computing dominators and loop info) analysis.
  28. ///
  29. /// The output is added to Result, as pairs of <from,to> edge info.
  30. void llvm::FindFunctionBackedges(const Function &F,
  31. SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
  32. const BasicBlock *BB = &F.getEntryBlock();
  33. if (succ_empty(BB))
  34. return;
  35. SmallPtrSet<const BasicBlock*, 8> Visited;
  36. SmallVector<std::pair<const BasicBlock *, const_succ_iterator>, 8> VisitStack;
  37. SmallPtrSet<const BasicBlock*, 8> InStack;
  38. Visited.insert(BB);
  39. VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
  40. InStack.insert(BB);
  41. do {
  42. std::pair<const BasicBlock *, const_succ_iterator> &Top = VisitStack.back();
  43. const BasicBlock *ParentBB = Top.first;
  44. const_succ_iterator &I = Top.second;
  45. bool FoundNew = false;
  46. while (I != succ_end(ParentBB)) {
  47. BB = *I++;
  48. if (Visited.insert(BB).second) {
  49. FoundNew = true;
  50. break;
  51. }
  52. // Successor is in VisitStack, it's a back edge.
  53. if (InStack.count(BB))
  54. Result.push_back(std::make_pair(ParentBB, BB));
  55. }
  56. if (FoundNew) {
  57. // Go down one level if there is a unvisited successor.
  58. InStack.insert(BB);
  59. VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
  60. } else {
  61. // Go up one level.
  62. InStack.erase(VisitStack.pop_back_val().first);
  63. }
  64. } while (!VisitStack.empty());
  65. }
  66. /// GetSuccessorNumber - Search for the specified successor of basic block BB
  67. /// and return its position in the terminator instruction's list of
  68. /// successors. It is an error to call this with a block that is not a
  69. /// successor.
  70. unsigned llvm::GetSuccessorNumber(const BasicBlock *BB,
  71. const BasicBlock *Succ) {
  72. const Instruction *Term = BB->getTerminator();
  73. #ifndef NDEBUG
  74. unsigned e = Term->getNumSuccessors();
  75. #endif
  76. for (unsigned i = 0; ; ++i) {
  77. assert(i != e && "Didn't find edge?");
  78. if (Term->getSuccessor(i) == Succ)
  79. return i;
  80. }
  81. }
  82. /// isCriticalEdge - Return true if the specified edge is a critical edge.
  83. /// Critical edges are edges from a block with multiple successors to a block
  84. /// with multiple predecessors.
  85. bool llvm::isCriticalEdge(const Instruction *TI, unsigned SuccNum,
  86. bool AllowIdenticalEdges) {
  87. assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
  88. return isCriticalEdge(TI, TI->getSuccessor(SuccNum), AllowIdenticalEdges);
  89. }
  90. bool llvm::isCriticalEdge(const Instruction *TI, const BasicBlock *Dest,
  91. bool AllowIdenticalEdges) {
  92. assert(TI->isTerminator() && "Must be a terminator to have successors!");
  93. if (TI->getNumSuccessors() == 1) return false;
  94. assert(is_contained(predecessors(Dest), TI->getParent()) &&
  95. "No edge between TI's block and Dest.");
  96. const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
  97. // If there is more than one predecessor, this is a critical edge...
  98. assert(I != E && "No preds, but we have an edge to the block?");
  99. const BasicBlock *FirstPred = *I;
  100. ++I; // Skip one edge due to the incoming arc from TI.
  101. if (!AllowIdenticalEdges)
  102. return I != E;
  103. // If AllowIdenticalEdges is true, then we allow this edge to be considered
  104. // non-critical iff all preds come from TI's block.
  105. for (; I != E; ++I)
  106. if (*I != FirstPred)
  107. return true;
  108. return false;
  109. }
  110. // LoopInfo contains a mapping from basic block to the innermost loop. Find
  111. // the outermost loop in the loop nest that contains BB.
  112. static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
  113. const Loop *L = LI->getLoopFor(BB);
  114. if (L) {
  115. while (const Loop *Parent = L->getParentLoop())
  116. L = Parent;
  117. }
  118. return L;
  119. }
  120. bool llvm::isPotentiallyReachableFromMany(
  121. SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
  122. const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
  123. const LoopInfo *LI) {
  124. // When the stop block is unreachable, it's dominated from everywhere,
  125. // regardless of whether there's a path between the two blocks.
  126. if (DT && !DT->isReachableFromEntry(StopBB))
  127. DT = nullptr;
  128. // We can't skip directly from a block that dominates the stop block if the
  129. // exclusion block is potentially in between.
  130. if (ExclusionSet && !ExclusionSet->empty())
  131. DT = nullptr;
  132. // Normally any block in a loop is reachable from any other block in a loop,
  133. // however excluded blocks might partition the body of a loop to make that
  134. // untrue.
  135. SmallPtrSet<const Loop *, 8> LoopsWithHoles;
  136. if (LI && ExclusionSet) {
  137. for (auto BB : *ExclusionSet) {
  138. if (const Loop *L = getOutermostLoop(LI, BB))
  139. LoopsWithHoles.insert(L);
  140. }
  141. }
  142. const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr;
  143. unsigned Limit = DefaultMaxBBsToExplore;
  144. SmallPtrSet<const BasicBlock*, 32> Visited;
  145. do {
  146. BasicBlock *BB = Worklist.pop_back_val();
  147. if (!Visited.insert(BB).second)
  148. continue;
  149. if (BB == StopBB)
  150. return true;
  151. if (ExclusionSet && ExclusionSet->count(BB))
  152. continue;
  153. if (DT && DT->dominates(BB, StopBB))
  154. return true;
  155. const Loop *Outer = nullptr;
  156. if (LI) {
  157. Outer = getOutermostLoop(LI, BB);
  158. // If we're in a loop with a hole, not all blocks in the loop are
  159. // reachable from all other blocks. That implies we can't simply jump to
  160. // the loop's exit blocks, as that exit might need to pass through an
  161. // excluded block. Clear Outer so we process BB's successors.
  162. if (LoopsWithHoles.count(Outer))
  163. Outer = nullptr;
  164. if (StopLoop && Outer == StopLoop)
  165. return true;
  166. }
  167. if (!--Limit) {
  168. // We haven't been able to prove it one way or the other. Conservatively
  169. // answer true -- that there is potentially a path.
  170. return true;
  171. }
  172. if (Outer) {
  173. // All blocks in a single loop are reachable from all other blocks. From
  174. // any of these blocks, we can skip directly to the exits of the loop,
  175. // ignoring any other blocks inside the loop body.
  176. Outer->getExitBlocks(Worklist);
  177. } else {
  178. Worklist.append(succ_begin(BB), succ_end(BB));
  179. }
  180. } while (!Worklist.empty());
  181. // We have exhausted all possible paths and are certain that 'To' can not be
  182. // reached from 'From'.
  183. return false;
  184. }
  185. bool llvm::isPotentiallyReachable(
  186. const BasicBlock *A, const BasicBlock *B,
  187. const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
  188. const LoopInfo *LI) {
  189. assert(A->getParent() == B->getParent() &&
  190. "This analysis is function-local!");
  191. if (DT) {
  192. if (DT->isReachableFromEntry(A) && !DT->isReachableFromEntry(B))
  193. return false;
  194. if (!ExclusionSet || ExclusionSet->empty()) {
  195. if (A->isEntryBlock() && DT->isReachableFromEntry(B))
  196. return true;
  197. if (B->isEntryBlock() && DT->isReachableFromEntry(A))
  198. return false;
  199. }
  200. }
  201. SmallVector<BasicBlock*, 32> Worklist;
  202. Worklist.push_back(const_cast<BasicBlock*>(A));
  203. return isPotentiallyReachableFromMany(Worklist, const_cast<BasicBlock *>(B),
  204. ExclusionSet, DT, LI);
  205. }
  206. bool llvm::isPotentiallyReachable(
  207. const Instruction *A, const Instruction *B,
  208. const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
  209. const LoopInfo *LI) {
  210. assert(A->getParent()->getParent() == B->getParent()->getParent() &&
  211. "This analysis is function-local!");
  212. if (A->getParent() == B->getParent()) {
  213. // The same block case is special because it's the only time we're looking
  214. // within a single block to see which instruction comes first. Once we
  215. // start looking at multiple blocks, the first instruction of the block is
  216. // reachable, so we only need to determine reachability between whole
  217. // blocks.
  218. BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
  219. // If the block is in a loop then we can reach any instruction in the block
  220. // from any other instruction in the block by going around a backedge.
  221. if (LI && LI->getLoopFor(BB) != nullptr)
  222. return true;
  223. // If A comes before B, then B is definitively reachable from A.
  224. if (A == B || A->comesBefore(B))
  225. return true;
  226. // Can't be in a loop if it's the entry block -- the entry block may not
  227. // have predecessors.
  228. if (BB->isEntryBlock())
  229. return false;
  230. // Otherwise, continue doing the normal per-BB CFG walk.
  231. SmallVector<BasicBlock*, 32> Worklist;
  232. Worklist.append(succ_begin(BB), succ_end(BB));
  233. if (Worklist.empty()) {
  234. // We've proven that there's no path!
  235. return false;
  236. }
  237. return isPotentiallyReachableFromMany(
  238. Worklist, const_cast<BasicBlock *>(B->getParent()), ExclusionSet,
  239. DT, LI);
  240. }
  241. return isPotentiallyReachable(
  242. A->getParent(), B->getParent(), ExclusionSet, DT, LI);
  243. }