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.
188 NodeT *Label, *Child;
189 unsigned Parent, Ancestor;
191 std::vector<NodeT*> Bucket;
193 InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
197 DenseMap<NodeT*, NodeT*> IDoms;
199 // Vertex - Map the DFS number to the BasicBlock*
200 std::vector<NodeT*> Vertex;
202 // Info - Collection of information used during the computation of idoms.
203 DenseMap<NodeT*, InfoRec> Info;
206 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
207 E = DomTreeNodes.end(); I != E; ++I)
209 DomTreeNodes.clear();
216 // NewBB is split and now it has one successor. Update dominator tree to
217 // reflect this change.
218 template<class N, class GraphT>
219 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
220 typename GraphT::NodeType* NewBB) {
221 assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
222 && "NewBB should have a single successor!");
223 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
225 std::vector<typename GraphT::NodeType*> PredBlocks;
226 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
227 GraphTraits<Inverse<N> >::child_begin(NewBB),
228 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
229 PredBlocks.push_back(*PI);
231 assert(!PredBlocks.empty() && "No predblocks??");
233 // The newly inserted basic block will dominate existing basic blocks iff the
234 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
235 // the non-pred blocks, then they all must be the same block!
237 bool NewBBDominatesNewBBSucc = true;
239 typename GraphT::NodeType* OnePred = PredBlocks[0];
240 unsigned i = 1, e = PredBlocks.size();
241 for (i = 1; !DT.isReachableFromEntry(OnePred); ++i) {
242 assert(i != e && "Didn't find reachable pred?");
243 OnePred = PredBlocks[i];
247 if (PredBlocks[i] != OnePred && DT.isReachableFromEntry(OnePred)) {
248 NewBBDominatesNewBBSucc = false;
252 if (NewBBDominatesNewBBSucc)
253 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
254 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
255 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
256 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
257 NewBBDominatesNewBBSucc = false;
262 // The other scenario where the new block can dominate its successors are when
263 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
265 if (!NewBBDominatesNewBBSucc) {
266 NewBBDominatesNewBBSucc = true;
267 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
268 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
269 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
270 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI)) {
271 NewBBDominatesNewBBSucc = false;
276 // Find NewBB's immediate dominator and create new dominator tree node for
278 NodeT *NewBBIDom = 0;
280 for (i = 0; i < PredBlocks.size(); ++i)
281 if (DT.isReachableFromEntry(PredBlocks[i])) {
282 NewBBIDom = PredBlocks[i];
285 assert(i != PredBlocks.size() && "No reachable preds?");
286 for (i = i + 1; i < PredBlocks.size(); ++i) {
287 if (DT.isReachableFromEntry(PredBlocks[i]))
288 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
290 assert(NewBBIDom && "No immediate dominator found??");
292 // Create the new dominator tree node... and set the idom of NewBB.
293 DomTreeNodeBase<NodeT> *NewBBNode = DT.addNewBlock(NewBB, NewBBIDom);
295 // If NewBB strictly dominates other blocks, then it is now the immediate
296 // dominator of NewBBSucc. Update the dominator tree as appropriate.
297 if (NewBBDominatesNewBBSucc) {
298 DomTreeNodeBase<NodeT> *NewBBSuccNode = DT.getNode(NewBBSucc);
299 DT.changeImmediateDominator(NewBBSuccNode, NewBBNode);
304 explicit DominatorTreeBase(bool isPostDom)
305 : DominatorBase<NodeT>(isPostDom), DFSInfoValid(false), SlowQueries(0) {}
306 virtual ~DominatorTreeBase() { reset(); }
308 // FIXME: Should remove this
309 virtual bool runOnFunction(Function &F) { return false; }
311 virtual void releaseMemory() { reset(); }
313 /// getNode - return the (Post)DominatorTree node for the specified basic
314 /// block. This is the same as using operator[] on this class.
316 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
317 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
318 return I != DomTreeNodes.end() ? I->second : 0;
321 /// getRootNode - This returns the entry node for the CFG of the function. If
322 /// this tree represents the post-dominance relations for a function, however,
323 /// this root may be a node with the block == NULL. This is the case when
324 /// there are multiple exit nodes from a particular function. Consumers of
325 /// post-dominance information must be capable of dealing with this
328 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
329 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
331 /// properlyDominates - Returns true iff this dominates N and this != N.
332 /// Note that this is not a constant time operation!
334 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
335 DomTreeNodeBase<NodeT> *B) const {
336 if (A == 0 || B == 0) return false;
337 return dominatedBySlowTreeWalk(A, B);
340 inline bool properlyDominates(NodeT *A, NodeT *B) {
341 return properlyDominates(getNode(A), getNode(B));
344 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
345 const DomTreeNodeBase<NodeT> *B) const {
346 const DomTreeNodeBase<NodeT> *IDom;
347 if (A == 0 || B == 0) return false;
348 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
349 B = IDom; // Walk up the tree
354 /// isReachableFromEntry - Return true if A is dominated by the entry
355 /// block of the function containing it.
356 bool isReachableFromEntry(NodeT* A) {
357 assert (!this->isPostDominator()
358 && "This is not implemented for post dominators");
359 return dominates(&A->getParent()->front(), A);
362 /// dominates - Returns true iff A dominates B. Note that this is not a
363 /// constant time operation!
365 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
366 DomTreeNodeBase<NodeT> *B) {
368 return true; // A node trivially dominates itself.
370 if (A == 0 || B == 0)
374 return B->DominatedBy(A);
376 // If we end up with too many slow queries, just update the
377 // DFS numbers on the theory that we are going to keep querying.
379 if (SlowQueries > 32) {
381 return B->DominatedBy(A);
384 return dominatedBySlowTreeWalk(A, B);
387 inline bool dominates(NodeT *A, NodeT *B) {
391 return dominates(getNode(A), getNode(B));
394 NodeT *getRoot() const {
395 assert(this->Roots.size() == 1 && "Should always have entry node!");
396 return this->Roots[0];
399 /// findNearestCommonDominator - Find nearest common dominator basic block
400 /// for basic block A and B. If there is no such block then return NULL.
401 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
403 assert (!this->isPostDominator()
404 && "This is not implemented for post dominators");
405 assert (A->getParent() == B->getParent()
406 && "Two blocks are not in same function");
408 // If either A or B is a entry block then it is nearest common dominator.
409 NodeT &Entry = A->getParent()->front();
410 if (A == &Entry || B == &Entry)
413 // If B dominates A then B is nearest common dominator.
417 // If A dominates B then A is nearest common dominator.
421 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
422 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
424 // Collect NodeA dominators set.
425 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
426 NodeADoms.insert(NodeA);
427 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
429 NodeADoms.insert(IDomA);
430 IDomA = IDomA->getIDom();
433 // Walk NodeB immediate dominators chain and find common dominator node.
434 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
436 if (NodeADoms.count(IDomB) != 0)
437 return IDomB->getBlock();
439 IDomB = IDomB->getIDom();
445 //===--------------------------------------------------------------------===//
446 // API to update (Post)DominatorTree information based on modifications to
449 /// addNewBlock - Add a new node to the dominator tree information. This
450 /// creates a new node as a child of DomBB dominator node,linking it into
451 /// the children list of the immediate dominator.
452 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
453 assert(getNode(BB) == 0 && "Block already in dominator tree!");
454 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
455 assert(IDomNode && "Not immediate dominator specified for block!");
456 DFSInfoValid = false;
457 return DomTreeNodes[BB] =
458 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
461 /// changeImmediateDominator - This method is used to update the dominator
462 /// tree information when a node's immediate dominator changes.
464 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
465 DomTreeNodeBase<NodeT> *NewIDom) {
466 assert(N && NewIDom && "Cannot change null node pointers!");
467 DFSInfoValid = false;
471 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
472 changeImmediateDominator(getNode(BB), getNode(NewBB));
475 /// eraseNode - Removes a node from the dominator tree. Block must not
476 /// domiante any other blocks. Removes node from its immediate dominator's
477 /// children list. Deletes dominator node associated with basic block BB.
478 void eraseNode(NodeT *BB) {
479 DomTreeNodeBase<NodeT> *Node = getNode(BB);
480 assert (Node && "Removing node that isn't in dominator tree.");
481 assert (Node->getChildren().empty() && "Node is not a leaf node.");
483 // Remove node from immediate dominator's children list.
484 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
486 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
487 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
488 assert(I != IDom->Children.end() &&
489 "Not in immediate dominator children set!");
490 // I am no longer your child...
491 IDom->Children.erase(I);
494 DomTreeNodes.erase(BB);
498 /// removeNode - Removes a node from the dominator tree. Block must not
499 /// dominate any other blocks. Invalidates any node pointing to removed
501 void removeNode(NodeT *BB) {
502 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
503 DomTreeNodes.erase(BB);
506 /// splitBlock - BB is split and now it has one successor. Update dominator
507 /// tree to reflect this change.
508 void splitBlock(NodeT* NewBB) {
509 if (this->IsPostDominators)
510 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
512 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
515 /// print - Convert to human readable form
517 virtual void print(std::ostream &o, const Module* ) const {
518 o << "=============================--------------------------------\n";
519 if (this->isPostDominator())
520 o << "Inorder PostDominator Tree: ";
522 o << "Inorder Dominator Tree: ";
523 if (this->DFSInfoValid)
524 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
527 PrintDomTree<NodeT>(getRootNode(), o, 1);
530 void print(std::ostream *OS, const Module* M = 0) const {
531 if (OS) print(*OS, M);
534 virtual void dump() {
539 template<class GraphT>
540 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
541 typename GraphT::NodeType* VIn);
543 template<class GraphT>
544 friend typename GraphT::NodeType* Eval(
545 DominatorTreeBase<typename GraphT::NodeType>& DT,
546 typename GraphT::NodeType* V);
548 template<class GraphT>
549 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
550 unsigned DFSNumV, typename GraphT::NodeType* W,
551 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
553 template<class GraphT>
554 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
555 typename GraphT::NodeType* V,
558 template<class FuncT, class N>
559 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
562 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
563 /// dominator tree in dfs order.
564 void updateDFSNumbers() {
567 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
568 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
570 for (unsigned i = 0, e = this->Roots.size(); i != e; ++i) {
571 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
572 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
573 ThisRoot->DFSNumIn = DFSNum++;
575 while (!WorkStack.empty()) {
576 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
577 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
578 WorkStack.back().second;
580 // If we visited all of the children of this node, "recurse" back up the
581 // stack setting the DFOutNum.
582 if (ChildIt == Node->end()) {
583 Node->DFSNumOut = DFSNum++;
584 WorkStack.pop_back();
586 // Otherwise, recursively visit this child.
587 DomTreeNodeBase<NodeT> *Child = *ChildIt;
588 ++WorkStack.back().second;
590 WorkStack.push_back(std::make_pair(Child, Child->begin()));
591 Child->DFSNumIn = DFSNum++;
600 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
601 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
604 // Haven't calculated this node yet? Get or calculate the node for the
605 // immediate dominator.
606 NodeT *IDom = getIDom(BB);
608 // skip all non root nodes that have no dominator
609 if (!IDom && std::count(this->Roots.begin(), this->Roots.end(), BB) == 0)
612 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
614 // skip all nodes that are dominated by a non root node that, by itself,
619 // Add a new tree node for this BasicBlock, and link it as a child of
621 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
622 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
625 inline NodeT *getIDom(NodeT *BB) const {
626 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
627 return I != IDoms.end() ? I->second : 0;
630 inline void addRoot(NodeT* BB) {
631 this->Roots.push_back(BB);
635 /// recalculate - compute a dominator tree for the given function
637 void recalculate(FT& F) {
638 if (!this->IsPostDominators) {
642 this->Roots.push_back(&F.front());
643 this->IDoms[&F.front()] = 0;
644 this->DomTreeNodes[&F.front()] = 0;
645 this->Vertex.push_back(0);
647 Calculate<FT, NodeT*>(*this, F);
651 reset(); // Reset from the last time we were run...
653 // Initialize the roots list
654 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
655 if (std::distance(GraphTraits<FT*>::child_begin(I),
656 GraphTraits<FT*>::child_end(I)) == 0)
659 // Prepopulate maps so that we don't get iterator invalidation issues later.
661 this->DomTreeNodes[I] = 0;
664 this->Vertex.push_back(0);
666 Calculate<FT, Inverse<NodeT*> >(*this, F);
671 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
673 //===-------------------------------------
674 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
675 /// compute a normal dominator tree.
677 class DominatorTree : public FunctionPass {
679 static char ID; // Pass ID, replacement for typeid
680 DominatorTreeBase<BasicBlock>* DT;
682 DominatorTree() : FunctionPass(intptr_t(&ID)) {
683 DT = new DominatorTreeBase<BasicBlock>(false);
691 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
693 /// getRoots - Return the root blocks of the current CFG. This may include
694 /// multiple blocks if we are computing post dominators. For forward
695 /// dominators, this will always be a single block (the entry node).
697 inline const std::vector<BasicBlock*> &getRoots() const {
698 return DT->getRoots();
701 inline BasicBlock *getRoot() const {
702 return DT->getRoot();
705 inline DomTreeNode *getRootNode() const {
706 return DT->getRootNode();
709 virtual bool runOnFunction(Function &F);
711 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
712 AU.setPreservesAll();
715 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
716 return DT->dominates(A, B);
719 inline bool dominates(BasicBlock* A, BasicBlock* B) const {
720 return DT->dominates(A, B);
723 // dominates - Return true if A dominates B. This performs the
724 // special checks necessary if A and B are in the same basic block.
725 bool dominates(Instruction *A, Instruction *B) const {
726 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
727 if (BBA != BBB) return DT->dominates(BBA, BBB);
729 // It is not possible to determine dominance between two PHI nodes
730 // based on their ordering.
731 if (isa<PHINode>(A) && isa<PHINode>(B))
734 // Loop through the basic block until we find A or B.
735 BasicBlock::iterator I = BBA->begin();
736 for (; &*I != A && &*I != B; ++I) /*empty*/;
738 //if(!DT.IsPostDominators) {
739 // A dominates B if it is found first in the basic block.
742 // // A post-dominates B if B is found first in the basic block.
747 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
748 return DT->properlyDominates(A, B);
751 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
752 return DT->properlyDominates(A, B);
755 /// findNearestCommonDominator - Find nearest common dominator basic block
756 /// for basic block A and B. If there is no such block then return NULL.
757 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
758 return DT->findNearestCommonDominator(A, B);
761 inline DomTreeNode *operator[](BasicBlock *BB) const {
762 return DT->getNode(BB);
765 /// getNode - return the (Post)DominatorTree node for the specified basic
766 /// block. This is the same as using operator[] on this class.
768 inline DomTreeNode *getNode(BasicBlock *BB) const {
769 return DT->getNode(BB);
772 /// addNewBlock - Add a new node to the dominator tree information. This
773 /// creates a new node as a child of DomBB dominator node,linking it into
774 /// the children list of the immediate dominator.
775 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
776 return DT->addNewBlock(BB, DomBB);
779 /// changeImmediateDominator - This method is used to update the dominator
780 /// tree information when a node's immediate dominator changes.
782 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
783 DT->changeImmediateDominator(N, NewIDom);
786 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
787 DT->changeImmediateDominator(N, NewIDom);
790 /// eraseNode - Removes a node from the dominator tree. Block must not
791 /// domiante any other blocks. Removes node from its immediate dominator's
792 /// children list. Deletes dominator node associated with basic block BB.
793 inline void eraseNode(BasicBlock *BB) {
797 /// splitBlock - BB is split and now it has one successor. Update dominator
798 /// tree to reflect this change.
799 inline void splitBlock(BasicBlock* NewBB) {
800 DT->splitBlock(NewBB);
804 virtual void releaseMemory() {
808 virtual void print(std::ostream &OS, const Module* M= 0) const {
813 //===-------------------------------------
814 /// DominatorTree GraphTraits specialization so the DominatorTree can be
815 /// iterable by generic graph iterators.
817 template <> struct GraphTraits<DomTreeNode *> {
818 typedef DomTreeNode NodeType;
819 typedef NodeType::iterator ChildIteratorType;
821 static NodeType *getEntryNode(NodeType *N) {
824 static inline ChildIteratorType child_begin(NodeType* N) {
827 static inline ChildIteratorType child_end(NodeType* N) {
832 template <> struct GraphTraits<DominatorTree*>
833 : public GraphTraits<DomTreeNode *> {
834 static NodeType *getEntryNode(DominatorTree *DT) {
835 return DT->getRootNode();
840 //===----------------------------------------------------------------------===//
841 /// DominanceFrontierBase - Common base class for computing forward and inverse
842 /// dominance frontiers for a function.
844 class DominanceFrontierBase : public FunctionPass {
846 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
847 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
849 DomSetMapType Frontiers;
850 std::vector<BasicBlock*> Roots;
851 const bool IsPostDominators;
854 DominanceFrontierBase(intptr_t ID, bool isPostDom)
855 : FunctionPass(ID), IsPostDominators(isPostDom) {}
857 /// getRoots - Return the root blocks of the current CFG. This may include
858 /// multiple blocks if we are computing post dominators. For forward
859 /// dominators, this will always be a single block (the entry node).
861 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
863 /// isPostDominator - Returns true if analysis based of postdoms
865 bool isPostDominator() const { return IsPostDominators; }
867 virtual void releaseMemory() { Frontiers.clear(); }
869 // Accessor interface:
870 typedef DomSetMapType::iterator iterator;
871 typedef DomSetMapType::const_iterator const_iterator;
872 iterator begin() { return Frontiers.begin(); }
873 const_iterator begin() const { return Frontiers.begin(); }
874 iterator end() { return Frontiers.end(); }
875 const_iterator end() const { return Frontiers.end(); }
876 iterator find(BasicBlock *B) { return Frontiers.find(B); }
877 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
879 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
880 assert(find(BB) == end() && "Block already in DominanceFrontier!");
881 Frontiers.insert(std::make_pair(BB, frontier));
884 /// removeBlock - Remove basic block BB's frontier.
885 void removeBlock(BasicBlock *BB) {
886 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
887 for (iterator I = begin(), E = end(); I != E; ++I)
892 void addToFrontier(iterator I, BasicBlock *Node) {
893 assert(I != end() && "BB is not in DominanceFrontier!");
894 I->second.insert(Node);
897 void removeFromFrontier(iterator I, BasicBlock *Node) {
898 assert(I != end() && "BB is not in DominanceFrontier!");
899 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
900 I->second.erase(Node);
903 /// print - Convert to human readable form
905 virtual void print(std::ostream &OS, const Module* = 0) const;
906 void print(std::ostream *OS, const Module* M = 0) const {
907 if (OS) print(*OS, M);
913 //===-------------------------------------
914 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
915 /// used to compute a forward dominator frontiers.
917 class DominanceFrontier : public DominanceFrontierBase {
919 static char ID; // Pass ID, replacement for typeid
920 DominanceFrontier() :
921 DominanceFrontierBase(intptr_t(&ID), false) {}
923 BasicBlock *getRoot() const {
924 assert(Roots.size() == 1 && "Should always have entry node!");
928 virtual bool runOnFunction(Function &) {
930 DominatorTree &DT = getAnalysis<DominatorTree>();
931 Roots = DT.getRoots();
932 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
933 calculate(DT, DT[Roots[0]]);
937 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
938 AU.setPreservesAll();
939 AU.addRequired<DominatorTree>();
942 /// splitBlock - BB is split and now it has one successor. Update dominance
943 /// frontier to reflect this change.
944 void splitBlock(BasicBlock *BB);
946 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
947 /// to reflect this change.
948 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
950 // NewBB is now dominating BB. Which means BB's dominance
951 // frontier is now part of NewBB's dominance frontier. However, BB
952 // itself is not member of NewBB's dominance frontier.
953 DominanceFrontier::iterator NewDFI = find(NewBB);
954 DominanceFrontier::iterator DFI = find(BB);
955 DominanceFrontier::DomSetType BBSet = DFI->second;
956 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
957 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
958 BasicBlock *DFMember = *BBSetI;
959 // Insert only if NewBB dominates DFMember.
960 if (!DT->dominates(NewBB, DFMember))
961 NewDFI->second.insert(DFMember);
963 NewDFI->second.erase(BB);
967 const DomSetType &calculate(const DominatorTree &DT,
968 const DomTreeNode *Node);
972 } // End llvm namespace