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 bool DominatorTree::dominates(const BasicBlock *BB, const Use &U) const {
116   Instruction *UserInst = cast<Instruction>(U.getUser());
117   if (auto *PN = dyn_cast<PHINode>(UserInst))
118     // A phi use using a value from a block is dominated by the end of that
119     // block.  Note that the phi's parent block may not be.
120     return dominates(BB, PN->getIncomingBlock(U));
121   else
122     return properlyDominates(BB, UserInst->getParent());
123 }
124 
125 // dominates - Return true if Def dominates a use in User. This performs
126 // the special checks necessary if Def and User are in the same basic block.
127 // Note that Def doesn't dominate a use in Def itself!
128 bool DominatorTree::dominates(const Value *DefV,
129                               const Instruction *User) const {
130   const Instruction *Def = dyn_cast<Instruction>(DefV);
131   if (!Def) {
132     assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
133            "Should be called with an instruction, argument or constant");
134     return true; // Arguments and constants dominate everything.
135   }
136 
137   const BasicBlock *UseBB = User->getParent();
138   const BasicBlock *DefBB = Def->getParent();
139 
140   // Any unreachable use is dominated, even if Def == User.
141   if (!isReachableFromEntry(UseBB))
142     return true;
143 
144   // Unreachable definitions don't dominate anything.
145   if (!isReachableFromEntry(DefBB))
146     return false;
147 
148   // An instruction doesn't dominate a use in itself.
149   if (Def == User)
150     return false;
151 
152   // The value defined by an invoke dominates an instruction only if it
153   // dominates every instruction in UseBB.
154   // A PHI is dominated only if the instruction dominates every possible use in
155   // the UseBB.
156   if (isa<InvokeInst>(Def) || isa<CallBrInst>(Def) || isa<PHINode>(User))
157     return dominates(Def, UseBB);
158 
159   if (DefBB != UseBB)
160     return dominates(DefBB, UseBB);
161 
162   return Def->comesBefore(User);
163 }
164 
165 // true if Def would dominate a use in any instruction in UseBB.
166 // note that dominates(Def, Def->getParent()) is false.
167 bool DominatorTree::dominates(const Instruction *Def,
168                               const BasicBlock *UseBB) const {
169   const BasicBlock *DefBB = Def->getParent();
170 
171   // Any unreachable use is dominated, even if DefBB == UseBB.
172   if (!isReachableFromEntry(UseBB))
173     return true;
174 
175   // Unreachable definitions don't dominate anything.
176   if (!isReachableFromEntry(DefBB))
177     return false;
178 
179   if (DefBB == UseBB)
180     return false;
181 
182   // Invoke results are only usable in the normal destination, not in the
183   // exceptional destination.
184   if (const auto *II = dyn_cast<InvokeInst>(Def)) {
185     BasicBlock *NormalDest = II->getNormalDest();
186     BasicBlockEdge E(DefBB, NormalDest);
187     return dominates(E, UseBB);
188   }
189 
190   // Callbr results are similarly only usable in the default destination.
191   if (const auto *CBI = dyn_cast<CallBrInst>(Def)) {
192     BasicBlock *NormalDest = CBI->getDefaultDest();
193     BasicBlockEdge E(DefBB, NormalDest);
194     return dominates(E, UseBB);
195   }
196 
197   return dominates(DefBB, UseBB);
198 }
199 
200 bool DominatorTree::dominates(const BasicBlockEdge &BBE,
201                               const BasicBlock *UseBB) const {
202   // If the BB the edge ends in doesn't dominate the use BB, then the
203   // edge also doesn't.
204   const BasicBlock *Start = BBE.getStart();
205   const BasicBlock *End = BBE.getEnd();
206   if (!dominates(End, UseBB))
207     return false;
208 
209   // Simple case: if the end BB has a single predecessor, the fact that it
210   // dominates the use block implies that the edge also does.
211   if (End->getSinglePredecessor())
212     return true;
213 
214   // The normal edge from the invoke is critical. Conceptually, what we would
215   // like to do is split it and check if the new block dominates the use.
216   // With X being the new block, the graph would look like:
217   //
218   //        DefBB
219   //          /\      .  .
220   //         /  \     .  .
221   //        /    \    .  .
222   //       /      \   |  |
223   //      A        X  B  C
224   //      |         \ | /
225   //      .          \|/
226   //      .      NormalDest
227   //      .
228   //
229   // Given the definition of dominance, NormalDest is dominated by X iff X
230   // dominates all of NormalDest's predecessors (X, B, C in the example). X
231   // trivially dominates itself, so we only have to find if it dominates the
232   // other predecessors. Since the only way out of X is via NormalDest, X can
233   // only properly dominate a node if NormalDest dominates that node too.
234   int IsDuplicateEdge = 0;
235   for (const BasicBlock *BB : predecessors(End)) {
236     if (BB == Start) {
237       // If there are multiple edges between Start and End, by definition they
238       // can't dominate anything.
239       if (IsDuplicateEdge++)
240         return false;
241       continue;
242     }
243 
244     if (!dominates(End, BB))
245       return false;
246   }
247   return true;
248 }
249 
250 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
251   Instruction *UserInst = cast<Instruction>(U.getUser());
252   // A PHI in the end of the edge is dominated by it.
253   PHINode *PN = dyn_cast<PHINode>(UserInst);
254   if (PN && PN->getParent() == BBE.getEnd() &&
255       PN->getIncomingBlock(U) == BBE.getStart())
256     return true;
257 
258   // Otherwise use the edge-dominates-block query, which
259   // handles the crazy critical edge cases properly.
260   const BasicBlock *UseBB;
261   if (PN)
262     UseBB = PN->getIncomingBlock(U);
263   else
264     UseBB = UserInst->getParent();
265   return dominates(BBE, UseBB);
266 }
267 
268 bool DominatorTree::dominates(const Value *DefV, const Use &U) const {
269   const Instruction *Def = dyn_cast<Instruction>(DefV);
270   if (!Def) {
271     assert((isa<Argument>(DefV) || isa<Constant>(DefV)) &&
272            "Should be called with an instruction, argument or constant");
273     return true; // Arguments and constants dominate everything.
274   }
275 
276   Instruction *UserInst = cast<Instruction>(U.getUser());
277   const BasicBlock *DefBB = Def->getParent();
278 
279   // Determine the block in which the use happens. PHI nodes use
280   // their operands on edges; simulate this by thinking of the use
281   // happening at the end of the predecessor block.
282   const BasicBlock *UseBB;
283   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
284     UseBB = PN->getIncomingBlock(U);
285   else
286     UseBB = UserInst->getParent();
287 
288   // Any unreachable use is dominated, even if Def == User.
289   if (!isReachableFromEntry(UseBB))
290     return true;
291 
292   // Unreachable definitions don't dominate anything.
293   if (!isReachableFromEntry(DefBB))
294     return false;
295 
296   // Invoke instructions define their return values on the edges to their normal
297   // successors, so we have to handle them specially.
298   // Among other things, this means they don't dominate anything in
299   // their own block, except possibly a phi, so we don't need to
300   // walk the block in any case.
301   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
302     BasicBlock *NormalDest = II->getNormalDest();
303     BasicBlockEdge E(DefBB, NormalDest);
304     return dominates(E, U);
305   }
306 
307   // Callbr results are similarly only usable in the default destination.
308   if (const auto *CBI = dyn_cast<CallBrInst>(Def)) {
309     BasicBlock *NormalDest = CBI->getDefaultDest();
310     BasicBlockEdge E(DefBB, NormalDest);
311     return dominates(E, U);
312   }
313 
314   // If the def and use are in different blocks, do a simple CFG dominator
315   // tree query.
316   if (DefBB != UseBB)
317     return dominates(DefBB, UseBB);
318 
319   // Ok, def and use are in the same block. If the def is an invoke, it
320   // doesn't dominate anything in the block. If it's a PHI, it dominates
321   // everything in the block.
322   if (isa<PHINode>(UserInst))
323     return true;
324 
325   return Def->comesBefore(UserInst);
326 }
327 
328 bool DominatorTree::isReachableFromEntry(const Use &U) const {
329   Instruction *I = dyn_cast<Instruction>(U.getUser());
330 
331   // ConstantExprs aren't really reachable from the entry block, but they
332   // don't need to be treated like unreachable code either.
333   if (!I) return true;
334 
335   // PHI nodes use their operands on their incoming edges.
336   if (PHINode *PN = dyn_cast<PHINode>(I))
337     return isReachableFromEntry(PN->getIncomingBlock(U));
338 
339   // Everything else uses their operands in their own block.
340   return isReachableFromEntry(I->getParent());
341 }
342 
343 // Edge BBE1 dominates edge BBE2 if they match or BBE1 dominates start of BBE2.
344 bool DominatorTree::dominates(const BasicBlockEdge &BBE1,
345                               const BasicBlockEdge &BBE2) const {
346   if (BBE1.getStart() == BBE2.getStart() && BBE1.getEnd() == BBE2.getEnd())
347     return true;
348   return dominates(BBE1, BBE2.getStart());
349 }
350 
351 //===----------------------------------------------------------------------===//
352 //  DominatorTreeAnalysis and related pass implementations
353 //===----------------------------------------------------------------------===//
354 //
355 // This implements the DominatorTreeAnalysis which is used with the new pass
356 // manager. It also implements some methods from utility passes.
357 //
358 //===----------------------------------------------------------------------===//
359 
360 DominatorTree DominatorTreeAnalysis::run(Function &F,
361                                          FunctionAnalysisManager &) {
362   DominatorTree DT;
363   DT.recalculate(F);
364   return DT;
365 }
366 
367 AnalysisKey DominatorTreeAnalysis::Key;
368 
369 DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
370 
371 PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
372                                                 FunctionAnalysisManager &AM) {
373   OS << "DominatorTree for function: " << F.getName() << "\n";
374   AM.getResult<DominatorTreeAnalysis>(F).print(OS);
375 
376   return PreservedAnalyses::all();
377 }
378 
379 PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
380                                                  FunctionAnalysisManager &AM) {
381   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
382   assert(DT.verify());
383   (void)DT;
384   return PreservedAnalyses::all();
385 }
386 
387 //===----------------------------------------------------------------------===//
388 //  DominatorTreeWrapperPass Implementation
389 //===----------------------------------------------------------------------===//
390 //
391 // The implementation details of the wrapper pass that holds a DominatorTree
392 // suitable for use with the legacy pass manager.
393 //
394 //===----------------------------------------------------------------------===//
395 
396 char DominatorTreeWrapperPass::ID = 0;
397 
398 DominatorTreeWrapperPass::DominatorTreeWrapperPass() : FunctionPass(ID) {
399   initializeDominatorTreeWrapperPassPass(*PassRegistry::getPassRegistry());
400 }
401 
402 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
403                 "Dominator Tree Construction", true, true)
404 
405 bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
406   DT.recalculate(F);
407   return false;
408 }
409 
410 void DominatorTreeWrapperPass::verifyAnalysis() const {
411   if (VerifyDomInfo)
412     assert(DT.verify(DominatorTree::VerificationLevel::Full));
413   else if (ExpensiveChecksEnabled)
414     assert(DT.verify(DominatorTree::VerificationLevel::Basic));
415 }
416 
417 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
418   DT.print(OS);
419 }
420