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