1 //===- llvm/Analysis/Dominators.h - Dominator Info Calculation --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
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.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ANALYSIS_DOMINATORS_H
22 #define LLVM_ANALYSIS_DOMINATORS_H
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"
42 //===----------------------------------------------------------------------===//
43 /// DominatorBase - Base class that other, more interesting dominator analyses
46 template <class NodeT>
49 std::vector<NodeT*> Roots;
50 const bool IsPostDominators;
51 inline DominatorBase(bool isPostDom) :
52 Roots(), IsPostDominators(isPostDom) {}
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).
59 inline const std::vector<NodeT*> &getRoots() const { return Roots; }
61 /// isPostDominator - Returns true if analysis based of postdoms
63 bool isPostDominator() const { return IsPostDominators; }
67 //===----------------------------------------------------------------------===//
68 // DomTreeNode - Dominator Tree Node
69 template<class NodeT> class DominatorTreeBase;
70 struct PostDominatorTree;
71 class MachineBasicBlock;
73 template <class NodeT>
74 class DomTreeNodeBase {
76 DomTreeNodeBase<NodeT> *IDom;
77 std::vector<DomTreeNodeBase<NodeT> *> Children;
78 int DFSNumIn, DFSNumOut;
80 template<class N> friend class DominatorTreeBase;
81 friend struct PostDominatorTree;
83 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
84 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
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(); }
92 NodeT *getBlock() const { return TheBB; }
93 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
94 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
98 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
99 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
101 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
102 Children.push_back(C);
106 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
107 assert(IDom && "No immediate dominator?");
108 if (IDom != NewIDom) {
109 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
110 std::find(IDom->Children.begin(), IDom->Children.end(), this);
111 assert(I != IDom->Children.end() &&
112 "Not in immediate dominator children set!");
113 // I am no longer your child...
114 IDom->Children.erase(I);
116 // Switch to new dominator
118 IDom->Children.push_back(this);
122 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
124 unsigned getDFSNumIn() const { return DFSNumIn; }
125 unsigned getDFSNumOut() const { return DFSNumOut; }
127 // Return true if this node is dominated by other. Use this only if DFS info
129 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
130 return this->DFSNumIn >= other->DFSNumIn &&
131 this->DFSNumOut <= other->DFSNumOut;
135 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
136 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
138 template<class NodeT>
139 static std::ostream &operator<<(std::ostream &o,
140 const DomTreeNodeBase<NodeT> *Node) {
141 if (Node->getBlock())
142 WriteAsOperand(o, Node->getBlock(), false);
144 o << " <<exit node>>";
146 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
151 template<class NodeT>
152 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, std::ostream &o,
154 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
155 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
156 E = N->end(); I != E; ++I)
157 PrintDomTree<NodeT>(*I, o, Lev+1);
160 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
162 //===----------------------------------------------------------------------===//
163 /// DominatorTree - Calculate the immediate dominator tree for a function.
166 template<class FuncT, class N>
167 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
170 template<class NodeT>
171 class DominatorTreeBase : public DominatorBase<NodeT> {
173 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
174 DomTreeNodeMapType DomTreeNodes;
175 DomTreeNodeBase<NodeT> *RootNode;
178 unsigned int SlowQueries;
179 // Information record used during immediate dominators computation.
183 NodeT *Label, *Parent, *Child, *Ancestor;
185 std::vector<NodeT*> Bucket;
187 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0) {}
190 DenseMap<NodeT*, NodeT*> IDoms;
192 // Vertex - Map the DFS number to the BasicBlock*
193 std::vector<NodeT*> Vertex;
195 // Info - Collection of information used during the computation of idoms.
196 DenseMap<NodeT*, InfoRec> Info;
199 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
200 E = DomTreeNodes.end(); I != E; ++I)
202 DomTreeNodes.clear();
209 // NewBB is split and now it has one successor. Update dominator tree to
210 // reflect this change.
211 template<class N, class GraphT>
212 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
213 typename GraphT::NodeType* NewBB) {
214 assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
215 && "NewBB should have a single successor!");
216 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
218 std::vector<typename GraphT::NodeType*> PredBlocks;
219 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
220 GraphTraits<Inverse<N> >::child_begin(NewBB),
221 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
222 PredBlocks.push_back(*PI);
224 assert(!PredBlocks.empty() && "No predblocks??");
226 // The newly inserted basic block will dominate existing basic blocks iff the
227 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
228 // the non-pred blocks, then they all must be the same block!
230 bool NewBBDominatesNewBBSucc = true;
232 typename GraphT::NodeType* OnePred = PredBlocks[0];
233 unsigned i = 1, e = PredBlocks.size();
234 for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
235 assert(i != e && "Didn't find reachable pred?");
236 OnePred = PredBlocks[i];
240 if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
241 NewBBDominatesNewBBSucc = false;
245 if (NewBBDominatesNewBBSucc)
246 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
247 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
248 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
249 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
250 NewBBDominatesNewBBSucc = false;
255 // The other scenario where the new block can dominate its successors are when
256 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
258 if (!NewBBDominatesNewBBSucc) {
259 NewBBDominatesNewBBSucc = true;
260 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
261 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
262 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
263 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
264 NewBBDominatesNewBBSucc = false;
269 // Find NewBB's immediate dominator and create new dominator tree node for
271 NodeT *NewBBIDom = 0;
273 for (i = 0; i < PredBlocks.size(); ++i)
274 if (DT.isReachableFromEntry(PredBlocks[i])) {
275 NewBBIDom = PredBlocks[i];
278 assert(i != PredBlocks.size() && "No reachable preds?");
279 for (i = i + 1; i < PredBlocks.size(); ++i) {
280 if (DT.isReachableFromEntry(PredBlocks[i]))
281 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
283 assert(NewBBIDom && "No immediate dominator found??");
285 // Create the new dominator tree node... and set the idom of NewBB.
286 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
288 // If NewBB strictly dominates other blocks, then it is now the immediate
289 // dominator of NewBBSucc. Update the dominator tree as appropriate.
290 if (NewBBDominatesNewBBSucc) {
291 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
292 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
297 DominatorTreeBase(bool isPostDom)
298 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
299 virtual ~DominatorTreeBase() { reset(); }
301 // FIXME: Should remove this
302 virtual bool runOnFunction(Function &F) { return false; }
304 virtual void releaseMemory() { reset(); }
306 /// getNode - return the (Post)DominatorTree node for the specified basic
307 /// block. This is the same as using operator[] on this class.
309 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
310 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
311 return I != DomTreeNodes.end() ? I->second : 0;
314 /// getRootNode - This returns the entry node for the CFG of the function. If
315 /// this tree represents the post-dominance relations for a function, however,
316 /// this root may be a node with the block == NULL. This is the case when
317 /// there are multiple exit nodes from a particular function. Consumers of
318 /// post-dominance information must be capable of dealing with this
321 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
322 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
324 /// properlyDominates - Returns true iff this dominates N and this != N.
325 /// Note that this is not a constant time operation!
327 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
328 DomTreeNodeBase<NodeT> *B) const {
329 if (A == 0 || B == 0) return false;
330 return dominatedBySlowTreeWalk(A, B);
333 inline bool properlyDominates(NodeT *A, NodeT *B) {
334 return properlyDominates(getNode(A), getNode(B));
337 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
338 const DomTreeNodeBase<NodeT> *B) const {
339 const DomTreeNodeBase<NodeT> *IDom;
340 if (A == 0 || B == 0) return false;
341 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
342 B = IDom; // Walk up the tree
347 /// isReachableFromEntry - Return true if A is dominated by the entry
348 /// block of the function containing it.
349 bool isReachableFromEntry(NodeT* A) {
350 assert (!this->isPostDominator()
351 && "This is not implemented for post dominators");
352 return dominates(&A->getParent()->front(), A);
355 /// dominates - Returns true iff A dominates B. Note that this is not a
356 /// constant time operation!
358 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
359 DomTreeNodeBase<NodeT> *B) {
361 return true; // A node trivially dominates itself.
363 if (A == 0 || B == 0)
367 return B->DominatedBy(A);
369 // If we end up with too many slow queries, just update the
370 // DFS numbers on the theory that we are going to keep querying.
372 if (SlowQueries > 32) {
374 return B->DominatedBy(A);
377 return dominatedBySlowTreeWalk(A, B);
380 inline bool dominates(NodeT *A, NodeT *B) {
384 return dominates(getNode(A), getNode(B));
387 NodeT *getRoot() const {
388 assert(this->Roots.size() == 1 && "Should always have entry node!");
389 return this->Roots[0];
392 /// findNearestCommonDominator - Find nearest common dominator basic block
393 /// for basic block A and B. If there is no such block then return NULL.
394 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
396 assert (!this->isPostDominator()
397 && "This is not implemented for post dominators");
398 assert (A->getParent() == B->getParent()
399 && "Two blocks are not in same function");
401 // If either A or B is a entry block then it is nearest common dominator.
402 NodeT &Entry = A->getParent()->front();
403 if (A == &Entry || B == &Entry)
406 // If B dominates A then B is nearest common dominator.
410 // If A dominates B then A is nearest common dominator.
414 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
415 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
417 // Collect NodeA dominators set.
418 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
419 NodeADoms.insert(NodeA);
420 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
422 NodeADoms.insert(IDomA);
423 IDomA = IDomA->getIDom();
426 // Walk NodeB immediate dominators chain and find common dominator node.
427 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
429 if (NodeADoms.count(IDomB) != 0)
430 return IDomB->getBlock();
432 IDomB = IDomB->getIDom();
438 //===--------------------------------------------------------------------===//
439 // API to update (Post)DominatorTree information based on modifications to
442 /// addNewBlock - Add a new node to the dominator tree information. This
443 /// creates a new node as a child of DomBB dominator node,linking it into
444 /// the children list of the immediate dominator.
445 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
446 assert(getNode(BB) == 0 && "Block already in dominator tree!");
447 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
448 assert(IDomNode && "Not immediate dominator specified for block!");
449 DFSInfoValid = false;
450 return DomTreeNodes[BB] =
451 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
454 /// changeImmediateDominator - This method is used to update the dominator
455 /// tree information when a node's immediate dominator changes.
457 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
458 DomTreeNodeBase<NodeT> *NewIDom) {
459 assert(N && NewIDom && "Cannot change null node pointers!");
460 DFSInfoValid = false;
464 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
465 changeImmediateDominator(getNode(BB), getNode(NewBB));
468 /// eraseNode - Removes a node from the dominator tree. Block must not
469 /// domiante any other blocks. Removes node from its immediate dominator's
470 /// children list. Deletes dominator node associated with basic block BB.
471 void eraseNode(NodeT *BB) {
472 DomTreeNodeBase<NodeT> *Node = getNode(BB);
473 assert (Node && "Removing node that isn't in dominator tree.");
474 assert (Node->getChildren().empty() && "Node is not a leaf node.");
476 // Remove node from immediate dominator's children list.
477 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
479 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
480 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
481 assert(I != IDom->Children.end() &&
482 "Not in immediate dominator children set!");
483 // I am no longer your child...
484 IDom->Children.erase(I);
487 DomTreeNodes.erase(BB);
491 /// removeNode - Removes a node from the dominator tree. Block must not
492 /// dominate any other blocks. Invalidates any node pointing to removed
494 void removeNode(NodeT *BB) {
495 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
496 DomTreeNodes.erase(BB);
499 /// splitBlock - BB is split and now it has one successor. Update dominator
500 /// tree to reflect this change.
501 void splitBlock(NodeT* NewBB) {
502 if (this->IsPostDominators)
503 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
505 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
508 /// print - Convert to human readable form
510 virtual void print(std::ostream &o, const Module* ) const {
511 o << "=============================--------------------------------\n";
512 if (this->isPostDominator())
513 o << "Inorder PostDominator Tree: ";
515 o << "Inorder Dominator Tree: ";
516 if (this->DFSInfoValid)
517 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
520 PrintDomTree<NodeT>(getRootNode(), o, 1);
523 void print(std::ostream *OS, const Module* M = 0) const {
524 if (OS) print(*OS, M);
527 virtual void dump() {
532 template<class GraphT>
533 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
534 typename GraphT::NodeType* VIn);
536 template<class GraphT>
537 friend typename GraphT::NodeType* Eval(
538 DominatorTreeBase<typename GraphT::NodeType>& DT,
539 typename GraphT::NodeType* V);
541 template<class GraphT>
542 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
543 typename GraphT::NodeType* V,
544 typename GraphT::NodeType* W,
545 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
547 template<class GraphT>
548 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
549 typename GraphT::NodeType* V,
552 template<class FuncT, class N>
553 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
556 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
557 /// dominator tree in dfs order.
558 void updateDFSNumbers() {
561 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
562 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
564 for (unsigned i = 0, e = this->Roots.size(); i != e; ++i) {
565 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
566 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
567 ThisRoot->DFSNumIn = DFSNum++;
569 while (!WorkStack.empty()) {
570 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
571 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
572 WorkStack.back().second;
574 // If we visited all of the children of this node, "recurse" back up the
575 // stack setting the DFOutNum.
576 if (ChildIt == Node->end()) {
577 Node->DFSNumOut = DFSNum++;
578 WorkStack.pop_back();
580 // Otherwise, recursively visit this child.
581 DomTreeNodeBase<NodeT> *Child = *ChildIt;
582 ++WorkStack.back().second;
584 WorkStack.push_back(std::make_pair(Child, Child->begin()));
585 Child->DFSNumIn = DFSNum++;
594 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
595 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
598 // Haven't calculated this node yet? Get or calculate the node for the
599 // immediate dominator.
600 NodeT *IDom = getIDom(BB);
601 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
603 // Add a new tree node for this BasicBlock, and link it as a child of
605 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
606 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
609 inline NodeT *getIDom(NodeT *BB) const {
610 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
611 return I != IDoms.end() ? I->second : 0;
614 inline void addRoot(NodeT* BB) {
615 // Unreachable block is not a root node.
616 if (!isa<UnreachableInst>(&BB->back()))
617 this->Roots.push_back(BB);
621 /// recalculate - compute a dominator tree for the given function
623 void recalculate(FT& F) {
624 if (!this->IsPostDominators) {
628 this->Roots.push_back(&F.front());
629 this->IDoms[&F.front()] = 0;
630 this->DomTreeNodes[&F.front()] = 0;
631 this->Vertex.push_back(0);
633 Calculate<FT, NodeT*>(*this, F);
637 reset(); // Reset from the last time we were run...
639 // Initialize the roots list
640 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
641 if (std::distance(GraphTraits<FT*>::child_begin(I),
642 GraphTraits<FT*>::child_end(I)) == 0)
645 // Prepopulate maps so that we don't get iterator invalidation issues later.
647 this->DomTreeNodes[I] = 0;
650 this->Vertex.push_back(0);
652 Calculate<FT, Inverse<NodeT*> >(*this, F);
657 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
659 //===-------------------------------------
660 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
661 /// compute a normal dominator tree.
663 class DominatorTree : public FunctionPass {
665 static char ID; // Pass ID, replacement for typeid
666 DominatorTreeBase<BasicBlock>* DT;
668 DominatorTree() : FunctionPass(intptr_t(&ID)) {
669 DT = new DominatorTreeBase<BasicBlock>(false);
677 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
679 /// getRoots - Return the root blocks of the current CFG. This may include
680 /// multiple blocks if we are computing post dominators. For forward
681 /// dominators, this will always be a single block (the entry node).
683 inline const std::vector<BasicBlock*> &getRoots() const {
684 return DT->getRoots();
687 inline BasicBlock *getRoot() const {
688 return DT->getRoot();
691 inline DomTreeNode *getRootNode() const {
692 return DT->getRootNode();
695 virtual bool runOnFunction(Function &F);
697 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
698 AU.setPreservesAll();
701 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
702 return DT->dominates(A, B);
705 inline bool dominates(BasicBlock* A, BasicBlock* B) const {
706 return DT->dominates(A, B);
709 // dominates - Return true if A dominates B. This performs the
710 // special checks necessary if A and B are in the same basic block.
711 bool dominates(Instruction *A, Instruction *B) const {
712 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
713 if (BBA != BBB) return DT->dominates(BBA, BBB);
715 // It is not possible to determine dominance between two PHI nodes
716 // based on their ordering.
717 if (isa<PHINode>(A) && isa<PHINode>(B))
720 // Loop through the basic block until we find A or B.
721 BasicBlock::iterator I = BBA->begin();
722 for (; &*I != A && &*I != B; ++I) /*empty*/;
724 //if(!DT.IsPostDominators) {
725 // A dominates B if it is found first in the basic block.
728 // // A post-dominates B if B is found first in the basic block.
733 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
734 return DT->properlyDominates(A, B);
737 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
738 return DT->properlyDominates(A, B);
741 /// findNearestCommonDominator - Find nearest common dominator basic block
742 /// for basic block A and B. If there is no such block then return NULL.
743 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
744 return DT->findNearestCommonDominator(A, B);
747 inline DomTreeNode *operator[](BasicBlock *BB) const {
748 return DT->getNode(BB);
751 /// getNode - return the (Post)DominatorTree node for the specified basic
752 /// block. This is the same as using operator[] on this class.
754 inline DomTreeNode *getNode(BasicBlock *BB) const {
755 return DT->getNode(BB);
758 /// addNewBlock - Add a new node to the dominator tree information. This
759 /// creates a new node as a child of DomBB dominator node,linking it into
760 /// the children list of the immediate dominator.
761 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
762 return DT->addNewBlock(BB, DomBB);
765 /// changeImmediateDominator - This method is used to update the dominator
766 /// tree information when a node's immediate dominator changes.
768 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
769 DT->changeImmediateDominator(N, NewIDom);
772 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
773 DT->changeImmediateDominator(N, NewIDom);
776 /// eraseNode - Removes a node from the dominator tree. Block must not
777 /// domiante any other blocks. Removes node from its immediate dominator's
778 /// children list. Deletes dominator node associated with basic block BB.
779 inline void eraseNode(BasicBlock *BB) {
783 /// splitBlock - BB is split and now it has one successor. Update dominator
784 /// tree to reflect this change.
785 inline void splitBlock(BasicBlock* NewBB) {
786 DT->splitBlock(NewBB);
790 virtual void releaseMemory() {
794 virtual void print(std::ostream &OS, const Module* M= 0) const {
799 //===-------------------------------------
800 /// DominatorTree GraphTraits specialization so the DominatorTree can be
801 /// iterable by generic graph iterators.
803 template <> struct GraphTraits<DomTreeNode *> {
804 typedef DomTreeNode NodeType;
805 typedef NodeType::iterator ChildIteratorType;
807 static NodeType *getEntryNode(NodeType *N) {
810 static inline ChildIteratorType child_begin(NodeType* N) {
813 static inline ChildIteratorType child_end(NodeType* N) {
818 template <> struct GraphTraits<DominatorTree*>
819 : public GraphTraits<DomTreeNode *> {
820 static NodeType *getEntryNode(DominatorTree *DT) {
821 return DT->getRootNode();
826 //===----------------------------------------------------------------------===//
827 /// DominanceFrontierBase - Common base class for computing forward and inverse
828 /// dominance frontiers for a function.
830 class DominanceFrontierBase : public FunctionPass {
832 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
833 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
835 DomSetMapType Frontiers;
836 std::vector<BasicBlock*> Roots;
837 const bool IsPostDominators;
840 DominanceFrontierBase(intptr_t ID, bool isPostDom)
841 : FunctionPass(ID), IsPostDominators(isPostDom) {}
843 /// getRoots - Return the root blocks of the current CFG. This may include
844 /// multiple blocks if we are computing post dominators. For forward
845 /// dominators, this will always be a single block (the entry node).
847 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
849 /// isPostDominator - Returns true if analysis based of postdoms
851 bool isPostDominator() const { return IsPostDominators; }
853 virtual void releaseMemory() { Frontiers.clear(); }
855 // Accessor interface:
856 typedef DomSetMapType::iterator iterator;
857 typedef DomSetMapType::const_iterator const_iterator;
858 iterator begin() { return Frontiers.begin(); }
859 const_iterator begin() const { return Frontiers.begin(); }
860 iterator end() { return Frontiers.end(); }
861 const_iterator end() const { return Frontiers.end(); }
862 iterator find(BasicBlock *B) { return Frontiers.find(B); }
863 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
865 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
866 assert(find(BB) == end() && "Block already in DominanceFrontier!");
867 Frontiers.insert(std::make_pair(BB, frontier));
870 /// removeBlock - Remove basic block BB's frontier.
871 void removeBlock(BasicBlock *BB) {
872 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
873 for (iterator I = begin(), E = end(); I != E; ++I)
878 void addToFrontier(iterator I, BasicBlock *Node) {
879 assert(I != end() && "BB is not in DominanceFrontier!");
880 I->second.insert(Node);
883 void removeFromFrontier(iterator I, BasicBlock *Node) {
884 assert(I != end() && "BB is not in DominanceFrontier!");
885 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
886 I->second.erase(Node);
889 /// print - Convert to human readable form
891 virtual void print(std::ostream &OS, const Module* = 0) const;
892 void print(std::ostream *OS, const Module* M = 0) const {
893 if (OS) print(*OS, M);
899 //===-------------------------------------
900 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
901 /// used to compute a forward dominator frontiers.
903 class DominanceFrontier : public DominanceFrontierBase {
905 static char ID; // Pass ID, replacement for typeid
906 DominanceFrontier() :
907 DominanceFrontierBase(intptr_t(&ID), false) {}
909 BasicBlock *getRoot() const {
910 assert(Roots.size() == 1 && "Should always have entry node!");
914 virtual bool runOnFunction(Function &) {
916 DominatorTree &DT = getAnalysis<DominatorTree>();
917 Roots = DT.getRoots();
918 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
919 calculate(DT, DT[Roots[0]]);
923 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
924 AU.setPreservesAll();
925 AU.addRequired<DominatorTree>();
928 /// splitBlock - BB is split and now it has one successor. Update dominance
929 /// frontier to reflect this change.
930 void splitBlock(BasicBlock *BB);
932 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
933 /// to reflect this change.
934 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
936 // NewBB is now dominating BB. Which means BB's dominance
937 // frontier is now part of NewBB's dominance frontier. However, BB
938 // itself is not member of NewBB's dominance frontier.
939 DominanceFrontier::iterator NewDFI = find(NewBB);
940 DominanceFrontier::iterator DFI = find(BB);
941 DominanceFrontier::DomSetType BBSet = DFI->second;
942 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
943 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
944 BasicBlock *DFMember = *BBSetI;
945 // Insert only if NewBB dominates DFMember.
946 if (!DT->dominates(NewBB, DFMember))
947 NewDFI->second.insert(DFMember);
949 NewDFI->second.erase(BB);
953 const DomSetType &calculate(const DominatorTree &DT,
954 const DomTreeNode *Node);
958 } // End llvm namespace