1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements simple dominator construction algorithms for finding
11 // forward dominators. Postdominators are available in libanalysis, but are not
12 // included in libvmcore, because it's not needed. Forward dominators are
13 // needed to support the Verifier pass.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Analysis/Dominators.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/SetOperations.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Support/Streams.h"
29 static std::ostream &operator<<(std::ostream &o,
30 const std::set<BasicBlock*> &BBs) {
31 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
34 WriteAsOperand(o, *I, false);
36 o << " <<exit node>>";
41 //===----------------------------------------------------------------------===//
42 // DominatorTree Implementation
43 //===----------------------------------------------------------------------===//
45 // DominatorTree construction - This pass constructs immediate dominator
46 // information for a flow-graph based on the algorithm described in this
49 // A Fast Algorithm for Finding Dominators in a Flowgraph
50 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
52 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
53 // LINK, but it turns out that the theoretically slower O(n*log(n))
54 // implementation is actually faster than the "efficient" algorithm (even for
55 // large CFGs) because the constant overheads are substantially smaller. The
56 // lower-complexity version can be enabled with the following #define:
58 #define BALANCE_IDOM_TREE 0
60 //===----------------------------------------------------------------------===//
62 char DominatorTree::ID = 0;
63 static RegisterPass<DominatorTree>
64 E("domtree", "Dominator Tree Construction", true);
66 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
68 // This is more understandable as a recursive algorithm, but we can't use the
69 // recursive algorithm due to stack depth issues. Keep it here for
70 // documentation purposes.
75 Vertex.push_back(V); // Vertex[n] = V;
76 //Info[V].Ancestor = 0; // Ancestor[n] = 0
77 //Info[V].Child = 0; // Child[v] = 0
78 VInfo.Size = 1; // Size[v] = 1
80 for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
81 InfoRec &SuccVInfo = Info[*SI];
82 if (SuccVInfo.Semi == 0) {
84 N = DFSPass(*SI, SuccVInfo, N);
88 std::vector<std::pair<BasicBlock*, unsigned> > Worklist;
89 Worklist.push_back(std::make_pair(V, 0U));
90 while (!Worklist.empty()) {
91 BasicBlock *BB = Worklist.back().first;
92 unsigned NextSucc = Worklist.back().second;
94 // First time we visited this BB?
96 InfoRec &BBInfo = Info[BB];
100 Vertex.push_back(BB); // Vertex[n] = V;
101 //BBInfo[V].Ancestor = 0; // Ancestor[n] = 0
102 //BBInfo[V].Child = 0; // Child[v] = 0
103 BBInfo.Size = 1; // Size[v] = 1
106 // If we are done with this block, remove it from the worklist.
107 if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
112 // Otherwise, increment the successor number for the next time we get to it.
113 ++Worklist.back().second;
115 // Visit the successor next, if it isn't already visited.
116 BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
118 InfoRec &SuccVInfo = Info[Succ];
119 if (SuccVInfo.Semi == 0) {
120 SuccVInfo.Parent = BB;
121 Worklist.push_back(std::make_pair(Succ, 0U));
128 void DominatorTree::Compress(BasicBlock *VIn) {
130 std::vector<BasicBlock *> Work;
131 std::set<BasicBlock *> Visited;
132 InfoRec &VInInfo = Info[VIn];
133 BasicBlock *VInAncestor = VInInfo.Ancestor;
134 InfoRec &VInVAInfo = Info[VInAncestor];
136 if (VInVAInfo.Ancestor != 0)
139 while (!Work.empty()) {
140 BasicBlock *V = Work.back();
141 InfoRec &VInfo = Info[V];
142 BasicBlock *VAncestor = VInfo.Ancestor;
143 InfoRec &VAInfo = Info[VAncestor];
145 // Process Ancestor first
146 if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
147 Work.push_back(VAncestor);
148 Visited.insert(VAncestor);
153 // Update VINfo based on Ancestor info
154 if (VAInfo.Ancestor == 0)
156 BasicBlock *VAncestorLabel = VAInfo.Label;
157 BasicBlock *VLabel = VInfo.Label;
158 if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
159 VInfo.Label = VAncestorLabel;
160 VInfo.Ancestor = VAInfo.Ancestor;
164 BasicBlock *DominatorTree::Eval(BasicBlock *V) {
165 InfoRec &VInfo = Info[V];
166 #if !BALANCE_IDOM_TREE
167 // Higher-complexity but faster implementation
168 if (VInfo.Ancestor == 0)
173 // Lower-complexity but slower implementation
174 if (VInfo.Ancestor == 0)
177 BasicBlock *VLabel = VInfo.Label;
179 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
180 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
183 return VAncestorLabel;
187 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
188 #if !BALANCE_IDOM_TREE
189 // Higher-complexity but faster implementation
192 // Lower-complexity but slower implementation
193 BasicBlock *WLabel = WInfo.Label;
194 unsigned WLabelSemi = Info[WLabel].Semi;
196 InfoRec *SInfo = &Info[S];
198 BasicBlock *SChild = SInfo->Child;
199 InfoRec *SChildInfo = &Info[SChild];
201 while (WLabelSemi < Info[SChildInfo->Label].Semi) {
202 BasicBlock *SChildChild = SChildInfo->Child;
203 if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
204 SChildInfo->Ancestor = S;
205 SInfo->Child = SChild = SChildChild;
206 SChildInfo = &Info[SChild];
208 SChildInfo->Size = SInfo->Size;
209 S = SInfo->Ancestor = SChild;
211 SChild = SChildChild;
212 SChildInfo = &Info[SChild];
216 InfoRec &VInfo = Info[V];
217 SInfo->Label = WLabel;
219 assert(V != W && "The optimization here will not work in this case!");
220 unsigned WSize = WInfo.Size;
221 unsigned VSize = (VInfo.Size += WSize);
224 std::swap(S, VInfo.Child);
234 void DominatorTree::calculate(Function& F) {
235 BasicBlock* Root = Roots[0];
237 // Add a node for the root...
238 ETNode *ERoot = new ETNode(Root);
239 ETNodes[Root] = ERoot;
240 DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0, ERoot);
244 // Step #1: Number blocks in depth-first order and initialize variables used
245 // in later stages of the algorithm.
247 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
248 N = DFSPass(Roots[i], Info[Roots[i]], 0);
250 for (unsigned i = N; i >= 2; --i) {
251 BasicBlock *W = Vertex[i];
252 InfoRec &WInfo = Info[W];
254 // Step #2: Calculate the semidominators of all vertices
255 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
256 if (Info.count(*PI)) { // Only if this predecessor is reachable!
257 unsigned SemiU = Info[Eval(*PI)].Semi;
258 if (SemiU < WInfo.Semi)
262 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
264 BasicBlock *WParent = WInfo.Parent;
265 Link(WParent, W, WInfo);
267 // Step #3: Implicitly define the immediate dominator of vertices
268 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
269 while (!WParentBucket.empty()) {
270 BasicBlock *V = WParentBucket.back();
271 WParentBucket.pop_back();
272 BasicBlock *U = Eval(V);
273 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
277 // Step #4: Explicitly define the immediate dominator of each vertex
278 for (unsigned i = 2; i <= N; ++i) {
279 BasicBlock *W = Vertex[i];
280 BasicBlock *&WIDom = IDoms[W];
281 if (WIDom != Vertex[Info[W].Semi])
282 WIDom = IDoms[WIDom];
285 // Loop over all of the reachable blocks in the function...
286 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
287 if (BasicBlock *ImmDom = getIDom(I)) { // Reachable block.
288 DomTreeNode *&BBNode = DomTreeNodes[I];
289 if (!BBNode) { // Haven't calculated this node yet?
290 // Get or calculate the node for the immediate dominator
291 DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
293 // Add a new tree node for this BasicBlock, and link it as a child of
295 ETNode *ET = new ETNode(I);
297 DomTreeNode *C = new DomTreeNode(I, IDomNode, ET);
299 BBNode = IDomNode->addChild(C);
303 // Free temporary memory used to construct idom's
306 std::vector<BasicBlock*>().swap(Vertex);
311 void DominatorTreeBase::updateDFSNumbers()
314 // Iterate over all nodes in depth first order.
315 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
316 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
317 E = df_end(Roots[i]); I != E; ++I) {
319 ETNode *ETN = getNode(BB)->getETNode();
320 if (ETN && !ETN->hasFather())
321 ETN->assignDFSNumber(dfsnum);
327 // dominates - Return true if A dominates B. THis performs the
328 // special checks necessary if A and B are in the same basic block.
329 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
330 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
331 if (BBA != BBB) return dominates(BBA, BBB);
333 // It is not possible to determine dominance between two PHI nodes
334 // based on their ordering.
335 if (isa<PHINode>(A) && isa<PHINode>(B))
338 // Loop through the basic block until we find A or B.
339 BasicBlock::iterator I = BBA->begin();
340 for (; &*I != A && &*I != B; ++I) /*empty*/;
342 if(!IsPostDominators) {
343 // A dominates B if it is found first in the basic block.
346 // A post-dominates B if B is found first in the basic block.
351 // DominatorTreeBase::reset - Free all of the tree node memory.
353 void DominatorTreeBase::reset() {
354 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), E = DomTreeNodes.end(); I != E; ++I)
356 DomTreeNodes.clear();
363 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
364 assert(IDom && "No immediate dominator?");
365 if (IDom != NewIDom) {
366 std::vector<DomTreeNode*>::iterator I =
367 std::find(IDom->Children.begin(), IDom->Children.end(), this);
368 assert(I != IDom->Children.end() &&
369 "Not in immediate dominator children set!");
370 // I am no longer your child...
371 IDom->Children.erase(I);
373 // Switch to new dominator
375 IDom->Children.push_back(this);
377 if (!ETN->hasFather())
378 ETN->setFather(IDom->getETNode());
379 else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
381 ETN->setFather(IDom->getETNode());
386 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
387 DomTreeNode *&BBNode = DomTreeNodes[BB];
388 if (BBNode) return BBNode;
390 // Haven't calculated this node yet? Get or calculate the node for the
391 // immediate dominator.
392 BasicBlock *IDom = getIDom(BB);
393 DomTreeNode *IDomNode = getNodeForBlock(IDom);
395 // Add a new tree node for this BasicBlock, and link it as a child of
397 ETNode *ET = new ETNode(BB);
399 DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
400 DomTreeNodes[BB] = C;
401 return BBNode = IDomNode->addChild(C);
404 static std::ostream &operator<<(std::ostream &o,
405 const DomTreeNode *Node) {
406 if (Node->getBlock())
407 WriteAsOperand(o, Node->getBlock(), false);
409 o << " <<exit node>>";
413 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
415 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
416 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
418 PrintDomTree(*I, o, Lev+1);
421 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
422 o << "=============================--------------------------------\n"
423 << "Inorder Dominator Tree:\n";
424 PrintDomTree(getRootNode(), o, 1);
427 void DominatorTreeBase::dump() {
431 bool DominatorTree::runOnFunction(Function &F) {
432 reset(); // Reset from the last time we were run...
433 Roots.push_back(&F.getEntryBlock());
438 //===----------------------------------------------------------------------===//
439 // DominanceFrontier Implementation
440 //===----------------------------------------------------------------------===//
442 char DominanceFrontier::ID = 0;
443 static RegisterPass<DominanceFrontier>
444 G("domfrontier", "Dominance Frontier Construction", true);
447 class DFCalculateWorkObject {
449 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
450 const DomTreeNode *N,
451 const DomTreeNode *PN)
452 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
453 BasicBlock *currentBB;
454 BasicBlock *parentBB;
455 const DomTreeNode *Node;
456 const DomTreeNode *parentNode;
460 const DominanceFrontier::DomSetType &
461 DominanceFrontier::calculate(const DominatorTree &DT,
462 const DomTreeNode *Node) {
463 BasicBlock *BB = Node->getBlock();
464 DomSetType *Result = NULL;
466 std::vector<DFCalculateWorkObject> workList;
467 SmallPtrSet<BasicBlock *, 32> visited;
469 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
471 DFCalculateWorkObject *currentW = &workList.back();
472 assert (currentW && "Missing work object.");
474 BasicBlock *currentBB = currentW->currentBB;
475 BasicBlock *parentBB = currentW->parentBB;
476 const DomTreeNode *currentNode = currentW->Node;
477 const DomTreeNode *parentNode = currentW->parentNode;
478 assert (currentBB && "Invalid work object. Missing current Basic Block");
479 assert (currentNode && "Invalid work object. Missing current Node");
480 DomSetType &S = Frontiers[currentBB];
482 // Visit each block only once.
483 if (visited.count(currentBB) == 0) {
484 visited.insert(currentBB);
486 // Loop over CFG successors to calculate DFlocal[currentNode]
487 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
489 // Does Node immediately dominate this successor?
490 if (DT[*SI]->getIDom() != currentNode)
495 // At this point, S is DFlocal. Now we union in DFup's of our children...
496 // Loop through and visit the nodes that Node immediately dominates (Node's
497 // children in the IDomTree)
498 bool visitChild = false;
499 for (DomTreeNode::const_iterator NI = currentNode->begin(),
500 NE = currentNode->end(); NI != NE; ++NI) {
501 DomTreeNode *IDominee = *NI;
502 BasicBlock *childBB = IDominee->getBlock();
503 if (visited.count(childBB) == 0) {
504 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
505 IDominee, currentNode));
510 // If all children are visited or there is any child then pop this block
511 // from the workList.
519 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
520 DomSetType &parentSet = Frontiers[parentBB];
521 for (; CDFI != CDFE; ++CDFI) {
522 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
523 parentSet.insert(*CDFI);
528 } while (!workList.empty());
533 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
534 for (const_iterator I = begin(), E = end(); I != E; ++I) {
535 o << " DomFrontier for BB";
537 WriteAsOperand(o, I->first, false);
539 o << " <<exit node>>";
540 o << " is:\t" << I->second << "\n";
544 void DominanceFrontierBase::dump() {
549 //===----------------------------------------------------------------------===//
550 // ETOccurrence Implementation
551 //===----------------------------------------------------------------------===//
553 void ETOccurrence::Splay() {
554 ETOccurrence *father;
555 ETOccurrence *grandfather;
563 fatherdepth = Parent->Depth;
564 grandfather = father->Parent;
566 // If we have no grandparent, a single zig or zag will do.
568 setDepthAdd(fatherdepth);
569 MinOccurrence = father->MinOccurrence;
572 // See what we have to rotate
573 if (father->Left == this) {
575 father->setLeft(Right);
578 father->Left->setDepthAdd(occdepth);
581 father->setRight(Left);
584 father->Right->setDepthAdd(occdepth);
586 father->setDepth(-occdepth);
589 father->recomputeMin();
593 // If we have a grandfather, we need to do some
594 // combination of zig and zag.
595 int grandfatherdepth = grandfather->Depth;
597 setDepthAdd(fatherdepth + grandfatherdepth);
598 MinOccurrence = grandfather->MinOccurrence;
599 Min = grandfather->Min;
601 ETOccurrence *greatgrandfather = grandfather->Parent;
603 if (grandfather->Left == father) {
604 if (father->Left == this) {
606 grandfather->setLeft(father->Right);
607 father->setLeft(Right);
609 father->setRight(grandfather);
611 father->setDepth(-occdepth);
614 father->Left->setDepthAdd(occdepth);
616 grandfather->setDepth(-fatherdepth);
617 if (grandfather->Left)
618 grandfather->Left->setDepthAdd(fatherdepth);
621 grandfather->setLeft(Right);
622 father->setRight(Left);
624 setRight(grandfather);
626 father->setDepth(-occdepth);
628 father->Right->setDepthAdd(occdepth);
629 grandfather->setDepth(-occdepth - fatherdepth);
630 if (grandfather->Left)
631 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
634 if (father->Left == this) {
636 grandfather->setRight(Left);
637 father->setLeft(Right);
638 setLeft(grandfather);
641 father->setDepth(-occdepth);
643 father->Left->setDepthAdd(occdepth);
644 grandfather->setDepth(-occdepth - fatherdepth);
645 if (grandfather->Right)
646 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
648 grandfather->setRight(father->Left);
649 father->setRight(Left);
651 father->setLeft(grandfather);
653 father->setDepth(-occdepth);
655 father->Right->setDepthAdd(occdepth);
656 grandfather->setDepth(-fatherdepth);
657 if (grandfather->Right)
658 grandfather->Right->setDepthAdd(fatherdepth);
662 // Might need one more rotate depending on greatgrandfather.
663 setParent(greatgrandfather);
664 if (greatgrandfather) {
665 if (greatgrandfather->Left == grandfather)
666 greatgrandfather->Left = this;
668 greatgrandfather->Right = this;
671 grandfather->recomputeMin();
672 father->recomputeMin();
676 //===----------------------------------------------------------------------===//
677 // ETNode implementation
678 //===----------------------------------------------------------------------===//
680 void ETNode::Split() {
681 ETOccurrence *right, *left;
682 ETOccurrence *rightmost = RightmostOcc;
683 ETOccurrence *parent;
685 // Update the occurrence tree first.
686 RightmostOcc->Splay();
688 // Find the leftmost occurrence in the rightmost subtree, then splay
690 for (right = rightmost->Right; right->Left; right = right->Left);
695 right->Left->Parent = NULL;
701 parent->Right->Parent = NULL;
703 right->setLeft(left);
705 right->recomputeMin();
708 rightmost->Depth = 0;
713 // Now update *our* tree
715 if (Father->Son == this)
718 if (Father->Son == this)
728 void ETNode::setFather(ETNode *NewFather) {
729 ETOccurrence *rightmost;
730 ETOccurrence *leftpart;
731 ETOccurrence *NewFatherOcc;
734 // First update the path in the splay tree
735 NewFatherOcc = new ETOccurrence(NewFather);
737 rightmost = NewFather->RightmostOcc;
740 leftpart = rightmost->Left;
745 NewFatherOcc->setLeft(leftpart);
746 NewFatherOcc->setRight(temp);
750 NewFatherOcc->recomputeMin();
752 rightmost->setLeft(NewFatherOcc);
754 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
755 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
756 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
760 ParentOcc = NewFatherOcc;
782 bool ETNode::Below(ETNode *other) {
783 ETOccurrence *up = other->RightmostOcc;
784 ETOccurrence *down = RightmostOcc;
791 ETOccurrence *left, *right;
801 right->Parent = NULL;
805 if (left == down || left->Parent != NULL) {
812 // If the two occurrences are in different trees, put things
813 // back the way they were.
814 if (right && right->Parent != NULL)
821 if (down->Depth <= 0)
824 return !down->Right || down->Right->Min + down->Depth >= 0;
827 ETNode *ETNode::NCA(ETNode *other) {
828 ETOccurrence *occ1 = RightmostOcc;
829 ETOccurrence *occ2 = other->RightmostOcc;
831 ETOccurrence *left, *right, *ret;
832 ETOccurrence *occmin;
846 right->Parent = NULL;
849 if (left == occ2 || (left && left->Parent != NULL)) {
854 right->Parent = occ1;
858 occ1->setRight(occ2);
863 if (occ2->Depth > 0) {
865 mindepth = occ1->Depth;
868 mindepth = occ2->Depth + occ1->Depth;
871 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
872 return ret->MinOccurrence->OccFor;
874 return occmin->OccFor;
877 void ETNode::assignDFSNumber(int num) {
878 std::vector<ETNode *> workStack;
879 std::set<ETNode *> visitedNodes;
881 workStack.push_back(this);
882 visitedNodes.insert(this);
883 this->DFSNumIn = num++;
885 while (!workStack.empty()) {
886 ETNode *Node = workStack.back();
888 // If this is leaf node then set DFSNumOut and pop the stack
890 Node->DFSNumOut = num++;
891 workStack.pop_back();
895 ETNode *son = Node->Son;
897 // Visit Node->Son first
898 if (visitedNodes.count(son) == 0) {
899 son->DFSNumIn = num++;
900 workStack.push_back(son);
901 visitedNodes.insert(son);
905 bool visitChild = false;
906 // Visit remaining children
907 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
908 if (visitedNodes.count(s) == 0) {
911 workStack.push_back(s);
912 visitedNodes.insert(s);
917 // If we reach here means all children are visited
918 Node->DFSNumOut = num++;
919 workStack.pop_back();
924 //===----------------------------------------------------------------------===//
925 // ETForest implementation
926 //===----------------------------------------------------------------------===//
928 char ETForest::ID = 0;
929 static RegisterPass<ETForest>
930 D("etforest", "ET Forest Construction", true);
932 void ETForestBase::reset() {
933 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
938 void ETForestBase::updateDFSNumbers()
941 // Iterate over all nodes in depth first order.
942 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
943 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
944 E = df_end(Roots[i]); I != E; ++I) {
946 ETNode *ETN = getNode(BB);
947 if (ETN && !ETN->hasFather())
948 ETN->assignDFSNumber(dfsnum);
954 // dominates - Return true if A dominates B. THis performs the
955 // special checks necessary if A and B are in the same basic block.
956 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
957 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
958 if (BBA != BBB) return dominates(BBA, BBB);
960 // It is not possible to determine dominance between two PHI nodes
961 // based on their ordering.
962 if (isa<PHINode>(A) && isa<PHINode>(B))
965 // Loop through the basic block until we find A or B.
966 BasicBlock::iterator I = BBA->begin();
967 for (; &*I != A && &*I != B; ++I) /*empty*/;
969 if(!IsPostDominators) {
970 // A dominates B if it is found first in the basic block.
973 // A post-dominates B if B is found first in the basic block.
978 /// isReachableFromEntry - Return true if A is dominated by the entry
979 /// block of the function containing it.
980 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
981 return dominates(&A->getParent()->getEntryBlock(), A);
984 // FIXME : There is no need to make getNodeForBlock public. Fix
985 // predicate simplifier.
986 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
987 ETNode *&BBNode = Nodes[BB];
988 if (BBNode) return BBNode;
990 // Haven't calculated this node yet? Get or calculate the node for the
991 // immediate dominator.
992 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
994 // If we are unreachable, we may not have an immediate dominator.
995 if (!node || !node->getIDom())
996 return BBNode = new ETNode(BB);
998 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1000 // Add a new tree node for this BasicBlock, and link it as a child of
1002 BBNode = new ETNode(BB);
1003 BBNode->setFather(IDomNode);
1008 void ETForest::calculate(const DominatorTree &DT) {
1009 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1010 BasicBlock *Root = Roots[0];
1011 Nodes[Root] = new ETNode(Root); // Add a node for the root
1013 Function *F = Root->getParent();
1014 // Loop over all of the reachable blocks in the function...
1015 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1016 DomTreeNode* node = DT.getNode(I);
1017 if (node && node->getIDom()) { // Reachable block.
1018 BasicBlock* ImmDom = node->getIDom()->getBlock();
1019 ETNode *&BBNode = Nodes[I];
1020 if (!BBNode) { // Haven't calculated this node yet?
1021 // Get or calculate the node for the immediate dominator
1022 ETNode *IDomNode = getNodeForBlock(ImmDom);
1024 // Add a new ETNode for this BasicBlock, and set it's parent
1025 // to it's immediate dominator.
1026 BBNode = new ETNode(I);
1027 BBNode->setFather(IDomNode);
1032 // Make sure we've got nodes around for every block
1033 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1034 ETNode *&BBNode = Nodes[I];
1036 BBNode = new ETNode(I);
1039 updateDFSNumbers ();
1042 //===----------------------------------------------------------------------===//
1043 // ETForestBase Implementation
1044 //===----------------------------------------------------------------------===//
1046 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1047 ETNode *&BBNode = Nodes[BB];
1048 assert(!BBNode && "BasicBlock already in ET-Forest");
1050 BBNode = new ETNode(BB);
1051 BBNode->setFather(getNode(IDom));
1052 DFSInfoValid = false;
1055 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1056 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1057 assert(getNode(newIDom) && "IDom not in ET-Forest");
1059 ETNode *Node = getNode(BB);
1060 if (Node->hasFather()) {
1061 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1065 Node->setFather(getNode(newIDom));
1066 DFSInfoValid= false;
1069 void ETForestBase::print(std::ostream &o, const Module *) const {
1070 o << "=============================--------------------------------\n";
1071 o << "ET Forest:\n";
1077 o << " up to date\n";
1079 Function *F = getRoots()[0]->getParent();
1080 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1081 o << " DFS Numbers For Basic Block:";
1082 WriteAsOperand(o, I, false);
1084 if (ETNode *EN = getNode(I)) {
1085 o << "In: " << EN->getDFSNumIn();
1086 o << " Out: " << EN->getDFSNumOut() << "\n";
1088 o << "No associated ETNode";
1095 void ETForestBase::dump() {