LLVM API Documentation

CFG.cpp
Go to the documentation of this file.
00001 //===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This family of functions performs analyses on basic blocks, and instructions
00011 // contained within basic blocks.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/CFG.h"
00016 #include "llvm/ADT/SmallSet.h"
00017 #include "llvm/Analysis/LoopInfo.h"
00018 #include "llvm/IR/Dominators.h"
00019 
00020 using namespace llvm;
00021 
00022 /// FindFunctionBackedges - Analyze the specified function to find all of the
00023 /// loop backedges in the function and return them.  This is a relatively cheap
00024 /// (compared to computing dominators and loop info) analysis.
00025 ///
00026 /// The output is added to Result, as pairs of <from,to> edge info.
00027 void llvm::FindFunctionBackedges(const Function &F,
00028      SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
00029   const BasicBlock *BB = &F.getEntryBlock();
00030   if (succ_begin(BB) == succ_end(BB))
00031     return;
00032 
00033   SmallPtrSet<const BasicBlock*, 8> Visited;
00034   SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
00035   SmallPtrSet<const BasicBlock*, 8> InStack;
00036 
00037   Visited.insert(BB);
00038   VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
00039   InStack.insert(BB);
00040   do {
00041     std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
00042     const BasicBlock *ParentBB = Top.first;
00043     succ_const_iterator &I = Top.second;
00044 
00045     bool FoundNew = false;
00046     while (I != succ_end(ParentBB)) {
00047       BB = *I++;
00048       if (Visited.insert(BB)) {
00049         FoundNew = true;
00050         break;
00051       }
00052       // Successor is in VisitStack, it's a back edge.
00053       if (InStack.count(BB))
00054         Result.push_back(std::make_pair(ParentBB, BB));
00055     }
00056 
00057     if (FoundNew) {
00058       // Go down one level if there is a unvisited successor.
00059       InStack.insert(BB);
00060       VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
00061     } else {
00062       // Go up one level.
00063       InStack.erase(VisitStack.pop_back_val().first);
00064     }
00065   } while (!VisitStack.empty());
00066 }
00067 
00068 /// GetSuccessorNumber - Search for the specified successor of basic block BB
00069 /// and return its position in the terminator instruction's list of
00070 /// successors.  It is an error to call this with a block that is not a
00071 /// successor.
00072 unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
00073   TerminatorInst *Term = BB->getTerminator();
00074 #ifndef NDEBUG
00075   unsigned e = Term->getNumSuccessors();
00076 #endif
00077   for (unsigned i = 0; ; ++i) {
00078     assert(i != e && "Didn't find edge?");
00079     if (Term->getSuccessor(i) == Succ)
00080       return i;
00081   }
00082 }
00083 
00084 /// isCriticalEdge - Return true if the specified edge is a critical edge.
00085 /// Critical edges are edges from a block with multiple successors to a block
00086 /// with multiple predecessors.
00087 bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum,
00088                           bool AllowIdenticalEdges) {
00089   assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
00090   if (TI->getNumSuccessors() == 1) return false;
00091 
00092   const BasicBlock *Dest = TI->getSuccessor(SuccNum);
00093   const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
00094 
00095   // If there is more than one predecessor, this is a critical edge...
00096   assert(I != E && "No preds, but we have an edge to the block?");
00097   const BasicBlock *FirstPred = *I;
00098   ++I;        // Skip one edge due to the incoming arc from TI.
00099   if (!AllowIdenticalEdges)
00100     return I != E;
00101 
00102   // If AllowIdenticalEdges is true, then we allow this edge to be considered
00103   // non-critical iff all preds come from TI's block.
00104   for (; I != E; ++I)
00105     if (*I != FirstPred)
00106       return true;
00107   return false;
00108 }
00109 
00110 // LoopInfo contains a mapping from basic block to the innermost loop. Find
00111 // the outermost loop in the loop nest that contains BB.
00112 static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
00113   const Loop *L = LI->getLoopFor(BB);
00114   if (L) {
00115     while (const Loop *Parent = L->getParentLoop())
00116       L = Parent;
00117   }
00118   return L;
00119 }
00120 
00121 // True if there is a loop which contains both BB1 and BB2.
00122 static bool loopContainsBoth(const LoopInfo *LI,
00123                              const BasicBlock *BB1, const BasicBlock *BB2) {
00124   const Loop *L1 = getOutermostLoop(LI, BB1);
00125   const Loop *L2 = getOutermostLoop(LI, BB2);
00126   return L1 != nullptr && L1 == L2;
00127 }
00128 
00129 static bool isPotentiallyReachableInner(SmallVectorImpl<BasicBlock *> &Worklist,
00130                                         BasicBlock *StopBB,
00131                                         const DominatorTree *DT,
00132                                         const LoopInfo *LI) {
00133   // When the stop block is unreachable, it's dominated from everywhere,
00134   // regardless of whether there's a path between the two blocks.
00135   if (DT && !DT->isReachableFromEntry(StopBB))
00136     DT = nullptr;
00137 
00138   // Limit the number of blocks we visit. The goal is to avoid run-away compile
00139   // times on large CFGs without hampering sensible code. Arbitrarily chosen.
00140   unsigned Limit = 32;
00141   SmallSet<const BasicBlock*, 64> Visited;
00142   do {
00143     BasicBlock *BB = Worklist.pop_back_val();
00144     if (!Visited.insert(BB))
00145       continue;
00146     if (BB == StopBB)
00147       return true;
00148     if (DT && DT->dominates(BB, StopBB))
00149       return true;
00150     if (LI && loopContainsBoth(LI, BB, StopBB))
00151       return true;
00152 
00153     if (!--Limit) {
00154       // We haven't been able to prove it one way or the other. Conservatively
00155       // answer true -- that there is potentially a path.
00156       return true;
00157     }
00158 
00159     if (const Loop *Outer = LI ? getOutermostLoop(LI, BB) : nullptr) {
00160       // All blocks in a single loop are reachable from all other blocks. From
00161       // any of these blocks, we can skip directly to the exits of the loop,
00162       // ignoring any other blocks inside the loop body.
00163       Outer->getExitBlocks(Worklist);
00164     } else {
00165       Worklist.append(succ_begin(BB), succ_end(BB));
00166     }
00167   } while (!Worklist.empty());
00168 
00169   // We have exhausted all possible paths and are certain that 'To' can not be
00170   // reached from 'From'.
00171   return false;
00172 }
00173 
00174 bool llvm::isPotentiallyReachable(const BasicBlock *A, const BasicBlock *B,
00175                                   const DominatorTree *DT, const LoopInfo *LI) {
00176   assert(A->getParent() == B->getParent() &&
00177          "This analysis is function-local!");
00178 
00179   SmallVector<BasicBlock*, 32> Worklist;
00180   Worklist.push_back(const_cast<BasicBlock*>(A));
00181 
00182   return isPotentiallyReachableInner(Worklist, const_cast<BasicBlock*>(B),
00183                                      DT, LI);
00184 }
00185 
00186 bool llvm::isPotentiallyReachable(const Instruction *A, const Instruction *B,
00187                                   const DominatorTree *DT, const LoopInfo *LI) {
00188   assert(A->getParent()->getParent() == B->getParent()->getParent() &&
00189          "This analysis is function-local!");
00190 
00191   SmallVector<BasicBlock*, 32> Worklist;
00192 
00193   if (A->getParent() == B->getParent()) {
00194     // The same block case is special because it's the only time we're looking
00195     // within a single block to see which instruction comes first. Once we
00196     // start looking at multiple blocks, the first instruction of the block is
00197     // reachable, so we only need to determine reachability between whole
00198     // blocks.
00199     BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
00200 
00201     // If the block is in a loop then we can reach any instruction in the block
00202     // from any other instruction in the block by going around a backedge.
00203     if (LI && LI->getLoopFor(BB) != nullptr)
00204       return true;
00205 
00206     // Linear scan, start at 'A', see whether we hit 'B' or the end first.
00207     for (BasicBlock::const_iterator I = A, E = BB->end(); I != E; ++I) {
00208       if (&*I == B)
00209         return true;
00210     }
00211 
00212     // Can't be in a loop if it's the entry block -- the entry block may not
00213     // have predecessors.
00214     if (BB == &BB->getParent()->getEntryBlock())
00215       return false;
00216 
00217     // Otherwise, continue doing the normal per-BB CFG walk.
00218     Worklist.append(succ_begin(BB), succ_end(BB));
00219 
00220     if (Worklist.empty()) {
00221       // We've proven that there's no path!
00222       return false;
00223     }
00224   } else {
00225     Worklist.push_back(const_cast<BasicBlock*>(A->getParent()));
00226   }
00227 
00228   if (A->getParent() == &A->getParent()->getParent()->getEntryBlock())
00229     return true;
00230   if (B->getParent() == &A->getParent()->getParent()->getEntryBlock())
00231     return false;
00232 
00233   return isPotentiallyReachableInner(Worklist,
00234                                      const_cast<BasicBlock*>(B->getParent()),
00235                                      DT, LI);
00236 }