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 size_t 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 /// compare - Return false if the other dominator tree base maches this
312 /// dominator tree base. Otherwise return true.
313 bool compare(DominatorTreeBase &Other) const {
316 SmallPtrSet<const NodeT *,4> MyBBs;
317 for (typename DomTreeNodeMapType::const_iterator
318 I = this->DomTreeNodes.begin(),
319 E = this->DomTreeNodes.end(); I != E; ++I) {
320 const NodeT *BB = I->first;
324 SmallPtrSet<const NodeT *,4> OtherBBs;
325 const DomTreeNodeMapType &OtherDomTreeNodes = Other.DomTreeNodes;
326 for (typename DomTreeNodeMapType::const_iterator
327 I = OtherDomTreeNodes.begin(),
328 E = OtherDomTreeNodes.end(); I != E; ++I) {
329 const NodeT *BB = I->first;
333 if (OtherBBs.size() != MyBBs.size())
336 // Compare node sets.
337 for (typename SmallPtrSet<const NodeT *,4>::const_iterator I = MyBBs.begin(),
338 E = MyBBs.end(); I != E; ++I) {
339 const NodeT *BB = *I;
340 if (OtherBBs.erase(BB) == 0)
343 if (!OtherBBs.empty())
348 virtual void releaseMemory() { reset(); }
350 /// getNode - return the (Post)DominatorTree node for the specified basic
351 /// block. This is the same as using operator[] on this class.
353 inline DomTreeNodeBase<NodeT> *getNode(NodeT *BB) const {
354 typename DomTreeNodeMapType::const_iterator I = DomTreeNodes.find(BB);
355 return I != DomTreeNodes.end() ? I->second : 0;
358 /// getRootNode - This returns the entry node for the CFG of the function. If
359 /// this tree represents the post-dominance relations for a function, however,
360 /// this root may be a node with the block == NULL. This is the case when
361 /// there are multiple exit nodes from a particular function. Consumers of
362 /// post-dominance information must be capable of dealing with this
365 DomTreeNodeBase<NodeT> *getRootNode() { return RootNode; }
366 const DomTreeNodeBase<NodeT> *getRootNode() const { return RootNode; }
368 /// properlyDominates - Returns true iff this dominates N and this != N.
369 /// Note that this is not a constant time operation!
371 bool properlyDominates(const DomTreeNodeBase<NodeT> *A,
372 DomTreeNodeBase<NodeT> *B) const {
373 if (A == 0 || B == 0) return false;
374 return dominatedBySlowTreeWalk(A, B);
377 inline bool properlyDominates(NodeT *A, NodeT *B) {
378 return properlyDominates(getNode(A), getNode(B));
381 bool dominatedBySlowTreeWalk(const DomTreeNodeBase<NodeT> *A,
382 const DomTreeNodeBase<NodeT> *B) const {
383 const DomTreeNodeBase<NodeT> *IDom;
384 if (A == 0 || B == 0) return false;
385 while ((IDom = B->getIDom()) != 0 && IDom != A && IDom != B)
386 B = IDom; // Walk up the tree
391 /// isReachableFromEntry - Return true if A is dominated by the entry
392 /// block of the function containing it.
393 bool isReachableFromEntry(NodeT* A) {
394 assert (!this->isPostDominator()
395 && "This is not implemented for post dominators");
396 return dominates(&A->getParent()->front(), A);
399 /// dominates - Returns true iff A dominates B. Note that this is not a
400 /// constant time operation!
402 inline bool dominates(const DomTreeNodeBase<NodeT> *A,
403 DomTreeNodeBase<NodeT> *B) {
405 return true; // A node trivially dominates itself.
407 if (A == 0 || B == 0)
411 return B->DominatedBy(A);
413 // If we end up with too many slow queries, just update the
414 // DFS numbers on the theory that we are going to keep querying.
416 if (SlowQueries > 32) {
418 return B->DominatedBy(A);
421 return dominatedBySlowTreeWalk(A, B);
424 inline bool dominates(NodeT *A, NodeT *B) {
428 return dominates(getNode(A), getNode(B));
431 NodeT *getRoot() const {
432 assert(this->Roots.size() == 1 && "Should always have entry node!");
433 return this->Roots[0];
436 /// findNearestCommonDominator - Find nearest common dominator basic block
437 /// for basic block A and B. If there is no such block then return NULL.
438 NodeT *findNearestCommonDominator(NodeT *A, NodeT *B) {
440 assert (!this->isPostDominator()
441 && "This is not implemented for post dominators");
442 assert (A->getParent() == B->getParent()
443 && "Two blocks are not in same function");
445 // If either A or B is a entry block then it is nearest common dominator.
446 NodeT &Entry = A->getParent()->front();
447 if (A == &Entry || B == &Entry)
450 // If B dominates A then B is nearest common dominator.
454 // If A dominates B then A is nearest common dominator.
458 DomTreeNodeBase<NodeT> *NodeA = getNode(A);
459 DomTreeNodeBase<NodeT> *NodeB = getNode(B);
461 // Collect NodeA dominators set.
462 SmallPtrSet<DomTreeNodeBase<NodeT>*, 16> NodeADoms;
463 NodeADoms.insert(NodeA);
464 DomTreeNodeBase<NodeT> *IDomA = NodeA->getIDom();
466 NodeADoms.insert(IDomA);
467 IDomA = IDomA->getIDom();
470 // Walk NodeB immediate dominators chain and find common dominator node.
471 DomTreeNodeBase<NodeT> *IDomB = NodeB->getIDom();
473 if (NodeADoms.count(IDomB) != 0)
474 return IDomB->getBlock();
476 IDomB = IDomB->getIDom();
482 //===--------------------------------------------------------------------===//
483 // API to update (Post)DominatorTree information based on modifications to
486 /// addNewBlock - Add a new node to the dominator tree information. This
487 /// creates a new node as a child of DomBB dominator node,linking it into
488 /// the children list of the immediate dominator.
489 DomTreeNodeBase<NodeT> *addNewBlock(NodeT *BB, NodeT *DomBB) {
490 assert(getNode(BB) == 0 && "Block already in dominator tree!");
491 DomTreeNodeBase<NodeT> *IDomNode = getNode(DomBB);
492 assert(IDomNode && "Not immediate dominator specified for block!");
493 DFSInfoValid = false;
494 return DomTreeNodes[BB] =
495 IDomNode->addChild(new DomTreeNodeBase<NodeT>(BB, IDomNode));
498 /// changeImmediateDominator - This method is used to update the dominator
499 /// tree information when a node's immediate dominator changes.
501 void changeImmediateDominator(DomTreeNodeBase<NodeT> *N,
502 DomTreeNodeBase<NodeT> *NewIDom) {
503 assert(N && NewIDom && "Cannot change null node pointers!");
504 DFSInfoValid = false;
508 void changeImmediateDominator(NodeT *BB, NodeT *NewBB) {
509 changeImmediateDominator(getNode(BB), getNode(NewBB));
512 /// eraseNode - Removes a node from the dominator tree. Block must not
513 /// domiante any other blocks. Removes node from its immediate dominator's
514 /// children list. Deletes dominator node associated with basic block BB.
515 void eraseNode(NodeT *BB) {
516 DomTreeNodeBase<NodeT> *Node = getNode(BB);
517 assert (Node && "Removing node that isn't in dominator tree.");
518 assert (Node->getChildren().empty() && "Node is not a leaf node.");
520 // Remove node from immediate dominator's children list.
521 DomTreeNodeBase<NodeT> *IDom = Node->getIDom();
523 typename std::vector<DomTreeNodeBase<NodeT>*>::iterator I =
524 std::find(IDom->Children.begin(), IDom->Children.end(), Node);
525 assert(I != IDom->Children.end() &&
526 "Not in immediate dominator children set!");
527 // I am no longer your child...
528 IDom->Children.erase(I);
531 DomTreeNodes.erase(BB);
535 /// removeNode - Removes a node from the dominator tree. Block must not
536 /// dominate any other blocks. Invalidates any node pointing to removed
538 void removeNode(NodeT *BB) {
539 assert(getNode(BB) && "Removing node that isn't in dominator tree.");
540 DomTreeNodes.erase(BB);
543 /// splitBlock - BB is split and now it has one successor. Update dominator
544 /// tree to reflect this change.
545 void splitBlock(NodeT* NewBB) {
546 if (this->IsPostDominators)
547 this->Split<Inverse<NodeT*>, GraphTraits<Inverse<NodeT*> > >(*this, NewBB);
549 this->Split<NodeT*, GraphTraits<NodeT*> >(*this, NewBB);
552 /// print - Convert to human readable form
554 virtual void print(std::ostream &o, const Module* ) const {
555 o << "=============================--------------------------------\n";
556 if (this->isPostDominator())
557 o << "Inorder PostDominator Tree: ";
559 o << "Inorder Dominator Tree: ";
560 if (this->DFSInfoValid)
561 o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
564 PrintDomTree<NodeT>(getRootNode(), o, 1);
567 void print(std::ostream *OS, const Module* M = 0) const {
568 if (OS) print(*OS, M);
571 virtual void dump() {
576 template<class GraphT>
577 friend void Compress(DominatorTreeBase<typename GraphT::NodeType>& DT,
578 typename GraphT::NodeType* VIn);
580 template<class GraphT>
581 friend typename GraphT::NodeType* Eval(
582 DominatorTreeBase<typename GraphT::NodeType>& DT,
583 typename GraphT::NodeType* V);
585 template<class GraphT>
586 friend void Link(DominatorTreeBase<typename GraphT::NodeType>& DT,
587 unsigned DFSNumV, typename GraphT::NodeType* W,
588 typename DominatorTreeBase<typename GraphT::NodeType>::InfoRec &WInfo);
590 template<class GraphT>
591 friend unsigned DFSPass(DominatorTreeBase<typename GraphT::NodeType>& DT,
592 typename GraphT::NodeType* V,
595 template<class FuncT, class N>
596 friend void Calculate(DominatorTreeBase<typename GraphTraits<N>::NodeType>& DT,
599 /// updateDFSNumbers - Assign In and Out numbers to the nodes while walking
600 /// dominator tree in dfs order.
601 void updateDFSNumbers() {
604 SmallVector<std::pair<DomTreeNodeBase<NodeT>*,
605 typename DomTreeNodeBase<NodeT>::iterator>, 32> WorkStack;
607 for (unsigned i = 0, e = (unsigned)this->Roots.size(); i != e; ++i) {
608 DomTreeNodeBase<NodeT> *ThisRoot = getNode(this->Roots[i]);
609 WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
610 ThisRoot->DFSNumIn = DFSNum++;
612 while (!WorkStack.empty()) {
613 DomTreeNodeBase<NodeT> *Node = WorkStack.back().first;
614 typename DomTreeNodeBase<NodeT>::iterator ChildIt =
615 WorkStack.back().second;
617 // If we visited all of the children of this node, "recurse" back up the
618 // stack setting the DFOutNum.
619 if (ChildIt == Node->end()) {
620 Node->DFSNumOut = DFSNum++;
621 WorkStack.pop_back();
623 // Otherwise, recursively visit this child.
624 DomTreeNodeBase<NodeT> *Child = *ChildIt;
625 ++WorkStack.back().second;
627 WorkStack.push_back(std::make_pair(Child, Child->begin()));
628 Child->DFSNumIn = DFSNum++;
637 DomTreeNodeBase<NodeT> *getNodeForBlock(NodeT *BB) {
638 if (DomTreeNodeBase<NodeT> *BBNode = this->DomTreeNodes[BB])
641 // Haven't calculated this node yet? Get or calculate the node for the
642 // immediate dominator.
643 NodeT *IDom = getIDom(BB);
645 assert(IDom || this->DomTreeNodes[NULL]);
646 DomTreeNodeBase<NodeT> *IDomNode = getNodeForBlock(IDom);
648 // Add a new tree node for this BasicBlock, and link it as a child of
650 DomTreeNodeBase<NodeT> *C = new DomTreeNodeBase<NodeT>(BB, IDomNode);
651 return this->DomTreeNodes[BB] = IDomNode->addChild(C);
654 inline NodeT *getIDom(NodeT *BB) const {
655 typename DenseMap<NodeT*, NodeT*>::const_iterator I = IDoms.find(BB);
656 return I != IDoms.end() ? I->second : 0;
659 inline void addRoot(NodeT* BB) {
660 this->Roots.push_back(BB);
664 /// recalculate - compute a dominator tree for the given function
666 void recalculate(FT& F) {
667 if (!this->IsPostDominators) {
671 this->Roots.push_back(&F.front());
672 this->IDoms[&F.front()] = 0;
673 this->DomTreeNodes[&F.front()] = 0;
674 this->Vertex.push_back(0);
676 Calculate<FT, NodeT*>(*this, F);
680 reset(); // Reset from the last time we were run...
682 // Initialize the roots list
683 for (typename FT::iterator I = F.begin(), E = F.end(); I != E; ++I) {
684 if (std::distance(GraphTraits<FT*>::child_begin(I),
685 GraphTraits<FT*>::child_end(I)) == 0)
688 // Prepopulate maps so that we don't get iterator invalidation issues later.
690 this->DomTreeNodes[I] = 0;
693 this->Vertex.push_back(0);
695 Calculate<FT, Inverse<NodeT*> >(*this, F);
700 EXTERN_TEMPLATE_INSTANTIATION(class DominatorTreeBase<BasicBlock>);
702 //===-------------------------------------
703 /// DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to
704 /// compute a normal dominator tree.
706 class DominatorTree : public FunctionPass {
708 static char ID; // Pass ID, replacement for typeid
709 DominatorTreeBase<BasicBlock>* DT;
711 DominatorTree() : FunctionPass(intptr_t(&ID)) {
712 DT = new DominatorTreeBase<BasicBlock>(false);
720 DominatorTreeBase<BasicBlock>& getBase() { return *DT; }
722 /// getRoots - Return the root blocks of the current CFG. This may include
723 /// multiple blocks if we are computing post dominators. For forward
724 /// dominators, this will always be a single block (the entry node).
726 inline const std::vector<BasicBlock*> &getRoots() const {
727 return DT->getRoots();
730 inline BasicBlock *getRoot() const {
731 return DT->getRoot();
734 inline DomTreeNode *getRootNode() const {
735 return DT->getRootNode();
738 /// compare - Return false if the other dominator tree maches this
739 /// dominator tree. Otherwise return true.
740 inline bool compare(DominatorTree &Other) const {
741 DomTreeNode *R = getRootNode();
742 DomTreeNode *OtherR = Other.getRootNode();
744 if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
747 if (DT->compare(Other.getBase()))
753 virtual bool runOnFunction(Function &F);
755 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
756 AU.setPreservesAll();
759 inline bool dominates(DomTreeNode* A, DomTreeNode* B) const {
760 return DT->dominates(A, B);
763 inline bool dominates(BasicBlock* A, BasicBlock* B) const {
764 return DT->dominates(A, B);
767 // dominates - Return true if A dominates B. This performs the
768 // special checks necessary if A and B are in the same basic block.
769 bool dominates(Instruction *A, Instruction *B) const {
770 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
771 if (BBA != BBB) return DT->dominates(BBA, BBB);
773 // It is not possible to determine dominance between two PHI nodes
774 // based on their ordering.
775 if (isa<PHINode>(A) && isa<PHINode>(B))
778 // Loop through the basic block until we find A or B.
779 BasicBlock::iterator I = BBA->begin();
780 for (; &*I != A && &*I != B; ++I) /*empty*/;
782 //if(!DT.IsPostDominators) {
783 // A dominates B if it is found first in the basic block.
786 // // A post-dominates B if B is found first in the basic block.
791 inline bool properlyDominates(const DomTreeNode* A, DomTreeNode* B) const {
792 return DT->properlyDominates(A, B);
795 inline bool properlyDominates(BasicBlock* A, BasicBlock* B) const {
796 return DT->properlyDominates(A, B);
799 /// findNearestCommonDominator - Find nearest common dominator basic block
800 /// for basic block A and B. If there is no such block then return NULL.
801 inline BasicBlock *findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
802 return DT->findNearestCommonDominator(A, B);
805 inline DomTreeNode *operator[](BasicBlock *BB) const {
806 return DT->getNode(BB);
809 /// getNode - return the (Post)DominatorTree node for the specified basic
810 /// block. This is the same as using operator[] on this class.
812 inline DomTreeNode *getNode(BasicBlock *BB) const {
813 return DT->getNode(BB);
816 /// addNewBlock - Add a new node to the dominator tree information. This
817 /// creates a new node as a child of DomBB dominator node,linking it into
818 /// the children list of the immediate dominator.
819 inline DomTreeNode *addNewBlock(BasicBlock *BB, BasicBlock *DomBB) {
820 return DT->addNewBlock(BB, DomBB);
823 /// changeImmediateDominator - This method is used to update the dominator
824 /// tree information when a node's immediate dominator changes.
826 inline void changeImmediateDominator(BasicBlock *N, BasicBlock* NewIDom) {
827 DT->changeImmediateDominator(N, NewIDom);
830 inline void changeImmediateDominator(DomTreeNode *N, DomTreeNode* NewIDom) {
831 DT->changeImmediateDominator(N, NewIDom);
834 /// eraseNode - Removes a node from the dominator tree. Block must not
835 /// domiante any other blocks. Removes node from its immediate dominator's
836 /// children list. Deletes dominator node associated with basic block BB.
837 inline void eraseNode(BasicBlock *BB) {
841 /// splitBlock - BB is split and now it has one successor. Update dominator
842 /// tree to reflect this change.
843 inline void splitBlock(BasicBlock* NewBB) {
844 DT->splitBlock(NewBB);
847 bool isReachableFromEntry(BasicBlock* A) {
848 return DT->isReachableFromEntry(A);
852 virtual void releaseMemory() {
856 virtual void print(std::ostream &OS, const Module* M= 0) const {
861 //===-------------------------------------
862 /// DominatorTree GraphTraits specialization so the DominatorTree can be
863 /// iterable by generic graph iterators.
865 template <> struct GraphTraits<DomTreeNode *> {
866 typedef DomTreeNode NodeType;
867 typedef NodeType::iterator ChildIteratorType;
869 static NodeType *getEntryNode(NodeType *N) {
872 static inline ChildIteratorType child_begin(NodeType* N) {
875 static inline ChildIteratorType child_end(NodeType* N) {
880 template <> struct GraphTraits<DominatorTree*>
881 : public GraphTraits<DomTreeNode *> {
882 static NodeType *getEntryNode(DominatorTree *DT) {
883 return DT->getRootNode();
888 //===----------------------------------------------------------------------===//
889 /// DominanceFrontierBase - Common base class for computing forward and inverse
890 /// dominance frontiers for a function.
892 class DominanceFrontierBase : public FunctionPass {
894 typedef std::set<BasicBlock*> DomSetType; // Dom set for a bb
895 typedef std::map<BasicBlock*, DomSetType> DomSetMapType; // Dom set map
897 DomSetMapType Frontiers;
898 std::vector<BasicBlock*> Roots;
899 const bool IsPostDominators;
902 DominanceFrontierBase(intptr_t ID, bool isPostDom)
903 : FunctionPass(ID), IsPostDominators(isPostDom) {}
905 /// getRoots - Return the root blocks of the current CFG. This may include
906 /// multiple blocks if we are computing post dominators. For forward
907 /// dominators, this will always be a single block (the entry node).
909 inline const std::vector<BasicBlock*> &getRoots() const { return Roots; }
911 /// isPostDominator - Returns true if analysis based of postdoms
913 bool isPostDominator() const { return IsPostDominators; }
915 virtual void releaseMemory() { Frontiers.clear(); }
917 // Accessor interface:
918 typedef DomSetMapType::iterator iterator;
919 typedef DomSetMapType::const_iterator const_iterator;
920 iterator begin() { return Frontiers.begin(); }
921 const_iterator begin() const { return Frontiers.begin(); }
922 iterator end() { return Frontiers.end(); }
923 const_iterator end() const { return Frontiers.end(); }
924 iterator find(BasicBlock *B) { return Frontiers.find(B); }
925 const_iterator find(BasicBlock *B) const { return Frontiers.find(B); }
927 void addBasicBlock(BasicBlock *BB, const DomSetType &frontier) {
928 assert(find(BB) == end() && "Block already in DominanceFrontier!");
929 Frontiers.insert(std::make_pair(BB, frontier));
932 /// removeBlock - Remove basic block BB's frontier.
933 void removeBlock(BasicBlock *BB) {
934 assert(find(BB) != end() && "Block is not in DominanceFrontier!");
935 for (iterator I = begin(), E = end(); I != E; ++I)
940 void addToFrontier(iterator I, BasicBlock *Node) {
941 assert(I != end() && "BB is not in DominanceFrontier!");
942 I->second.insert(Node);
945 void removeFromFrontier(iterator I, BasicBlock *Node) {
946 assert(I != end() && "BB is not in DominanceFrontier!");
947 assert(I->second.count(Node) && "Node is not in DominanceFrontier of BB");
948 I->second.erase(Node);
951 /// compareDomSet - Return false if two domsets match. Otherwise
953 bool compareDomSet(DomSetType &DS1, const DomSetType &DS2) const {
954 std::set<BasicBlock *> tmpSet;
955 for (DomSetType::const_iterator I = DS2.begin(),
956 E = DS2.end(); I != E; ++I)
959 for (DomSetType::const_iterator I = DS1.begin(),
960 E = DS1.end(); I != E; ++I) {
961 BasicBlock *Node = *I;
963 if (tmpSet.erase(Node) == 0)
964 // Node is in DS1 but not in DS2.
969 // There are nodes that are in DS2 but not in DS1.
972 // DS1 and DS2 matches.
976 /// compare - Return true if the other dominance frontier base matches
977 /// this dominance frontier base. Otherwise return false.
978 bool compare(DominanceFrontierBase &Other) const {
979 DomSetMapType tmpFrontiers;
980 for (DomSetMapType::const_iterator I = Other.begin(),
981 E = Other.end(); I != E; ++I)
982 tmpFrontiers.insert(std::make_pair(I->first, I->second));
984 for (DomSetMapType::iterator I = tmpFrontiers.begin(),
985 E = tmpFrontiers.end(); I != E; ++I) {
986 BasicBlock *Node = I->first;
987 const_iterator DFI = find(Node);
991 if (compareDomSet(I->second, DFI->second))
994 tmpFrontiers.erase(Node);
997 if (!tmpFrontiers.empty())
1003 /// print - Convert to human readable form
1005 virtual void print(std::ostream &OS, const Module* = 0) const;
1006 void print(std::ostream *OS, const Module* M = 0) const {
1007 if (OS) print(*OS, M);
1009 virtual void dump();
1013 //===-------------------------------------
1014 /// DominanceFrontier Class - Concrete subclass of DominanceFrontierBase that is
1015 /// used to compute a forward dominator frontiers.
1017 class DominanceFrontier : public DominanceFrontierBase {
1019 static char ID; // Pass ID, replacement for typeid
1020 DominanceFrontier() :
1021 DominanceFrontierBase(intptr_t(&ID), false) {}
1023 BasicBlock *getRoot() const {
1024 assert(Roots.size() == 1 && "Should always have entry node!");
1028 virtual bool runOnFunction(Function &) {
1030 DominatorTree &DT = getAnalysis<DominatorTree>();
1031 Roots = DT.getRoots();
1032 assert(Roots.size() == 1 && "Only one entry block for forward domfronts!");
1033 calculate(DT, DT[Roots[0]]);
1037 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1038 AU.setPreservesAll();
1039 AU.addRequired<DominatorTree>();
1042 /// splitBlock - BB is split and now it has one successor. Update dominance
1043 /// frontier to reflect this change.
1044 void splitBlock(BasicBlock *BB);
1046 /// BasicBlock BB's new dominator is NewBB. Update BB's dominance frontier
1047 /// to reflect this change.
1048 void changeImmediateDominator(BasicBlock *BB, BasicBlock *NewBB,
1049 DominatorTree *DT) {
1050 // NewBB is now dominating BB. Which means BB's dominance
1051 // frontier is now part of NewBB's dominance frontier. However, BB
1052 // itself is not member of NewBB's dominance frontier.
1053 DominanceFrontier::iterator NewDFI = find(NewBB);
1054 DominanceFrontier::iterator DFI = find(BB);
1055 // If BB was an entry block then its frontier is empty.
1058 DominanceFrontier::DomSetType BBSet = DFI->second;
1059 for (DominanceFrontier::DomSetType::iterator BBSetI = BBSet.begin(),
1060 BBSetE = BBSet.end(); BBSetI != BBSetE; ++BBSetI) {
1061 BasicBlock *DFMember = *BBSetI;
1062 // Insert only if NewBB dominates DFMember.
1063 if (!DT->dominates(NewBB, DFMember))
1064 NewDFI->second.insert(DFMember);
1066 NewDFI->second.erase(BB);
1069 const DomSetType &calculate(const DominatorTree &DT,
1070 const DomTreeNode *Node);
1074 } // End llvm namespace