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