CFG.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. //===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This family of functions performs analyses on basic blocks, and instructions
  11. // contained within basic blocks.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Analysis/CFG.h"
  15. #include "llvm/ADT/SmallSet.h"
  16. #include "llvm/Analysis/LoopInfo.h"
  17. #include "llvm/IR/Dominators.h"
  18. using namespace llvm;
  19. /// FindFunctionBackedges - Analyze the specified function to find all of the
  20. /// loop backedges in the function and return them. This is a relatively cheap
  21. /// (compared to computing dominators and loop info) analysis.
  22. ///
  23. /// The output is added to Result, as pairs of <from,to> edge info.
  24. void llvm::FindFunctionBackedges(const Function &F,
  25. SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
  26. const BasicBlock *BB = &F.getEntryBlock();
  27. if (succ_empty(BB))
  28. return;
  29. SmallPtrSet<const BasicBlock*, 8> Visited;
  30. SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
  31. SmallPtrSet<const BasicBlock*, 8> InStack;
  32. Visited.insert(BB);
  33. VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
  34. InStack.insert(BB);
  35. do {
  36. std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
  37. const BasicBlock *ParentBB = Top.first;
  38. succ_const_iterator &I = Top.second;
  39. bool FoundNew = false;
  40. while (I != succ_end(ParentBB)) {
  41. BB = *I++;
  42. if (Visited.insert(BB).second) {
  43. FoundNew = true;
  44. break;
  45. }
  46. // Successor is in VisitStack, it's a back edge.
  47. if (InStack.count(BB))
  48. Result.push_back(std::make_pair(ParentBB, BB));
  49. }
  50. if (FoundNew) {
  51. // Go down one level if there is a unvisited successor.
  52. InStack.insert(BB);
  53. VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
  54. } else {
  55. // Go up one level.
  56. InStack.erase(VisitStack.pop_back_val().first);
  57. }
  58. } while (!VisitStack.empty());
  59. }
  60. /// GetSuccessorNumber - Search for the specified successor of basic block BB
  61. /// and return its position in the terminator instruction's list of
  62. /// successors. It is an error to call this with a block that is not a
  63. /// successor.
  64. unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
  65. TerminatorInst *Term = BB->getTerminator();
  66. #ifndef NDEBUG
  67. unsigned e = Term->getNumSuccessors();
  68. #endif
  69. for (unsigned i = 0; ; ++i) {
  70. assert(i != e && "Didn't find edge?");
  71. if (Term->getSuccessor(i) == Succ)
  72. return i;
  73. }
  74. }
  75. /// isCriticalEdge - Return true if the specified edge is a critical edge.
  76. /// Critical edges are edges from a block with multiple successors to a block
  77. /// with multiple predecessors.
  78. bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum,
  79. bool AllowIdenticalEdges) {
  80. assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
  81. if (TI->getNumSuccessors() == 1) return false;
  82. const BasicBlock *Dest = TI->getSuccessor(SuccNum);
  83. const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
  84. // If there is more than one predecessor, this is a critical edge...
  85. assert(I != E && "No preds, but we have an edge to the block?");
  86. const BasicBlock *FirstPred = *I;
  87. ++I; // Skip one edge due to the incoming arc from TI.
  88. if (!AllowIdenticalEdges)
  89. return I != E;
  90. // If AllowIdenticalEdges is true, then we allow this edge to be considered
  91. // non-critical iff all preds come from TI's block.
  92. for (; I != E; ++I)
  93. if (*I != FirstPred)
  94. return true;
  95. return false;
  96. }
  97. // LoopInfo contains a mapping from basic block to the innermost loop. Find
  98. // the outermost loop in the loop nest that contains BB.
  99. static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
  100. const Loop *L = LI->getLoopFor(BB);
  101. if (L) {
  102. while (const Loop *Parent = L->getParentLoop())
  103. L = Parent;
  104. }
  105. return L;
  106. }
  107. // True if there is a loop which contains both BB1 and BB2.
  108. static bool loopContainsBoth(const LoopInfo *LI,
  109. const BasicBlock *BB1, const BasicBlock *BB2) {
  110. const Loop *L1 = getOutermostLoop(LI, BB1);
  111. const Loop *L2 = getOutermostLoop(LI, BB2);
  112. return L1 != nullptr && L1 == L2;
  113. }
  114. bool llvm::isPotentiallyReachableFromMany(
  115. SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
  116. const DominatorTree *DT, const LoopInfo *LI) {
  117. // When the stop block is unreachable, it's dominated from everywhere,
  118. // regardless of whether there's a path between the two blocks.
  119. if (DT && !DT->isReachableFromEntry(StopBB))
  120. DT = nullptr;
  121. // Limit the number of blocks we visit. The goal is to avoid run-away compile
  122. // times on large CFGs without hampering sensible code. Arbitrarily chosen.
  123. unsigned Limit = 32;
  124. SmallSet<const BasicBlock*, 64> Visited;
  125. do {
  126. BasicBlock *BB = Worklist.pop_back_val();
  127. if (!Visited.insert(BB).second)
  128. continue;
  129. if (BB == StopBB)
  130. return true;
  131. if (DT && DT->dominates(BB, StopBB))
  132. return true;
  133. if (LI && loopContainsBoth(LI, BB, StopBB))
  134. return true;
  135. if (!--Limit) {
  136. // We haven't been able to prove it one way or the other. Conservatively
  137. // answer true -- that there is potentially a path.
  138. return true;
  139. }
  140. if (const Loop *Outer = LI ? getOutermostLoop(LI, BB) : nullptr) {
  141. // All blocks in a single loop are reachable from all other blocks. From
  142. // any of these blocks, we can skip directly to the exits of the loop,
  143. // ignoring any other blocks inside the loop body.
  144. Outer->getExitBlocks(Worklist);
  145. } else {
  146. Worklist.append(succ_begin(BB), succ_end(BB));
  147. }
  148. } while (!Worklist.empty());
  149. // We have exhausted all possible paths and are certain that 'To' can not be
  150. // reached from 'From'.
  151. return false;
  152. }
  153. bool llvm::isPotentiallyReachable(const BasicBlock *A, const BasicBlock *B,
  154. const DominatorTree *DT, const LoopInfo *LI) {
  155. assert(A->getParent() == B->getParent() &&
  156. "This analysis is function-local!");
  157. SmallVector<BasicBlock*, 32> Worklist;
  158. Worklist.push_back(const_cast<BasicBlock*>(A));
  159. return isPotentiallyReachableFromMany(Worklist, const_cast<BasicBlock *>(B),
  160. DT, LI);
  161. }
  162. bool llvm::isPotentiallyReachable(const Instruction *A, const Instruction *B,
  163. const DominatorTree *DT, const LoopInfo *LI) {
  164. assert(A->getParent()->getParent() == B->getParent()->getParent() &&
  165. "This analysis is function-local!");
  166. SmallVector<BasicBlock*, 32> Worklist;
  167. if (A->getParent() == B->getParent()) {
  168. // The same block case is special because it's the only time we're looking
  169. // within a single block to see which instruction comes first. Once we
  170. // start looking at multiple blocks, the first instruction of the block is
  171. // reachable, so we only need to determine reachability between whole
  172. // blocks.
  173. BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
  174. // If the block is in a loop then we can reach any instruction in the block
  175. // from any other instruction in the block by going around a backedge.
  176. if (LI && LI->getLoopFor(BB) != nullptr)
  177. return true;
  178. // Linear scan, start at 'A', see whether we hit 'B' or the end first.
  179. for (BasicBlock::const_iterator I = A, E = BB->end(); I != E; ++I) {
  180. if (&*I == B)
  181. return true;
  182. }
  183. // Can't be in a loop if it's the entry block -- the entry block may not
  184. // have predecessors.
  185. if (BB == &BB->getParent()->getEntryBlock())
  186. return false;
  187. // Otherwise, continue doing the normal per-BB CFG walk.
  188. Worklist.append(succ_begin(BB), succ_end(BB));
  189. if (Worklist.empty()) {
  190. // We've proven that there's no path!
  191. return false;
  192. }
  193. } else {
  194. Worklist.push_back(const_cast<BasicBlock*>(A->getParent()));
  195. }
  196. if (A->getParent() == &A->getParent()->getParent()->getEntryBlock())
  197. return true;
  198. if (B->getParent() == &A->getParent()->getParent()->getEntryBlock())
  199. return false;
  200. return isPotentiallyReachableFromMany(
  201. Worklist, const_cast<BasicBlock *>(B->getParent()), DT, LI);
  202. }