Dominators.cpp 15 KB

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