Dominators.cpp 16 KB

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