Dominators.h 12 KB

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