Dominators.h revision 9c7ee6b19fab7a269994264bc19bf4d19c33b3c3
1//===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the following classes: 11// 1. DominatorTree: Represent dominators as an explicit tree structure. 12// 2. ETForest: Efficient data structure for dominance comparisons and 13// nearest-common-ancestor queries. 14// 3. DominanceFrontier: Calculate and hold the dominance frontier for a 15// function. 16// 17// These data structures are listed in increasing order of complexity. It 18// takes longer to calculate the dominator frontier, for example, than the 19// DominatorTree mapping. 20// 21//===----------------------------------------------------------------------===// 22 23#ifndef LLVM_ANALYSIS_DOMINATORS_H 24#define LLVM_ANALYSIS_DOMINATORS_H 25 26#include "llvm/Analysis/ET-Forest.h" 27#include "llvm/Pass.h" 28#include <set> 29 30namespace llvm { 31 32class Instruction; 33 34template <typename GraphType> struct GraphTraits; 35 36//===----------------------------------------------------------------------===// 37/// DominatorBase - Base class that other, more interesting dominator analyses 38/// inherit from. 39/// 40class DominatorBase : public FunctionPass { 41protected: 42 std::vector<BasicBlock*> Roots; 43 const bool IsPostDominators; 44 inline DominatorBase(intptr_t ID, bool isPostDom) : 45 FunctionPass(ID), Roots(), IsPostDominators(isPostDom) {} 46public: 47 48 /// getRoots - Return the root blocks of the current CFG. This may include 49 /// multiple blocks if we are computing post dominators. For forward 50 /// dominators, this will always be a single block (the entry node). 51 /// 52 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; } 53 54 /// isPostDominator - Returns true if analysis based of postdoms 55 /// 56 bool isPostDominator() const { return IsPostDominators; } 57}; 58 59 60//===----------------------------------------------------------------------===// 61// DomTreeNode - Dominator Tree Node 62class DominatorTreeBase; 63class PostDominatorTree; 64class DomTreeNode { 65 BasicBlock *TheBB; 66 DomTreeNode *IDom; 67 std::vector<DomTreeNode*> Children; 68 int DFSNumIn, DFSNumOut; 69 70 friend class DominatorTreeBase; 71 friend class PostDominatorTree; 72public: 73 typedef std::vector<DomTreeNode*>::iterator iterator; 74 typedef std::vector<DomTreeNode*>::const_iterator const_iterator; 75 76 iterator begin() { return Children.begin(); } 77 iterator end() { return Children.end(); } 78 const_iterator begin() const { return Children.begin(); } 79 const_iterator end() const { return Children.end(); } 80 81 inline BasicBlock *getBlock() const { return TheBB; } 82 inline DomTreeNode *getIDom() const { return IDom; } 83 inline const std::vector<DomTreeNode*> &getChildren() const { return Children; } 84 85 inline DomTreeNode(BasicBlock *BB, DomTreeNode *iDom) 86 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { } 87 inline DomTreeNode *addChild(DomTreeNode *C) { Children.push_back(C); return C; } 88 void setIDom(DomTreeNode *NewIDom); 89 90private: 91 // Return true if this node is dominated by other. Use this only if DFS info is valid. 92 bool DominatedBy(const DomTreeNode *other) const { 93 return this->DFSNumIn >= other->DFSNumIn && 94 this->DFSNumOut <= other->DFSNumOut; 95 } 96 97 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree 98 /// in dfs order. 99 void assignDFSNumber(int num); 100}; 101 102//===----------------------------------------------------------------------===// 103/// DominatorTree - Calculate the immediate dominator tree for a function. 104/// 105class DominatorTreeBase : public DominatorBase { 106 107protected: 108 void reset(); 109 typedef std::map<BasicBlock*, DomTreeNode*> DomTreeNodeMapType; 110 DomTreeNodeMapType DomTreeNodes; 111 DomTreeNode *RootNode; 112 113 bool DFSInfoValid; 114 unsigned int SlowQueries; 115 // Information record used during immediate dominators computation. 116 struct InfoRec { 117 unsigned Semi; 118 unsigned Size; 119 BasicBlock *Label, *Parent, *Child, *Ancestor; 120 121 std::vector<BasicBlock*> Bucket; 122 123 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0){} 124 }; 125 126 std::map<BasicBlock*, BasicBlock*> IDoms; 127 128 // Vertex - Map the DFS number to the BasicBlock* 129 std::vector<BasicBlock*> Vertex; 130 131 // Info - Collection of information used during the computation of idoms. 132 std::map<BasicBlock*, InfoRec> Info; 133 134 public: 135 DominatorTreeBase(intptr_t ID, bool isPostDom) 136 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {} 137 ~DominatorTreeBase() { reset(); } 138 139 virtual void releaseMemory() { reset(); } 140 141 /// getNode - return the (Post)DominatorTree node for the specified basic 142 /// block. This is the same as using operator[] on this class. 143 /// 144 inline DomTreeNode *getNode(BasicBlock *BB) const { 145 DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB); 146 return (i != DomTreeNodes.end()) ? i->second : 0; 147 } 148 149 inline DomTreeNode *operator[](BasicBlock *BB) const { 150 return getNode(BB); 151 } 152 153 /// getIDomBlock - return basic block BB's immediate dominator basic block. 154 /// 155 BasicBlock *getIDomBlock(BasicBlock *BB) { 156 DomTreeNode *N = getNode(BB); 157 assert (N && "Missing dominator tree node"); 158 DomTreeNode *I = N->getIDom(); 159 assert (N && "Missing immediate dominator"); 160 return I->getBlock(); 161 } 162 163 /// getRootNode - This returns the entry node for the CFG of the function. If 164 /// this tree represents the post-dominance relations for a function, however, 165 /// this root may be a node with the block == NULL. This is the case when 166 /// there are multiple exit nodes from a particular function. Consumers of 167 /// post-dominance information must be capable of dealing with this 168 /// possibility. 169 /// 170 DomTreeNode *getRootNode() { return RootNode; } 171 const DomTreeNode *getRootNode() const { return RootNode; } 172 173 /// properlyDominates - Returns true iff this dominates N and this != N. 174 /// Note that this is not a constant time operation! 175 /// 176 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const { 177 if (A == 0 || B == 0) return false; 178 return dominatedBySlowTreeWalk(A, B); 179 } 180 181 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) { 182 return properlyDominates(getNode(A), getNode(B)); 183 } 184 185 bool dominatedBySlowTreeWalk(const DomTreeNode *A, 186 const DomTreeNode *B) const { 187 const DomTreeNode *IDom; 188 if (A == 0 || B == 0) return false; 189 while ((IDom = B->getIDom()) != 0 && IDom != A) 190 B = IDom; // Walk up the tree 191 return IDom != 0; 192 } 193 194 void updateDFSNumbers(); 195 196 /// isReachableFromEntry - Return true if A is dominated by the entry 197 /// block of the function containing it. 198 const bool isReachableFromEntry(BasicBlock* A); 199 200 /// dominates - Returns true iff this dominates N. Note that this is not a 201 /// constant time operation! 202 /// 203 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) { 204 if (B == A) 205 return true; // A node trivially dominates itself. 206 207 if (A == 0 || B == 0) 208 return false; 209 210 if (DFSInfoValid) 211 return B->DominatedBy(A); 212 213 // If we end up with too many slow queries, just update the 214 // DFS numbers on the theory that we are going to keep querying. 215 SlowQueries++; 216 if (SlowQueries > 32) { 217 updateDFSNumbers(); 218 return B->DominatedBy(A); 219 } 220 221 return dominatedBySlowTreeWalk(A, B); 222 } 223 224 inline bool dominates(BasicBlock *A, BasicBlock *B) { 225 if (A == B) 226 return true; 227 228 return dominates(getNode(A), getNode(B)); 229 } 230 231 /// findNearestCommonDominator - Find nearest common dominator basic block 232 /// for basic block A and B. If there is no such block then return NULL. 233 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B); 234 235 // dominates - Return true if A dominates B. This performs the 236 // special checks necessary if A and B are in the same basic block. 237 bool dominates(Instruction *A, Instruction *B); 238 239 //===--------------------------------------------------------------------===// 240 // API to update (Post)DominatorTree information based on modifications to 241 // the CFG... 242 243 /// addNewBlock - Add a new node to the dominator tree information. This 244 /// creates a new node as a child of DomBB dominator node,linking it into 245 /// the children list of the immediate dominator. 246 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) { 247 assert(getNode(BB) == 0 && "Block already in dominator tree!"); 248 DomTreeNode *IDomNode = getNode(DomBB); 249 assert(IDomNode && "Not immediate dominator specified for block!"); 250 DFSInfoValid = false; 251 return DomTreeNodes[BB] = 252 IDomNode->addChild(new DomTreeNode(BB, IDomNode)); 253 } 254 255 /// changeImmediateDominator - This method is used to update the dominator 256 /// tree information when a node's immediate dominator changes. 257 /// 258 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) { 259 assert(N && NewIDom && "Cannot change null node pointers!"); 260 DFSInfoValid = false; 261 N->setIDom(NewIDom); 262 } 263 264 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) { 265 changeImmediateDominator(getNode(BB), getNode(NewBB)); 266 } 267 268 /// removeNode - Removes a node from the dominator tree. Block must not 269 /// dominate any other blocks. Invalidates any node pointing to removed 270 /// block. 271 void removeNode(BasicBlock *BB) { 272 assert(getNode(BB) && "Removing node that isn't in dominator tree."); 273 DomTreeNodes.erase(BB); 274 } 275 276 /// print - Convert to human readable form 277 /// 278 virtual void print(std::ostream &OS, const Module* = 0) const; 279 void print(std::ostream *OS, const Module* M = 0) const { 280 if (OS) print(*OS, M); 281 } 282 virtual void dump(); 283}; 284 285//===------------------------------------- 286/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to 287/// compute a normal dominator tree. 288/// 289class DominatorTree : public DominatorTreeBase { 290public: 291 static char ID; // Pass ID, replacement for typeid 292 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {} 293 294 BasicBlock *getRoot() const { 295 assert(Roots.size() == 1 && "Should always have entry node!"); 296 return Roots[0]; 297 } 298 299 virtual bool runOnFunction(Function &F); 300 301 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 302 AU.setPreservesAll(); 303 } 304private: 305 void calculate(Function& F); 306 DomTreeNode *getNodeForBlock(BasicBlock *BB); 307 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N); 308 void Compress(BasicBlock *V); 309 BasicBlock *Eval(BasicBlock *v); 310 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo); 311 inline BasicBlock *getIDom(BasicBlock *BB) const { 312 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB); 313 return I != IDoms.end() ? I->second : 0; 314 } 315}; 316 317//===------------------------------------- 318/// DominatorTree GraphTraits specialization so the DominatorTree can be 319/// iterable by generic graph iterators. 320/// 321template <> struct GraphTraits<DomTreeNode*> { 322 typedef DomTreeNode NodeType; 323 typedef NodeType::iterator ChildIteratorType; 324 325 static NodeType *getEntryNode(NodeType *N) { 326 return N; 327 } 328 static inline ChildIteratorType child_begin(NodeType* N) { 329 return N->begin(); 330 } 331 static inline ChildIteratorType child_end(NodeType* N) { 332 return N->end(); 333 } 334}; 335 336template <> struct GraphTraits<DominatorTree*> 337 : public GraphTraits<DomTreeNode*> { 338 static NodeType *getEntryNode(DominatorTree *DT) { 339 return DT->getRootNode(); 340 } 341}; 342 343 344//===------------------------------------- 345/// ET-Forest Class - Class used to construct forwards and backwards 346/// ET-Forests 347/// 348class ETForestBase : public DominatorBase { 349public: 350 ETForestBase(intptr_t ID, bool isPostDom) 351 : DominatorBase(ID, isPostDom), Nodes(), 352 DFSInfoValid(false), SlowQueries(0) {} 353 354 virtual void releaseMemory() { reset(); } 355 356 typedef std::map<BasicBlock*, ETNode*> ETMapType; 357 358 // FIXME : There is no need to make this interface public. 359 // Fix predicate simplifier. 360 void updateDFSNumbers(); 361 362 /// dominates - Return true if A dominates B. 363 /// 364 inline bool dominates(BasicBlock *A, BasicBlock *B) { 365 if (A == B) 366 return true; 367 368 ETNode *NodeA = getNode(A); 369 ETNode *NodeB = getNode(B); 370 371 if (DFSInfoValid) 372 return NodeB->DominatedBy(NodeA); 373 else { 374 // If we end up with too many slow queries, just update the 375 // DFS numbers on the theory that we are going to keep querying. 376 SlowQueries++; 377 if (SlowQueries > 32) { 378 updateDFSNumbers(); 379 return NodeB->DominatedBy(NodeA); 380 } 381 return NodeB->DominatedBySlow(NodeA); 382 } 383 } 384 385 // dominates - Return true if A dominates B. This performs the 386 // special checks necessary if A and B are in the same basic block. 387 bool dominates(Instruction *A, Instruction *B); 388 389 /// properlyDominates - Return true if A dominates B and A != B. 390 /// 391 bool properlyDominates(BasicBlock *A, BasicBlock *B) { 392 return dominates(A, B) && A != B; 393 } 394 395 /// isReachableFromEntry - Return true if A is dominated by the entry 396 /// block of the function containing it. 397 const bool isReachableFromEntry(BasicBlock* A); 398 399 /// Return the nearest common dominator of A and B. 400 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const { 401 ETNode *NodeA = getNode(A); 402 ETNode *NodeB = getNode(B); 403 404 ETNode *Common = NodeA->NCA(NodeB); 405 if (!Common) 406 return NULL; 407 return Common->getData<BasicBlock>(); 408 } 409 410 /// Return the immediate dominator of A. 411 BasicBlock *getIDom(BasicBlock *A) const { 412 ETNode *NodeA = getNode(A); 413 if (!NodeA) return 0; 414 const ETNode *idom = NodeA->getFather(); 415 return idom ? idom->getData<BasicBlock>() : 0; 416 } 417 418 void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const { 419 ETNode *NodeA = getNode(A); 420 if (!NodeA) return; 421 const ETNode* son = NodeA->getSon(); 422 423 if (!son) return; 424 children.push_back(son->getData<BasicBlock>()); 425 426 const ETNode* brother = son->getBrother(); 427 while (brother != son) { 428 children.push_back(brother->getData<BasicBlock>()); 429 brother = brother->getBrother(); 430 } 431 } 432 433 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 434 AU.setPreservesAll(); 435 AU.addRequired<DominatorTree>(); 436 } 437 //===--------------------------------------------------------------------===// 438 // API to update Forest information based on modifications 439 // to the CFG... 440 441 /// addNewBlock - Add a new block to the CFG, with the specified immediate 442 /// dominator. 443 /// 444 void addNewBlock(BasicBlock *BB, BasicBlock *IDom); 445 446 /// setImmediateDominator - Update the immediate dominator information to 447 /// change the current immediate dominator for the specified block 448 /// to another block. This method requires that BB for NewIDom 449 /// already have an ETNode, otherwise just use addNewBlock. 450 /// 451 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom); 452 /// print - Convert to human readable form 453 /// 454 virtual void print(std::ostream &OS, const Module* = 0) const; 455 void print(std::ostream *OS, const Module* M = 0) const { 456 if (OS) print(*OS, M); 457 } 458 virtual void dump(); 459protected: 460 /// getNode - return the (Post)DominatorTree node for the specified basic 461 /// block. This is the same as using operator[] on this class. 462 /// 463 inline ETNode *getNode(BasicBlock *BB) const { 464 ETMapType::const_iterator i = Nodes.find(BB); 465 return (i != Nodes.end()) ? i->second : 0; 466 } 467 468 inline ETNode *operator[](BasicBlock *BB) const { 469 return getNode(BB); 470 } 471 472 void reset(); 473 ETMapType Nodes; 474 bool DFSInfoValid; 475 unsigned int SlowQueries; 476 477}; 478 479//==------------------------------------- 480/// ETForest Class - Concrete subclass of ETForestBase that is used to 481/// compute a forwards ET-Forest. 482 483class ETForest : public ETForestBase { 484public: 485 static char ID; // Pass identification, replacement for typeid 486 487 ETForest() : ETForestBase((intptr_t)&ID, false) {} 488 489 BasicBlock *getRoot() const { 490 assert(Roots.size() == 1 && "Should always have entry node!"); 491 return Roots[0]; 492 } 493 494 virtual bool runOnFunction(Function &F) { 495 reset(); // Reset from the last time we were run... 496 DominatorTree &DT = getAnalysis<DominatorTree>(); 497 Roots = DT.getRoots(); 498 calculate(DT); 499 return false; 500 } 501 502 void calculate(const DominatorTree &DT); 503 // FIXME : There is no need to make getNodeForBlock public. Fix 504 // predicate simplifier. 505 ETNode *getNodeForBlock(BasicBlock *BB); 506}; 507 508//===----------------------------------------------------------------------===// 509/// DominanceFrontierBase - Common base class for computing forward and inverse 510/// dominance frontiers for a function. 511/// 512class DominanceFrontierBase : public DominatorBase { 513public: 514 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb 515 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map 516protected: 517 DomSetMapType Frontiers; 518public: 519 DominanceFrontierBase(intptr_t ID, bool isPostDom) 520 : DominatorBase(ID, isPostDom) {} 521 522 virtual void releaseMemory() { Frontiers.clear(); } 523 524 // Accessor interface: 525 typedef DomSetMapType::iterator iterator; 526 typedef DomSetMapType::const_iterator const_iterator; 527 iterator begin() { return Frontiers.begin(); } 528 const_iterator begin() const { return Frontiers.begin(); } 529 iterator end() { return Frontiers.end(); } 530 const_iterator end() const { return Frontiers.end(); } 531 iterator find(BasicBlock *B) { return Frontiers.find(B); } 532 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); } 533 534 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) { 535 assert(find(BB) == end() && "Block already in DominanceFrontier!"); 536 Frontiers.insert(std::make_pair(BB, frontier)); 537 } 538 539 void addToFrontier(iterator I, BasicBlock *Node) { 540 assert(I != end() && "BB is not in DominanceFrontier!"); 541 I->second.insert(Node); 542 } 543 544 void removeFromFrontier(iterator I, BasicBlock *Node) { 545 assert(I != end() && "BB is not in DominanceFrontier!"); 546 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB"); 547 I->second.erase(Node); 548 } 549 550 /// print - Convert to human readable form 551 /// 552 virtual void print(std::ostream &OS, const Module* = 0) const; 553 void print(std::ostream *OS, const Module* M = 0) const { 554 if (OS) print(*OS, M); 555 } 556 virtual void dump(); 557}; 558 559 560//===------------------------------------- 561/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is 562/// used to compute a forward dominator frontiers. 563/// 564class DominanceFrontier : public DominanceFrontierBase { 565public: 566 static char ID; // Pass ID, replacement for typeid 567 DominanceFrontier() : 568 DominanceFrontierBase((intptr_t)& ID, false) {} 569 570 BasicBlock *getRoot() const { 571 assert(Roots.size() == 1 && "Should always have entry node!"); 572 return Roots[0]; 573 } 574 575 virtual bool runOnFunction(Function &) { 576 Frontiers.clear(); 577 DominatorTree &DT = getAnalysis<DominatorTree>(); 578 Roots = DT.getRoots(); 579 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!"); 580 calculate(DT, DT[Roots[0]]); 581 return false; 582 } 583 584 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 585 AU.setPreservesAll(); 586 AU.addRequired<DominatorTree>(); 587 } 588 589private: 590 const DomSetType &calculate(const DominatorTree &DT, 591 const DomTreeNode *Node); 592}; 593 594 595} // End llvm namespace 596 597#endif 598