Dominators.h revision fde781b8d6020c78bb2f3a59845dba251e84808d
1//===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// 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. DominanceFrontier: Calculate and hold the dominance frontier for a 13// function. 14// 15// These data structures are listed in increasing order of complexity. It 16// takes longer to calculate the dominator frontier, for example, than the 17// DominatorTree mapping. 18// 19//===----------------------------------------------------------------------===// 20 21#ifndef LLVM_ANALYSIS_DOMINATORS_H 22#define LLVM_ANALYSIS_DOMINATORS_H 23 24#include "llvm/Pass.h" 25#include "llvm/Function.h" 26#include "llvm/Instructions.h" 27#include "llvm/ADT/DenseMap.h" 28#include "llvm/ADT/DepthFirstIterator.h" 29#include "llvm/ADT/GraphTraits.h" 30#include "llvm/ADT/SmallPtrSet.h" 31#include "llvm/ADT/SmallVector.h" 32#include "llvm/Assembly/Writer.h" 33#include "llvm/Support/CFG.h" 34#include "llvm/Support/Compiler.h" 35#include "llvm/Support/raw_ostream.h" 36#include <algorithm> 37#include <map> 38#include <set> 39 40namespace llvm { 41 42//===----------------------------------------------------------------------===// 43/// DominatorBase - Base class that other, more interesting dominator analyses 44/// inherit from. 45/// 46template <class NodeT> 47class DominatorBase { 48protected: 49 std::vector<NodeT*> Roots; 50 const bool IsPostDominators; 51 inline explicit DominatorBase(bool isPostDom) : 52 Roots(), IsPostDominators(isPostDom) {} 53public: 54 55 /// getRoots - Return the root blocks of the current CFG. This may include 56 /// multiple blocks if we are computing post dominators. For forward 57 /// dominators, this will always be a single block (the entry node). 58 /// 59 inline const std::vector<NodeT*> &getRoots() const { return Roots; } 60 61 /// isPostDominator - Returns true if analysis based of postdoms 62 /// 63 bool isPostDominator() const { return IsPostDominators; } 64}; 65 66 67//===----------------------------------------------------------------------===// 68// DomTreeNode - Dominator Tree Node 69template<class NodeT> class DominatorTreeBase; 70struct PostDominatorTree; 71class MachineBasicBlock; 72 73template <class NodeT> 74class DomTreeNodeBase { 75 NodeT *TheBB; 76 DomTreeNodeBase<NodeT> *IDom; 77 std::vector<DomTreeNodeBase<NodeT> *> Children; 78 int DFSNumIn, DFSNumOut; 79 80 template<class N> friend class DominatorTreeBase; 81 friend struct PostDominatorTree; 82public: 83 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator; 84 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator 85 const_iterator; 86 87 iterator begin() { return Children.begin(); } 88 iterator end() { return Children.end(); } 89 const_iterator begin() const { return Children.begin(); } 90 const_iterator end() const { return Children.end(); } 91 92 NodeT *getBlock() const { return TheBB; } 93 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; } 94 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const { 95 return Children; 96 } 97 98 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom) 99 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { } 100 101 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) { 102 Children.push_back(C); 103 return C; 104 } 105 106 size_t getNumChildren() const { 107 return Children.size(); 108 } 109 110 void clearAllChildren() { 111 Children.clear(); 112 } 113 114 bool compare(DomTreeNodeBase<NodeT> *Other) { 115 if (getNumChildren() != Other->getNumChildren()) 116 return true; 117 118 SmallPtrSet<NodeT *, 4> OtherChildren; 119 for(iterator I = Other->begin(), E = Other->end(); I != E; ++I) { 120 NodeT *Nd = (*I)->getBlock(); 121 OtherChildren.insert(Nd); 122 } 123 124 for(iterator I = begin(), E = end(); I != E; ++I) { 125 NodeT *N = (*I)->getBlock(); 126 if (OtherChildren.count(N) == 0) 127 return true; 128 } 129 return false; 130 } 131 132 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) { 133 assert(IDom && "No immediate dominator?"); 134 if (IDom != NewIDom) { 135 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I = 136 std::find(IDom->Children.begin(), IDom->Children.end(), this); 137 assert(I != IDom->Children.end() && 138 "Not in immediate dominator children set!"); 139 // I am no longer your child... 140 IDom->Children.erase(I); 141 142 // Switch to new dominator 143 IDom = NewIDom; 144 IDom->Children.push_back(this); 145 } 146 } 147 148 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do 149 /// not call them. 150 unsigned getDFSNumIn() const { return DFSNumIn; } 151 unsigned getDFSNumOut() const { return DFSNumOut; } 152private: 153 // Return true if this node is dominated by other. Use this only if DFS info 154 // is valid. 155 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const { 156 return this->DFSNumIn >= other->DFSNumIn && 157 this->DFSNumOut <= other->DFSNumOut; 158 } 159}; 160 161EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>); 162EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>); 163 164template<class NodeT> 165static raw_ostream &operator<<(raw_ostream &o, 166 const DomTreeNodeBase<NodeT> *Node) { 167 if (Node->getBlock()) 168 WriteAsOperand(o, Node->getBlock(), false); 169 else 170 o << " <<exit node>>"; 171 172 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}"; 173 174 return o << "\n"; 175} 176 177template<class NodeT> 178static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o, 179 unsigned Lev) { 180 o.indent(2*Lev) << "[" << Lev << "] " << N; 181 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(), 182 E = N->end(); I != E; ++I) 183 PrintDomTree<NodeT>(*I, o, Lev+1); 184} 185 186typedef DomTreeNodeBase<BasicBlock> DomTreeNode; 187 188//===----------------------------------------------------------------------===// 189/// DominatorTree - Calculate the immediate dominator tree for a function. 190/// 191 192template<class FuncT, class N> 193void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT, 194 FuncT& F); 195 196template<class NodeT> 197class DominatorTreeBase : public DominatorBase<NodeT> { 198protected: 199 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType; 200 DomTreeNodeMapType DomTreeNodes; 201 DomTreeNodeBase<NodeT> *RootNode; 202 203 bool DFSInfoValid; 204 unsigned int SlowQueries; 205 // Information record used during immediate dominators computation. 206 struct InfoRec { 207 unsigned DFSNum; 208 unsigned Semi; 209 unsigned Size; 210 NodeT *Label, *Child; 211 unsigned Parent, Ancestor; 212 213 std::vector<NodeT*> Bucket; 214 215 InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0), 216 Ancestor(0) {} 217 }; 218 219 DenseMap<NodeT*, NodeT*> IDoms; 220 221 // Vertex - Map the DFS number to the BasicBlock* 222 std::vector<NodeT*> Vertex; 223 224 // Info - Collection of information used during the computation of idoms. 225 DenseMap<NodeT*, InfoRec> Info; 226 227 void reset() { 228 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(), 229 E = DomTreeNodes.end(); I != E; ++I) 230 delete I->second; 231 DomTreeNodes.clear(); 232 IDoms.clear(); 233 this->Roots.clear(); 234 Vertex.clear(); 235 RootNode = 0; 236 } 237 238 // NewBB is split and now it has one successor. Update dominator tree to 239 // reflect this change. 240 template<class N, class GraphT> 241 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT, 242 typename GraphT::NodeType* NewBB) { 243 assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1 244 && "NewBB should have a single successor!"); 245 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB); 246 247 std::vector<typename GraphT::NodeType*> PredBlocks; 248 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI = 249 GraphTraits<Inverse<N> >::child_begin(NewBB), 250 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI) 251 PredBlocks.push_back(*PI); 252 253 assert(!PredBlocks.empty() && "No predblocks??"); 254 255 bool NewBBDominatesNewBBSucc = true; 256 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI = 257 GraphTraits<Inverse<N> >::child_begin(NewBBSucc), 258 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI) 259 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI) && 260 DT.isReachableFromEntry(*PI)) { 261 NewBBDominatesNewBBSucc = false; 262 break; 263 } 264 265 // Find NewBB's immediate dominator and create new dominator tree node for 266 // NewBB. 267 NodeT *NewBBIDom = 0; 268 unsigned i = 0; 269 for (i = 0; i < PredBlocks.size(); ++i) 270 if (DT.isReachableFromEntry(PredBlocks[i])) { 271 NewBBIDom = PredBlocks[i]; 272 break; 273 } 274 275 // It's possible that none of the predecessors of NewBB are reachable; 276 // in that case, NewBB itself is unreachable, so nothing needs to be 277 // changed. 278 if (!NewBBIDom) 279 return; 280 281 for (i = i + 1; i < PredBlocks.size(); ++i) { 282 if (DT.isReachableFromEntry(PredBlocks[i])) 283 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]); 284 } 285 286 // Create the new dominator tree node... and set the idom of NewBB. 287 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom); 288 289 // If NewBB strictly dominates other blocks, then it is now the immediate 290 // dominator of NewBBSucc. Update the dominator tree as appropriate. 291 if (NewBBDominatesNewBBSucc) { 292 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc); 293 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode); 294 } 295 } 296 297public: 298 explicit DominatorTreeBase(bool isPostDom) 299 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {} 300 virtual ~DominatorTreeBase() { reset(); } 301 302 // FIXME: Should remove this 303 virtual bool runOnFunction(Function &F) { return false; } 304 305 /// compare - Return false if the other dominator tree base matches this 306 /// dominator tree base. Otherwise return true. 307 bool compare(DominatorTreeBase &Other) const { 308 309 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes; 310 if (DomTreeNodes.size() != OtherDomTreeNodes.size()) 311 return true; 312 313 for (typename DomTreeNodeMapType::const_iterator 314 I = this->DomTreeNodes.begin(), 315 E = this->DomTreeNodes.end(); I != E; ++I) { 316 NodeT *BB = I->first; 317 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB); 318 if (OI == OtherDomTreeNodes.end()) 319 return true; 320 321 DomTreeNodeBase<NodeT>* MyNd = I->second; 322 DomTreeNodeBase<NodeT>* OtherNd = OI->second; 323 324 if (MyNd->compare(OtherNd)) 325 return true; 326 } 327 328 return false; 329 } 330 331 virtual void releaseMemory() { reset(); } 332 333 /// getNode - return the (Post)DominatorTree node for the specified basic 334 /// block. This is the same as using operator[] on this class. 335 /// 336 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const { 337 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB); 338 return I != DomTreeNodes.end() ? I->second : 0; 339 } 340 341 /// getRootNode - This returns the entry node for the CFG of the function. If 342 /// this tree represents the post-dominance relations for a function, however, 343 /// this root may be a node with the block == NULL. This is the case when 344 /// there are multiple exit nodes from a particular function. Consumers of 345 /// post-dominance information must be capable of dealing with this 346 /// possibility. 347 /// 348 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; } 349 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; } 350 351 /// properlyDominates - Returns true iff this dominates N and this != N. 352 /// Note that this is not a constant time operation! 353 /// 354 bool properlyDominates(const DomTreeNodeBase<NodeT> *A, 355 const DomTreeNodeBase<NodeT> *B) const { 356 if (A == 0 || B == 0) return false; 357 return dominatedBySlowTreeWalk(A, B); 358 } 359 360 inline bool properlyDominates(NodeT *A, NodeT *B) { 361 return properlyDominates(getNode(A), getNode(B)); 362 } 363 364 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A, 365 const DomTreeNodeBase<NodeT> *B) const { 366 const DomTreeNodeBase<NodeT> *IDom; 367 if (A == 0 || B == 0) return false; 368 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B) 369 B = IDom; // Walk up the tree 370 return IDom != 0; 371 } 372 373 374 /// isReachableFromEntry - Return true if A is dominated by the entry 375 /// block of the function containing it. 376 bool isReachableFromEntry(NodeT* A) { 377 assert (!this->isPostDominator() 378 && "This is not implemented for post dominators"); 379 return dominates(&A->getParent()->front(), A); 380 } 381 382 /// dominates - Returns true iff A dominates B. Note that this is not a 383 /// constant time operation! 384 /// 385 inline bool dominates(const DomTreeNodeBase<NodeT> *A, 386 const DomTreeNodeBase<NodeT> *B) { 387 if (B == A) 388 return true; // A node trivially dominates itself. 389 390 if (A == 0 || B == 0) 391 return false; 392 393 // Compare the result of the tree walk and the dfs numbers, if expensive 394 // checks are enabled. 395#ifdef XDEBUG 396 assert(!DFSInfoValid 397 || (dominatedBySlowTreeWalk(A, B) == B->DominatedBy(A))); 398#endif 399 400 if (DFSInfoValid) 401 return B->DominatedBy(A); 402 403 // If we end up with too many slow queries, just update the 404 // DFS numbers on the theory that we are going to keep querying. 405 SlowQueries++; 406 if (SlowQueries > 32) { 407 updateDFSNumbers(); 408 return B->DominatedBy(A); 409 } 410 411 return dominatedBySlowTreeWalk(A, B); 412 } 413 414 inline bool dominates(const NodeT *A, const NodeT *B) { 415 if (A == B) 416 return true; 417 418 // Cast away the const qualifiers here. This is ok since 419 // this function doesn't actually return the values returned 420 // from getNode. 421 return dominates(getNode(const_cast<NodeT *>(A)), 422 getNode(const_cast<NodeT *>(B))); 423 } 424 425 NodeT *getRoot() const { 426 assert(this->Roots.size() == 1 && "Should always have entry node!"); 427 return this->Roots[0]; 428 } 429 430 /// findNearestCommonDominator - Find nearest common dominator basic block 431 /// for basic block A and B. If there is no such block then return NULL. 432 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) { 433 434 assert (!this->isPostDominator() 435 && "This is not implemented for post dominators"); 436 assert (A->getParent() == B->getParent() 437 && "Two blocks are not in same function"); 438 439 // If either A or B is a entry block then it is nearest common dominator. 440 NodeT &Entry = A->getParent()->front(); 441 if (A == &Entry || B == &Entry) 442 return &Entry; 443 444 // If B dominates A then B is nearest common dominator. 445 if (dominates(B, A)) 446 return B; 447 448 // If A dominates B then A is nearest common dominator. 449 if (dominates(A, B)) 450 return A; 451 452 DomTreeNodeBase<NodeT> *NodeA = getNode(A); 453 DomTreeNodeBase<NodeT> *NodeB = getNode(B); 454 455 // Collect NodeA dominators set. 456 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms; 457 NodeADoms.insert(NodeA); 458 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom(); 459 while (IDomA) { 460 NodeADoms.insert(IDomA); 461 IDomA = IDomA->getIDom(); 462 } 463 464 // Walk NodeB immediate dominators chain and find common dominator node. 465 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom(); 466 while(IDomB) { 467 if (NodeADoms.count(IDomB) != 0) 468 return IDomB->getBlock(); 469 470 IDomB = IDomB->getIDom(); 471 } 472 473 return NULL; 474 } 475 476 //===--------------------------------------------------------------------===// 477 // API to update (Post)DominatorTree information based on modifications to 478 // the CFG... 479 480 /// addNewBlock - Add a new node to the dominator tree information. This 481 /// creates a new node as a child of DomBB dominator node,linking it into 482 /// the children list of the immediate dominator. 483 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) { 484 assert(getNode(BB) == 0 && "Block already in dominator tree!"); 485 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB); 486 assert(IDomNode && "Not immediate dominator specified for block!"); 487 DFSInfoValid = false; 488 return DomTreeNodes[BB] = 489 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode)); 490 } 491 492 /// changeImmediateDominator - This method is used to update the dominator 493 /// tree information when a node's immediate dominator changes. 494 /// 495 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N, 496 DomTreeNodeBase<NodeT> *NewIDom) { 497 assert(N && NewIDom && "Cannot change null node pointers!"); 498 DFSInfoValid = false; 499 N->setIDom(NewIDom); 500 } 501 502 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) { 503 changeImmediateDominator(getNode(BB), getNode(NewBB)); 504 } 505 506 /// eraseNode - Removes a node from the dominator tree. Block must not 507 /// domiante any other blocks. Removes node from its immediate dominator's 508 /// children list. Deletes dominator node associated with basic block BB. 509 void eraseNode(NodeT *BB) { 510 DomTreeNodeBase<NodeT> *Node = getNode(BB); 511 assert (Node && "Removing node that isn't in dominator tree."); 512 assert (Node->getChildren().empty() && "Node is not a leaf node."); 513 514 // Remove node from immediate dominator's children list. 515 DomTreeNodeBase<NodeT> *IDom = Node->getIDom(); 516 if (IDom) { 517 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I = 518 std::find(IDom->Children.begin(), IDom->Children.end(), Node); 519 assert(I != IDom->Children.end() && 520 "Not in immediate dominator children set!"); 521 // I am no longer your child... 522 IDom->Children.erase(I); 523 } 524 525 DomTreeNodes.erase(BB); 526 delete Node; 527 } 528 529 /// removeNode - Removes a node from the dominator tree. Block must not 530 /// dominate any other blocks. Invalidates any node pointing to removed 531 /// block. 532 void removeNode(NodeT *BB) { 533 assert(getNode(BB) && "Removing node that isn't in dominator tree."); 534 DomTreeNodes.erase(BB); 535 } 536 537 /// splitBlock - BB is split and now it has one successor. Update dominator 538 /// tree to reflect this change. 539 void splitBlock(NodeT* NewBB) { 540 if (this->IsPostDominators) 541 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB); 542 else 543 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB); 544 } 545 546 /// print - Convert to human readable form 547 /// 548 void print(raw_ostream &o) const { 549 o << "=============================--------------------------------\n"; 550 if (this->isPostDominator()) 551 o << "Inorder PostDominator Tree: "; 552 else 553 o << "Inorder Dominator Tree: "; 554 if (this->DFSInfoValid) 555 o << "DFSNumbers invalid: " << SlowQueries << " slow queries."; 556 o << "\n"; 557 558 // The postdom tree can have a null root if there are no returns. 559 if (getRootNode()) 560 PrintDomTree<NodeT>(getRootNode(), o, 1); 561 } 562 563protected: 564 template<class GraphT> 565 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT, 566 typename GraphT::NodeType* VIn); 567 568 template<class GraphT> 569 friend typename GraphT::NodeType* Eval( 570 DominatorTreeBase<typename GraphT::NodeType>& DT, 571 typename GraphT::NodeType* V); 572 573 template<class GraphT> 574 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT, 575 unsigned DFSNumV, typename GraphT::NodeType* W, 576 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo); 577 578 template<class GraphT> 579 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT, 580 typename GraphT::NodeType* V, 581 unsigned N); 582 583 template<class FuncT, class N> 584 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT, 585 FuncT& F); 586 587 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking 588 /// dominator tree in dfs order. 589 void updateDFSNumbers() { 590 unsigned DFSNum = 0; 591 592 SmallVector<std::pair<DomTreeNodeBase<NodeT>*, 593 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack; 594 595 DomTreeNodeBase<NodeT> *ThisRoot = getRootNode(); 596 597 if (!ThisRoot) 598 return; 599 600 // Even in the case of multiple exits that form the post dominator root 601 // nodes, do not iterate over all exits, but start from the virtual root 602 // node. Otherwise bbs, that are not post dominated by any exit but by the 603 // virtual root node, will never be assigned a DFS number. 604 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin())); 605 ThisRoot->DFSNumIn = DFSNum++; 606 607 while (!WorkStack.empty()) { 608 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first; 609 typename DomTreeNodeBase<NodeT>::iterator ChildIt = 610 WorkStack.back().second; 611 612 // If we visited all of the children of this node, "recurse" back up the 613 // stack setting the DFOutNum. 614 if (ChildIt == Node->end()) { 615 Node->DFSNumOut = DFSNum++; 616 WorkStack.pop_back(); 617 } else { 618 // Otherwise, recursively visit this child. 619 DomTreeNodeBase<NodeT> *Child = *ChildIt; 620 ++WorkStack.back().second; 621 622 WorkStack.push_back(std::make_pair(Child, Child->begin())); 623 Child->DFSNumIn = DFSNum++; 624 } 625 } 626 627 SlowQueries = 0; 628 DFSInfoValid = true; 629 } 630 631 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) { 632 typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB); 633 if (I != this->DomTreeNodes.end() && I->second) 634 return I->second; 635 636 // Haven't calculated this node yet? Get or calculate the node for the 637 // immediate dominator. 638 NodeT *IDom = getIDom(BB); 639 640 assert(IDom || this->DomTreeNodes[NULL]); 641 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom); 642 643 // Add a new tree node for this BasicBlock, and link it as a child of 644 // IDomNode 645 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode); 646 return this->DomTreeNodes[BB] = IDomNode->addChild(C); 647 } 648 649 inline NodeT *getIDom(NodeT *BB) const { 650 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB); 651 return I != IDoms.end() ? I->second : 0; 652 } 653 654 inline void addRoot(NodeT* BB) { 655 this->Roots.push_back(BB); 656 } 657 658public: 659 /// recalculate - compute a dominator tree for the given function 660 template<class FT> 661 void recalculate(FT& F) { 662 reset(); 663 this->Vertex.push_back(0); 664 665 if (!this->IsPostDominators) { 666 // Initialize root 667 this->Roots.push_back(&F.front()); 668 this->IDoms[&F.front()] = 0; 669 this->DomTreeNodes[&F.front()] = 0; 670 671 Calculate<FT, NodeT*>(*this, F); 672 } else { 673 // Initialize the roots list 674 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) { 675 if (std::distance(GraphTraits<FT*>::child_begin(I), 676 GraphTraits<FT*>::child_end(I)) == 0) 677 addRoot(I); 678 679 // Prepopulate maps so that we don't get iterator invalidation issues later. 680 this->IDoms[I] = 0; 681 this->DomTreeNodes[I] = 0; 682 } 683 684 Calculate<FT, Inverse<NodeT*> >(*this, F); 685 } 686 } 687}; 688 689EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>); 690 691//===------------------------------------- 692/// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to 693/// compute a normal dominator tree. 694/// 695class DominatorTree : public FunctionPass { 696public: 697 static char ID; // Pass ID, replacement for typeid 698 DominatorTreeBase<BasicBlock>* DT; 699 700 DominatorTree() : FunctionPass(&ID) { 701 DT = new DominatorTreeBase<BasicBlock>(false); 702 } 703 704 ~DominatorTree() { 705 DT->releaseMemory(); 706 delete DT; 707 } 708 709 DominatorTreeBase<BasicBlock>& getBase() { return *DT; } 710 711 /// getRoots - Return the root blocks of the current CFG. This may include 712 /// multiple blocks if we are computing post dominators. For forward 713 /// dominators, this will always be a single block (the entry node). 714 /// 715 inline const std::vector<BasicBlock*> &getRoots() const { 716 return DT->getRoots(); 717 } 718 719 inline BasicBlock *getRoot() const { 720 return DT->getRoot(); 721 } 722 723 inline DomTreeNode *getRootNode() const { 724 return DT->getRootNode(); 725 } 726 727 /// compare - Return false if the other dominator tree matches this 728 /// dominator tree. Otherwise return true. 729 inline bool compare(DominatorTree &Other) const { 730 DomTreeNode *R = getRootNode(); 731 DomTreeNode *OtherR = Other.getRootNode(); 732 733 if (!R || !OtherR || R->getBlock() != OtherR->getBlock()) 734 return true; 735 736 if (DT->compare(Other.getBase())) 737 return true; 738 739 return false; 740 } 741 742 virtual bool runOnFunction(Function &F); 743 744 virtual void verifyAnalysis() const; 745 746 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 747 AU.setPreservesAll(); 748 } 749 750 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const { 751 return DT->dominates(A, B); 752 } 753 754 inline bool dominates(const BasicBlock* A, const BasicBlock* B) const { 755 return DT->dominates(A, B); 756 } 757 758 // dominates - Return true if A dominates B. This performs the 759 // special checks necessary if A and B are in the same basic block. 760 bool dominates(const Instruction *A, const Instruction *B) const; 761 762 bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const { 763 return DT->properlyDominates(A, B); 764 } 765 766 bool properlyDominates(BasicBlock *A, BasicBlock *B) const { 767 return DT->properlyDominates(A, B); 768 } 769 770 /// findNearestCommonDominator - Find nearest common dominator basic block 771 /// for basic block A and B. If there is no such block then return NULL. 772 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) { 773 return DT->findNearestCommonDominator(A, B); 774 } 775 776 inline DomTreeNode *operator[](BasicBlock *BB) const { 777 return DT->getNode(BB); 778 } 779 780 /// getNode - return the (Post)DominatorTree node for the specified basic 781 /// block. This is the same as using operator[] on this class. 782 /// 783 inline DomTreeNode *getNode(BasicBlock *BB) const { 784 return DT->getNode(BB); 785 } 786 787 /// addNewBlock - Add a new node to the dominator tree information. This 788 /// creates a new node as a child of DomBB dominator node,linking it into 789 /// the children list of the immediate dominator. 790 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) { 791 return DT->addNewBlock(BB, DomBB); 792 } 793 794 /// changeImmediateDominator - This method is used to update the dominator 795 /// tree information when a node's immediate dominator changes. 796 /// 797 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) { 798 DT->changeImmediateDominator(N, NewIDom); 799 } 800 801 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) { 802 DT->changeImmediateDominator(N, NewIDom); 803 } 804 805 /// eraseNode - Removes a node from the dominator tree. Block must not 806 /// domiante any other blocks. Removes node from its immediate dominator's 807 /// children list. Deletes dominator node associated with basic block BB. 808 inline void eraseNode(BasicBlock *BB) { 809 DT->eraseNode(BB); 810 } 811 812 /// splitBlock - BB is split and now it has one successor. Update dominator 813 /// tree to reflect this change. 814 inline void splitBlock(BasicBlock* NewBB) { 815 DT->splitBlock(NewBB); 816 } 817 818 bool isReachableFromEntry(BasicBlock* A) { 819 return DT->isReachableFromEntry(A); 820 } 821 822 823 virtual void releaseMemory() { 824 DT->releaseMemory(); 825 } 826 827 virtual void print(raw_ostream &OS, const Module* M= 0) const; 828}; 829 830//===------------------------------------- 831/// DominatorTree GraphTraits specialization so the DominatorTree can be 832/// iterable by generic graph iterators. 833/// 834template <> struct GraphTraits<DomTreeNode*> { 835 typedef DomTreeNode NodeType; 836 typedef NodeType::iterator ChildIteratorType; 837 838 static NodeType *getEntryNode(NodeType *N) { 839 return N; 840 } 841 static inline ChildIteratorType child_begin(NodeType *N) { 842 return N->begin(); 843 } 844 static inline ChildIteratorType child_end(NodeType *N) { 845 return N->end(); 846 } 847 848 typedef df_iterator<DomTreeNode*> nodes_iterator; 849 850 static nodes_iterator nodes_begin(DomTreeNode *N) { 851 return df_begin(getEntryNode(N)); 852 } 853 854 static nodes_iterator nodes_end(DomTreeNode *N) { 855 return df_end(getEntryNode(N)); 856 } 857}; 858 859template <> struct GraphTraits<DominatorTree*> 860 : public GraphTraits<DomTreeNode*> { 861 static NodeType *getEntryNode(DominatorTree *DT) { 862 return DT->getRootNode(); 863 } 864 865 static nodes_iterator nodes_begin(DominatorTree *N) { 866 return df_begin(getEntryNode(N)); 867 } 868 869 static nodes_iterator nodes_end(DominatorTree *N) { 870 return df_end(getEntryNode(N)); 871 } 872}; 873 874 875//===----------------------------------------------------------------------===// 876/// DominanceFrontierBase - Common base class for computing forward and inverse 877/// dominance frontiers for a function. 878/// 879class DominanceFrontierBase : public FunctionPass { 880public: 881 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb 882 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map 883protected: 884 DomSetMapType Frontiers; 885 std::vector<BasicBlock*> Roots; 886 const bool IsPostDominators; 887 888public: 889 DominanceFrontierBase(void *ID, bool isPostDom) 890 : FunctionPass(ID), IsPostDominators(isPostDom) {} 891 892 /// getRoots - Return the root blocks of the current CFG. This may include 893 /// multiple blocks if we are computing post dominators. For forward 894 /// dominators, this will always be a single block (the entry node). 895 /// 896 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; } 897 898 /// isPostDominator - Returns true if analysis based of postdoms 899 /// 900 bool isPostDominator() const { return IsPostDominators; } 901 902 virtual void releaseMemory() { Frontiers.clear(); } 903 904 // Accessor interface: 905 typedef DomSetMapType::iterator iterator; 906 typedef DomSetMapType::const_iterator const_iterator; 907 iterator begin() { return Frontiers.begin(); } 908 const_iterator begin() const { return Frontiers.begin(); } 909 iterator end() { return Frontiers.end(); } 910 const_iterator end() const { return Frontiers.end(); } 911 iterator find(BasicBlock *B) { return Frontiers.find(B); } 912 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); } 913 914 iterator addBasicBlock(BasicBlock *BB, const DomSetType &frontier) { 915 assert(find(BB) == end() && "Block already in DominanceFrontier!"); 916 return Frontiers.insert(std::make_pair(BB, frontier)).first; 917 } 918 919 /// removeBlock - Remove basic block BB's frontier. 920 void removeBlock(BasicBlock *BB) { 921 assert(find(BB) != end() && "Block is not in DominanceFrontier!"); 922 for (iterator I = begin(), E = end(); I != E; ++I) 923 I->second.erase(BB); 924 Frontiers.erase(BB); 925 } 926 927 void addToFrontier(iterator I, BasicBlock *Node) { 928 assert(I != end() && "BB is not in DominanceFrontier!"); 929 I->second.insert(Node); 930 } 931 932 void removeFromFrontier(iterator I, BasicBlock *Node) { 933 assert(I != end() && "BB is not in DominanceFrontier!"); 934 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB"); 935 I->second.erase(Node); 936 } 937 938 /// compareDomSet - Return false if two domsets match. Otherwise 939 /// return true; 940 bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const { 941 std::set<BasicBlock *> tmpSet; 942 for (DomSetType::const_iterator I = DS2.begin(), 943 E = DS2.end(); I != E; ++I) 944 tmpSet.insert(*I); 945 946 for (DomSetType::const_iterator I = DS1.begin(), 947 E = DS1.end(); I != E; ) { 948 BasicBlock *Node = *I++; 949 950 if (tmpSet.erase(Node) == 0) 951 // Node is in DS1 but not in DS2. 952 return true; 953 } 954 955 if(!tmpSet.empty()) 956 // There are nodes that are in DS2 but not in DS1. 957 return true; 958 959 // DS1 and DS2 matches. 960 return false; 961 } 962 963 /// compare - Return true if the other dominance frontier base matches 964 /// this dominance frontier base. Otherwise return false. 965 bool compare(DominanceFrontierBase &Other) const { 966 DomSetMapType tmpFrontiers; 967 for (DomSetMapType::const_iterator I = Other.begin(), 968 E = Other.end(); I != E; ++I) 969 tmpFrontiers.insert(std::make_pair(I->first, I->second)); 970 971 for (DomSetMapType::iterator I = tmpFrontiers.begin(), 972 E = tmpFrontiers.end(); I != E; ) { 973 BasicBlock *Node = I->first; 974 const_iterator DFI = find(Node); 975 if (DFI == end()) 976 return true; 977 978 if (compareDomSet(I->second, DFI->second)) 979 return true; 980 981 ++I; 982 tmpFrontiers.erase(Node); 983 } 984 985 if (!tmpFrontiers.empty()) 986 return true; 987 988 return false; 989 } 990 991 /// print - Convert to human readable form 992 /// 993 virtual void print(raw_ostream &OS, const Module* = 0) const; 994}; 995 996 997//===------------------------------------- 998/// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is 999/// used to compute a forward dominator frontiers. 1000/// 1001class DominanceFrontier : public DominanceFrontierBase { 1002public: 1003 static char ID; // Pass ID, replacement for typeid 1004 DominanceFrontier() : 1005 DominanceFrontierBase(&ID, false) {} 1006 1007 BasicBlock *getRoot() const { 1008 assert(Roots.size() == 1 && "Should always have entry node!"); 1009 return Roots[0]; 1010 } 1011 1012 virtual bool runOnFunction(Function &) { 1013 Frontiers.clear(); 1014 DominatorTree &DT = getAnalysis<DominatorTree>(); 1015 Roots = DT.getRoots(); 1016 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!"); 1017 calculate(DT, DT[Roots[0]]); 1018 return false; 1019 } 1020 1021 virtual void verifyAnalysis() const; 1022 1023 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 1024 AU.setPreservesAll(); 1025 AU.addRequired<DominatorTree>(); 1026 } 1027 1028 /// splitBlock - BB is split and now it has one successor. Update dominance 1029 /// frontier to reflect this change. 1030 void splitBlock(BasicBlock *BB); 1031 1032 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier 1033 /// to reflect this change. 1034 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB, 1035 DominatorTree *DT) { 1036 // NewBB is now dominating BB. Which means BB's dominance 1037 // frontier is now part of NewBB's dominance frontier. However, BB 1038 // itself is not member of NewBB's dominance frontier. 1039 DominanceFrontier::iterator NewDFI = find(NewBB); 1040 DominanceFrontier::iterator DFI = find(BB); 1041 // If BB was an entry block then its frontier is empty. 1042 if (DFI == end()) 1043 return; 1044 DominanceFrontier::DomSetType BBSet = DFI->second; 1045 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(), 1046 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) { 1047 BasicBlock *DFMember = *BBSetI; 1048 // Insert only if NewBB dominates DFMember. 1049 if (!DT->dominates(NewBB, DFMember)) 1050 NewDFI->second.insert(DFMember); 1051 } 1052 NewDFI->second.erase(BB); 1053 } 1054 1055 const DomSetType &calculate(const DominatorTree &DT, 1056 const DomTreeNode *Node); 1057}; 1058 1059 1060} // End llvm namespace 1061 1062#endif 1063