Dominators.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. //===- Dominators.cpp - Dominator Calculation -----------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements simple dominator construction algorithms for finding
  11. // forward dominators. Postdominators are available in libanalysis, but are not
  12. // included in libvmcore, because it's not needed. Forward dominators are
  13. // needed to support the Verifier pass.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/IR/Dominators.h"
  17. #include "llvm/ADT/DepthFirstIterator.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/IR/CFG.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/PassManager.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Compiler.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/GenericDomTreeConstruction.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <algorithm>
  29. using namespace llvm;
  30. // Always verify dominfo if expensive checking is enabled.
  31. #ifdef XDEBUG
  32. static bool VerifyDomInfo = true;
  33. #else
  34. static bool VerifyDomInfo = false;
  35. #endif
  36. static cl::opt<bool,true>
  37. VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
  38. cl::desc("Verify dominator info (time consuming)"));
  39. bool BasicBlockEdge::isSingleEdge() const {
  40. const TerminatorInst *TI = Start->getTerminator();
  41. unsigned NumEdgesToEnd = 0;
  42. for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
  43. if (TI->getSuccessor(i) == End)
  44. ++NumEdgesToEnd;
  45. if (NumEdgesToEnd >= 2)
  46. return false;
  47. }
  48. assert(NumEdgesToEnd == 1);
  49. return true;
  50. }
  51. //===----------------------------------------------------------------------===//
  52. // DominatorTree Implementation
  53. //===----------------------------------------------------------------------===//
  54. //
  55. // Provide public access to DominatorTree information. Implementation details
  56. // can be found in Dominators.h, GenericDomTree.h, and
  57. // GenericDomTreeConstruction.h.
  58. //
  59. //===----------------------------------------------------------------------===//
  60. template class llvm::DomTreeNodeBase<BasicBlock>;
  61. template class llvm::DominatorTreeBase<BasicBlock>;
  62. template void llvm::Calculate<Function, BasicBlock *>(
  63. DominatorTreeBase<GraphTraits<BasicBlock *>::NodeType> &DT, Function &F);
  64. template void llvm::Calculate<Function, Inverse<BasicBlock *>>(
  65. DominatorTreeBase<GraphTraits<Inverse<BasicBlock *>>::NodeType> &DT,
  66. Function &F);
  67. // dominates - Return true if Def dominates a use in User. This performs
  68. // the special checks necessary if Def and User are in the same basic block.
  69. // Note that Def doesn't dominate a use in Def itself!
  70. bool DominatorTree::dominates(const Instruction *Def,
  71. const Instruction *User) const {
  72. const BasicBlock *UseBB = User->getParent();
  73. const BasicBlock *DefBB = Def->getParent();
  74. // Any unreachable use is dominated, even if Def == User.
  75. if (!isReachableFromEntry(UseBB))
  76. return true;
  77. // Unreachable definitions don't dominate anything.
  78. if (!isReachableFromEntry(DefBB))
  79. return false;
  80. // An instruction doesn't dominate a use in itself.
  81. if (Def == User)
  82. return false;
  83. // The value defined by an invoke dominates an instruction only if
  84. // it dominates every instruction in UseBB.
  85. // A PHI is dominated only if the instruction dominates every possible use
  86. // in the UseBB.
  87. if (isa<InvokeInst>(Def) || isa<PHINode>(User))
  88. return dominates(Def, UseBB);
  89. if (DefBB != UseBB)
  90. return dominates(DefBB, UseBB);
  91. // Loop through the basic block until we find Def or User.
  92. BasicBlock::const_iterator I = DefBB->begin();
  93. for (; &*I != Def && &*I != User; ++I)
  94. /*empty*/;
  95. return &*I == Def;
  96. }
  97. // true if Def would dominate a use in any instruction in UseBB.
  98. // note that dominates(Def, Def->getParent()) is false.
  99. bool DominatorTree::dominates(const Instruction *Def,
  100. const BasicBlock *UseBB) const {
  101. const BasicBlock *DefBB = Def->getParent();
  102. // Any unreachable use is dominated, even if DefBB == UseBB.
  103. if (!isReachableFromEntry(UseBB))
  104. return true;
  105. // Unreachable definitions don't dominate anything.
  106. if (!isReachableFromEntry(DefBB))
  107. return false;
  108. if (DefBB == UseBB)
  109. return false;
  110. const InvokeInst *II = dyn_cast<InvokeInst>(Def);
  111. if (!II)
  112. return dominates(DefBB, UseBB);
  113. // Invoke results are only usable in the normal destination, not in the
  114. // exceptional destination.
  115. BasicBlock *NormalDest = II->getNormalDest();
  116. BasicBlockEdge E(DefBB, NormalDest);
  117. return dominates(E, UseBB);
  118. }
  119. bool DominatorTree::dominates(const BasicBlockEdge &BBE,
  120. const BasicBlock *UseBB) const {
  121. // Assert that we have a single edge. We could handle them by simply
  122. // returning false, but since isSingleEdge is linear on the number of
  123. // edges, the callers can normally handle them more efficiently.
  124. assert(BBE.isSingleEdge());
  125. // If the BB the edge ends in doesn't dominate the use BB, then the
  126. // edge also doesn't.
  127. const BasicBlock *Start = BBE.getStart();
  128. const BasicBlock *End = BBE.getEnd();
  129. if (!dominates(End, UseBB))
  130. return false;
  131. // Simple case: if the end BB has a single predecessor, the fact that it
  132. // dominates the use block implies that the edge also does.
  133. if (End->getSinglePredecessor())
  134. return true;
  135. // The normal edge from the invoke is critical. Conceptually, what we would
  136. // like to do is split it and check if the new block dominates the use.
  137. // With X being the new block, the graph would look like:
  138. //
  139. // DefBB
  140. // /\ . .
  141. // / \ . .
  142. // / \ . .
  143. // / \ | |
  144. // A X B C
  145. // | \ | /
  146. // . \|/
  147. // . NormalDest
  148. // .
  149. //
  150. // Given the definition of dominance, NormalDest is dominated by X iff X
  151. // dominates all of NormalDest's predecessors (X, B, C in the example). X
  152. // trivially dominates itself, so we only have to find if it dominates the
  153. // other predecessors. Since the only way out of X is via NormalDest, X can
  154. // only properly dominate a node if NormalDest dominates that node too.
  155. for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
  156. PI != E; ++PI) {
  157. const BasicBlock *BB = *PI;
  158. if (BB == Start)
  159. continue;
  160. if (!dominates(End, BB))
  161. return false;
  162. }
  163. return true;
  164. }
  165. bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
  166. // Assert that we have a single edge. We could handle them by simply
  167. // returning false, but since isSingleEdge is linear on the number of
  168. // edges, the callers can normally handle them more efficiently.
  169. assert(BBE.isSingleEdge());
  170. Instruction *UserInst = cast<Instruction>(U.getUser());
  171. // A PHI in the end of the edge is dominated by it.
  172. PHINode *PN = dyn_cast<PHINode>(UserInst);
  173. if (PN && PN->getParent() == BBE.getEnd() &&
  174. PN->getIncomingBlock(U) == BBE.getStart())
  175. return true;
  176. // Otherwise use the edge-dominates-block query, which
  177. // handles the crazy critical edge cases properly.
  178. const BasicBlock *UseBB;
  179. if (PN)
  180. UseBB = PN->getIncomingBlock(U);
  181. else
  182. UseBB = UserInst->getParent();
  183. return dominates(BBE, UseBB);
  184. }
  185. bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
  186. Instruction *UserInst = cast<Instruction>(U.getUser());
  187. const BasicBlock *DefBB = Def->getParent();
  188. // Determine the block in which the use happens. PHI nodes use
  189. // their operands on edges; simulate this by thinking of the use
  190. // happening at the end of the predecessor block.
  191. const BasicBlock *UseBB;
  192. if (PHINode *PN = dyn_cast<PHINode>(UserInst))
  193. UseBB = PN->getIncomingBlock(U);
  194. else
  195. UseBB = UserInst->getParent();
  196. // Any unreachable use is dominated, even if Def == User.
  197. if (!isReachableFromEntry(UseBB))
  198. return true;
  199. // Unreachable definitions don't dominate anything.
  200. if (!isReachableFromEntry(DefBB))
  201. return false;
  202. // Invoke instructions define their return values on the edges
  203. // to their normal successors, so we have to handle them specially.
  204. // Among other things, this means they don't dominate anything in
  205. // their own block, except possibly a phi, so we don't need to
  206. // walk the block in any case.
  207. if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
  208. BasicBlock *NormalDest = II->getNormalDest();
  209. BasicBlockEdge E(DefBB, NormalDest);
  210. return dominates(E, U);
  211. }
  212. // If the def and use are in different blocks, do a simple CFG dominator
  213. // tree query.
  214. if (DefBB != UseBB)
  215. return dominates(DefBB, UseBB);
  216. // Ok, def and use are in the same block. If the def is an invoke, it
  217. // doesn't dominate anything in the block. If it's a PHI, it dominates
  218. // everything in the block.
  219. if (isa<PHINode>(UserInst))
  220. return true;
  221. // Otherwise, just loop through the basic block until we find Def or User.
  222. BasicBlock::const_iterator I = DefBB->begin();
  223. for (; &*I != Def && &*I != UserInst; ++I)
  224. /*empty*/;
  225. return &*I != UserInst;
  226. }
  227. bool DominatorTree::isReachableFromEntry(const Use &U) const {
  228. Instruction *I = dyn_cast<Instruction>(U.getUser());
  229. // ConstantExprs aren't really reachable from the entry block, but they
  230. // don't need to be treated like unreachable code either.
  231. if (!I) return true;
  232. // PHI nodes use their operands on their incoming edges.
  233. if (PHINode *PN = dyn_cast<PHINode>(I))
  234. return isReachableFromEntry(PN->getIncomingBlock(U));
  235. // Everything else uses their operands in their own block.
  236. return isReachableFromEntry(I->getParent());
  237. }
  238. void DominatorTree::verifyDomTree() const {
  239. Function &F = *getRoot()->getParent();
  240. DominatorTree OtherDT;
  241. OtherDT.recalculate(F);
  242. if (compare(OtherDT)) {
  243. errs() << "DominatorTree is not up to date!\nComputed:\n";
  244. print(errs());
  245. errs() << "\nActual:\n";
  246. OtherDT.print(errs());
  247. abort();
  248. }
  249. }
  250. //===----------------------------------------------------------------------===//
  251. // DominatorTreeAnalysis and related pass implementations
  252. //===----------------------------------------------------------------------===//
  253. //
  254. // This implements the DominatorTreeAnalysis which is used with the new pass
  255. // manager. It also implements some methods from utility passes.
  256. //
  257. //===----------------------------------------------------------------------===//
  258. DominatorTree DominatorTreeAnalysis::run(Function &F) {
  259. DominatorTree DT;
  260. DT.recalculate(F);
  261. return DT;
  262. }
  263. char DominatorTreeAnalysis::PassID;
  264. DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
  265. PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
  266. FunctionAnalysisManager *AM) {
  267. OS << "DominatorTree for function: " << F.getName() << "\n";
  268. AM->getResult<DominatorTreeAnalysis>(F).print(OS);
  269. return PreservedAnalyses::all();
  270. }
  271. PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
  272. FunctionAnalysisManager *AM) {
  273. AM->getResult<DominatorTreeAnalysis>(F).verifyDomTree();
  274. return PreservedAnalyses::all();
  275. }
  276. //===----------------------------------------------------------------------===//
  277. // DominatorTreeWrapperPass Implementation
  278. //===----------------------------------------------------------------------===//
  279. //
  280. // The implementation details of the wrapper pass that holds a DominatorTree
  281. // suitable for use with the legacy pass manager.
  282. //
  283. //===----------------------------------------------------------------------===//
  284. char DominatorTreeWrapperPass::ID = 0;
  285. INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
  286. "Dominator Tree Construction", true, true)
  287. bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
  288. DT.recalculate(F);
  289. return false;
  290. }
  291. void DominatorTreeWrapperPass::verifyAnalysis() const {
  292. if (VerifyDomInfo)
  293. DT.verifyDomTree();
  294. }
  295. void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
  296. DT.print(OS);
  297. }