Dominators.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. //===- Dominators.h - Dominator Info Calculation ----------------*- C++ -*-===//
  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 defines the DominatorTree class, which provides fast and efficient
  10. // dominance queries.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_IR_DOMINATORS_H
  14. #define LLVM_IR_DOMINATORS_H
  15. #include "llvm/ADT/DenseMapInfo.h"
  16. #include "llvm/ADT/DepthFirstIterator.h"
  17. #include "llvm/ADT/GraphTraits.h"
  18. #include "llvm/ADT/Hashing.h"
  19. #include "llvm/IR/BasicBlock.h"
  20. #include "llvm/IR/CFG.h"
  21. #include "llvm/IR/PassManager.h"
  22. #include "llvm/Pass.h"
  23. #include "llvm/Support/GenericDomTree.h"
  24. #include <utility>
  25. namespace llvm {
  26. class Function;
  27. class Instruction;
  28. class Module;
  29. class raw_ostream;
  30. extern template class DomTreeNodeBase<BasicBlock>;
  31. extern template class DominatorTreeBase<BasicBlock, false>; // DomTree
  32. extern template class DominatorTreeBase<BasicBlock, true>; // PostDomTree
  33. extern template class cfg::Update<BasicBlock *>;
  34. namespace DomTreeBuilder {
  35. using BBDomTree = DomTreeBase<BasicBlock>;
  36. using BBPostDomTree = PostDomTreeBase<BasicBlock>;
  37. using BBUpdates = ArrayRef<llvm::cfg::Update<BasicBlock *>>;
  38. using BBDomTreeGraphDiff = GraphDiff<BasicBlock *, false>;
  39. using BBPostDomTreeGraphDiff = GraphDiff<BasicBlock *, true>;
  40. extern template void Calculate<BBDomTree>(BBDomTree &DT);
  41. extern template void CalculateWithUpdates<BBDomTree>(BBDomTree &DT,
  42. BBUpdates U);
  43. extern template void Calculate<BBPostDomTree>(BBPostDomTree &DT);
  44. extern template void InsertEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From,
  45. BasicBlock *To);
  46. extern template void InsertEdge<BBPostDomTree>(BBPostDomTree &DT,
  47. BasicBlock *From,
  48. BasicBlock *To);
  49. extern template void DeleteEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From,
  50. BasicBlock *To);
  51. extern template void DeleteEdge<BBPostDomTree>(BBPostDomTree &DT,
  52. BasicBlock *From,
  53. BasicBlock *To);
  54. extern template void ApplyUpdates<BBDomTree>(BBDomTree &DT,
  55. BBDomTreeGraphDiff &,
  56. BBDomTreeGraphDiff *);
  57. extern template void ApplyUpdates<BBPostDomTree>(BBPostDomTree &DT,
  58. BBPostDomTreeGraphDiff &,
  59. BBPostDomTreeGraphDiff *);
  60. extern template bool Verify<BBDomTree>(const BBDomTree &DT,
  61. BBDomTree::VerificationLevel VL);
  62. extern template bool Verify<BBPostDomTree>(const BBPostDomTree &DT,
  63. BBPostDomTree::VerificationLevel VL);
  64. } // namespace DomTreeBuilder
  65. using DomTreeNode = DomTreeNodeBase<BasicBlock>;
  66. class BasicBlockEdge {
  67. const BasicBlock *Start;
  68. const BasicBlock *End;
  69. public:
  70. BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) :
  71. Start(Start_), End(End_) {}
  72. BasicBlockEdge(const std::pair<BasicBlock *, BasicBlock *> &Pair)
  73. : Start(Pair.first), End(Pair.second) {}
  74. BasicBlockEdge(const std::pair<const BasicBlock *, const BasicBlock *> &Pair)
  75. : Start(Pair.first), End(Pair.second) {}
  76. const BasicBlock *getStart() const {
  77. return Start;
  78. }
  79. const BasicBlock *getEnd() const {
  80. return End;
  81. }
  82. /// Check if this is the only edge between Start and End.
  83. bool isSingleEdge() const;
  84. };
  85. template <> struct DenseMapInfo<BasicBlockEdge> {
  86. using BBInfo = DenseMapInfo<const BasicBlock *>;
  87. static unsigned getHashValue(const BasicBlockEdge *V);
  88. static inline BasicBlockEdge getEmptyKey() {
  89. return BasicBlockEdge(BBInfo::getEmptyKey(), BBInfo::getEmptyKey());
  90. }
  91. static inline BasicBlockEdge getTombstoneKey() {
  92. return BasicBlockEdge(BBInfo::getTombstoneKey(), BBInfo::getTombstoneKey());
  93. }
  94. static unsigned getHashValue(const BasicBlockEdge &Edge) {
  95. return hash_combine(BBInfo::getHashValue(Edge.getStart()),
  96. BBInfo::getHashValue(Edge.getEnd()));
  97. }
  98. static bool isEqual(const BasicBlockEdge &LHS, const BasicBlockEdge &RHS) {
  99. return BBInfo::isEqual(LHS.getStart(), RHS.getStart()) &&
  100. BBInfo::isEqual(LHS.getEnd(), RHS.getEnd());
  101. }
  102. };
  103. /// Concrete subclass of DominatorTreeBase that is used to compute a
  104. /// normal dominator tree.
  105. ///
  106. /// Definition: A block is said to be forward statically reachable if there is
  107. /// a path from the entry of the function to the block. A statically reachable
  108. /// block may become statically unreachable during optimization.
  109. ///
  110. /// A forward unreachable block may appear in the dominator tree, or it may
  111. /// not. If it does, dominance queries will return results as if all reachable
  112. /// blocks dominate it. When asking for a Node corresponding to a potentially
  113. /// unreachable block, calling code must handle the case where the block was
  114. /// unreachable and the result of getNode() is nullptr.
  115. ///
  116. /// Generally, a block known to be unreachable when the dominator tree is
  117. /// constructed will not be in the tree. One which becomes unreachable after
  118. /// the dominator tree is initially constructed may still exist in the tree,
  119. /// even if the tree is properly updated. Calling code should not rely on the
  120. /// preceding statements; this is stated only to assist human understanding.
  121. class DominatorTree : public DominatorTreeBase<BasicBlock, false> {
  122. public:
  123. using Base = DominatorTreeBase<BasicBlock, false>;
  124. DominatorTree() = default;
  125. explicit DominatorTree(Function &F) { recalculate(F); }
  126. explicit DominatorTree(DominatorTree &DT, DomTreeBuilder::BBUpdates U) {
  127. recalculate(*DT.Parent, U);
  128. }
  129. /// Handle invalidation explicitly.
  130. bool invalidate(Function &F, const PreservedAnalyses &PA,
  131. FunctionAnalysisManager::Invalidator &);
  132. // Ensure base-class overloads are visible.
  133. using Base::dominates;
  134. /// Return true if the (end of the) basic block BB dominates the use U.
  135. bool dominates(const BasicBlock *BB, const Use &U) const;
  136. /// Return true if value Def dominates use U, in the sense that Def is
  137. /// available at U, and could be substituted as the used value without
  138. /// violating the SSA dominance requirement.
  139. ///
  140. /// In particular, it is worth noting that:
  141. /// * Non-instruction Defs dominate everything.
  142. /// * Def does not dominate a use in Def itself (outside of degenerate cases
  143. /// like unreachable code or trivial phi cycles).
  144. /// * Invoke/callbr Defs only dominate uses in their default destination.
  145. bool dominates(const Value *Def, const Use &U) const;
  146. /// Return true if value Def dominates all possible uses inside instruction
  147. /// User. Same comments as for the Use-based API apply.
  148. bool dominates(const Value *Def, const Instruction *User) const;
  149. // Does not accept Value to avoid ambiguity with dominance checks between
  150. // two basic blocks.
  151. bool dominates(const Instruction *Def, const BasicBlock *BB) const;
  152. /// Return true if an edge dominates a use.
  153. ///
  154. /// If BBE is not a unique edge between start and end of the edge, it can
  155. /// never dominate the use.
  156. bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
  157. bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
  158. /// Returns true if edge \p BBE1 dominates edge \p BBE2.
  159. bool dominates(const BasicBlockEdge &BBE1, const BasicBlockEdge &BBE2) const;
  160. // Ensure base class overloads are visible.
  161. using Base::isReachableFromEntry;
  162. /// Provide an overload for a Use.
  163. bool isReachableFromEntry(const Use &U) const;
  164. // Pop up a GraphViz/gv window with the Dominator Tree rendered using `dot`.
  165. void viewGraph(const Twine &Name, const Twine &Title);
  166. void viewGraph();
  167. };
  168. //===-------------------------------------
  169. // DominatorTree GraphTraits specializations so the DominatorTree can be
  170. // iterable by generic graph iterators.
  171. template <class Node, class ChildIterator> struct DomTreeGraphTraitsBase {
  172. using NodeRef = Node *;
  173. using ChildIteratorType = ChildIterator;
  174. using nodes_iterator = df_iterator<Node *, df_iterator_default_set<Node*>>;
  175. static NodeRef getEntryNode(NodeRef N) { return N; }
  176. static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
  177. static ChildIteratorType child_end(NodeRef N) { return N->end(); }
  178. static nodes_iterator nodes_begin(NodeRef N) {
  179. return df_begin(getEntryNode(N));
  180. }
  181. static nodes_iterator nodes_end(NodeRef N) { return df_end(getEntryNode(N)); }
  182. };
  183. template <>
  184. struct GraphTraits<DomTreeNode *>
  185. : public DomTreeGraphTraitsBase<DomTreeNode, DomTreeNode::const_iterator> {
  186. };
  187. template <>
  188. struct GraphTraits<const DomTreeNode *>
  189. : public DomTreeGraphTraitsBase<const DomTreeNode,
  190. DomTreeNode::const_iterator> {};
  191. template <> struct GraphTraits<DominatorTree*>
  192. : public GraphTraits<DomTreeNode*> {
  193. static NodeRef getEntryNode(DominatorTree *DT) { return DT->getRootNode(); }
  194. static nodes_iterator nodes_begin(DominatorTree *N) {
  195. return df_begin(getEntryNode(N));
  196. }
  197. static nodes_iterator nodes_end(DominatorTree *N) {
  198. return df_end(getEntryNode(N));
  199. }
  200. };
  201. /// Analysis pass which computes a \c DominatorTree.
  202. class DominatorTreeAnalysis : public AnalysisInfoMixin<DominatorTreeAnalysis> {
  203. friend AnalysisInfoMixin<DominatorTreeAnalysis>;
  204. static AnalysisKey Key;
  205. public:
  206. /// Provide the result typedef for this analysis pass.
  207. using Result = DominatorTree;
  208. /// Run the analysis pass over a function and produce a dominator tree.
  209. DominatorTree run(Function &F, FunctionAnalysisManager &);
  210. };
  211. /// Printer pass for the \c DominatorTree.
  212. class DominatorTreePrinterPass
  213. : public PassInfoMixin<DominatorTreePrinterPass> {
  214. raw_ostream &OS;
  215. public:
  216. explicit DominatorTreePrinterPass(raw_ostream &OS);
  217. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  218. };
  219. /// Verifier pass for the \c DominatorTree.
  220. struct DominatorTreeVerifierPass : PassInfoMixin<DominatorTreeVerifierPass> {
  221. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  222. };
  223. /// Legacy analysis pass which computes a \c DominatorTree.
  224. class DominatorTreeWrapperPass : public FunctionPass {
  225. DominatorTree DT;
  226. public:
  227. static char ID;
  228. DominatorTreeWrapperPass();
  229. DominatorTree &getDomTree() { return DT; }
  230. const DominatorTree &getDomTree() const { return DT; }
  231. bool runOnFunction(Function &F) override;
  232. void verifyAnalysis() const override;
  233. void getAnalysisUsage(AnalysisUsage &AU) const override {
  234. AU.setPreservesAll();
  235. }
  236. void releaseMemory() override { DT.reset(); }
  237. void print(raw_ostream &OS, const Module *M = nullptr) const override;
  238. };
  239. } // end namespace llvm
  240. #endif // LLVM_IR_DOMINATORS_H