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