blob: 18b83d6838cc94d985115a828432d52e59c28947 [file] [log] [blame]
Nick Lewycky0b682452013-07-27 01:24:00 +00001//===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Nick Lewycky0b682452013-07-27 01:24:00 +00006//
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"
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +000015#include "llvm/ADT/SmallPtrSet.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000016#include "llvm/ADT/SmallSet.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000017#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000018#include "llvm/IR/Dominators.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000019
20using namespace llvm;
21
22/// FindFunctionBackedges - Analyze the specified function to find all of the
23/// loop backedges in the function and return them. This is a relatively cheap
24/// (compared to computing dominators and loop info) analysis.
25///
26/// The output is added to Result, as pairs of <from,to> edge info.
27void llvm::FindFunctionBackedges(const Function &F,
28 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
29 const BasicBlock *BB = &F.getEntryBlock();
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +000030 if (succ_empty(BB))
Nick Lewycky0b682452013-07-27 01:24:00 +000031 return;
32
33 SmallPtrSet<const BasicBlock*, 8> Visited;
34 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
35 SmallPtrSet<const BasicBlock*, 8> InStack;
36
37 Visited.insert(BB);
38 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
39 InStack.insert(BB);
40 do {
41 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
42 const BasicBlock *ParentBB = Top.first;
43 succ_const_iterator &I = Top.second;
44
45 bool FoundNew = false;
46 while (I != succ_end(ParentBB)) {
47 BB = *I++;
David Blaikie70573dc2014-11-19 07:49:26 +000048 if (Visited.insert(BB).second) {
Nick Lewycky0b682452013-07-27 01:24:00 +000049 FoundNew = true;
50 break;
51 }
52 // Successor is in VisitStack, it's a back edge.
53 if (InStack.count(BB))
54 Result.push_back(std::make_pair(ParentBB, BB));
55 }
56
57 if (FoundNew) {
58 // Go down one level if there is a unvisited successor.
59 InStack.insert(BB);
60 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
61 } else {
62 // Go up one level.
63 InStack.erase(VisitStack.pop_back_val().first);
64 }
65 } while (!VisitStack.empty());
66}
67
68/// GetSuccessorNumber - Search for the specified successor of basic block BB
69/// and return its position in the terminator instruction's list of
70/// successors. It is an error to call this with a block that is not a
71/// successor.
Rong Xua1f61fe2015-11-20 23:02:06 +000072unsigned llvm::GetSuccessorNumber(const BasicBlock *BB,
73 const BasicBlock *Succ) {
Chandler Carruthedb12a82018-10-15 10:04:59 +000074 const Instruction *Term = BB->getTerminator();
Nick Lewycky0b682452013-07-27 01:24:00 +000075#ifndef NDEBUG
76 unsigned e = Term->getNumSuccessors();
77#endif
78 for (unsigned i = 0; ; ++i) {
79 assert(i != e && "Didn't find edge?");
80 if (Term->getSuccessor(i) == Succ)
81 return i;
82 }
83}
84
85/// isCriticalEdge - Return true if the specified edge is a critical edge.
86/// Critical edges are edges from a block with multiple successors to a block
87/// with multiple predecessors.
Chandler Carruthb99a24682018-10-15 09:17:09 +000088bool llvm::isCriticalEdge(const Instruction *TI, unsigned SuccNum,
Nick Lewycky0b682452013-07-27 01:24:00 +000089 bool AllowIdenticalEdges) {
Florian Hahn2d7227e2019-07-30 16:43:39 +000090 assert(TI->isTerminator() && "Must be a terminator to have successors!");
Florian Hahnd0b6f422019-07-30 17:04:58 +000091 assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
Nick Lewycky0b682452013-07-27 01:24:00 +000092 if (TI->getNumSuccessors() == 1) return false;
93
Florian Hahnd0b6f422019-07-30 17:04:58 +000094 const BasicBlock *Dest = TI->getSuccessor(SuccNum);
Nick Lewycky0b682452013-07-27 01:24:00 +000095 const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
96
97 // If there is more than one predecessor, this is a critical edge...
98 assert(I != E && "No preds, but we have an edge to the block?");
99 const BasicBlock *FirstPred = *I;
100 ++I; // Skip one edge due to the incoming arc from TI.
101 if (!AllowIdenticalEdges)
102 return I != E;
103
104 // If AllowIdenticalEdges is true, then we allow this edge to be considered
105 // non-critical iff all preds come from TI's block.
Erik Verbruggene706b882014-03-25 09:06:18 +0000106 for (; I != E; ++I)
107 if (*I != FirstPred)
Nick Lewycky0b682452013-07-27 01:24:00 +0000108 return true;
Nick Lewycky0b682452013-07-27 01:24:00 +0000109 return false;
110}
111
112// LoopInfo contains a mapping from basic block to the innermost loop. Find
113// the outermost loop in the loop nest that contains BB.
Jakub Staszakd184e2d2013-08-20 23:04:15 +0000114static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
Nick Lewycky0b682452013-07-27 01:24:00 +0000115 const Loop *L = LI->getLoopFor(BB);
116 if (L) {
117 while (const Loop *Parent = L->getParentLoop())
118 L = Parent;
119 }
120 return L;
121}
122
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +0000123bool llvm::isPotentiallyReachableFromMany(
124 SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000125 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
126 const LoopInfo *LI) {
Nick Lewycky0b682452013-07-27 01:24:00 +0000127 // When the stop block is unreachable, it's dominated from everywhere,
128 // regardless of whether there's a path between the two blocks.
129 if (DT && !DT->isReachableFromEntry(StopBB))
Craig Topper9f008862014-04-15 04:59:12 +0000130 DT = nullptr;
Nick Lewycky0b682452013-07-27 01:24:00 +0000131
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000132 // We can't skip directly from a block that dominates the stop block if the
133 // exclusion block is potentially in between.
134 if (ExclusionSet && !ExclusionSet->empty())
135 DT = nullptr;
136
137 // Normally any block in a loop is reachable from any other block in a loop,
138 // however excluded blocks might partition the body of a loop to make that
139 // untrue.
140 SmallPtrSet<const Loop *, 8> LoopsWithHoles;
141 if (LI && ExclusionSet) {
142 for (auto BB : *ExclusionSet) {
143 if (const Loop *L = getOutermostLoop(LI, BB))
144 LoopsWithHoles.insert(L);
145 }
146 }
147
148 const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr;
149
Nick Lewycky0b682452013-07-27 01:24:00 +0000150 // Limit the number of blocks we visit. The goal is to avoid run-away compile
151 // times on large CFGs without hampering sensible code. Arbitrarily chosen.
152 unsigned Limit = 32;
Matthias Braunb30f2f512016-01-30 01:24:31 +0000153 SmallPtrSet<const BasicBlock*, 32> Visited;
Nick Lewycky0b682452013-07-27 01:24:00 +0000154 do {
155 BasicBlock *BB = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +0000156 if (!Visited.insert(BB).second)
Nick Lewycky0b682452013-07-27 01:24:00 +0000157 continue;
158 if (BB == StopBB)
159 return true;
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000160 if (ExclusionSet && ExclusionSet->count(BB))
161 continue;
Nick Lewycky0b682452013-07-27 01:24:00 +0000162 if (DT && DT->dominates(BB, StopBB))
163 return true;
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000164
165 const Loop *Outer = nullptr;
166 if (LI) {
167 Outer = getOutermostLoop(LI, BB);
168 // If we're in a loop with a hole, not all blocks in the loop are
169 // reachable from all other blocks. That implies we can't simply jump to
170 // the loop's exit blocks, as that exit might need to pass through an
171 // excluded block. Clear Outer so we process BB's successors.
172 if (LoopsWithHoles.count(Outer))
173 Outer = nullptr;
174 if (StopLoop && Outer == StopLoop)
175 return true;
176 }
Nick Lewycky0b682452013-07-27 01:24:00 +0000177
178 if (!--Limit) {
179 // We haven't been able to prove it one way or the other. Conservatively
180 // answer true -- that there is potentially a path.
181 return true;
182 }
183
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000184 if (Outer) {
Nick Lewycky0b682452013-07-27 01:24:00 +0000185 // All blocks in a single loop are reachable from all other blocks. From
186 // any of these blocks, we can skip directly to the exits of the loop,
187 // ignoring any other blocks inside the loop body.
188 Outer->getExitBlocks(Worklist);
189 } else {
Benjamin Kramer3c29c072014-02-10 14:17:42 +0000190 Worklist.append(succ_begin(BB), succ_end(BB));
Nick Lewycky0b682452013-07-27 01:24:00 +0000191 }
192 } while (!Worklist.empty());
193
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000194 // We have exhausted all possible paths and are certain that 'To' can not be
195 // reached from 'From'.
Nick Lewycky0b682452013-07-27 01:24:00 +0000196 return false;
197}
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000198
199bool llvm::isPotentiallyReachable(const BasicBlock *A, const BasicBlock *B,
Jakub Staszakd184e2d2013-08-20 23:04:15 +0000200 const DominatorTree *DT, const LoopInfo *LI) {
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000201 assert(A->getParent() == B->getParent() &&
202 "This analysis is function-local!");
203
204 SmallVector<BasicBlock*, 32> Worklist;
205 Worklist.push_back(const_cast<BasicBlock*>(A));
206
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +0000207 return isPotentiallyReachableFromMany(Worklist, const_cast<BasicBlock *>(B),
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000208 nullptr, DT, LI);
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000209}
210
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000211bool llvm::isPotentiallyReachable(
212 const Instruction *A, const Instruction *B,
213 const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
214 const LoopInfo *LI) {
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000215 assert(A->getParent()->getParent() == B->getParent()->getParent() &&
216 "This analysis is function-local!");
217
218 SmallVector<BasicBlock*, 32> Worklist;
219
220 if (A->getParent() == B->getParent()) {
221 // The same block case is special because it's the only time we're looking
222 // within a single block to see which instruction comes first. Once we
223 // start looking at multiple blocks, the first instruction of the block is
224 // reachable, so we only need to determine reachability between whole
225 // blocks.
226 BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
227
228 // If the block is in a loop then we can reach any instruction in the block
229 // from any other instruction in the block by going around a backedge.
Craig Topper9f008862014-04-15 04:59:12 +0000230 if (LI && LI->getLoopFor(BB) != nullptr)
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000231 return true;
232
233 // Linear scan, start at 'A', see whether we hit 'B' or the end first.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000234 for (BasicBlock::const_iterator I = A->getIterator(), E = BB->end(); I != E;
235 ++I) {
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000236 if (&*I == B)
237 return true;
238 }
239
240 // Can't be in a loop if it's the entry block -- the entry block may not
241 // have predecessors.
242 if (BB == &BB->getParent()->getEntryBlock())
243 return false;
244
245 // Otherwise, continue doing the normal per-BB CFG walk.
Benjamin Kramer3c29c072014-02-10 14:17:42 +0000246 Worklist.append(succ_begin(BB), succ_end(BB));
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000247
248 if (Worklist.empty()) {
249 // We've proven that there's no path!
250 return false;
251 }
252 } else {
253 Worklist.push_back(const_cast<BasicBlock*>(A->getParent()));
254 }
255
Nick Lewycky66d7eb92019-04-01 20:03:16 +0000256 if (DT) {
Nick Lewyckya6ed16c2019-04-04 23:09:40 +0000257 if (DT->isReachableFromEntry(A->getParent()) &&
258 !DT->isReachableFromEntry(B->getParent()))
Nick Lewycky66d7eb92019-04-01 20:03:16 +0000259 return false;
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000260 if (!ExclusionSet || ExclusionSet->empty()) {
261 if (A->getParent() == &A->getParent()->getParent()->getEntryBlock() &&
262 DT->isReachableFromEntry(B->getParent()))
263 return true;
264 if (B->getParent() == &A->getParent()->getParent()->getEntryBlock() &&
265 DT->isReachableFromEntry(A->getParent()))
266 return false;
267 }
Nick Lewycky66d7eb92019-04-01 20:03:16 +0000268 }
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000269
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +0000270 return isPotentiallyReachableFromMany(
Nick Lewyckyc0ebfbe32019-04-02 01:05:48 +0000271 Worklist, const_cast<BasicBlock *>(B->getParent()), ExclusionSet, DT, LI);
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000272}