Dominators.h revision 6857e366f57dbf6a83c3fdfbd643dba5de305065
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 void updateDFSNumbers(); 135 136 public: 137 DominatorTreeBase(intptr_t ID, bool isPostDom) 138 : DominatorBase(ID, isPostDom), DFSInfoValid(false), SlowQueries(0) {} 139 ~DominatorTreeBase() { reset(); } 140 141 virtual void releaseMemory() { reset(); } 142 143 /// getNode - return the (Post)DominatorTree node for the specified basic 144 /// block. This is the same as using operator[] on this class. 145 /// 146 inline DomTreeNode *getNode(BasicBlock *BB) const { 147 DomTreeNodeMapType::const_iterator i = DomTreeNodes.find(BB); 148 return (i != DomTreeNodes.end()) ? i->second : 0; 149 } 150 151 inline DomTreeNode *operator[](BasicBlock *BB) const { 152 return getNode(BB); 153 } 154 155 /// getIDomBlock - return basic block BB's immediate dominator basic block. 156 /// 157 BasicBlock *getIDomBlock(BasicBlock *BB) { 158 DomTreeNode *N = getNode(BB); 159 assert (N && "Missing dominator tree node"); 160 DomTreeNode *I = N->getIDom(); 161 assert (N && "Missing immediate dominator"); 162 return I->getBlock(); 163 } 164 165 /// getRootNode - This returns the entry node for the CFG of the function. If 166 /// this tree represents the post-dominance relations for a function, however, 167 /// this root may be a node with the block == NULL. This is the case when 168 /// there are multiple exit nodes from a particular function. Consumers of 169 /// post-dominance information must be capable of dealing with this 170 /// possibility. 171 /// 172 DomTreeNode *getRootNode() { return RootNode; } 173 const DomTreeNode *getRootNode() const { return RootNode; } 174 175 /// properlyDominates - Returns true iff this dominates N and this != N. 176 /// Note that this is not a constant time operation! 177 /// 178 bool properlyDominates(const DomTreeNode *A, DomTreeNode *B) const { 179 if (A == 0 || B == 0) return false; 180 return dominatedBySlowTreeWalk(A, B); 181 } 182 183 inline bool properlyDominates(BasicBlock *A, BasicBlock *B) { 184 return properlyDominates(getNode(A), getNode(B)); 185 } 186 187 bool dominatedBySlowTreeWalk(const DomTreeNode *A, 188 const DomTreeNode *B) const { 189 const DomTreeNode *IDom; 190 if (A == 0 || B == 0) return false; 191 while ((IDom = B->getIDom()) != 0 && IDom != A) 192 B = IDom; // Walk up the tree 193 return IDom != 0; 194 } 195 196 197 /// isReachableFromEntry - Return true if A is dominated by the entry 198 /// block of the function containing it. 199 const bool isReachableFromEntry(BasicBlock* A); 200 201 /// dominates - Returns true iff A dominates B. Note that this is not a 202 /// constant time operation! 203 /// 204 inline bool dominates(const DomTreeNode *A, DomTreeNode *B) { 205 if (B == A) 206 return true; // A node trivially dominates itself. 207 208 if (A == 0 || B == 0) 209 return false; 210 211 if (DFSInfoValid) 212 return B->DominatedBy(A); 213 214 // If we end up with too many slow queries, just update the 215 // DFS numbers on the theory that we are going to keep querying. 216 SlowQueries++; 217 if (SlowQueries > 32) { 218 updateDFSNumbers(); 219 return B->DominatedBy(A); 220 } 221 222 return dominatedBySlowTreeWalk(A, B); 223 } 224 225 inline bool dominates(BasicBlock *A, BasicBlock *B) { 226 if (A == B) 227 return true; 228 229 return dominates(getNode(A), getNode(B)); 230 } 231 232 /// findNearestCommonDominator - Find nearest common dominator basic block 233 /// for basic block A and B. If there is no such block then return NULL. 234 BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B); 235 236 // dominates - Return true if A dominates B. This performs the 237 // special checks necessary if A and B are in the same basic block. 238 bool dominates(Instruction *A, Instruction *B); 239 240 //===--------------------------------------------------------------------===// 241 // API to update (Post)DominatorTree information based on modifications to 242 // the CFG... 243 244 /// addNewBlock - Add a new node to the dominator tree information. This 245 /// creates a new node as a child of DomBB dominator node,linking it into 246 /// the children list of the immediate dominator. 247 DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) { 248 assert(getNode(BB) == 0 && "Block already in dominator tree!"); 249 DomTreeNode *IDomNode = getNode(DomBB); 250 assert(IDomNode && "Not immediate dominator specified for block!"); 251 DFSInfoValid = false; 252 return DomTreeNodes[BB] = 253 IDomNode->addChild(new DomTreeNode(BB, IDomNode)); 254 } 255 256 /// changeImmediateDominator - This method is used to update the dominator 257 /// tree information when a node's immediate dominator changes. 258 /// 259 void changeImmediateDominator(DomTreeNode *N, DomTreeNode *NewIDom) { 260 assert(N && NewIDom && "Cannot change null node pointers!"); 261 DFSInfoValid = false; 262 N->setIDom(NewIDom); 263 } 264 265 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB) { 266 changeImmediateDominator(getNode(BB), getNode(NewBB)); 267 } 268 269 /// removeNode - Removes a node from the dominator tree. Block must not 270 /// dominate any other blocks. Invalidates any node pointing to removed 271 /// block. 272 void removeNode(BasicBlock *BB) { 273 assert(getNode(BB) && "Removing node that isn't in dominator tree."); 274 DomTreeNodes.erase(BB); 275 } 276 277 /// print - Convert to human readable form 278 /// 279 virtual void print(std::ostream &OS, const Module* = 0) const; 280 void print(std::ostream *OS, const Module* M = 0) const { 281 if (OS) print(*OS, M); 282 } 283 virtual void dump(); 284}; 285 286//===------------------------------------- 287/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to 288/// compute a normal dominator tree. 289/// 290class DominatorTree : public DominatorTreeBase { 291public: 292 static char ID; // Pass ID, replacement for typeid 293 DominatorTree() : DominatorTreeBase((intptr_t)&ID, false) {} 294 295 BasicBlock *getRoot() const { 296 assert(Roots.size() == 1 && "Should always have entry node!"); 297 return Roots[0]; 298 } 299 300 virtual bool runOnFunction(Function &F); 301 302 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 303 AU.setPreservesAll(); 304 } 305private: 306 void calculate(Function& F); 307 DomTreeNode *getNodeForBlock(BasicBlock *BB); 308 unsigned DFSPass(BasicBlock *V, InfoRec &VInfo, unsigned N); 309 void Compress(BasicBlock *V); 310 BasicBlock *Eval(BasicBlock *v); 311 void Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo); 312 inline BasicBlock *getIDom(BasicBlock *BB) const { 313 std::map<BasicBlock*, BasicBlock*>::const_iterator I = IDoms.find(BB); 314 return I != IDoms.end() ? I->second : 0; 315 } 316}; 317 318//===------------------------------------- 319/// DominatorTree GraphTraits specialization so the DominatorTree can be 320/// iterable by generic graph iterators. 321/// 322template <> struct GraphTraits<DomTreeNode*> { 323 typedef DomTreeNode NodeType; 324 typedef NodeType::iterator ChildIteratorType; 325 326 static NodeType *getEntryNode(NodeType *N) { 327 return N; 328 } 329 static inline ChildIteratorType child_begin(NodeType* N) { 330 return N->begin(); 331 } 332 static inline ChildIteratorType child_end(NodeType* N) { 333 return N->end(); 334 } 335}; 336 337template <> struct GraphTraits<DominatorTree*> 338 : public GraphTraits<DomTreeNode*> { 339 static NodeType *getEntryNode(DominatorTree *DT) { 340 return DT->getRootNode(); 341 } 342}; 343 344 345//===------------------------------------- 346/// ET-Forest Class - Class used to construct forwards and backwards 347/// ET-Forests 348/// 349class ETForestBase : public DominatorBase { 350public: 351 ETForestBase(intptr_t ID, bool isPostDom) 352 : DominatorBase(ID, isPostDom), Nodes(), 353 DFSInfoValid(false), SlowQueries(0) {} 354 355 virtual void releaseMemory() { reset(); } 356 357 typedef std::map<BasicBlock*, ETNode*> ETMapType; 358 359 // FIXME : There is no need to make this interface public. 360 // Fix predicate simplifier. 361 void updateDFSNumbers(); 362 363 /// dominates - Return true if A dominates B. 364 /// 365 inline bool dominates(BasicBlock *A, BasicBlock *B) { 366 if (A == B) 367 return true; 368 369 ETNode *NodeA = getNode(A); 370 ETNode *NodeB = getNode(B); 371 372 if (DFSInfoValid) 373 return NodeB->DominatedBy(NodeA); 374 else { 375 // If we end up with too many slow queries, just update the 376 // DFS numbers on the theory that we are going to keep querying. 377 SlowQueries++; 378 if (SlowQueries > 32) { 379 updateDFSNumbers(); 380 return NodeB->DominatedBy(NodeA); 381 } 382 return NodeB->DominatedBySlow(NodeA); 383 } 384 } 385 386 // dominates - Return true if A dominates B. This performs the 387 // special checks necessary if A and B are in the same basic block. 388 bool dominates(Instruction *A, Instruction *B); 389 390 /// properlyDominates - Return true if A dominates B and A != B. 391 /// 392 bool properlyDominates(BasicBlock *A, BasicBlock *B) { 393 return dominates(A, B) && A != B; 394 } 395 396 /// isReachableFromEntry - Return true if A is dominated by the entry 397 /// block of the function containing it. 398 const bool isReachableFromEntry(BasicBlock* A); 399 400 /// Return the nearest common dominator of A and B. 401 BasicBlock *nearestCommonDominator(BasicBlock *A, BasicBlock *B) const { 402 ETNode *NodeA = getNode(A); 403 ETNode *NodeB = getNode(B); 404 405 ETNode *Common = NodeA->NCA(NodeB); 406 if (!Common) 407 return NULL; 408 return Common->getData<BasicBlock>(); 409 } 410 411 /// Return the immediate dominator of A. 412 BasicBlock *getIDom(BasicBlock *A) const { 413 ETNode *NodeA = getNode(A); 414 if (!NodeA) return 0; 415 const ETNode *idom = NodeA->getFather(); 416 return idom ? idom->getData<BasicBlock>() : 0; 417 } 418 419 void getETNodeChildren(BasicBlock *A, std::vector<BasicBlock*>& children) const { 420 ETNode *NodeA = getNode(A); 421 if (!NodeA) return; 422 const ETNode* son = NodeA->getSon(); 423 424 if (!son) return; 425 children.push_back(son->getData<BasicBlock>()); 426 427 const ETNode* brother = son->getBrother(); 428 while (brother != son) { 429 children.push_back(brother->getData<BasicBlock>()); 430 brother = brother->getBrother(); 431 } 432 } 433 434 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 435 AU.setPreservesAll(); 436 AU.addRequired<DominatorTree>(); 437 } 438 //===--------------------------------------------------------------------===// 439 // API to update Forest information based on modifications 440 // to the CFG... 441 442 /// addNewBlock - Add a new block to the CFG, with the specified immediate 443 /// dominator. 444 /// 445 void addNewBlock(BasicBlock *BB, BasicBlock *IDom); 446 447 /// setImmediateDominator - Update the immediate dominator information to 448 /// change the current immediate dominator for the specified block 449 /// to another block. This method requires that BB for NewIDom 450 /// already have an ETNode, otherwise just use addNewBlock. 451 /// 452 void setImmediateDominator(BasicBlock *BB, BasicBlock *NewIDom); 453 /// print - Convert to human readable form 454 /// 455 virtual void print(std::ostream &OS, const Module* = 0) const; 456 void print(std::ostream *OS, const Module* M = 0) const { 457 if (OS) print(*OS, M); 458 } 459 virtual void dump(); 460protected: 461 /// getNode - return the (Post)DominatorTree node for the specified basic 462 /// block. This is the same as using operator[] on this class. 463 /// 464 inline ETNode *getNode(BasicBlock *BB) const { 465 ETMapType::const_iterator i = Nodes.find(BB); 466 return (i != Nodes.end()) ? i->second : 0; 467 } 468 469 inline ETNode *operator[](BasicBlock *BB) const { 470 return getNode(BB); 471 } 472 473 void reset(); 474 ETMapType Nodes; 475 bool DFSInfoValid; 476 unsigned int SlowQueries; 477 478}; 479 480//==------------------------------------- 481/// ETForest Class - Concrete subclass of ETForestBase that is used to 482/// compute a forwards ET-Forest. 483 484class ETForest : public ETForestBase { 485public: 486 static char ID; // Pass identification, replacement for typeid 487 488 ETForest() : ETForestBase((intptr_t)&ID, false) {} 489 490 BasicBlock *getRoot() const { 491 assert(Roots.size() == 1 && "Should always have entry node!"); 492 return Roots[0]; 493 } 494 495 virtual bool runOnFunction(Function &F) { 496 reset(); // Reset from the last time we were run... 497 DominatorTree &DT = getAnalysis<DominatorTree>(); 498 Roots = DT.getRoots(); 499 calculate(DT); 500 return false; 501 } 502 503 void calculate(const DominatorTree &DT); 504 // FIXME : There is no need to make getNodeForBlock public. Fix 505 // predicate simplifier. 506 ETNode *getNodeForBlock(BasicBlock *BB); 507}; 508 509//===----------------------------------------------------------------------===// 510/// DominanceFrontierBase - Common base class for computing forward and inverse 511/// dominance frontiers for a function. 512/// 513class DominanceFrontierBase : public DominatorBase { 514public: 515 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb 516 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map 517protected: 518 DomSetMapType Frontiers; 519public: 520 DominanceFrontierBase(intptr_t ID, bool isPostDom) 521 : DominatorBase(ID, isPostDom) {} 522 523 virtual void releaseMemory() { Frontiers.clear(); } 524 525 // Accessor interface: 526 typedef DomSetMapType::iterator iterator; 527 typedef DomSetMapType::const_iterator const_iterator; 528 iterator begin() { return Frontiers.begin(); } 529 const_iterator begin() const { return Frontiers.begin(); } 530 iterator end() { return Frontiers.end(); } 531 const_iterator end() const { return Frontiers.end(); } 532 iterator find(BasicBlock *B) { return Frontiers.find(B); } 533 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); } 534 535 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) { 536 assert(find(BB) == end() && "Block already in DominanceFrontier!"); 537 Frontiers.insert(std::make_pair(BB, frontier)); 538 } 539 540 void addToFrontier(iterator I, BasicBlock *Node) { 541 assert(I != end() && "BB is not in DominanceFrontier!"); 542 I->second.insert(Node); 543 } 544 545 void removeFromFrontier(iterator I, BasicBlock *Node) { 546 assert(I != end() && "BB is not in DominanceFrontier!"); 547 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB"); 548 I->second.erase(Node); 549 } 550 551 /// print - Convert to human readable form 552 /// 553 virtual void print(std::ostream &OS, const Module* = 0) const; 554 void print(std::ostream *OS, const Module* M = 0) const { 555 if (OS) print(*OS, M); 556 } 557 virtual void dump(); 558}; 559 560 561//===------------------------------------- 562/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is 563/// used to compute a forward dominator frontiers. 564/// 565class DominanceFrontier : public DominanceFrontierBase { 566public: 567 static char ID; // Pass ID, replacement for typeid 568 DominanceFrontier() : 569 DominanceFrontierBase((intptr_t)& ID, false) {} 570 571 BasicBlock *getRoot() const { 572 assert(Roots.size() == 1 && "Should always have entry node!"); 573 return Roots[0]; 574 } 575 576 virtual bool runOnFunction(Function &) { 577 Frontiers.clear(); 578 DominatorTree &DT = getAnalysis<DominatorTree>(); 579 Roots = DT.getRoots(); 580 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!"); 581 calculate(DT, DT[Roots[0]]); 582 return false; 583 } 584 585 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 586 AU.setPreservesAll(); 587 AU.addRequired<DominatorTree>(); 588 } 589 590private: 591 const DomSetType &calculate(const DominatorTree &DT, 592 const DomTreeNode *Node); 593}; 594 595 596} // End llvm namespace 597 598#endif 599