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/DepthFirstIterator.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/IR/CFG.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/PassManager.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/GenericDomTreeConstruction.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 using namespace llvm;
31 
32 bool llvm::VerifyDomInfo = false;
33 static cl::opt<bool, true>
34     VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo), cl::Hidden,
35                    cl::desc("Verify dominator info (time consuming)"));
36 
37 #ifdef EXPENSIVE_CHECKS
38 static constexpr bool ExpensiveChecksEnabled = true;
39 #else
40 static constexpr bool ExpensiveChecksEnabled = false;
41 #endif
42 
43 bool BasicBlockEdge::isSingleEdge() const {
44   const Instruction *TI = Start->getTerminator();
45   unsigned NumEdgesToEnd = 0;
46   for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
47     if (TI->getSuccessor(i) == End)
48       ++NumEdgesToEnd;
49     if (NumEdgesToEnd >= 2)
50       return false;
51   }
52   assert(NumEdgesToEnd == 1);
53   return true;
54 }
55 
56 //===----------------------------------------------------------------------===//
57 //  DominatorTree Implementation
58 //===----------------------------------------------------------------------===//
59 //
60 // Provide public access to DominatorTree information.  Implementation details
61 // can be found in Dominators.h, GenericDomTree.h, and
62 // GenericDomTreeConstruction.h.
63 //
64 //===----------------------------------------------------------------------===//
65 
66 template class llvm::DomTreeNodeBase<BasicBlock>;
67 template class llvm::DominatorTreeBase<BasicBlock, false>; // DomTreeBase
68 template class llvm::DominatorTreeBase<BasicBlock, true>; // PostDomTreeBase
69 
70 template class llvm::cfg::Update<BasicBlock *>;
71 
72 template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBDomTree>(
73     DomTreeBuilder::BBDomTree &DT);
74 template void
75 llvm::DomTreeBuilder::CalculateWithUpdates<DomTreeBuilder::BBDomTree>(
76     DomTreeBuilder::BBDomTree &DT, BBUpdates U);
77 
78 template void llvm::DomTreeBuilder::Calculate<DomTreeBuilder::BBPostDomTree>(
79     DomTreeBuilder::BBPostDomTree &DT);
80 // No CalculateWithUpdates<PostDomTree> instantiation, unless a usecase arises.
81 
82 template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBDomTree>(
83     DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);
84 template void llvm::DomTreeBuilder::InsertEdge<DomTreeBuilder::BBPostDomTree>(
85     DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);
86 
87 template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBDomTree>(
88     DomTreeBuilder::BBDomTree &DT, BasicBlock *From, BasicBlock *To);
89 template void llvm::DomTreeBuilder::DeleteEdge<DomTreeBuilder::BBPostDomTree>(
90     DomTreeBuilder::BBPostDomTree &DT, BasicBlock *From, BasicBlock *To);
91 
92 template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBDomTree>(
93     DomTreeBuilder::BBDomTree &DT, DomTreeBuilder::BBDomTreeGraphDiff &,
94     DomTreeBuilder::BBDomTreeGraphDiff *);
95 template void llvm::DomTreeBuilder::ApplyUpdates<DomTreeBuilder::BBPostDomTree>(
96     DomTreeBuilder::BBPostDomTree &DT, DomTreeBuilder::BBPostDomTreeGraphDiff &,
97     DomTreeBuilder::BBPostDomTreeGraphDiff *);
98 
99 template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBDomTree>(
100     const DomTreeBuilder::BBDomTree &DT,
101     DomTreeBuilder::BBDomTree::VerificationLevel VL);
102 template bool llvm::DomTreeBuilder::Verify<DomTreeBuilder::BBPostDomTree>(
103     const DomTreeBuilder::BBPostDomTree &DT,
104     DomTreeBuilder::BBPostDomTree::VerificationLevel VL);
105 
106 bool DominatorTree::invalidate(Function &F, const PreservedAnalyses &PA,
107                                FunctionAnalysisManager::Invalidator &) {
108   // Check whether the analysis, all analyses on functions, or the function's
109   // CFG have been preserved.
110   auto PAC = PA.getChecker<DominatorTreeAnalysis>();
111   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
112            PAC.preservedSet<CFGAnalyses>());
113 }
114 
115 // dominates - Return true if Def dominates a use in User. This performs
116 // the special checks necessary if Def and User are in the same basic block.
117 // Note that Def doesn't dominate a use in Def itself!
118 bool DominatorTree::dominates(const Value *DefV,
119                               const Instruction *User) const {
120   const Instruction *Def = dyn_cast<Instruction>(DefV);
121   if (!Def) {
122     assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
123            "Should be called with an instruction, argument or constant");
124     return true; // Arguments and constants dominate everything.
125   }
126 
127   const BasicBlock *UseBB = User->getParent();
128   const BasicBlock *DefBB = Def->getParent();
129 
130   // Any unreachable use is dominated, even if Def == User.
131   if (!isReachableFromEntry(UseBB))
132     return true;
133 
134   // Unreachable definitions don't dominate anything.
135   if (!isReachableFromEntry(DefBB))
136     return false;
137 
138   // An instruction doesn't dominate a use in itself.
139   if (Def == User)
140     return false;
141 
142   // The value defined by an invoke dominates an instruction only if it
143   // dominates every instruction in UseBB.
144   // A PHI is dominated only if the instruction dominates every possible use in
145   // the UseBB.
146   if (isa<InvokeInst>(Def) || isa<CallBrInst>(Def) || isa<PHINode>(User))
147     return dominates(Def, UseBB);
148 
149   if (DefBB != UseBB)
150     return dominates(DefBB, UseBB);
151 
152   return Def->comesBefore(User);
153 }
154 
155 // true if Def would dominate a use in any instruction in UseBB.
156 // note that dominates(Def, Def->getParent()) is false.
157 bool DominatorTree::dominates(const Instruction *Def,
158                               const BasicBlock *UseBB) const {
159   const BasicBlock *DefBB = Def->getParent();
160 
161   // Any unreachable use is dominated, even if DefBB == UseBB.
162   if (!isReachableFromEntry(UseBB))
163     return true;
164 
165   // Unreachable definitions don't dominate anything.
166   if (!isReachableFromEntry(DefBB))
167     return false;
168 
169   if (DefBB == UseBB)
170     return false;
171 
172   // Invoke results are only usable in the normal destination, not in the
173   // exceptional destination.
174   if (const auto *II = dyn_cast<InvokeInst>(Def)) {
175     BasicBlock *NormalDest = II->getNormalDest();
176     BasicBlockEdge E(DefBB, NormalDest);
177     return dominates(E, UseBB);
178   }
179 
180   // Callbr results are similarly only usable in the default destination.
181   if (const auto *CBI = dyn_cast<CallBrInst>(Def)) {
182     BasicBlock *NormalDest = CBI->getDefaultDest();
183     BasicBlockEdge E(DefBB, NormalDest);
184     return dominates(E, UseBB);
185   }
186 
187   return dominates(DefBB, UseBB);
188 }
189 
190 bool DominatorTree::dominates(const BasicBlockEdge &BBE,
191                               const BasicBlock *UseBB) const {
192   // If the BB the edge ends in doesn't dominate the use BB, then the
193   // edge also doesn't.
194   const BasicBlock *Start = BBE.getStart();
195   const BasicBlock *End = BBE.getEnd();
196   if (!dominates(End, UseBB))
197     return false;
198 
199   // Simple case: if the end BB has a single predecessor, the fact that it
200   // dominates the use block implies that the edge also does.
201   if (End->getSinglePredecessor())
202     return true;
203 
204   // The normal edge from the invoke is critical. Conceptually, what we would
205   // like to do is split it and check if the new block dominates the use.
206   // With X being the new block, the graph would look like:
207   //
208   //        DefBB
209   //          /\      .  .
210   //         /  \     .  .
211   //        /    \    .  .
212   //       /      \   |  |
213   //      A        X  B  C
214   //      |         \ | /
215   //      .          \|/
216   //      .      NormalDest
217   //      .
218   //
219   // Given the definition of dominance, NormalDest is dominated by X iff X
220   // dominates all of NormalDest's predecessors (X, B, C in the example). X
221   // trivially dominates itself, so we only have to find if it dominates the
222   // other predecessors. Since the only way out of X is via NormalDest, X can
223   // only properly dominate a node if NormalDest dominates that node too.
224   int IsDuplicateEdge = 0;
225   for (const BasicBlock *BB : predecessors(End)) {
226     if (BB == Start) {
227       // If there are multiple edges between Start and End, by definition they
228       // can't dominate anything.
229       if (IsDuplicateEdge++)
230         return false;
231       continue;
232     }
233 
234     if (!dominates(End, BB))
235       return false;
236   }
237   return true;
238 }
239 
240 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
241   Instruction *UserInst = cast<Instruction>(U.getUser());
242   // A PHI in the end of the edge is dominated by it.
243   PHINode *PN = dyn_cast<PHINode>(UserInst);
244   if (PN && PN->getParent() == BBE.getEnd() &&
245       PN->getIncomingBlock(U) == BBE.getStart())
246     return true;
247 
248   // Otherwise use the edge-dominates-block query, which
249   // handles the crazy critical edge cases properly.
250   const BasicBlock *UseBB;
251   if (PN)
252     UseBB = PN->getIncomingBlock(U);
253   else
254     UseBB = UserInst->getParent();
255   return dominates(BBE, UseBB);
256 }
257 
258 bool DominatorTree::dominates(const Value *DefV, const Use &U) const {
259   const Instruction *Def = dyn_cast<Instruction>(DefV);
260   if (!Def) {
261     assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
262            "Should be called with an instruction, argument or constant");
263     return true; // Arguments and constants dominate everything.
264   }
265 
266   Instruction *UserInst = cast<Instruction>(U.getUser());
267   const BasicBlock *DefBB = Def->getParent();
268 
269   // Determine the block in which the use happens. PHI nodes use
270   // their operands on edges; simulate this by thinking of the use
271   // happening at the end of the predecessor block.
272   const BasicBlock *UseBB;
273   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
274     UseBB = PN->getIncomingBlock(U);
275   else
276     UseBB = UserInst->getParent();
277 
278   // Any unreachable use is dominated, even if Def == User.
279   if (!isReachableFromEntry(UseBB))
280     return true;
281 
282   // Unreachable definitions don't dominate anything.
283   if (!isReachableFromEntry(DefBB))
284     return false;
285 
286   // Invoke instructions define their return values on the edges to their normal
287   // successors, so we have to handle them specially.
288   // Among other things, this means they don't dominate anything in
289   // their own block, except possibly a phi, so we don't need to
290   // walk the block in any case.
291   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
292     BasicBlock *NormalDest = II->getNormalDest();
293     BasicBlockEdge E(DefBB, NormalDest);
294     return dominates(E, U);
295   }
296 
297   // Callbr results are similarly only usable in the default destination.
298   if (const auto *CBI = dyn_cast<CallBrInst>(Def)) {
299     BasicBlock *NormalDest = CBI->getDefaultDest();
300     BasicBlockEdge E(DefBB, NormalDest);
301     return dominates(E, U);
302   }
303 
304   // If the def and use are in different blocks, do a simple CFG dominator
305   // tree query.
306   if (DefBB != UseBB)
307     return dominates(DefBB, UseBB);
308 
309   // Ok, def and use are in the same block. If the def is an invoke, it
310   // doesn't dominate anything in the block. If it's a PHI, it dominates
311   // everything in the block.
312   if (isa<PHINode>(UserInst))
313     return true;
314 
315   return Def->comesBefore(UserInst);
316 }
317 
318 bool DominatorTree::isReachableFromEntry(const Use &U) const {
319   Instruction *I = dyn_cast<Instruction>(U.getUser());
320 
321   // ConstantExprs aren't really reachable from the entry block, but they
322   // don't need to be treated like unreachable code either.
323   if (!I) return true;
324 
325   // PHI nodes use their operands on their incoming edges.
326   if (PHINode *PN = dyn_cast<PHINode>(I))
327     return isReachableFromEntry(PN->getIncomingBlock(U));
328 
329   // Everything else uses their operands in their own block.
330   return isReachableFromEntry(I->getParent());
331 }
332 
333 // Edge BBE1 dominates edge BBE2 if they match or BBE1 dominates start of BBE2.
334 bool DominatorTree::dominates(const BasicBlockEdge &BBE1,
335                               const BasicBlockEdge &BBE2) const {
336   if (BBE1.getStart() == BBE2.getStart() && BBE1.getEnd() == BBE2.getEnd())
337     return true;
338   return dominates(BBE1, BBE2.getStart());
339 }
340 
341 //===----------------------------------------------------------------------===//
342 //  DominatorTreeAnalysis and related pass implementations
343 //===----------------------------------------------------------------------===//
344 //
345 // This implements the DominatorTreeAnalysis which is used with the new pass
346 // manager. It also implements some methods from utility passes.
347 //
348 //===----------------------------------------------------------------------===//
349 
350 DominatorTree DominatorTreeAnalysis::run(Function &F,
351                                          FunctionAnalysisManager &) {
352   DominatorTree DT;
353   DT.recalculate(F);
354   return DT;
355 }
356 
357 AnalysisKey DominatorTreeAnalysis::Key;
358 
359 DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
360 
361 PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
362                                                 FunctionAnalysisManager &AM) {
363   OS << "DominatorTree for function: " << F.getName() << "\n";
364   AM.getResult<DominatorTreeAnalysis>(F).print(OS);
365 
366   return PreservedAnalyses::all();
367 }
368 
369 PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
370                                                  FunctionAnalysisManager &AM) {
371   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
372   assert(DT.verify());
373   (void)DT;
374   return PreservedAnalyses::all();
375 }
376 
377 //===----------------------------------------------------------------------===//
378 //  DominatorTreeWrapperPass Implementation
379 //===----------------------------------------------------------------------===//
380 //
381 // The implementation details of the wrapper pass that holds a DominatorTree
382 // suitable for use with the legacy pass manager.
383 //
384 //===----------------------------------------------------------------------===//
385 
386 char DominatorTreeWrapperPass::ID = 0;
387 
388 DominatorTreeWrapperPass::DominatorTreeWrapperPass() : FunctionPass(ID) {
389   initializeDominatorTreeWrapperPassPass(*PassRegistry::getPassRegistry());
390 }
391 
392 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
393                 "Dominator Tree Construction", true, true)
394 
395 bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
396   DT.recalculate(F);
397   return false;
398 }
399 
400 void DominatorTreeWrapperPass::verifyAnalysis() const {
401   if (VerifyDomInfo)
402     assert(DT.verify(DominatorTree::VerificationLevel::Full));
403   else if (ExpensiveChecksEnabled)
404     assert(DT.verify(DominatorTree::VerificationLevel::Basic));
405 }
406 
407 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
408   DT.print(OS);
409 }
410