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 explicit 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 size_t getNumChildren() const {
107 return Children.size();
110 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
111 assert(IDom && "No immediate dominator?");
112 if (IDom != NewIDom) {
113 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
114 std::find(IDom->Children.begin(), IDom->Children.end(), this);
115 assert(I != IDom->Children.end() &&
116 "Not in immediate dominator children set!");
117 // I am no longer your child...
118 IDom->Children.erase(I);
120 // Switch to new dominator
122 IDom->Children.push_back(this);
126 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
128 unsigned getDFSNumIn() const { return DFSNumIn; }
129 unsigned getDFSNumOut() const { return DFSNumOut; }
131 // Return true if this node is dominated by other. Use this only if DFS info
133 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
134 return this->DFSNumIn >= other->DFSNumIn &&
135 this->DFSNumOut <= other->DFSNumOut;
139 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
140 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
142 template<class NodeT>
143 static std::ostream &operator<<(std::ostream &o,
144 const DomTreeNodeBase<NodeT> *Node) {
145 if (Node->getBlock())
146 WriteAsOperand(o, Node->getBlock(), false);
148 o << " <<exit node>>";
150 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
155 template<class NodeT>
156 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, std::ostream &o,
158 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
159 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
160 E = N->end(); I != E; ++I)
161 PrintDomTree<NodeT>(*I, o, Lev+1);
164 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
166 //===----------------------------------------------------------------------===//
167 /// DominatorTree - Calculate the immediate dominator tree for a function.
170 template<class FuncT, class N>
171 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
174 template<class NodeT>
175 class DominatorTreeBase : public DominatorBase<NodeT> {
177 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
178 DomTreeNodeMapType DomTreeNodes;
179 DomTreeNodeBase<NodeT> *RootNode;
182 unsigned int SlowQueries;
183 // Information record used during immediate dominators computation.
187 NodeT *Label, *Parent, *Child, *Ancestor;
189 std::vector<NodeT*> Bucket;
191 InfoRec() : Semi(0), Size(0), Label(0), Parent(0), Child(0), Ancestor(0) {}
194 DenseMap<NodeT*, NodeT*> IDoms;
196 // Vertex - Map the DFS number to the BasicBlock*
197 std::vector<NodeT*> Vertex;
199 // Info - Collection of information used during the computation of idoms.
200 DenseMap<NodeT*, InfoRec> Info;
203 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
204 E = DomTreeNodes.end(); I != E; ++I)
206 DomTreeNodes.clear();
213 // NewBB is split and now it has one successor. Update dominator tree to
214 // reflect this change.
215 template<class N, class GraphT>
216 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
217 typename GraphT::NodeType* NewBB) {
218 assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
219 && "NewBB should have a single successor!");
220 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
222 std::vector<typename GraphT::NodeType*> PredBlocks;
223 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
224 GraphTraits<Inverse<N> >::child_begin(NewBB),
225 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
226 PredBlocks.push_back(*PI);
228 assert(!PredBlocks.empty() && "No predblocks??");
230 // The newly inserted basic block will dominate existing basic blocks iff the
231 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
232 // the non-pred blocks, then they all must be the same block!
234 bool NewBBDominatesNewBBSucc = true;
236 typename GraphT::NodeType* OnePred = PredBlocks[0];
237 unsigned i = 1, e = PredBlocks.size();
238 for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
239 assert(i != e && "Didn't find reachable pred?");
240 OnePred = PredBlocks[i];
244 if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
245 NewBBDominatesNewBBSucc = false;
249 if (NewBBDominatesNewBBSucc)
250 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
251 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
252 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
253 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
254 NewBBDominatesNewBBSucc = false;
259 // The other scenario where the new block can dominate its successors are when
260 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
262 if (!NewBBDominatesNewBBSucc) {
263 NewBBDominatesNewBBSucc = true;
264 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
265 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
266 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
267 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
268 NewBBDominatesNewBBSucc = false;
273 // Find NewBB's immediate dominator and create new dominator tree node for
275 NodeT *NewBBIDom = 0;
277 for (i = 0; i < PredBlocks.size(); ++i)
278 if (DT.isReachableFromEntry(PredBlocks[i])) {
279 NewBBIDom = PredBlocks[i];
282 assert(i != PredBlocks.size() && "No reachable preds?");
283 for (i = i + 1; i < PredBlocks.size(); ++i) {
284 if (DT.isReachableFromEntry(PredBlocks[i]))
285 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
287 assert(NewBBIDom && "No immediate dominator found??");
289 // Create the new dominator tree node... and set the idom of NewBB.
290 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
292 // If NewBB strictly dominates other blocks, then it is now the immediate
293 // dominator of NewBBSucc. Update the dominator tree as appropriate.
294 if (NewBBDominatesNewBBSucc) {
295 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
296 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
301 explicit DominatorTreeBase(bool isPostDom)
302 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
303 virtual ~DominatorTreeBase() { reset(); }
305 // FIXME: Should remove this
306 virtual bool runOnFunction(Function &F) { return false; }
308 virtual void releaseMemory() { reset(); }
310 /// getNode - return the (Post)DominatorTree node for the specified basic
311 /// block. This is the same as using operator[] on this class.
313 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
314 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
315 return I != DomTreeNodes.end() ? I->second : 0;
318 /// getRootNode - This returns the entry node for the CFG of the function. If
319 /// this tree represents the post-dominance relations for a function, however,
320 /// this root may be a node with the block == NULL. This is the case when
321 /// there are multiple exit nodes from a particular function. Consumers of
322 /// post-dominance information must be capable of dealing with this
325 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
326 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
328 /// properlyDominates - Returns true iff this dominates N and this != N.
329 /// Note that this is not a constant time operation!
331 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
332 DomTreeNodeBase<NodeT> *B) const {
333 if (A == 0 || B == 0) return false;
334 return dominatedBySlowTreeWalk(A, B);
337 inline bool properlyDominates(NodeT *A, NodeT *B) {
338 return properlyDominates(getNode(A), getNode(B));
341 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
342 const DomTreeNodeBase<NodeT> *B) const {
343 const DomTreeNodeBase<NodeT> *IDom;
344 if (A == 0 || B == 0) return false;
345 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
346 B = IDom; // Walk up the tree
351 /// isReachableFromEntry - Return true if A is dominated by the entry
352 /// block of the function containing it.
353 bool isReachableFromEntry(NodeT* A) {
354 assert (!this->isPostDominator()
355 && "This is not implemented for post dominators");
356 return dominates(&A->getParent()->front(), A);
359 /// dominates - Returns true iff A dominates B. Note that this is not a
360 /// constant time operation!
362 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
363 DomTreeNodeBase<NodeT> *B) {
365 return true; // A node trivially dominates itself.
367 if (A == 0 || B == 0)
371 return B->DominatedBy(A);
373 // If we end up with too many slow queries, just update the
374 // DFS numbers on the theory that we are going to keep querying.
376 if (SlowQueries > 32) {
378 return B->DominatedBy(A);
381 return dominatedBySlowTreeWalk(A, B);
384 inline bool dominates(NodeT *A, NodeT *B) {
388 return dominates(getNode(A), getNode(B));
391 NodeT *getRoot() const {
392 assert(this->Roots.size() == 1 && "Should always have entry node!");
393 return this->Roots[0];
396 /// findNearestCommonDominator - Find nearest common dominator basic block
397 /// for basic block A and B. If there is no such block then return NULL.
398 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
400 assert (!this->isPostDominator()
401 && "This is not implemented for post dominators");
402 assert (A->getParent() == B->getParent()
403 && "Two blocks are not in same function");
405 // If either A or B is a entry block then it is nearest common dominator.
406 NodeT &Entry = A->getParent()->front();
407 if (A == &Entry || B == &Entry)
410 // If B dominates A then B is nearest common dominator.
414 // If A dominates B then A is nearest common dominator.
418 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
419 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
421 // Collect NodeA dominators set.
422 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
423 NodeADoms.insert(NodeA);
424 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
426 NodeADoms.insert(IDomA);
427 IDomA = IDomA->getIDom();
430 // Walk NodeB immediate dominators chain and find common dominator node.
431 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
433 if (NodeADoms.count(IDomB) != 0)
434 return IDomB->getBlock();
436 IDomB = IDomB->getIDom();
442 //===--------------------------------------------------------------------===//
443 // API to update (Post)DominatorTree information based on modifications to
446 /// addNewBlock - Add a new node to the dominator tree information. This
447 /// creates a new node as a child of DomBB dominator node,linking it into
448 /// the children list of the immediate dominator.
449 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
450 assert(getNode(BB) == 0 && "Block already in dominator tree!");
451 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
452 assert(IDomNode && "Not immediate dominator specified for block!");
453 DFSInfoValid = false;
454 return DomTreeNodes[BB] =
455 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
458 /// changeImmediateDominator - This method is used to update the dominator
459 /// tree information when a node's immediate dominator changes.
461 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
462 DomTreeNodeBase<NodeT> *NewIDom) {
463 assert(N && NewIDom && "Cannot change null node pointers!");
464 DFSInfoValid = false;
468 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
469 changeImmediateDominator(getNode(BB), getNode(NewBB));
472 /// eraseNode - Removes a node from the dominator tree. Block must not
473 /// domiante any other blocks. Removes node from its immediate dominator's
474 /// children list. Deletes dominator node associated with basic block BB.
475 void eraseNode(NodeT *BB) {
476 DomTreeNodeBase<NodeT> *Node = getNode(BB);
477 assert (Node && "Removing node that isn't in dominator tree.");
478 assert (Node->getChildren().empty() && "Node is not a leaf node.");
480 // Remove node from immediate dominator's children list.
481 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
483 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
484 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
485 assert(I != IDom->Children.end() &&
486 "Not in immediate dominator children set!");
487 // I am no longer your child...
488 IDom->Children.erase(I);
491 DomTreeNodes.erase(BB);
495 /// removeNode - Removes a node from the dominator tree. Block must not
496 /// dominate any other blocks. Invalidates any node pointing to removed
498 void removeNode(NodeT *BB) {
499 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
500 DomTreeNodes.erase(BB);
503 /// splitBlock - BB is split and now it has one successor. Update dominator
504 /// tree to reflect this change.
505 void splitBlock(NodeT* NewBB) {
506 if (this->IsPostDominators)
507 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
509 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
512 /// print - Convert to human readable form
514 virtual void print(std::ostream &o, const Module* ) const {
515 o << "=============================--------------------------------\n";
516 if (this->isPostDominator())
517 o << "Inorder PostDominator Tree: ";
519 o << "Inorder Dominator Tree: ";
520 if (this->DFSInfoValid)
521 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
524 PrintDomTree<NodeT>(getRootNode(), o, 1);
527 void print(std::ostream *OS, const Module* M = 0) const {
528 if (OS) print(*OS, M);
531 virtual void dump() {
536 template<class GraphT>
537 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
538 typename GraphT::NodeType* VIn);
540 template<class GraphT>
541 friend typename GraphT::NodeType* Eval(
542 DominatorTreeBase<typename GraphT::NodeType>& DT,
543 typename GraphT::NodeType* V);
545 template<class GraphT>
546 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
547 typename GraphT::NodeType* V,
548 typename GraphT::NodeType* W,
549 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
551 template<class GraphT>
552 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
553 typename GraphT::NodeType* V,
556 template<class FuncT, class N>
557 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
560 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
561 /// dominator tree in dfs order.
562 void updateDFSNumbers() {
565 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
566 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
568 for (unsigned i = 0, e = this->Roots.size(); i != e; ++i) {
569 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
570 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
571 ThisRoot->DFSNumIn = DFSNum++;
573 while (!WorkStack.empty()) {
574 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
575 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
576 WorkStack.back().second;
578 // If we visited all of the children of this node, "recurse" back up the
579 // stack setting the DFOutNum.
580 if (ChildIt == Node->end()) {
581 Node->DFSNumOut = DFSNum++;
582 WorkStack.pop_back();
584 // Otherwise, recursively visit this child.
585 DomTreeNodeBase<NodeT> *Child = *ChildIt;
586 ++WorkStack.back().second;
588 WorkStack.push_back(std::make_pair(Child, Child->begin()));
589 Child->DFSNumIn = DFSNum++;
598 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
599 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
602 // Haven't calculated this node yet? Get or calculate the node for the
603 // immediate dominator.
604 NodeT *IDom = getIDom(BB);
605 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
607 // Add a new tree node for this BasicBlock, and link it as a child of
609 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
610 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
613 inline NodeT *getIDom(NodeT *BB) const {
614 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
615 return I != IDoms.end() ? I->second : 0;
618 inline void addRoot(NodeT* BB) {
619 // Unreachable block is not a root node.
620 if (!isa<UnreachableInst>(&BB->back()))
621 this->Roots.push_back(BB);
625 /// recalculate - compute a dominator tree for the given function
627 void recalculate(FT& F) {
628 if (!this->IsPostDominators) {
632 this->Roots.push_back(&F.front());
633 this->IDoms[&F.front()] = 0;
634 this->DomTreeNodes[&F.front()] = 0;
635 this->Vertex.push_back(0);
637 Calculate<FT, NodeT*>(*this, F);
641 reset(); // Reset from the last time we were run...
643 // Initialize the roots list
644 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
645 if (std::distance(GraphTraits<FT*>::child_begin(I),
646 GraphTraits<FT*>::child_end(I)) == 0)
649 // Prepopulate maps so that we don't get iterator invalidation issues later.
651 this->DomTreeNodes[I] = 0;
654 this->Vertex.push_back(0);
656 Calculate<FT, Inverse<NodeT*> >(*this, F);
661 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
663 //===-------------------------------------
664 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
665 /// compute a normal dominator tree.
667 class DominatorTree : public FunctionPass {
669 static char ID; // Pass ID, replacement for typeid
670 DominatorTreeBase<BasicBlock>* DT;
672 DominatorTree() : FunctionPass(intptr_t(&ID)) {
673 DT = new DominatorTreeBase<BasicBlock>(false);
681 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
683 /// getRoots - Return the root blocks of the current CFG. This may include
684 /// multiple blocks if we are computing post dominators. For forward
685 /// dominators, this will always be a single block (the entry node).
687 inline const std::vector<BasicBlock*> &getRoots() const {
688 return DT->getRoots();
691 inline BasicBlock *getRoot() const {
692 return DT->getRoot();
695 inline DomTreeNode *getRootNode() const {
696 return DT->getRootNode();
699 virtual bool runOnFunction(Function &F);
701 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
702 AU.setPreservesAll();
705 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
706 return DT->dominates(A, B);
709 inline bool dominates(BasicBlock* A, BasicBlock* B) const {
710 return DT->dominates(A, B);
713 // dominates - Return true if A dominates B. This performs the
714 // special checks necessary if A and B are in the same basic block.
715 bool dominates(Instruction *A, Instruction *B) const {
716 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
717 if (BBA != BBB) return DT->dominates(BBA, BBB);
719 // It is not possible to determine dominance between two PHI nodes
720 // based on their ordering.
721 if (isa<PHINode>(A) && isa<PHINode>(B))
724 // Loop through the basic block until we find A or B.
725 BasicBlock::iterator I = BBA->begin();
726 for (; &*I != A && &*I != B; ++I) /*empty*/;
728 //if(!DT.IsPostDominators) {
729 // A dominates B if it is found first in the basic block.
732 // // A post-dominates B if B is found first in the basic block.
737 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
738 return DT->properlyDominates(A, B);
741 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
742 return DT->properlyDominates(A, B);
745 /// findNearestCommonDominator - Find nearest common dominator basic block
746 /// for basic block A and B. If there is no such block then return NULL.
747 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
748 return DT->findNearestCommonDominator(A, B);
751 inline DomTreeNode *operator[](BasicBlock *BB) const {
752 return DT->getNode(BB);
755 /// getNode - return the (Post)DominatorTree node for the specified basic
756 /// block. This is the same as using operator[] on this class.
758 inline DomTreeNode *getNode(BasicBlock *BB) const {
759 return DT->getNode(BB);
762 /// addNewBlock - Add a new node to the dominator tree information. This
763 /// creates a new node as a child of DomBB dominator node,linking it into
764 /// the children list of the immediate dominator.
765 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
766 return DT->addNewBlock(BB, DomBB);
769 /// changeImmediateDominator - This method is used to update the dominator
770 /// tree information when a node's immediate dominator changes.
772 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
773 DT->changeImmediateDominator(N, NewIDom);
776 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
777 DT->changeImmediateDominator(N, NewIDom);
780 /// eraseNode - Removes a node from the dominator tree. Block must not
781 /// domiante any other blocks. Removes node from its immediate dominator's
782 /// children list. Deletes dominator node associated with basic block BB.
783 inline void eraseNode(BasicBlock *BB) {
787 /// splitBlock - BB is split and now it has one successor. Update dominator
788 /// tree to reflect this change.
789 inline void splitBlock(BasicBlock* NewBB) {
790 DT->splitBlock(NewBB);
794 virtual void releaseMemory() {
798 virtual void print(std::ostream &OS, const Module* M= 0) const {
803 //===-------------------------------------
804 /// DominatorTree GraphTraits specialization so the DominatorTree can be
805 /// iterable by generic graph iterators.
807 template <> struct GraphTraits<DomTreeNode *> {
808 typedef DomTreeNode NodeType;
809 typedef NodeType::iterator ChildIteratorType;
811 static NodeType *getEntryNode(NodeType *N) {
814 static inline ChildIteratorType child_begin(NodeType* N) {
817 static inline ChildIteratorType child_end(NodeType* N) {
822 template <> struct GraphTraits<DominatorTree*>
823 : public GraphTraits<DomTreeNode *> {
824 static NodeType *getEntryNode(DominatorTree *DT) {
825 return DT->getRootNode();
830 //===----------------------------------------------------------------------===//
831 /// DominanceFrontierBase - Common base class for computing forward and inverse
832 /// dominance frontiers for a function.
834 class DominanceFrontierBase : public FunctionPass {
836 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
837 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
839 DomSetMapType Frontiers;
840 std::vector<BasicBlock*> Roots;
841 const bool IsPostDominators;
844 DominanceFrontierBase(intptr_t ID, bool isPostDom)
845 : FunctionPass(ID), IsPostDominators(isPostDom) {}
847 /// getRoots - Return the root blocks of the current CFG. This may include
848 /// multiple blocks if we are computing post dominators. For forward
849 /// dominators, this will always be a single block (the entry node).
851 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
853 /// isPostDominator - Returns true if analysis based of postdoms
855 bool isPostDominator() const { return IsPostDominators; }
857 virtual void releaseMemory() { Frontiers.clear(); }
859 // Accessor interface:
860 typedef DomSetMapType::iterator iterator;
861 typedef DomSetMapType::const_iterator const_iterator;
862 iterator begin() { return Frontiers.begin(); }
863 const_iterator begin() const { return Frontiers.begin(); }
864 iterator end() { return Frontiers.end(); }
865 const_iterator end() const { return Frontiers.end(); }
866 iterator find(BasicBlock *B) { return Frontiers.find(B); }
867 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
869 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
870 assert(find(BB) == end() && "Block already in DominanceFrontier!");
871 Frontiers.insert(std::make_pair(BB, frontier));
874 /// removeBlock - Remove basic block BB's frontier.
875 void removeBlock(BasicBlock *BB) {
876 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
877 for (iterator I = begin(), E = end(); I != E; ++I)
882 void addToFrontier(iterator I, BasicBlock *Node) {
883 assert(I != end() && "BB is not in DominanceFrontier!");
884 I->second.insert(Node);
887 void removeFromFrontier(iterator I, BasicBlock *Node) {
888 assert(I != end() && "BB is not in DominanceFrontier!");
889 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
890 I->second.erase(Node);
893 /// print - Convert to human readable form
895 virtual void print(std::ostream &OS, const Module* = 0) const;
896 void print(std::ostream *OS, const Module* M = 0) const {
897 if (OS) print(*OS, M);
903 //===-------------------------------------
904 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
905 /// used to compute a forward dominator frontiers.
907 class DominanceFrontier : public DominanceFrontierBase {
909 static char ID; // Pass ID, replacement for typeid
910 DominanceFrontier() :
911 DominanceFrontierBase(intptr_t(&ID), false) {}
913 BasicBlock *getRoot() const {
914 assert(Roots.size() == 1 && "Should always have entry node!");
918 virtual bool runOnFunction(Function &) {
920 DominatorTree &DT = getAnalysis<DominatorTree>();
921 Roots = DT.getRoots();
922 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
923 calculate(DT, DT[Roots[0]]);
927 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
928 AU.setPreservesAll();
929 AU.addRequired<DominatorTree>();
932 /// splitBlock - BB is split and now it has one successor. Update dominance
933 /// frontier to reflect this change.
934 void splitBlock(BasicBlock *BB);
936 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
937 /// to reflect this change.
938 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
940 // NewBB is now dominating BB. Which means BB's dominance
941 // frontier is now part of NewBB's dominance frontier. However, BB
942 // itself is not member of NewBB's dominance frontier.
943 DominanceFrontier::iterator NewDFI = find(NewBB);
944 DominanceFrontier::iterator DFI = find(BB);
945 DominanceFrontier::DomSetType BBSet = DFI->second;
946 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
947 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
948 BasicBlock *DFMember = *BBSetI;
949 // Insert only if NewBB dominates DFMember.
950 if (!DT->dominates(NewBB, DFMember))
951 NewDFI->second.insert(DFMember);
953 NewDFI->second.erase(BB);
957 const DomSetType &calculate(const DominatorTree &DT,
958 const DomTreeNode *Node);
962 } // End llvm namespace