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/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/GraphTraits.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Assembly/Writer.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/raw_ostream.h"
41 //===----------------------------------------------------------------------===//
42 /// DominatorBase - Base class that other, more interesting dominator analyses
45 template <class NodeT>
48 std::vector<NodeT*> Roots;
49 const bool IsPostDominators;
50 inline explicit DominatorBase(bool isPostDom) :
51 Roots(), IsPostDominators(isPostDom) {}
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).
58 inline const std::vector<NodeT*> &getRoots() const { return Roots; }
60 /// isPostDominator - Returns true if analysis based of postdoms
62 bool isPostDominator() const { return IsPostDominators; }
66 //===----------------------------------------------------------------------===//
67 // DomTreeNode - Dominator Tree Node
68 template<class NodeT> class DominatorTreeBase;
69 struct PostDominatorTree;
70 class MachineBasicBlock;
72 template <class NodeT>
73 class DomTreeNodeBase {
75 DomTreeNodeBase<NodeT> *IDom;
76 std::vector<DomTreeNodeBase<NodeT> *> Children;
77 int DFSNumIn, DFSNumOut;
79 template<class N> friend class DominatorTreeBase;
80 friend struct PostDominatorTree;
82 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::iterator iterator;
83 typedef typename std::vector<DomTreeNodeBase<NodeT> *>::const_iterator
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(); }
91 NodeT *getBlock() const { return TheBB; }
92 DomTreeNodeBase<NodeT> *getIDom() const { return IDom; }
93 const std::vector<DomTreeNodeBase<NodeT>*> &getChildren() const {
97 DomTreeNodeBase(NodeT *BB, DomTreeNodeBase<NodeT> *iDom)
98 : TheBB(BB), IDom(iDom), DFSNumIn(-1), DFSNumOut(-1) { }
100 DomTreeNodeBase<NodeT> *addChild(DomTreeNodeBase<NodeT> *C) {
101 Children.push_back(C);
105 size_t getNumChildren() const {
106 return Children.size();
109 void clearAllChildren() {
113 bool compare(DomTreeNodeBase<NodeT> *Other) {
114 if (getNumChildren() != Other->getNumChildren())
117 SmallPtrSet<NodeT *, 4> OtherChildren;
118 for(iterator I = Other->begin(), E = Other->end(); I != E; ++I) {
119 NodeT *Nd = (*I)->getBlock();
120 OtherChildren.insert(Nd);
123 for(iterator I = begin(), E = end(); I != E; ++I) {
124 NodeT *N = (*I)->getBlock();
125 if (OtherChildren.count(N) == 0)
131 void setIDom(DomTreeNodeBase<NodeT> *NewIDom) {
132 assert(IDom && "No immediate dominator?");
133 if (IDom != NewIDom) {
134 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
135 std::find(IDom->Children.begin(), IDom->Children.end(), this);
136 assert(I != IDom->Children.end() &&
137 "Not in immediate dominator children set!");
138 // I am no longer your child...
139 IDom->Children.erase(I);
141 // Switch to new dominator
143 IDom->Children.push_back(this);
147 /// getDFSNumIn/getDFSNumOut - These are an internal implementation detail, do
149 unsigned getDFSNumIn() const { return DFSNumIn; }
150 unsigned getDFSNumOut() const { return DFSNumOut; }
152 // Return true if this node is dominated by other. Use this only if DFS info
154 bool DominatedBy(const DomTreeNodeBase<NodeT> *other) const {
155 return this->DFSNumIn >= other->DFSNumIn &&
156 this->DFSNumOut <= other->DFSNumOut;
160 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<BasicBlock>);
161 EXTERN_TEMPLATE_INSTANTIATION(class DomTreeNodeBase<MachineBasicBlock>);
163 template<class NodeT>
164 static raw_ostream &operator<<(raw_ostream &o,
165 const DomTreeNodeBase<NodeT> *Node) {
166 if (Node->getBlock())
167 WriteAsOperand(o, Node->getBlock(), false);
169 o << " <<exit node>>";
171 o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
176 template<class NodeT>
177 static void PrintDomTree(const DomTreeNodeBase<NodeT> *N, raw_ostream &o,
179 o.indent(2*Lev) << "[" << Lev << "] " << N;
180 for (typename DomTreeNodeBase<NodeT>::const_iterator I = N->begin(),
181 E = N->end(); I != E; ++I)
182 PrintDomTree<NodeT>(*I, o, Lev+1);
185 typedef DomTreeNodeBase<BasicBlock> DomTreeNode;
187 //===----------------------------------------------------------------------===//
188 /// DominatorTree - Calculate the immediate dominator tree for a function.
191 template<class FuncT, class N>
192 void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
195 template<class NodeT>
196 class DominatorTreeBase : public DominatorBase<NodeT> {
198 typedef DenseMap<NodeT*, DomTreeNodeBase<NodeT>*> DomTreeNodeMapType;
199 DomTreeNodeMapType DomTreeNodes;
200 DomTreeNodeBase<NodeT> *RootNode;
203 unsigned int SlowQueries;
204 // Information record used during immediate dominators computation.
209 NodeT *Label, *Child;
210 unsigned Parent, Ancestor;
212 std::vector<NodeT*> Bucket;
214 InfoRec() : DFSNum(0), Semi(0), Size(0), Label(0), Child(0), Parent(0),
218 DenseMap<NodeT*, NodeT*> IDoms;
220 // Vertex - Map the DFS number to the BasicBlock*
221 std::vector<NodeT*> Vertex;
223 // Info - Collection of information used during the computation of idoms.
224 DenseMap<NodeT*, InfoRec> Info;
227 for (typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.begin(),
228 E = DomTreeNodes.end(); I != E; ++I)
230 DomTreeNodes.clear();
237 // NewBB is split and now it has one successor. Update dominator tree to
238 // reflect this change.
239 template<class N, class GraphT>
240 void Split(DominatorTreeBase<typename GraphT::NodeType>& DT,
241 typename GraphT::NodeType* NewBB) {
242 assert(std::distance(GraphT::child_begin(NewBB), GraphT::child_end(NewBB)) == 1
243 && "NewBB should have a single successor!");
244 typename GraphT::NodeType* NewBBSucc = *GraphT::child_begin(NewBB);
246 std::vector<typename GraphT::NodeType*> PredBlocks;
247 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
248 GraphTraits<Inverse<N> >::child_begin(NewBB),
249 PE = GraphTraits<Inverse<N> >::child_end(NewBB); PI != PE; ++PI)
250 PredBlocks.push_back(*PI);
252 assert(!PredBlocks.empty() && "No predblocks??");
254 bool NewBBDominatesNewBBSucc = true;
255 for (typename GraphTraits<Inverse<N> >::ChildIteratorType PI =
256 GraphTraits<Inverse<N> >::child_begin(NewBBSucc),
257 E = GraphTraits<Inverse<N> >::child_end(NewBBSucc); PI != E; ++PI)
258 if (*PI != NewBB && !DT.dominates(NewBBSucc, *PI) &&
259 DT.isReachableFromEntry(*PI)) {
260 NewBBDominatesNewBBSucc = false;
264 // Find NewBB's immediate dominator and create new dominator tree node for
266 NodeT *NewBBIDom = 0;
268 for (i = 0; i < PredBlocks.size(); ++i)
269 if (DT.isReachableFromEntry(PredBlocks[i])) {
270 NewBBIDom = PredBlocks[i];
274 // It's possible that none of the predecessors of NewBB are reachable;
275 // in that case, NewBB itself is unreachable, so nothing needs to be
280 for (i = i + 1; i < PredBlocks.size(); ++i) {
281 if (DT.isReachableFromEntry(PredBlocks[i]))
282 NewBBIDom = DT.findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
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 explicit 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 /// compare - Return false if the other dominator tree base matches this
305 /// dominator tree base. Otherwise return true.
306 bool compare(DominatorTreeBase &Other) const {
308 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
309 if (DomTreeNodes.size() != OtherDomTreeNodes.size())
312 SmallPtrSet<const NodeT *,4> MyBBs;
313 for (typename DomTreeNodeMapType::const_iterator
314 I = this->DomTreeNodes.begin(),
315 E = this->DomTreeNodes.end(); I != E; ++I) {
316 NodeT *BB = I->first;
317 typename DomTreeNodeMapType::const_iterator OI = OtherDomTreeNodes.find(BB);
318 if (OI == OtherDomTreeNodes.end())
321 DomTreeNodeBase<NodeT>* MyNd = I->second;
322 DomTreeNodeBase<NodeT>* OtherNd = OI->second;
324 if (MyNd->compare(OtherNd))
331 virtual void releaseMemory() { reset(); }
333 /// getNode - return the (Post)DominatorTree node for the specified basic
334 /// block. This is the same as using operator[] on this class.
336 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
337 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
338 return I != DomTreeNodes.end() ? I->second : 0;
341 /// getRootNode - This returns the entry node for the CFG of the function. If
342 /// this tree represents the post-dominance relations for a function, however,
343 /// this root may be a node with the block == NULL. This is the case when
344 /// there are multiple exit nodes from a particular function. Consumers of
345 /// post-dominance information must be capable of dealing with this
348 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
349 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
351 /// properlyDominates - Returns true iff this dominates N and this != N.
352 /// Note that this is not a constant time operation!
354 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
355 const DomTreeNodeBase<NodeT> *B) const {
356 if (A == 0 || B == 0) return false;
357 return dominatedBySlowTreeWalk(A, B);
360 inline bool properlyDominates(NodeT *A, NodeT *B) {
361 return properlyDominates(getNode(A), getNode(B));
364 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
365 const DomTreeNodeBase<NodeT> *B) const {
366 const DomTreeNodeBase<NodeT> *IDom;
367 if (A == 0 || B == 0) return false;
368 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
369 B = IDom; // Walk up the tree
374 /// isReachableFromEntry - Return true if A is dominated by the entry
375 /// block of the function containing it.
376 bool isReachableFromEntry(NodeT* A) {
377 assert (!this->isPostDominator()
378 && "This is not implemented for post dominators");
379 return dominates(&A->getParent()->front(), A);
382 /// dominates - Returns true iff A dominates B. Note that this is not a
383 /// constant time operation!
385 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
386 const DomTreeNodeBase<NodeT> *B) {
388 return true; // A node trivially dominates itself.
390 if (A == 0 || B == 0)
394 return B->DominatedBy(A);
396 // If we end up with too many slow queries, just update the
397 // DFS numbers on the theory that we are going to keep querying.
399 if (SlowQueries > 32) {
401 return B->DominatedBy(A);
404 return dominatedBySlowTreeWalk(A, B);
407 inline bool dominates(const NodeT *A, const NodeT *B) {
411 // Cast away the const qualifiers here. This is ok since
412 // this function doesn't actually return the values returned
414 return dominates(getNode(const_cast<NodeT *>(A)),
415 getNode(const_cast<NodeT *>(B)));
418 NodeT *getRoot() const {
419 assert(this->Roots.size() == 1 && "Should always have entry node!");
420 return this->Roots[0];
423 /// findNearestCommonDominator - Find nearest common dominator basic block
424 /// for basic block A and B. If there is no such block then return NULL.
425 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
427 assert (!this->isPostDominator()
428 && "This is not implemented for post dominators");
429 assert (A->getParent() == B->getParent()
430 && "Two blocks are not in same function");
432 // If either A or B is a entry block then it is nearest common dominator.
433 NodeT &Entry = A->getParent()->front();
434 if (A == &Entry || B == &Entry)
437 // If B dominates A then B is nearest common dominator.
441 // If A dominates B then A is nearest common dominator.
445 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
446 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
448 // Collect NodeA dominators set.
449 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
450 NodeADoms.insert(NodeA);
451 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
453 NodeADoms.insert(IDomA);
454 IDomA = IDomA->getIDom();
457 // Walk NodeB immediate dominators chain and find common dominator node.
458 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
460 if (NodeADoms.count(IDomB) != 0)
461 return IDomB->getBlock();
463 IDomB = IDomB->getIDom();
469 //===--------------------------------------------------------------------===//
470 // API to update (Post)DominatorTree information based on modifications to
473 /// addNewBlock - Add a new node to the dominator tree information. This
474 /// creates a new node as a child of DomBB dominator node,linking it into
475 /// the children list of the immediate dominator.
476 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
477 assert(getNode(BB) == 0 && "Block already in dominator tree!");
478 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
479 assert(IDomNode && "Not immediate dominator specified for block!");
480 DFSInfoValid = false;
481 return DomTreeNodes[BB] =
482 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
485 /// changeImmediateDominator - This method is used to update the dominator
486 /// tree information when a node's immediate dominator changes.
488 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
489 DomTreeNodeBase<NodeT> *NewIDom) {
490 assert(N && NewIDom && "Cannot change null node pointers!");
491 DFSInfoValid = false;
495 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
496 changeImmediateDominator(getNode(BB), getNode(NewBB));
499 /// eraseNode - Removes a node from the dominator tree. Block must not
500 /// domiante any other blocks. Removes node from its immediate dominator's
501 /// children list. Deletes dominator node associated with basic block BB.
502 void eraseNode(NodeT *BB) {
503 DomTreeNodeBase<NodeT> *Node = getNode(BB);
504 assert (Node && "Removing node that isn't in dominator tree.");
505 assert (Node->getChildren().empty() && "Node is not a leaf node.");
507 // Remove node from immediate dominator's children list.
508 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
510 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
511 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
512 assert(I != IDom->Children.end() &&
513 "Not in immediate dominator children set!");
514 // I am no longer your child...
515 IDom->Children.erase(I);
518 DomTreeNodes.erase(BB);
522 /// removeNode - Removes a node from the dominator tree. Block must not
523 /// dominate any other blocks. Invalidates any node pointing to removed
525 void removeNode(NodeT *BB) {
526 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
527 DomTreeNodes.erase(BB);
530 /// splitBlock - BB is split and now it has one successor. Update dominator
531 /// tree to reflect this change.
532 void splitBlock(NodeT* NewBB) {
533 if (this->IsPostDominators)
534 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
536 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
539 /// print - Convert to human readable form
541 void print(raw_ostream &o) const {
542 o << "=============================--------------------------------\n";
543 if (this->isPostDominator())
544 o << "Inorder PostDominator Tree: ";
546 o << "Inorder Dominator Tree: ";
547 if (this->DFSInfoValid)
548 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
551 // The postdom tree can have a null root if there are no returns.
553 PrintDomTree<NodeT>(getRootNode(), o, 1);
557 template<class GraphT>
558 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
559 typename GraphT::NodeType* VIn);
561 template<class GraphT>
562 friend typename GraphT::NodeType* Eval(
563 DominatorTreeBase<typename GraphT::NodeType>& DT,
564 typename GraphT::NodeType* V);
566 template<class GraphT>
567 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
568 unsigned DFSNumV, typename GraphT::NodeType* W,
569 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
571 template<class GraphT>
572 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
573 typename GraphT::NodeType* V,
576 template<class FuncT, class N>
577 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
580 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
581 /// dominator tree in dfs order.
582 void updateDFSNumbers() {
585 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
586 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
588 for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
589 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
590 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
591 ThisRoot->DFSNumIn = DFSNum++;
593 while (!WorkStack.empty()) {
594 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
595 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
596 WorkStack.back().second;
598 // If we visited all of the children of this node, "recurse" back up the
599 // stack setting the DFOutNum.
600 if (ChildIt == Node->end()) {
601 Node->DFSNumOut = DFSNum++;
602 WorkStack.pop_back();
604 // Otherwise, recursively visit this child.
605 DomTreeNodeBase<NodeT> *Child = *ChildIt;
606 ++WorkStack.back().second;
608 WorkStack.push_back(std::make_pair(Child, Child->begin()));
609 Child->DFSNumIn = DFSNum++;
618 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
619 typename DomTreeNodeMapType::iterator I = this->DomTreeNodes.find(BB);
620 if (I != this->DomTreeNodes.end() && I->second)
623 // Haven't calculated this node yet? Get or calculate the node for the
624 // immediate dominator.
625 NodeT *IDom = getIDom(BB);
627 assert(IDom || this->DomTreeNodes[NULL]);
628 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
630 // Add a new tree node for this BasicBlock, and link it as a child of
632 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
633 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
636 inline NodeT *getIDom(NodeT *BB) const {
637 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
638 return I != IDoms.end() ? I->second : 0;
641 inline void addRoot(NodeT* BB) {
642 this->Roots.push_back(BB);
646 /// recalculate - compute a dominator tree for the given function
648 void recalculate(FT& F) {
649 if (!this->IsPostDominators) {
653 this->Roots.push_back(&F.front());
654 this->IDoms[&F.front()] = 0;
655 this->DomTreeNodes[&F.front()] = 0;
656 this->Vertex.push_back(0);
658 Calculate<FT, NodeT*>(*this, F);
662 reset(); // Reset from the last time we were run...
664 // Initialize the roots list
665 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
666 if (std::distance(GraphTraits<FT*>::child_begin(I),
667 GraphTraits<FT*>::child_end(I)) == 0)
670 // Prepopulate maps so that we don't get iterator invalidation issues later.
672 this->DomTreeNodes[I] = 0;
675 this->Vertex.push_back(0);
677 Calculate<FT, Inverse<NodeT*> >(*this, F);
682 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
684 //===-------------------------------------
685 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
686 /// compute a normal dominator tree.
688 class DominatorTree : public FunctionPass {
690 static char ID; // Pass ID, replacement for typeid
691 DominatorTreeBase<BasicBlock>* DT;
693 DominatorTree() : FunctionPass(&ID) {
694 DT = new DominatorTreeBase<BasicBlock>(false);
702 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
704 /// getRoots - Return the root blocks of the current CFG. This may include
705 /// multiple blocks if we are computing post dominators. For forward
706 /// dominators, this will always be a single block (the entry node).
708 inline const std::vector<BasicBlock*> &getRoots() const {
709 return DT->getRoots();
712 inline BasicBlock *getRoot() const {
713 return DT->getRoot();
716 inline DomTreeNode *getRootNode() const {
717 return DT->getRootNode();
720 /// compare - Return false if the other dominator tree matches this
721 /// dominator tree. Otherwise return true.
722 inline bool compare(DominatorTree &Other) const {
723 DomTreeNode *R = getRootNode();
724 DomTreeNode *OtherR = Other.getRootNode();
726 if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
729 if (DT->compare(Other.getBase()))
735 virtual bool runOnFunction(Function &F);
737 virtual void verifyAnalysis() const;
739 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
740 AU.setPreservesAll();
743 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
744 return DT->dominates(A, B);
747 inline bool dominates(const BasicBlock* A, const BasicBlock* B) const {
748 return DT->dominates(A, B);
751 // dominates - Return true if A dominates B. This performs the
752 // special checks necessary if A and B are in the same basic block.
753 bool dominates(const Instruction *A, const Instruction *B) const;
755 bool properlyDominates(const DomTreeNode *A, const DomTreeNode *B) const {
756 return DT->properlyDominates(A, B);
759 bool properlyDominates(BasicBlock *A, BasicBlock *B) const {
760 return DT->properlyDominates(A, B);
763 /// findNearestCommonDominator - Find nearest common dominator basic block
764 /// for basic block A and B. If there is no such block then return NULL.
765 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
766 return DT->findNearestCommonDominator(A, B);
769 inline DomTreeNode *operator[](BasicBlock *BB) const {
770 return DT->getNode(BB);
773 /// getNode - return the (Post)DominatorTree node for the specified basic
774 /// block. This is the same as using operator[] on this class.
776 inline DomTreeNode *getNode(BasicBlock *BB) const {
777 return DT->getNode(BB);
780 /// addNewBlock - Add a new node to the dominator tree information. This
781 /// creates a new node as a child of DomBB dominator node,linking it into
782 /// the children list of the immediate dominator.
783 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
784 return DT->addNewBlock(BB, DomBB);
787 /// changeImmediateDominator - This method is used to update the dominator
788 /// tree information when a node's immediate dominator changes.
790 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
791 DT->changeImmediateDominator(N, NewIDom);
794 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
795 DT->changeImmediateDominator(N, NewIDom);
798 /// eraseNode - Removes a node from the dominator tree. Block must not
799 /// domiante any other blocks. Removes node from its immediate dominator's
800 /// children list. Deletes dominator node associated with basic block BB.
801 inline void eraseNode(BasicBlock *BB) {
805 /// splitBlock - BB is split and now it has one successor. Update dominator
806 /// tree to reflect this change.
807 inline void splitBlock(BasicBlock* NewBB) {
808 DT->splitBlock(NewBB);
811 bool isReachableFromEntry(BasicBlock* A) {
812 return DT->isReachableFromEntry(A);
816 virtual void releaseMemory() {
820 virtual void print(raw_ostream &OS, const Module* M= 0) const;
823 //===-------------------------------------
824 /// DominatorTree GraphTraits specialization so the DominatorTree can be
825 /// iterable by generic graph iterators.
827 template <> struct GraphTraits<DomTreeNode *> {
828 typedef DomTreeNode NodeType;
829 typedef NodeType::iterator ChildIteratorType;
831 static NodeType *getEntryNode(NodeType *N) {
834 static inline ChildIteratorType child_begin(NodeType* N) {
837 static inline ChildIteratorType child_end(NodeType* N) {
842 template <> struct GraphTraits<DominatorTree*>
843 : public GraphTraits<DomTreeNode *> {
844 static NodeType *getEntryNode(DominatorTree *DT) {
845 return DT->getRootNode();
850 //===----------------------------------------------------------------------===//
851 /// DominanceFrontierBase - Common base class for computing forward and inverse
852 /// dominance frontiers for a function.
854 class DominanceFrontierBase : public FunctionPass {
856 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
857 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
859 DomSetMapType Frontiers;
860 std::vector<BasicBlock*> Roots;
861 const bool IsPostDominators;
864 DominanceFrontierBase(void *ID, bool isPostDom)
865 : FunctionPass(ID), IsPostDominators(isPostDom) {}
867 /// getRoots - Return the root blocks of the current CFG. This may include
868 /// multiple blocks if we are computing post dominators. For forward
869 /// dominators, this will always be a single block (the entry node).
871 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
873 /// isPostDominator - Returns true if analysis based of postdoms
875 bool isPostDominator() const { return IsPostDominators; }
877 virtual void releaseMemory() { Frontiers.clear(); }
879 // Accessor interface:
880 typedef DomSetMapType::iterator iterator;
881 typedef DomSetMapType::const_iterator const_iterator;
882 iterator begin() { return Frontiers.begin(); }
883 const_iterator begin() const { return Frontiers.begin(); }
884 iterator end() { return Frontiers.end(); }
885 const_iterator end() const { return Frontiers.end(); }
886 iterator find(BasicBlock *B) { return Frontiers.find(B); }
887 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
889 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
890 assert(find(BB) == end() && "Block already in DominanceFrontier!");
891 Frontiers.insert(std::make_pair(BB, frontier));
894 /// removeBlock - Remove basic block BB's frontier.
895 void removeBlock(BasicBlock *BB) {
896 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
897 for (iterator I = begin(), E = end(); I != E; ++I)
902 void addToFrontier(iterator I, BasicBlock *Node) {
903 assert(I != end() && "BB is not in DominanceFrontier!");
904 I->second.insert(Node);
907 void removeFromFrontier(iterator I, BasicBlock *Node) {
908 assert(I != end() && "BB is not in DominanceFrontier!");
909 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
910 I->second.erase(Node);
913 /// compareDomSet - Return false if two domsets match. Otherwise
915 bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
916 std::set<BasicBlock *> tmpSet;
917 for (DomSetType::const_iterator I = DS2.begin(),
918 E = DS2.end(); I != E; ++I)
921 for (DomSetType::const_iterator I = DS1.begin(),
922 E = DS1.end(); I != E; ) {
923 BasicBlock *Node = *I++;
925 if (tmpSet.erase(Node) == 0)
926 // Node is in DS1 but not in DS2.
931 // There are nodes that are in DS2 but not in DS1.
934 // DS1 and DS2 matches.
938 /// compare - Return true if the other dominance frontier base matches
939 /// this dominance frontier base. Otherwise return false.
940 bool compare(DominanceFrontierBase &Other) const {
941 DomSetMapType tmpFrontiers;
942 for (DomSetMapType::const_iterator I = Other.begin(),
943 E = Other.end(); I != E; ++I)
944 tmpFrontiers.insert(std::make_pair(I->first, I->second));
946 for (DomSetMapType::iterator I = tmpFrontiers.begin(),
947 E = tmpFrontiers.end(); I != E; ) {
948 BasicBlock *Node = I->first;
949 const_iterator DFI = find(Node);
953 if (compareDomSet(I->second, DFI->second))
957 tmpFrontiers.erase(Node);
960 if (!tmpFrontiers.empty())
966 /// print - Convert to human readable form
968 virtual void print(raw_ostream &OS, const Module* = 0) const;
972 //===-------------------------------------
973 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
974 /// used to compute a forward dominator frontiers.
976 class DominanceFrontier : public DominanceFrontierBase {
978 static char ID; // Pass ID, replacement for typeid
979 DominanceFrontier() :
980 DominanceFrontierBase(&ID, false) {}
982 BasicBlock *getRoot() const {
983 assert(Roots.size() == 1 && "Should always have entry node!");
987 virtual bool runOnFunction(Function &) {
989 DominatorTree &DT = getAnalysis<DominatorTree>();
990 Roots = DT.getRoots();
991 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
992 calculate(DT, DT[Roots[0]]);
996 virtual void verifyAnalysis() const;
998 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
999 AU.setPreservesAll();
1000 AU.addRequired<DominatorTree>();
1003 /// splitBlock - BB is split and now it has one successor. Update dominance
1004 /// frontier to reflect this change.
1005 void splitBlock(BasicBlock *BB);
1007 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1008 /// to reflect this change.
1009 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1010 DominatorTree *DT) {
1011 // NewBB is now dominating BB. Which means BB's dominance
1012 // frontier is now part of NewBB's dominance frontier. However, BB
1013 // itself is not member of NewBB's dominance frontier.
1014 DominanceFrontier::iterator NewDFI = find(NewBB);
1015 DominanceFrontier::iterator DFI = find(BB);
1016 // If BB was an entry block then its frontier is empty.
1019 DominanceFrontier::DomSetType BBSet = DFI->second;
1020 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1021 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1022 BasicBlock *DFMember = *BBSetI;
1023 // Insert only if NewBB dominates DFMember.
1024 if (!DT->dominates(NewBB, DFMember))
1025 NewDFI->second.insert(DFMember);
1027 NewDFI->second.erase(BB);
1030 const DomSetType &calculate(const DominatorTree &DT,
1031 const DomTreeNode *Node);
1035 } // End llvm namespace