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