Path: blob/main/contrib/llvm-project/llvm/lib/Analysis/CFG.cpp
35233 views
//===-- CFG.cpp - BasicBlock analysis --------------------------------------==//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This family of functions performs analyses on basic blocks, and instructions9// contained within basic blocks.10//11//===----------------------------------------------------------------------===//1213#include "llvm/Analysis/CFG.h"14#include "llvm/Analysis/LoopInfo.h"15#include "llvm/IR/Dominators.h"16#include "llvm/Support/CommandLine.h"1718using namespace llvm;1920// The max number of basic blocks explored during reachability analysis between21// two basic blocks. This is kept reasonably small to limit compile time when22// repeatedly used by clients of this analysis (such as captureTracking).23static cl::opt<unsigned> DefaultMaxBBsToExplore(24"dom-tree-reachability-max-bbs-to-explore", cl::Hidden,25cl::desc("Max number of BBs to explore for reachability analysis"),26cl::init(32));2728/// FindFunctionBackedges - Analyze the specified function to find all of the29/// loop backedges in the function and return them. This is a relatively cheap30/// (compared to computing dominators and loop info) analysis.31///32/// The output is added to Result, as pairs of <from,to> edge info.33void llvm::FindFunctionBackedges(const Function &F,34SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {35const BasicBlock *BB = &F.getEntryBlock();36if (succ_empty(BB))37return;3839SmallPtrSet<const BasicBlock*, 8> Visited;40SmallVector<std::pair<const BasicBlock *, const_succ_iterator>, 8> VisitStack;41SmallPtrSet<const BasicBlock*, 8> InStack;4243Visited.insert(BB);44VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));45InStack.insert(BB);46do {47std::pair<const BasicBlock *, const_succ_iterator> &Top = VisitStack.back();48const BasicBlock *ParentBB = Top.first;49const_succ_iterator &I = Top.second;5051bool FoundNew = false;52while (I != succ_end(ParentBB)) {53BB = *I++;54if (Visited.insert(BB).second) {55FoundNew = true;56break;57}58// Successor is in VisitStack, it's a back edge.59if (InStack.count(BB))60Result.push_back(std::make_pair(ParentBB, BB));61}6263if (FoundNew) {64// Go down one level if there is a unvisited successor.65InStack.insert(BB);66VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));67} else {68// Go up one level.69InStack.erase(VisitStack.pop_back_val().first);70}71} while (!VisitStack.empty());72}7374/// GetSuccessorNumber - Search for the specified successor of basic block BB75/// and return its position in the terminator instruction's list of76/// successors. It is an error to call this with a block that is not a77/// successor.78unsigned llvm::GetSuccessorNumber(const BasicBlock *BB,79const BasicBlock *Succ) {80const Instruction *Term = BB->getTerminator();81#ifndef NDEBUG82unsigned e = Term->getNumSuccessors();83#endif84for (unsigned i = 0; ; ++i) {85assert(i != e && "Didn't find edge?");86if (Term->getSuccessor(i) == Succ)87return i;88}89}9091/// isCriticalEdge - Return true if the specified edge is a critical edge.92/// Critical edges are edges from a block with multiple successors to a block93/// with multiple predecessors.94bool llvm::isCriticalEdge(const Instruction *TI, unsigned SuccNum,95bool AllowIdenticalEdges) {96assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");97return isCriticalEdge(TI, TI->getSuccessor(SuccNum), AllowIdenticalEdges);98}99100bool llvm::isCriticalEdge(const Instruction *TI, const BasicBlock *Dest,101bool AllowIdenticalEdges) {102assert(TI->isTerminator() && "Must be a terminator to have successors!");103if (TI->getNumSuccessors() == 1) return false;104105assert(is_contained(predecessors(Dest), TI->getParent()) &&106"No edge between TI's block and Dest.");107108const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);109110// If there is more than one predecessor, this is a critical edge...111assert(I != E && "No preds, but we have an edge to the block?");112const BasicBlock *FirstPred = *I;113++I; // Skip one edge due to the incoming arc from TI.114if (!AllowIdenticalEdges)115return I != E;116117// If AllowIdenticalEdges is true, then we allow this edge to be considered118// non-critical iff all preds come from TI's block.119for (; I != E; ++I)120if (*I != FirstPred)121return true;122return false;123}124125// LoopInfo contains a mapping from basic block to the innermost loop. Find126// the outermost loop in the loop nest that contains BB.127static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {128const Loop *L = LI->getLoopFor(BB);129return L ? L->getOutermostLoop() : nullptr;130}131132template <class StopSetT>133static bool isReachableImpl(SmallVectorImpl<BasicBlock *> &Worklist,134const StopSetT &StopSet,135const SmallPtrSetImpl<BasicBlock *> *ExclusionSet,136const DominatorTree *DT, const LoopInfo *LI) {137// When a stop block is unreachable, it's dominated from everywhere,138// regardless of whether there's a path between the two blocks.139if (DT) {140for (auto *BB : StopSet) {141if (!DT->isReachableFromEntry(BB)) {142DT = nullptr;143break;144}145}146}147148// We can't skip directly from a block that dominates the stop block if the149// exclusion block is potentially in between.150if (ExclusionSet && !ExclusionSet->empty())151DT = nullptr;152153// Normally any block in a loop is reachable from any other block in a loop,154// however excluded blocks might partition the body of a loop to make that155// untrue.156SmallPtrSet<const Loop *, 8> LoopsWithHoles;157if (LI && ExclusionSet) {158for (auto *BB : *ExclusionSet) {159if (const Loop *L = getOutermostLoop(LI, BB))160LoopsWithHoles.insert(L);161}162}163164SmallPtrSet<const Loop *, 2> StopLoops;165if (LI) {166for (auto *StopSetBB : StopSet) {167if (const Loop *L = getOutermostLoop(LI, StopSetBB))168StopLoops.insert(L);169}170}171172unsigned Limit = DefaultMaxBBsToExplore;173SmallPtrSet<const BasicBlock*, 32> Visited;174do {175BasicBlock *BB = Worklist.pop_back_val();176if (!Visited.insert(BB).second)177continue;178if (StopSet.contains(BB))179return true;180if (ExclusionSet && ExclusionSet->count(BB))181continue;182if (DT) {183if (llvm::any_of(StopSet, [&](const BasicBlock *StopBB) {184return DT->dominates(BB, StopBB);185}))186return true;187}188189const Loop *Outer = nullptr;190if (LI) {191Outer = getOutermostLoop(LI, BB);192// If we're in a loop with a hole, not all blocks in the loop are193// reachable from all other blocks. That implies we can't simply jump to194// the loop's exit blocks, as that exit might need to pass through an195// excluded block. Clear Outer so we process BB's successors.196if (LoopsWithHoles.count(Outer))197Outer = nullptr;198if (StopLoops.contains(Outer))199return true;200}201202if (!--Limit) {203// We haven't been able to prove it one way or the other. Conservatively204// answer true -- that there is potentially a path.205return true;206}207208if (Outer) {209// All blocks in a single loop are reachable from all other blocks. From210// any of these blocks, we can skip directly to the exits of the loop,211// ignoring any other blocks inside the loop body.212Outer->getExitBlocks(Worklist);213} else {214Worklist.append(succ_begin(BB), succ_end(BB));215}216} while (!Worklist.empty());217218// We have exhausted all possible paths and are certain that 'To' can not be219// reached from 'From'.220return false;221}222223template <class T> class SingleEntrySet {224public:225using const_iterator = const T *;226227SingleEntrySet(T Elem) : Elem(Elem) {}228229bool contains(T Other) const { return Elem == Other; }230231const_iterator begin() const { return &Elem; }232const_iterator end() const { return &Elem + 1; }233234private:235T Elem;236};237238bool llvm::isPotentiallyReachableFromMany(239SmallVectorImpl<BasicBlock *> &Worklist, const BasicBlock *StopBB,240const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,241const LoopInfo *LI) {242return isReachableImpl<SingleEntrySet<const BasicBlock *>>(243Worklist, SingleEntrySet<const BasicBlock *>(StopBB), ExclusionSet, DT,244LI);245}246247bool llvm::isManyPotentiallyReachableFromMany(248SmallVectorImpl<BasicBlock *> &Worklist,249const SmallPtrSetImpl<const BasicBlock *> &StopSet,250const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,251const LoopInfo *LI) {252return isReachableImpl<SmallPtrSetImpl<const BasicBlock *>>(253Worklist, StopSet, ExclusionSet, DT, LI);254}255256bool llvm::isPotentiallyReachable(257const BasicBlock *A, const BasicBlock *B,258const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,259const LoopInfo *LI) {260assert(A->getParent() == B->getParent() &&261"This analysis is function-local!");262263if (DT) {264if (DT->isReachableFromEntry(A) && !DT->isReachableFromEntry(B))265return false;266if (!ExclusionSet || ExclusionSet->empty()) {267if (A->isEntryBlock() && DT->isReachableFromEntry(B))268return true;269if (B->isEntryBlock() && DT->isReachableFromEntry(A))270return false;271}272}273274SmallVector<BasicBlock*, 32> Worklist;275Worklist.push_back(const_cast<BasicBlock*>(A));276277return isPotentiallyReachableFromMany(Worklist, B, ExclusionSet, DT, LI);278}279280bool llvm::isPotentiallyReachable(281const Instruction *A, const Instruction *B,282const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,283const LoopInfo *LI) {284assert(A->getParent()->getParent() == B->getParent()->getParent() &&285"This analysis is function-local!");286287if (A->getParent() == B->getParent()) {288// The same block case is special because it's the only time we're looking289// within a single block to see which instruction comes first. Once we290// start looking at multiple blocks, the first instruction of the block is291// reachable, so we only need to determine reachability between whole292// blocks.293BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());294295// If the block is in a loop then we can reach any instruction in the block296// from any other instruction in the block by going around a backedge.297if (LI && LI->getLoopFor(BB) != nullptr)298return true;299300// If A comes before B, then B is definitively reachable from A.301if (A == B || A->comesBefore(B))302return true;303304// Can't be in a loop if it's the entry block -- the entry block may not305// have predecessors.306if (BB->isEntryBlock())307return false;308309// Otherwise, continue doing the normal per-BB CFG walk.310SmallVector<BasicBlock*, 32> Worklist;311Worklist.append(succ_begin(BB), succ_end(BB));312if (Worklist.empty()) {313// We've proven that there's no path!314return false;315}316317return isPotentiallyReachableFromMany(Worklist, B->getParent(),318ExclusionSet, DT, LI);319}320321return isPotentiallyReachable(322A->getParent(), B->getParent(), ExclusionSet, DT, LI);323}324325326