LLVM 22.0.0git
Dominators.cpp
Go to the documentation of this file.
1//===- Dominators.cpp - Dominator Calculation -----------------------------===//
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 file implements simple dominator construction algorithms for finding
10// forward dominators. Postdominators are available in libanalysis, but are not
11// included in libvmcore, because it's not needed. Forward dominators are
12// needed to support the Verifier pass.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/IR/Dominators.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/Config/llvm-config.h"
19#include "llvm/IR/CFG.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instruction.h"
23#include "llvm/IR/PassManager.h"
25#include "llvm/PassRegistry.h"
31
32#include <cassert>
33
34namespace llvm {
35class Argument;
36class Constant;
37class Value;
38} // namespace llvm
39using namespace llvm;
40
44 cl::desc("Verify dominator info (time consuming)"));
45
46#ifdef EXPENSIVE_CHECKS
47static constexpr bool ExpensiveChecksEnabled = true;
48#else
49static constexpr bool ExpensiveChecksEnabled = false;
50#endif
51
53 unsigned NumEdgesToEnd = 0;
54 for (const BasicBlock *Succ : successors(Start)) {
55 if (Succ == End)
56 ++NumEdgesToEnd;
57 if (NumEdgesToEnd >= 2)
58 return false;
59 }
60 assert(NumEdgesToEnd == 1);
61 return true;
62}
63
64//===----------------------------------------------------------------------===//
65// DominatorTree Implementation
66//===----------------------------------------------------------------------===//
67//
68// Provide public access to DominatorTree information. Implementation details
69// can be found in Dominators.h, GenericDomTree.h, and
70// GenericDomTreeConstruction.h.
71//
72//===----------------------------------------------------------------------===//
73
75template class LLVM_EXPORT_TEMPLATE
77template class LLVM_EXPORT_TEMPLATE
79
81
83llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBDomTree>(
86llvm::DomTreeBuilder::CalculateWithUpdates<DomTreeBuilder::BBDomTree>(
87 DomTreeBuilder::BBDomTree &DT, BBUpdates U);
88
90llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBPostDomTree>(
92// No CalculateWithUpdates<PostDomTree> instantiation, unless a usecase arises.
93
95llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBDomTree>(
98llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBPostDomTree>(
100
102llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBDomTree>(
105llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBPostDomTree>(
107
109llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBDomTree>(
113llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBPostDomTree>(
116
118llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBDomTree>(
122llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBPostDomTree>(
125
128 // Check whether the analysis, all analyses on functions, or the function's
129 // CFG have been preserved.
130 auto PAC = PA.getChecker<DominatorTreeAnalysis>();
131 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
132 PAC.preservedSet<CFGAnalyses>());
133}
134
135bool DominatorTree::dominates(const BasicBlock *BB, const Use &U) const {
136 Instruction *UserInst = cast<Instruction>(U.getUser());
137 if (auto *PN = dyn_cast<PHINode>(UserInst))
138 // A phi use using a value from a block is dominated by the end of that
139 // block. Note that the phi's parent block may not be.
140 return dominates(BB, PN->getIncomingBlock(U));
141 else
142 return properlyDominates(BB, UserInst->getParent());
143}
144
145// dominates - Return true if Def dominates a use in User. This performs
146// the special checks necessary if Def and User are in the same basic block.
147// Note that Def doesn't dominate a use in Def itself!
149 const Instruction *User) const {
150 const Instruction *Def = dyn_cast<Instruction>(DefV);
151 if (!Def) {
152 assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
153 "Should be called with an instruction, argument or constant");
154 return true; // Arguments and constants dominate everything.
155 }
156
157 const BasicBlock *UseBB = User->getParent();
158 const BasicBlock *DefBB = Def->getParent();
159
160 // Any unreachable use is dominated, even if Def == User.
161 if (!isReachableFromEntry(UseBB))
162 return true;
163
164 // Unreachable definitions don't dominate anything.
165 if (!isReachableFromEntry(DefBB))
166 return false;
167
168 // An instruction doesn't dominate a use in itself.
169 if (Def == User)
170 return false;
171
172 // The value defined by an invoke dominates an instruction only if it
173 // dominates every instruction in UseBB.
174 // A PHI is dominated only if the instruction dominates every possible use in
175 // the UseBB.
176 if (isa<InvokeInst>(Def) || isa<CallBrInst>(Def) || isa<PHINode>(User))
177 return dominates(Def, UseBB);
178
179 if (DefBB != UseBB)
180 return dominates(DefBB, UseBB);
181
182 return Def->comesBefore(User);
183}
184
185// true if Def would dominate a use in any instruction in UseBB.
186// note that dominates(Def, Def->getParent()) is false.
188 const BasicBlock *UseBB) const {
189 const BasicBlock *DefBB = Def->getParent();
190
191 // Any unreachable use is dominated, even if DefBB == UseBB.
192 if (!isReachableFromEntry(UseBB))
193 return true;
194
195 // Unreachable definitions don't dominate anything.
196 if (!isReachableFromEntry(DefBB))
197 return false;
198
199 if (DefBB == UseBB)
200 return false;
201
202 // Invoke results are only usable in the normal destination, not in the
203 // exceptional destination.
204 if (const auto *II = dyn_cast<InvokeInst>(Def)) {
205 BasicBlock *NormalDest = II->getNormalDest();
206 BasicBlockEdge E(DefBB, NormalDest);
207 return dominates(E, UseBB);
208 }
209
210 return dominates(DefBB, UseBB);
211}
212
214 const BasicBlock *UseBB) const {
215 // If the BB the edge ends in doesn't dominate the use BB, then the
216 // edge also doesn't.
217 const BasicBlock *Start = BBE.getStart();
218 const BasicBlock *End = BBE.getEnd();
219 if (!dominates(End, UseBB))
220 return false;
221
222 // Simple case: if the end BB has a single predecessor, the fact that it
223 // dominates the use block implies that the edge also does.
224 if (End->getSinglePredecessor())
225 return true;
226
227 // The normal edge from the invoke is critical. Conceptually, what we would
228 // like to do is split it and check if the new block dominates the use.
229 // With X being the new block, the graph would look like:
230 //
231 // DefBB
232 // /\ . .
233 // / \ . .
234 // / \ . .
235 // / \ | |
236 // A X B C
237 // | \ | /
238 // . \|/
239 // . NormalDest
240 // .
241 //
242 // Given the definition of dominance, NormalDest is dominated by X iff X
243 // dominates all of NormalDest's predecessors (X, B, C in the example). X
244 // trivially dominates itself, so we only have to find if it dominates the
245 // other predecessors. Since the only way out of X is via NormalDest, X can
246 // only properly dominate a node if NormalDest dominates that node too.
247 int IsDuplicateEdge = 0;
248 for (const BasicBlock *BB : predecessors(End)) {
249 if (BB == Start) {
250 // If there are multiple edges between Start and End, by definition they
251 // can't dominate anything.
252 if (IsDuplicateEdge++)
253 return false;
254 continue;
255 }
256
257 if (!dominates(End, BB))
258 return false;
259 }
260 return true;
261}
262
263bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
264 Instruction *UserInst = cast<Instruction>(U.getUser());
265 // A PHI in the end of the edge is dominated by it.
266 PHINode *PN = dyn_cast<PHINode>(UserInst);
267 if (PN && PN->getParent() == BBE.getEnd() &&
268 PN->getIncomingBlock(U) == BBE.getStart())
269 return true;
270
271 // Otherwise use the edge-dominates-block query, which
272 // handles the crazy critical edge cases properly.
273 const BasicBlock *UseBB;
274 if (PN)
275 UseBB = PN->getIncomingBlock(U);
276 else
277 UseBB = UserInst->getParent();
278 return dominates(BBE, UseBB);
279}
280
281bool DominatorTree::dominates(const Value *DefV, const Use &U) const {
282 const Instruction *Def = dyn_cast<Instruction>(DefV);
283 if (!Def) {
284 assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
285 "Should be called with an instruction, argument or constant");
286 return true; // Arguments and constants dominate everything.
287 }
288
289 Instruction *UserInst = cast<Instruction>(U.getUser());
290 const BasicBlock *DefBB = Def->getParent();
291
292 // Determine the block in which the use happens. PHI nodes use
293 // their operands on edges; simulate this by thinking of the use
294 // happening at the end of the predecessor block.
295 const BasicBlock *UseBB;
296 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
297 UseBB = PN->getIncomingBlock(U);
298 else
299 UseBB = UserInst->getParent();
300
301 // Any unreachable use is dominated, even if Def == User.
302 if (!isReachableFromEntry(UseBB))
303 return true;
304
305 // Unreachable definitions don't dominate anything.
306 if (!isReachableFromEntry(DefBB))
307 return false;
308
309 // Invoke instructions define their return values on the edges to their normal
310 // successors, so we have to handle them specially.
311 // Among other things, this means they don't dominate anything in
312 // their own block, except possibly a phi, so we don't need to
313 // walk the block in any case.
314 if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
315 BasicBlock *NormalDest = II->getNormalDest();
316 BasicBlockEdge E(DefBB, NormalDest);
317 return dominates(E, U);
318 }
319
320 // If the def and use are in different blocks, do a simple CFG dominator
321 // tree query.
322 if (DefBB != UseBB)
323 return dominates(DefBB, UseBB);
324
325 // Ok, def and use are in the same block. If the def is an invoke, it
326 // doesn't dominate anything in the block. If it's a PHI, it dominates
327 // everything in the block.
328 if (isa<PHINode>(UserInst))
329 return true;
330
331 return Def->comesBefore(UserInst);
332}
333
335 Instruction *I = dyn_cast<Instruction>(U.getUser());
336
337 // ConstantExprs aren't really reachable from the entry block, but they
338 // don't need to be treated like unreachable code either.
339 if (!I) return true;
340
341 // PHI nodes use their operands on their incoming edges.
342 if (PHINode *PN = dyn_cast<PHINode>(I))
343 return isReachableFromEntry(PN->getIncomingBlock(U));
344
345 // Everything else uses their operands in their own block.
346 return isReachableFromEntry(I->getParent());
347}
348
349// Edge BBE1 dominates edge BBE2 if they match or BBE1 dominates start of BBE2.
351 const BasicBlockEdge &BBE2) const {
352 if (BBE1.getStart() == BBE2.getStart() && BBE1.getEnd() == BBE2.getEnd())
353 return true;
354 return dominates(BBE1, BBE2.getStart());
355}
356
358 Instruction *I2) const {
359 BasicBlock *BB1 = I1->getParent();
360 BasicBlock *BB2 = I2->getParent();
361 if (BB1 == BB2)
362 return I1->comesBefore(I2) ? I1 : I2;
363 if (!isReachableFromEntry(BB2))
364 return I1;
365 if (!isReachableFromEntry(BB1))
366 return I2;
367 BasicBlock *DomBB = findNearestCommonDominator(BB1, BB2);
368 if (BB1 == DomBB)
369 return I1;
370 if (BB2 == DomBB)
371 return I2;
372 return DomBB->getTerminator();
373}
374
375//===----------------------------------------------------------------------===//
376// DominatorTreeAnalysis and related pass implementations
377//===----------------------------------------------------------------------===//
378//
379// This implements the DominatorTreeAnalysis which is used with the new pass
380// manager. It also implements some methods from utility passes.
381//
382//===----------------------------------------------------------------------===//
383
386 DominatorTree DT;
387 DT.recalculate(F);
388 return DT;
389}
390
391AnalysisKey DominatorTreeAnalysis::Key;
392
394
397 OS << "DominatorTree for function: " << F.getName() << "\n";
399
400 return PreservedAnalyses::all();
401}
402
405 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
406 assert(DT.verify());
407 (void)DT;
408 return PreservedAnalyses::all();
409}
410
411//===----------------------------------------------------------------------===//
412// DominatorTreeWrapperPass Implementation
413//===----------------------------------------------------------------------===//
414//
415// The implementation details of the wrapper pass that holds a DominatorTree
416// suitable for use with the legacy pass manager.
417//
418//===----------------------------------------------------------------------===//
419
421
424}
425
427 "Dominator Tree Construction", true, true)
428
430 DT.recalculate(F);
431 return false;
432}
433
435 if (VerifyDomInfo)
436 assert(DT.verify(DominatorTree::VerificationLevel::Full));
437 else if (ExpensiveChecksEnabled)
438 assert(DT.verify(DominatorTree::VerificationLevel::Basic));
439}
440
442 DT.print(OS);
443}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
BlockVerifier::State From
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_EXPORT_TEMPLATE
Definition: Compiler.h:215
static constexpr bool ExpensiveChecksEnabled
Definition: Dominators.cpp:49
static cl::opt< bool, true > VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo), cl::Hidden, cl::desc("Verify dominator info (time consuming)"))
bool End
Definition: ELF_riscv.cpp:480
static bool runOnFunction(Function &F, bool PostInlining)
Generic dominator tree construction - this file provides routines to construct immediate dominator in...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
static constexpr bool ExpensiveChecksEnabled
raw_pwrite_stream & OS
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
Definition: Analysis.h:50
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:294
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
This class represents an incoming formal argument to a Function.
Definition: Argument.h:32
const BasicBlock * getEnd() const
Definition: Dominators.h:115
const BasicBlock * getStart() const
Definition: Dominators.h:111
LLVM_ABI bool isSingleEdge() const
Check if this is the only edge between Start and End.
Definition: Dominators.cpp:52
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
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
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:73
This is an important base class in LLVM.
Definition: Constant.h:43
Base class for the actual dominator tree node.
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:284
LLVM_ABI DominatorTree run(Function &F, FunctionAnalysisManager &)
Run the analysis pass over a function and produce a dominator tree.
Definition: Dominators.cpp:384
Core dominator tree base class.
void print(raw_ostream &O) const
print - Convert to human readable form
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
bool properlyDominates(const DomTreeNodeBase< BasicBlock > *A, const DomTreeNodeBase< BasicBlock > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
LLVM_ABI DominatorTreePrinterPass(raw_ostream &OS)
Definition: Dominators.cpp:393
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: Dominators.cpp:395
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:322
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
Definition: Dominators.cpp:441
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
Definition: Dominators.cpp:434
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:334
LLVM_ABI Instruction * findNearestCommonDominator(Instruction *I1, Instruction *I2) const
Find the nearest instruction I that dominates both I1 and I2, in the sense that a result produced bef...
Definition: Dominators.cpp:357
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.
Definition: Dominators.cpp:135
LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
Definition: Dominators.cpp:126
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
Invoke instruction.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: Analysis.h:275
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
LLVM Value Representation.
Definition: Value.h:75
const ParentTy * getParent() const
Definition: ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
LocationClass< Ty > location(Ty &L)
Definition: CommandLine.h:464
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto successors(const MachineBasicBlock *BB)
LLVM_ABI void initializeDominatorTreeWrapperPassPass(PassRegistry &)
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
Definition: Dominators.cpp:41
auto predecessors(const MachineBasicBlock *BB)
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:29
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: Dominators.cpp:403