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_pred_iterator PI = pred_begin(End), E = pred_end(End);
226        PI != E; ++PI) {
227     const BasicBlock *BB = *PI;
228     if (BB == Start) {
229       // If there are multiple edges between Start and End, by definition they
230       // can't dominate anything.
231       if (IsDuplicateEdge++)
232         return false;
233       continue;
234     }
235 
236     if (!dominates(End, BB))
237       return false;
238   }
239   return true;
240 }
241 
242 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
243   Instruction *UserInst = cast<Instruction>(U.getUser());
244   // A PHI in the end of the edge is dominated by it.
245   PHINode *PN = dyn_cast<PHINode>(UserInst);
246   if (PN && PN->getParent() == BBE.getEnd() &&
247       PN->getIncomingBlock(U) == BBE.getStart())
248     return true;
249 
250   // Otherwise use the edge-dominates-block query, which
251   // handles the crazy critical edge cases properly.
252   const BasicBlock *UseBB;
253   if (PN)
254     UseBB = PN->getIncomingBlock(U);
255   else
256     UseBB = UserInst->getParent();
257   return dominates(BBE, UseBB);
258 }
259 
260 bool DominatorTree::dominates(const Value *DefV, const Use &U) const {
261   const Instruction *Def = dyn_cast<Instruction>(DefV);
262   if (!Def) {
263     assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
264            "Should be called with an instruction, argument or constant");
265     return true; // Arguments and constants dominate everything.
266   }
267 
268   Instruction *UserInst = cast<Instruction>(U.getUser());
269   const BasicBlock *DefBB = Def->getParent();
270 
271   // Determine the block in which the use happens. PHI nodes use
272   // their operands on edges; simulate this by thinking of the use
273   // happening at the end of the predecessor block.
274   const BasicBlock *UseBB;
275   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
276     UseBB = PN->getIncomingBlock(U);
277   else
278     UseBB = UserInst->getParent();
279 
280   // Any unreachable use is dominated, even if Def == User.
281   if (!isReachableFromEntry(UseBB))
282     return true;
283 
284   // Unreachable definitions don't dominate anything.
285   if (!isReachableFromEntry(DefBB))
286     return false;
287 
288   // Invoke instructions define their return values on the edges to their normal
289   // successors, so we have to handle them specially.
290   // Among other things, this means they don't dominate anything in
291   // their own block, except possibly a phi, so we don't need to
292   // walk the block in any case.
293   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
294     BasicBlock *NormalDest = II->getNormalDest();
295     BasicBlockEdge E(DefBB, NormalDest);
296     return dominates(E, U);
297   }
298 
299   // Callbr results are similarly only usable in the default destination.
300   if (const auto *CBI = dyn_cast<CallBrInst>(Def)) {
301     BasicBlock *NormalDest = CBI->getDefaultDest();
302     BasicBlockEdge E(DefBB, NormalDest);
303     return dominates(E, U);
304   }
305 
306   // If the def and use are in different blocks, do a simple CFG dominator
307   // tree query.
308   if (DefBB != UseBB)
309     return dominates(DefBB, UseBB);
310 
311   // Ok, def and use are in the same block. If the def is an invoke, it
312   // doesn't dominate anything in the block. If it's a PHI, it dominates
313   // everything in the block.
314   if (isa<PHINode>(UserInst))
315     return true;
316 
317   return Def->comesBefore(UserInst);
318 }
319 
320 bool DominatorTree::isReachableFromEntry(const Use &U) const {
321   Instruction *I = dyn_cast<Instruction>(U.getUser());
322 
323   // ConstantExprs aren't really reachable from the entry block, but they
324   // don't need to be treated like unreachable code either.
325   if (!I) return true;
326 
327   // PHI nodes use their operands on their incoming edges.
328   if (PHINode *PN = dyn_cast<PHINode>(I))
329     return isReachableFromEntry(PN->getIncomingBlock(U));
330 
331   // Everything else uses their operands in their own block.
332   return isReachableFromEntry(I->getParent());
333 }
334 
335 // Edge BBE1 dominates edge BBE2 if they match or BBE1 dominates start of BBE2.
336 bool DominatorTree::dominates(const BasicBlockEdge &BBE1,
337                               const BasicBlockEdge &BBE2) const {
338   if (BBE1.getStart() == BBE2.getStart() && BBE1.getEnd() == BBE2.getEnd())
339     return true;
340   return dominates(BBE1, BBE2.getStart());
341 }
342 
343 //===----------------------------------------------------------------------===//
344 //  DominatorTreeAnalysis and related pass implementations
345 //===----------------------------------------------------------------------===//
346 //
347 // This implements the DominatorTreeAnalysis which is used with the new pass
348 // manager. It also implements some methods from utility passes.
349 //
350 //===----------------------------------------------------------------------===//
351 
352 DominatorTree DominatorTreeAnalysis::run(Function &F,
353                                          FunctionAnalysisManager &) {
354   DominatorTree DT;
355   DT.recalculate(F);
356   return DT;
357 }
358 
359 AnalysisKey DominatorTreeAnalysis::Key;
360 
361 DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
362 
363 PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
364                                                 FunctionAnalysisManager &AM) {
365   OS << "DominatorTree for function: " << F.getName() << "\n";
366   AM.getResult<DominatorTreeAnalysis>(F).print(OS);
367 
368   return PreservedAnalyses::all();
369 }
370 
371 PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
372                                                  FunctionAnalysisManager &AM) {
373   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
374   assert(DT.verify());
375   (void)DT;
376   return PreservedAnalyses::all();
377 }
378 
379 //===----------------------------------------------------------------------===//
380 //  DominatorTreeWrapperPass Implementation
381 //===----------------------------------------------------------------------===//
382 //
383 // The implementation details of the wrapper pass that holds a DominatorTree
384 // suitable for use with the legacy pass manager.
385 //
386 //===----------------------------------------------------------------------===//
387 
388 char DominatorTreeWrapperPass::ID = 0;
389 
390 DominatorTreeWrapperPass::DominatorTreeWrapperPass() : FunctionPass(ID) {
391   initializeDominatorTreeWrapperPassPass(*PassRegistry::getPassRegistry());
392 }
393 
394 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
395                 "Dominator Tree Construction", true, true)
396 
397 bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
398   DT.recalculate(F);
399   return false;
400 }
401 
402 void DominatorTreeWrapperPass::verifyAnalysis() const {
403   if (VerifyDomInfo)
404     assert(DT.verify(DominatorTree::VerificationLevel::Full));
405   else if (ExpensiveChecksEnabled)
406     assert(DT.verify(DominatorTree::VerificationLevel::Basic));
407 }
408 
409 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
410   DT.print(OS);
411 }
412