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 14 #ifndef LLVM_IR_DOMINATORS_H 15 #define LLVM_IR_DOMINATORS_H 16 17 #include "llvm/ADT/APInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/DenseMapInfo.h" 20 #include "llvm/ADT/DepthFirstIterator.h" 21 #include "llvm/ADT/Hashing.h" 22 #include "llvm/ADT/PointerIntPair.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/Twine.h" 25 #include "llvm/ADT/ilist_iterator.h" 26 #include "llvm/IR/BasicBlock.h" 27 #include "llvm/IR/CFG.h" 28 #include "llvm/IR/PassManager.h" 29 #include "llvm/IR/Use.h" 30 #include "llvm/Pass.h" 31 #include "llvm/Support/CFGDiff.h" 32 #include "llvm/Support/CFGUpdate.h" 33 #include "llvm/Support/Compiler.h" 34 #include "llvm/Support/GenericDomTree.h" 35 #include <algorithm> 36 #include <utility> 37 38 namespace llvm { 39 40 class Function; 41 class Instruction; 42 class Module; 43 class Value; 44 class raw_ostream; 45 template <class GraphType> struct GraphTraits; 46 47 extern template class LLVM_TEMPLATE_ABI DomTreeNodeBase<BasicBlock>; 48 extern template class LLVM_TEMPLATE_ABI 49 DominatorTreeBase<BasicBlock, false>; // DomTree 50 extern template class LLVM_TEMPLATE_ABI 51 DominatorTreeBase<BasicBlock, true>; // PostDomTree 52 53 extern template class cfg::Update<BasicBlock *>; 54 55 namespace DomTreeBuilder { 56 using BBDomTree = DomTreeBase<BasicBlock>; 57 using BBPostDomTree = PostDomTreeBase<BasicBlock>; 58 59 using BBUpdates = ArrayRef<llvm::cfg::Update<BasicBlock *>>; 60 61 using BBDomTreeGraphDiff = GraphDiff<BasicBlock *, false>; 62 using BBPostDomTreeGraphDiff = GraphDiff<BasicBlock *, true>; 63 64 extern template LLVM_TEMPLATE_ABI void Calculate<BBDomTree>(BBDomTree &DT); 65 extern template LLVM_TEMPLATE_ABI void 66 CalculateWithUpdates<BBDomTree>(BBDomTree &DT, BBUpdates U); 67 68 extern template LLVM_TEMPLATE_ABI void 69 Calculate<BBPostDomTree>(BBPostDomTree &DT); 70 71 extern template LLVM_TEMPLATE_ABI void 72 InsertEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From, BasicBlock *To); 73 extern template LLVM_TEMPLATE_ABI void 74 InsertEdge<BBPostDomTree>(BBPostDomTree &DT, BasicBlock *From, BasicBlock *To); 75 76 extern template LLVM_TEMPLATE_ABI void 77 DeleteEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From, BasicBlock *To); 78 extern template LLVM_TEMPLATE_ABI void 79 DeleteEdge<BBPostDomTree>(BBPostDomTree &DT, BasicBlock *From, BasicBlock *To); 80 81 extern template LLVM_TEMPLATE_ABI void 82 ApplyUpdates<BBDomTree>(BBDomTree &DT, BBDomTreeGraphDiff &, 83 BBDomTreeGraphDiff *); 84 extern template LLVM_TEMPLATE_ABI void 85 ApplyUpdates<BBPostDomTree>(BBPostDomTree &DT, BBPostDomTreeGraphDiff &, 86 BBPostDomTreeGraphDiff *); 87 88 extern template LLVM_TEMPLATE_ABI bool 89 Verify<BBDomTree>(const BBDomTree &DT, BBDomTree::VerificationLevel VL); 90 extern template LLVM_TEMPLATE_ABI bool 91 Verify<BBPostDomTree>(const BBPostDomTree &DT, 92 BBPostDomTree::VerificationLevel VL); 93 } // namespace DomTreeBuilder 94 95 using DomTreeNode = DomTreeNodeBase<BasicBlock>; 96 97 class BasicBlockEdge { 98 const BasicBlock *Start; 99 const BasicBlock *End; 100 101 public: BasicBlockEdge(const BasicBlock * Start_,const BasicBlock * End_)102 BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) : 103 Start(Start_), End(End_) {} 104 BasicBlockEdge(const std::pair<BasicBlock *,BasicBlock * > & Pair)105 BasicBlockEdge(const std::pair<BasicBlock *, BasicBlock *> &Pair) 106 : Start(Pair.first), End(Pair.second) {} 107 BasicBlockEdge(const std::pair<const BasicBlock *,const BasicBlock * > & Pair)108 BasicBlockEdge(const std::pair<const BasicBlock *, const BasicBlock *> &Pair) 109 : Start(Pair.first), End(Pair.second) {} 110 getStart()111 const BasicBlock *getStart() const { 112 return Start; 113 } 114 getEnd()115 const BasicBlock *getEnd() const { 116 return End; 117 } 118 119 /// Check if this is the only edge between Start and End. 120 LLVM_ABI bool isSingleEdge() const; 121 }; 122 123 template <> struct DenseMapInfo<BasicBlockEdge> { 124 using BBInfo = DenseMapInfo<const BasicBlock *>; 125 126 LLVM_ABI static unsigned getHashValue(const BasicBlockEdge *V); 127 128 static inline BasicBlockEdge getEmptyKey() { 129 return BasicBlockEdge(BBInfo::getEmptyKey(), BBInfo::getEmptyKey()); 130 } 131 132 static inline BasicBlockEdge getTombstoneKey() { 133 return BasicBlockEdge(BBInfo::getTombstoneKey(), BBInfo::getTombstoneKey()); 134 } 135 136 static unsigned getHashValue(const BasicBlockEdge &Edge) { 137 return hash_combine(BBInfo::getHashValue(Edge.getStart()), 138 BBInfo::getHashValue(Edge.getEnd())); 139 } 140 141 static bool isEqual(const BasicBlockEdge &LHS, const BasicBlockEdge &RHS) { 142 return BBInfo::isEqual(LHS.getStart(), RHS.getStart()) && 143 BBInfo::isEqual(LHS.getEnd(), RHS.getEnd()); 144 } 145 }; 146 147 /// Concrete subclass of DominatorTreeBase that is used to compute a 148 /// normal dominator tree. 149 /// 150 /// Definition: A block is said to be forward statically reachable if there is 151 /// a path from the entry of the function to the block. A statically reachable 152 /// block may become statically unreachable during optimization. 153 /// 154 /// A forward unreachable block may appear in the dominator tree, or it may 155 /// not. If it does, dominance queries will return results as if all reachable 156 /// blocks dominate it. When asking for a Node corresponding to a potentially 157 /// unreachable block, calling code must handle the case where the block was 158 /// unreachable and the result of getNode() is nullptr. 159 /// 160 /// Generally, a block known to be unreachable when the dominator tree is 161 /// constructed will not be in the tree. One which becomes unreachable after 162 /// the dominator tree is initially constructed may still exist in the tree, 163 /// even if the tree is properly updated. Calling code should not rely on the 164 /// preceding statements; this is stated only to assist human understanding. 165 class DominatorTree : public DominatorTreeBase<BasicBlock, false> { 166 public: 167 using Base = DominatorTreeBase<BasicBlock, false>; 168 169 DominatorTree() = default; 170 explicit DominatorTree(Function &F) { recalculate(F); } 171 explicit DominatorTree(DominatorTree &DT, DomTreeBuilder::BBUpdates U) { 172 recalculate(*DT.Parent, U); 173 } 174 175 /// Handle invalidation explicitly. 176 LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA, 177 FunctionAnalysisManager::Invalidator &); 178 179 // Ensure base-class overloads are visible. 180 using Base::dominates; 181 182 /// Return true if the (end of the) basic block BB dominates the use U. 183 LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const; 184 185 /// Return true if value Def dominates use U, in the sense that Def is 186 /// available at U, and could be substituted as the used value without 187 /// violating the SSA dominance requirement. 188 /// 189 /// In particular, it is worth noting that: 190 /// * Non-instruction Defs dominate everything. 191 /// * Def does not dominate a use in Def itself (outside of degenerate cases 192 /// like unreachable code or trivial phi cycles). 193 /// * Invoke Defs only dominate uses in their default destination. 194 LLVM_ABI bool dominates(const Value *Def, const Use &U) const; 195 196 /// Return true if value Def dominates all possible uses inside instruction 197 /// User. Same comments as for the Use-based API apply. 198 LLVM_ABI bool dominates(const Value *Def, const Instruction *User) const; 199 bool dominates(const Value *Def, BasicBlock::iterator User) const { 200 return dominates(Def, &*User); 201 } 202 203 /// Returns true if Def would dominate a use in any instruction in BB. 204 /// If Def is an instruction in BB, then Def does not dominate BB. 205 /// 206 /// Does not accept Value to avoid ambiguity with dominance checks between 207 /// two basic blocks. 208 LLVM_ABI bool dominates(const Instruction *Def, const BasicBlock *BB) const; 209 210 /// Return true if an edge dominates a use. 211 /// 212 /// If BBE is not a unique edge between start and end of the edge, it can 213 /// never dominate the use. 214 LLVM_ABI bool dominates(const BasicBlockEdge &BBE, const Use &U) const; 215 LLVM_ABI bool dominates(const BasicBlockEdge &BBE, 216 const BasicBlock *BB) const; 217 /// Returns true if edge \p BBE1 dominates edge \p BBE2. 218 LLVM_ABI bool dominates(const BasicBlockEdge &BBE1, 219 const BasicBlockEdge &BBE2) const; 220 221 // Ensure base class overloads are visible. 222 using Base::isReachableFromEntry; 223 224 /// Provide an overload for a Use. 225 LLVM_ABI bool isReachableFromEntry(const Use &U) const; 226 227 // Ensure base class overloads are visible. 228 using Base::findNearestCommonDominator; 229 230 /// Find the nearest instruction I that dominates both I1 and I2, in the sense 231 /// that a result produced before I will be available at both I1 and I2. 232 LLVM_ABI Instruction *findNearestCommonDominator(Instruction *I1, 233 Instruction *I2) const; 234 235 // Pop up a GraphViz/gv window with the Dominator Tree rendered using `dot`. 236 LLVM_ABI void viewGraph(const Twine &Name, const Twine &Title); 237 LLVM_ABI void viewGraph(); 238 }; 239 240 //===------------------------------------- 241 // DominatorTree GraphTraits specializations so the DominatorTree can be 242 // iterable by generic graph iterators. 243 244 template <class Node, class ChildIterator> struct DomTreeGraphTraitsBase { 245 using NodeRef = Node *; 246 using ChildIteratorType = ChildIterator; 247 using nodes_iterator = df_iterator<Node *, df_iterator_default_set<Node*>>; 248 249 static NodeRef getEntryNode(NodeRef N) { return N; } 250 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); } 251 static ChildIteratorType child_end(NodeRef N) { return N->end(); } 252 253 static nodes_iterator nodes_begin(NodeRef N) { 254 return df_begin(getEntryNode(N)); 255 } 256 257 static nodes_iterator nodes_end(NodeRef N) { return df_end(getEntryNode(N)); } 258 }; 259 260 template <> 261 struct GraphTraits<DomTreeNode *> 262 : public DomTreeGraphTraitsBase<DomTreeNode, DomTreeNode::const_iterator> { 263 }; 264 265 template <> 266 struct GraphTraits<const DomTreeNode *> 267 : public DomTreeGraphTraitsBase<const DomTreeNode, 268 DomTreeNode::const_iterator> {}; 269 270 template <> struct GraphTraits<DominatorTree*> 271 : public GraphTraits<DomTreeNode*> { 272 static NodeRef getEntryNode(DominatorTree *DT) { return DT->getRootNode(); } 273 274 static nodes_iterator nodes_begin(DominatorTree *N) { 275 return df_begin(getEntryNode(N)); 276 } 277 278 static nodes_iterator nodes_end(DominatorTree *N) { 279 return df_end(getEntryNode(N)); 280 } 281 }; 282 283 /// Analysis pass which computes a \c DominatorTree. 284 class DominatorTreeAnalysis : public AnalysisInfoMixin<DominatorTreeAnalysis> { 285 friend AnalysisInfoMixin<DominatorTreeAnalysis>; 286 LLVM_ABI static AnalysisKey Key; 287 288 public: 289 /// Provide the result typedef for this analysis pass. 290 using Result = DominatorTree; 291 292 /// Run the analysis pass over a function and produce a dominator tree. 293 LLVM_ABI DominatorTree run(Function &F, FunctionAnalysisManager &); 294 }; 295 296 /// Printer pass for the \c DominatorTree. 297 class DominatorTreePrinterPass 298 : public PassInfoMixin<DominatorTreePrinterPass> { 299 raw_ostream &OS; 300 301 public: 302 LLVM_ABI explicit DominatorTreePrinterPass(raw_ostream &OS); 303 304 LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); 305 306 static bool isRequired() { return true; } 307 }; 308 309 /// Verifier pass for the \c DominatorTree. 310 struct DominatorTreeVerifierPass : PassInfoMixin<DominatorTreeVerifierPass> { 311 LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); 312 static bool isRequired() { return true; } 313 }; 314 315 /// Enables verification of dominator trees. 316 /// 317 /// This check is expensive and is disabled by default. `-verify-dom-info` 318 /// allows selectively enabling the check without needing to recompile. 319 LLVM_ABI extern bool VerifyDomInfo; 320 321 /// Legacy analysis pass which computes a \c DominatorTree. 322 class LLVM_ABI DominatorTreeWrapperPass : public FunctionPass { 323 DominatorTree DT; 324 325 public: 326 static char ID; 327 328 DominatorTreeWrapperPass(); 329 330 DominatorTree &getDomTree() { return DT; } 331 const DominatorTree &getDomTree() const { return DT; } 332 333 bool runOnFunction(Function &F) override; 334 335 void verifyAnalysis() const override; 336 337 void getAnalysisUsage(AnalysisUsage &AU) const override { 338 AU.setPreservesAll(); 339 } 340 341 void releaseMemory() override { DT.reset(); } 342 343 void print(raw_ostream &OS, const Module *M = nullptr) const override; 344 }; 345 } // end namespace llvm 346 347 #endif // LLVM_IR_DOMINATORS_H 348