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