LLVM 23.0.0git
CFG.cpp
Go to the documentation of this file.
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
14#include "llvm/Analysis/CFG.h"
17#include "llvm/IR/Dominators.h"
20
21using namespace llvm;
22
23// The max number of basic blocks explored during reachability analysis between
24// two basic blocks. This is kept reasonably small to limit compile time when
25// repeatedly used by clients of this analysis (such as captureTracking).
27 "dom-tree-reachability-max-bbs-to-explore", cl::Hidden,
28 cl::desc("Max number of BBs to explore for reachability analysis"),
29 cl::init(32));
30
31/// FindFunctionBackedges - Analyze the specified function to find all of the
32/// loop backedges in the function and return them. This is a relatively cheap
33/// (compared to computing dominators and loop info) analysis.
34///
35/// The output is added to Result, as pairs of <from,to> edge info.
37 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
38 const BasicBlock *BB = &F.getEntryBlock();
39
40 // In the DFS traversal, we maintain three states: unvisited, visited in the
41 // past, and visited and currently in the DFS stack. If we have an edge to a
42 // block in the stack, we have found a backedge.
43 enum VisitState : uint8_t { Unvisited = 0, Visited = 1, InStack = 2 };
44 SmallVector<VisitState> BlockState(F.getMaxBlockNumber(), Unvisited);
45 struct StackEntry {
46 const BasicBlock *BB;
48 const_succ_iterator SuccEnd;
49
50 StackEntry(const BasicBlock *BB)
51 : BB(BB), SuccIt(nullptr), SuccEnd(nullptr) {
52 auto Succs = successors(BB);
53 SuccIt = Succs.begin();
54 SuccEnd = Succs.end();
55 }
56 };
58
59 BlockState[BB->getNumber()] = InStack;
60 VisitStack.emplace_back(BB);
61 do {
62 StackEntry &Top = VisitStack.back();
63 bool FoundNew = false;
64 while (Top.SuccIt != Top.SuccEnd) {
65 BB = *Top.SuccIt++;
66 if (BlockState[BB->getNumber()] == Unvisited) {
67 // Unvisited successor => go down one level.
68 BlockState[BB->getNumber()] = InStack;
69 VisitStack.emplace_back(BB);
70 FoundNew = true;
71 break;
72 }
73 // Successor in VisitStack => backedge.
74 if (BlockState[BB->getNumber()] == InStack)
75 Result.emplace_back(Top.BB, BB);
76 }
77
78 // Go up one level.
79 if (!FoundNew) {
80 BlockState[Top.BB->getNumber()] = Visited;
81 VisitStack.pop_back();
82 }
83 } while (!VisitStack.empty());
84}
85
86/// GetSuccessorNumber - Search for the specified successor of basic block BB
87/// and return its position in the terminator instruction's list of
88/// successors. It is an error to call this with a block that is not a
89/// successor.
91 const BasicBlock *Succ) {
92 const Instruction *Term = BB->getTerminator();
93#ifndef NDEBUG
94 unsigned e = Term->getNumSuccessors();
95#endif
96 for (unsigned i = 0; ; ++i) {
97 assert(i != e && "Didn't find edge?");
98 if (Term->getSuccessor(i) == Succ)
99 return i;
100 }
101}
102
103/// isCriticalEdge - Return true if the specified edge is a critical edge.
104/// Critical edges are edges from a block with multiple successors to a block
105/// with multiple predecessors.
106bool llvm::isCriticalEdge(const Instruction *TI, unsigned SuccNum,
107 bool AllowIdenticalEdges) {
108 assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
109 return isCriticalEdge(TI, TI->getSuccessor(SuccNum), AllowIdenticalEdges);
110}
111
112bool llvm::isCriticalEdge(const Instruction *TI, const BasicBlock *Dest,
113 bool AllowIdenticalEdges) {
114 assert(TI->isTerminator() && "Must be a terminator to have successors!");
115 if (TI->getNumSuccessors() == 1) return false;
116
118 "No edge between TI's block and Dest.");
119
120 const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
121
122 // If there is more than one predecessor, this is a critical edge...
123 assert(I != E && "No preds, but we have an edge to the block?");
124 const BasicBlock *FirstPred = *I;
125 ++I; // Skip one edge due to the incoming arc from TI.
126 if (!AllowIdenticalEdges)
127 return I != E;
128
129 // If AllowIdenticalEdges is true, then we allow this edge to be considered
130 // non-critical iff all preds come from TI's block.
131 for (; I != E; ++I)
132 if (*I != FirstPred)
133 return true;
134 return false;
135}
136
137// LoopInfo contains a mapping from basic block to the innermost loop. Find
138// the outermost loop in the loop nest that contains BB.
139static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
140 const Loop *L = LI->getLoopFor(BB);
141 return L ? L->getOutermostLoop() : nullptr;
142}
143
144template <class StopSetT>
146 const StopSetT &StopSet,
147 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet,
148 const DominatorTree *DT, const LoopInfo *LI,
149 const CycleInfo *CI) {
150 // If both LI and CI are passed, use CI, which gives us more information.
151 if (CI)
152 LI = nullptr;
153
154 // When a stop block is unreachable, it's dominated from everywhere,
155 // regardless of whether there's a path between the two blocks.
156 if (DT) {
157 for (auto *BB : StopSet) {
158 if (!DT->isReachableFromEntry(BB)) {
159 DT = nullptr;
160 break;
161 }
162 }
163 }
164
165 // We can't skip directly from a block that dominates the stop block if the
166 // exclusion block is potentially in between.
167 if (ExclusionSet && !ExclusionSet->empty())
168 DT = nullptr;
169
170 // Normally any block in a loop is reachable from any other block in a loop,
171 // however excluded blocks might partition the body of a loop to make that
172 // untrue.
173 SmallPtrSet<const Loop *, 8> LoopsWithHoles;
174 if (LI && ExclusionSet) {
175 for (auto *BB : *ExclusionSet) {
176 if (const Loop *L = getOutermostLoop(LI, BB))
177 LoopsWithHoles.insert(L);
178 }
179 }
180
181 SmallPtrSet<const Cycle *, 8> CyclesWithHoles;
182 if (CI && ExclusionSet) {
183 for (auto *BB : *ExclusionSet) {
184 if (const Cycle *C = CI->getTopLevelParentCycle(BB))
185 CyclesWithHoles.insert(C);
186 }
187 }
188
190 if (LI) {
191 for (auto *StopSetBB : StopSet) {
192 if (const Loop *L = getOutermostLoop(LI, StopSetBB))
193 StopLoops.insert(L);
194 }
195 }
196
198 if (CI) {
199 for (auto *StopSetBB : StopSet) {
200 if (const Cycle *C = CI->getTopLevelParentCycle(StopSetBB))
201 StopCycles.insert(C);
202 }
203 }
204
205 unsigned Limit = DefaultMaxBBsToExplore;
207 do {
208 BasicBlock *BB = Worklist.pop_back_val();
209 if (!Visited.insert(BB).second)
210 continue;
211 if (StopSet.contains(BB))
212 return true;
213 if (ExclusionSet && ExclusionSet->count(BB))
214 continue;
215 if (DT) {
216 if (llvm::any_of(StopSet, [&](const BasicBlock *StopBB) {
217 return DT->dominates(BB, StopBB);
218 }))
219 return true;
220 }
221
222 const Loop *OuterL = nullptr;
223 if (LI) {
224 OuterL = getOutermostLoop(LI, BB);
225 // If we're in a loop with a hole, not all blocks in the loop are
226 // reachable from all other blocks. That implies we can't simply jump to
227 // the loop's exit blocks, as that exit might need to pass through an
228 // excluded block. Clear Outer so we process BB's successors.
229 if (LoopsWithHoles.count(OuterL))
230 OuterL = nullptr;
231 else if (StopLoops.contains(OuterL))
232 return true;
233 }
234
235 const Cycle *OuterC = nullptr;
236 if (CI) {
237 OuterC = CI->getTopLevelParentCycle(BB);
238 if (CyclesWithHoles.count(OuterC))
239 OuterC = nullptr;
240 else if (StopCycles.contains(OuterC))
241 return true;
242 }
243
244 if (!--Limit) {
245 // We haven't been able to prove it one way or the other. Conservatively
246 // answer true -- that there is potentially a path.
247 return true;
248 }
249
250 if (OuterL) {
251 // All blocks in a single loop are reachable from all other blocks. From
252 // any of these blocks, we can skip directly to the exits of the loop,
253 // ignoring any other blocks inside the loop body.
254 OuterL->getExitBlocks(Worklist);
255 } else if (OuterC) {
256 OuterC->getExitBlocks(Worklist);
257 } else {
258 Worklist.append(succ_begin(BB), succ_end(BB));
259 }
260 } while (!Worklist.empty());
261
262 // We have exhausted all possible paths and are certain that 'To' can not be
263 // reached from 'From'.
264 return false;
265}
266
267template <class T> class SingleEntrySet {
268public:
269 using const_iterator = const T *;
270
271 SingleEntrySet(T Elem) : Elem(Elem) {}
272
273 bool contains(T Other) const { return Elem == Other; }
274
275 const_iterator begin() const { return &Elem; }
276 const_iterator end() const { return &Elem + 1; }
277
278private:
279 T Elem;
280};
281
283 SmallVectorImpl<BasicBlock *> &Worklist, const BasicBlock *StopBB,
284 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
285 const LoopInfo *LI, const CycleInfo *CI) {
287 Worklist, SingleEntrySet<const BasicBlock *>(StopBB), ExclusionSet, DT,
288 LI, CI);
289}
290
294 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
295 const LoopInfo *LI, const CycleInfo *CI) {
297 Worklist, StopSet, ExclusionSet, DT, LI, CI);
298}
299
301 const BasicBlock *A, const BasicBlock *B,
302 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
303 const LoopInfo *LI, const CycleInfo *CI) {
304 assert(A->getParent() == B->getParent() &&
305 "This analysis is function-local!");
306
307 if (DT) {
309 return false;
310 if (!ExclusionSet || ExclusionSet->empty()) {
311 if (A->isEntryBlock() && DT->isReachableFromEntry(B))
312 return true;
313 if (B->isEntryBlock() && DT->isReachableFromEntry(A))
314 return false;
315 }
316 }
317
319 Worklist.push_back(const_cast<BasicBlock*>(A));
320
321 return isPotentiallyReachableFromMany(Worklist, B, ExclusionSet, DT, LI, CI);
322}
323
325 const Instruction *A, const Instruction *B,
326 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
327 const LoopInfo *LI, const CycleInfo *CI) {
328 assert(A->getParent()->getParent() == B->getParent()->getParent() &&
329 "This analysis is function-local!");
330
331 if (A->getParent() == B->getParent()) {
332 // The same block case is special because it's the only time we're looking
333 // within a single block to see which instruction comes first. Once we
334 // start looking at multiple blocks, the first instruction of the block is
335 // reachable, so we only need to determine reachability between whole
336 // blocks.
337 BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
338
339 // If A comes before B, then B is definitively reachable from A.
340 if (A == B || A->comesBefore(B))
341 return true;
342
343 // If the block is in a cycle (and there are no excluded blocks), then we
344 // can reach any instruction in the block from any other instruction in the
345 // block by going around a backedge.
346 if (!ExclusionSet || ExclusionSet->empty()) {
347 // If cycle info is available, we can know for sure whether or not a
348 // block is part of a cycle.
349 if (CI)
350 return CI->getCycle(BB) != nullptr;
351
352 // If only loop info is available, even if the block is not part of a
353 // natural loop, it may still be part of an irreducible cycle.
354 if (LI && LI->getLoopFor(BB) != nullptr)
355 return true;
356 }
357
358 // Can't be in a loop if it's the entry block -- the entry block may not
359 // have predecessors.
360 if (BB->isEntryBlock())
361 return false;
362
363 // Otherwise, continue doing the normal per-BB CFG walk.
365 Worklist.append(succ_begin(BB), succ_end(BB));
366 if (Worklist.empty()) {
367 // We've proven that there's no path!
368 return false;
369 }
370
371 return isPotentiallyReachableFromMany(Worklist, B->getParent(),
372 ExclusionSet, DT, LI, CI);
373 }
374
375 return isPotentiallyReachable(A->getParent(), B->getParent(), ExclusionSet,
376 DT, LI, CI);
377}
378
380 if (auto *CB = dyn_cast<CallBase>(&I))
381 return CB->hasFnAttr(Attribute::NoReturn);
382 return false;
383}
384
385// A basic block can only return if it terminates with a ReturnInst and does not
386// contain calls to noreturn functions.
387static bool basicBlockCanReturn(const BasicBlock &BB) {
389 return false;
391}
392
393// FIXME: this doesn't handle recursion.
397
398 Visited.insert(&F.front());
399 Worklist.push_back(&F.front());
400
401 do {
402 const BasicBlock *BB = Worklist.pop_back_val();
403 if (basicBlockCanReturn(*BB))
404 return true;
405 for (const BasicBlock *Succ : successors(BB))
406 if (Visited.insert(Succ).second)
407 Worklist.push_back(Succ);
408 } while (!Worklist.empty());
409
410 return false;
411}
412
414 const BasicBlock &Dest) {
415 assert(Src.getParent() == Dest.getParent());
416 if (!Src.getParent()->isPresplitCoroutine())
417 return false;
418 if (auto *SW = dyn_cast<SwitchInst>(Src.getTerminator()))
419 if (auto *Intr = dyn_cast<IntrinsicInst>(SW->getCondition()))
420 return Intr->getIntrinsicID() == Intrinsic::coro_suspend &&
421 SW->getDefaultDest() == &Dest;
422 return false;
423}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static cl::opt< unsigned > DefaultMaxBBsToExplore("dom-tree-reachability-max-bbs-to-explore", cl::Hidden, cl::desc("Max number of BBs to explore for reachability analysis"), cl::init(32))
static const Loop * getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB)
Definition CFG.cpp:139
static bool instructionDoesNotReturn(const Instruction &I)
Definition CFG.cpp:379
static bool basicBlockCanReturn(const BasicBlock &BB)
Definition CFG.cpp:387
static bool isReachableImpl(SmallVectorImpl< BasicBlock * > &Worklist, const StopSetT &StopSet, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT, const LoopInfo *LI, const CycleInfo *CI)
Definition CFG.cpp:145
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
const_iterator end() const
Definition CFG.cpp:276
const_iterator begin() const
Definition CFG.cpp:275
const T * const_iterator
Definition CFG.cpp:269
bool contains(T Other) const
Definition CFG.cpp:273
SingleEntrySet(T Elem)
Definition CFG.cpp:271
LLVM Basic Block Representation.
Definition BasicBlock.h:62
unsigned getNumber() const
Definition BasicBlock.h:95
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition BasicBlock.h:233
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:159
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
CycleT * getTopLevelParentCycle(const BlockT *Block) const
CycleT * getCycle(const BlockT *Block) const
Find the innermost cycle containing a given block.
void getExitBlocks(SmallVectorImpl< BlockT * > &TmpStorage) const
Return all of the successor blocks of this cycle.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
bool isTerminator() const
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
const ParentTy * getParent() const
Definition ilist_node.h:34
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
LLVM_ABI bool isManyPotentiallyReachableFromMany(SmallVectorImpl< BasicBlock * > &Worklist, const SmallPtrSetImpl< const BasicBlock * > &StopSet, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether there is a potentially a path from at least one block in 'Worklist' to at least one...
Definition CFG.cpp:291
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:90
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
PredIterator< const BasicBlock, Value::const_user_iterator > const_pred_iterator
Definition CFG.h:106
CycleInfo::CycleT Cycle
Definition CycleInfo.h:26
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
@ Other
Any other memory.
Definition ModRef.h:68
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
LLVM_ABI bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet=nullptr, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether instruction 'To' is reachable from 'From', without passing through any blocks in Ex...
Definition CFG.cpp:324
LLVM_ABI bool isPotentiallyReachableFromMany(SmallVectorImpl< BasicBlock * > &Worklist, const BasicBlock *StopBB, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr, const CycleInfo *CI=nullptr)
Determine whether there is at least one path from a block in 'Worklist' to 'StopBB' without passing t...
Definition CFG.cpp:282
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
auto pred_begin(const MachineBasicBlock *BB)
LLVM_ABI bool isPresplitCoroSuspendExitEdge(const BasicBlock &Src, const BasicBlock &Dest)
Definition CFG.cpp:413
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Instruction::const_succ_iterator const_succ_iterator
Definition CFG.h:139
LLVM_ABI void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock * > > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them.
Definition CFG.cpp:36
LLVM_ABI bool canReturn(const Function &F)
Return true if there is at least a path through which F can return, false if there is no such path.
Definition CFG.cpp:394