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"
30 static std::ostream &operator<<(std::ostream &o,
31 const std::set<BasicBlock*> &BBs) {
32 for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
35 WriteAsOperand(o, *I, false);
37 o << " <<exit node>>";
42 //===----------------------------------------------------------------------===//
43 // DominatorTree Implementation
44 //===----------------------------------------------------------------------===//
46 // DominatorTree construction - This pass constructs immediate dominator
47 // information for a flow-graph based on the algorithm described in this
50 // A Fast Algorithm for Finding Dominators in a Flowgraph
51 // T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
53 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
54 // LINK, but it turns out that the theoretically slower O(n*log(n))
55 // implementation is actually faster than the "efficient" algorithm (even for
56 // large CFGs) because the constant overheads are substantially smaller. The
57 // lower-complexity version can be enabled with the following #define:
59 #define BALANCE_IDOM_TREE 0
61 //===----------------------------------------------------------------------===//
63 char DominatorTree::ID = 0;
64 static RegisterPass<DominatorTree>
65 E("domtree", "Dominator Tree Construction", true);
67 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
69 // This is more understandable as a recursive algorithm, but we can't use the
70 // recursive algorithm due to stack depth issues. Keep it here for
71 // documentation purposes.
76 Vertex.push_back(V); // Vertex[n] = V;
77 //Info[V].Ancestor = 0; // Ancestor[n] = 0
78 //Info[V].Child = 0; // Child[v] = 0
79 VInfo.Size = 1; // Size[v] = 1
81 for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
82 InfoRec &SuccVInfo = Info[*SI];
83 if (SuccVInfo.Semi == 0) {
85 N = DFSPass(*SI, SuccVInfo, N);
89 std::vector<std::pair<BasicBlock*, unsigned> > Worklist;
90 Worklist.push_back(std::make_pair(V, 0U));
91 while (!Worklist.empty()) {
92 BasicBlock *BB = Worklist.back().first;
93 unsigned NextSucc = Worklist.back().second;
95 // First time we visited this BB?
97 InfoRec &BBInfo = Info[BB];
101 Vertex.push_back(BB); // Vertex[n] = V;
102 //BBInfo[V].Ancestor = 0; // Ancestor[n] = 0
103 //BBInfo[V].Child = 0; // Child[v] = 0
104 BBInfo.Size = 1; // Size[v] = 1
107 // If we are done with this block, remove it from the worklist.
108 if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
113 // Otherwise, increment the successor number for the next time we get to it.
114 ++Worklist.back().second;
116 // Visit the successor next, if it isn't already visited.
117 BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
119 InfoRec &SuccVInfo = Info[Succ];
120 if (SuccVInfo.Semi == 0) {
121 SuccVInfo.Parent = BB;
122 Worklist.push_back(std::make_pair(Succ, 0U));
129 void DominatorTree::Compress(BasicBlock *VIn) {
131 std::vector<BasicBlock *> Work;
132 std::set<BasicBlock *> Visited;
133 InfoRec &VInInfo = Info[VIn];
134 BasicBlock *VInAncestor = VInInfo.Ancestor;
135 InfoRec &VInVAInfo = Info[VInAncestor];
137 if (VInVAInfo.Ancestor != 0)
140 while (!Work.empty()) {
141 BasicBlock *V = Work.back();
142 InfoRec &VInfo = Info[V];
143 BasicBlock *VAncestor = VInfo.Ancestor;
144 InfoRec &VAInfo = Info[VAncestor];
146 // Process Ancestor first
147 if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
148 Work.push_back(VAncestor);
149 Visited.insert(VAncestor);
154 // Update VINfo based on Ancestor info
155 if (VAInfo.Ancestor == 0)
157 BasicBlock *VAncestorLabel = VAInfo.Label;
158 BasicBlock *VLabel = VInfo.Label;
159 if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
160 VInfo.Label = VAncestorLabel;
161 VInfo.Ancestor = VAInfo.Ancestor;
165 BasicBlock *DominatorTree::Eval(BasicBlock *V) {
166 InfoRec &VInfo = Info[V];
167 #if !BALANCE_IDOM_TREE
168 // Higher-complexity but faster implementation
169 if (VInfo.Ancestor == 0)
174 // Lower-complexity but slower implementation
175 if (VInfo.Ancestor == 0)
178 BasicBlock *VLabel = VInfo.Label;
180 BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
181 if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
184 return VAncestorLabel;
188 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
189 #if !BALANCE_IDOM_TREE
190 // Higher-complexity but faster implementation
193 // Lower-complexity but slower implementation
194 BasicBlock *WLabel = WInfo.Label;
195 unsigned WLabelSemi = Info[WLabel].Semi;
197 InfoRec *SInfo = &Info[S];
199 BasicBlock *SChild = SInfo->Child;
200 InfoRec *SChildInfo = &Info[SChild];
202 while (WLabelSemi < Info[SChildInfo->Label].Semi) {
203 BasicBlock *SChildChild = SChildInfo->Child;
204 if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
205 SChildInfo->Ancestor = S;
206 SInfo->Child = SChild = SChildChild;
207 SChildInfo = &Info[SChild];
209 SChildInfo->Size = SInfo->Size;
210 S = SInfo->Ancestor = SChild;
212 SChild = SChildChild;
213 SChildInfo = &Info[SChild];
217 InfoRec &VInfo = Info[V];
218 SInfo->Label = WLabel;
220 assert(V != W && "The optimization here will not work in this case!");
221 unsigned WSize = WInfo.Size;
222 unsigned VSize = (VInfo.Size += WSize);
225 std::swap(S, VInfo.Child);
235 void DominatorTree::calculate(Function& F) {
236 BasicBlock* Root = Roots[0];
238 // Add a node for the root...
239 ETNode *ERoot = new ETNode(Root);
240 ETNodes[Root] = ERoot;
241 DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0, ERoot);
245 // Step #1: Number blocks in depth-first order and initialize variables used
246 // in later stages of the algorithm.
248 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
249 N = DFSPass(Roots[i], Info[Roots[i]], 0);
251 for (unsigned i = N; i >= 2; --i) {
252 BasicBlock *W = Vertex[i];
253 InfoRec &WInfo = Info[W];
255 // Step #2: Calculate the semidominators of all vertices
256 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
257 if (Info.count(*PI)) { // Only if this predecessor is reachable!
258 unsigned SemiU = Info[Eval(*PI)].Semi;
259 if (SemiU < WInfo.Semi)
263 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
265 BasicBlock *WParent = WInfo.Parent;
266 Link(WParent, W, WInfo);
268 // Step #3: Implicitly define the immediate dominator of vertices
269 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
270 while (!WParentBucket.empty()) {
271 BasicBlock *V = WParentBucket.back();
272 WParentBucket.pop_back();
273 BasicBlock *U = Eval(V);
274 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
278 // Step #4: Explicitly define the immediate dominator of each vertex
279 for (unsigned i = 2; i <= N; ++i) {
280 BasicBlock *W = Vertex[i];
281 BasicBlock *&WIDom = IDoms[W];
282 if (WIDom != Vertex[Info[W].Semi])
283 WIDom = IDoms[WIDom];
286 // Loop over all of the reachable blocks in the function...
287 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
288 if (BasicBlock *ImmDom = getIDom(I)) { // Reachable block.
289 DomTreeNode *&BBNode = DomTreeNodes[I];
290 if (!BBNode) { // Haven't calculated this node yet?
291 // Get or calculate the node for the immediate dominator
292 DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
294 // Add a new tree node for this BasicBlock, and link it as a child of
296 ETNode *ET = new ETNode(I);
298 DomTreeNode *C = new DomTreeNode(I, IDomNode, ET);
300 BBNode = IDomNode->addChild(C);
304 // Free temporary memory used to construct idom's
307 std::vector<BasicBlock*>().swap(Vertex);
312 void DominatorTreeBase::updateDFSNumbers()
315 // Iterate over all nodes in depth first order.
316 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
317 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
318 E = df_end(Roots[i]); I != E; ++I) {
320 DomTreeNode *BBNode = getNode(BB);
322 ETNode *ETN = BBNode->getETNode();
323 if (ETN && !ETN->hasFather())
324 ETN->assignDFSNumber(dfsnum);
331 /// isReachableFromEntry - Return true if A is dominated by the entry
332 /// block of the function containing it.
333 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
334 return dominates(&A->getParent()->getEntryBlock(), A);
337 // dominates - Return true if A dominates B. THis performs the
338 // special checks necessary if A and B are in the same basic block.
339 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
340 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
341 if (BBA != BBB) return dominates(BBA, BBB);
343 // It is not possible to determine dominance between two PHI nodes
344 // based on their ordering.
345 if (isa<PHINode>(A) && isa<PHINode>(B))
348 // Loop through the basic block until we find A or B.
349 BasicBlock::iterator I = BBA->begin();
350 for (; &*I != A && &*I != B; ++I) /*empty*/;
352 if(!IsPostDominators) {
353 // A dominates B if it is found first in the basic block.
356 // A post-dominates B if B is found first in the basic block.
361 // DominatorTreeBase::reset - Free all of the tree node memory.
363 void DominatorTreeBase::reset() {
364 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), E = DomTreeNodes.end(); I != E; ++I)
366 DomTreeNodes.clear();
373 /// findNearestCommonDominator - Find nearest common dominator basic block
374 /// for basic block A and B. If there is no such block then return NULL.
375 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A, BasicBlock *B) {
377 assert (!isPostDominator() && "This is not implemented for post dominators");
378 assert (A->getParent() == B->getParent() && "Two blocks are not in same function");
380 // If either A or B is a entry block then it is nearest common dominator.
381 BasicBlock &Entry = A->getParent()->getEntryBlock();
382 if (A == &Entry || B == &Entry)
385 // If A and B are same then A is nearest common dominator.
386 DomTreeNode *NodeA = getNode(A);
387 if (A != 0 && A == B)
390 DomTreeNode *NodeB = getNode(B);
392 // Collect NodeA dominators set.
393 std::set<DomTreeNode *> NodeADoms;
394 NodeADoms.insert(NodeA);
395 DomTreeNode *IDomA = NodeA->getIDom();
397 NodeADoms.insert(IDomA);
398 IDomA = IDomA->getIDom();
401 // If B dominates A then B is nearest common dominator.
402 if (NodeADoms.count(NodeB) != 0)
405 // Walk NodeB immediate dominators chain and find common dominator node.
406 DomTreeNode *IDomB = NodeB->getIDom();
408 if (NodeADoms.count(IDomB) != 0)
409 return IDomB->getBlock();
411 IDomB = IDomB->getIDom();
417 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
418 assert(IDom && "No immediate dominator?");
419 if (IDom != NewIDom) {
420 std::vector<DomTreeNode*>::iterator I =
421 std::find(IDom->Children.begin(), IDom->Children.end(), this);
422 assert(I != IDom->Children.end() &&
423 "Not in immediate dominator children set!");
424 // I am no longer your child...
425 IDom->Children.erase(I);
427 // Switch to new dominator
429 IDom->Children.push_back(this);
431 if (!ETN->hasFather())
432 ETN->setFather(IDom->getETNode());
433 else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
435 ETN->setFather(IDom->getETNode());
440 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
441 DomTreeNode *&BBNode = DomTreeNodes[BB];
442 if (BBNode) return BBNode;
444 // Haven't calculated this node yet? Get or calculate the node for the
445 // immediate dominator.
446 BasicBlock *IDom = getIDom(BB);
447 DomTreeNode *IDomNode = getNodeForBlock(IDom);
449 // Add a new tree node for this BasicBlock, and link it as a child of
451 ETNode *ET = new ETNode(BB);
453 DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
454 DomTreeNodes[BB] = C;
455 return BBNode = IDomNode->addChild(C);
458 static std::ostream &operator<<(std::ostream &o,
459 const DomTreeNode *Node) {
460 if (Node->getBlock())
461 WriteAsOperand(o, Node->getBlock(), false);
463 o << " <<exit node>>";
467 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
469 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
470 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
472 PrintDomTree(*I, o, Lev+1);
475 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
476 o << "=============================--------------------------------\n"
477 << "Inorder Dominator Tree:\n";
478 PrintDomTree(getRootNode(), o, 1);
481 void DominatorTreeBase::dump() {
485 bool DominatorTree::runOnFunction(Function &F) {
486 reset(); // Reset from the last time we were run...
487 Roots.push_back(&F.getEntryBlock());
492 //===----------------------------------------------------------------------===//
493 // DominanceFrontier Implementation
494 //===----------------------------------------------------------------------===//
496 char DominanceFrontier::ID = 0;
497 static RegisterPass<DominanceFrontier>
498 G("domfrontier", "Dominance Frontier Construction", true);
501 class DFCalculateWorkObject {
503 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
504 const DomTreeNode *N,
505 const DomTreeNode *PN)
506 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
507 BasicBlock *currentBB;
508 BasicBlock *parentBB;
509 const DomTreeNode *Node;
510 const DomTreeNode *parentNode;
514 const DominanceFrontier::DomSetType &
515 DominanceFrontier::calculate(const DominatorTree &DT,
516 const DomTreeNode *Node) {
517 BasicBlock *BB = Node->getBlock();
518 DomSetType *Result = NULL;
520 std::vector<DFCalculateWorkObject> workList;
521 SmallPtrSet<BasicBlock *, 32> visited;
523 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
525 DFCalculateWorkObject *currentW = &workList.back();
526 assert (currentW && "Missing work object.");
528 BasicBlock *currentBB = currentW->currentBB;
529 BasicBlock *parentBB = currentW->parentBB;
530 const DomTreeNode *currentNode = currentW->Node;
531 const DomTreeNode *parentNode = currentW->parentNode;
532 assert (currentBB && "Invalid work object. Missing current Basic Block");
533 assert (currentNode && "Invalid work object. Missing current Node");
534 DomSetType &S = Frontiers[currentBB];
536 // Visit each block only once.
537 if (visited.count(currentBB) == 0) {
538 visited.insert(currentBB);
540 // Loop over CFG successors to calculate DFlocal[currentNode]
541 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
543 // Does Node immediately dominate this successor?
544 if (DT[*SI]->getIDom() != currentNode)
549 // At this point, S is DFlocal. Now we union in DFup's of our children...
550 // Loop through and visit the nodes that Node immediately dominates (Node's
551 // children in the IDomTree)
552 bool visitChild = false;
553 for (DomTreeNode::const_iterator NI = currentNode->begin(),
554 NE = currentNode->end(); NI != NE; ++NI) {
555 DomTreeNode *IDominee = *NI;
556 BasicBlock *childBB = IDominee->getBlock();
557 if (visited.count(childBB) == 0) {
558 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
559 IDominee, currentNode));
564 // If all children are visited or there is any child then pop this block
565 // from the workList.
573 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
574 DomSetType &parentSet = Frontiers[parentBB];
575 for (; CDFI != CDFE; ++CDFI) {
576 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
577 parentSet.insert(*CDFI);
582 } while (!workList.empty());
587 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
588 for (const_iterator I = begin(), E = end(); I != E; ++I) {
589 o << " DomFrontier for BB";
591 WriteAsOperand(o, I->first, false);
593 o << " <<exit node>>";
594 o << " is:\t" << I->second << "\n";
598 void DominanceFrontierBase::dump() {
603 //===----------------------------------------------------------------------===//
604 // ETOccurrence Implementation
605 //===----------------------------------------------------------------------===//
607 void ETOccurrence::Splay() {
608 ETOccurrence *father;
609 ETOccurrence *grandfather;
617 fatherdepth = Parent->Depth;
618 grandfather = father->Parent;
620 // If we have no grandparent, a single zig or zag will do.
622 setDepthAdd(fatherdepth);
623 MinOccurrence = father->MinOccurrence;
626 // See what we have to rotate
627 if (father->Left == this) {
629 father->setLeft(Right);
632 father->Left->setDepthAdd(occdepth);
635 father->setRight(Left);
638 father->Right->setDepthAdd(occdepth);
640 father->setDepth(-occdepth);
643 father->recomputeMin();
647 // If we have a grandfather, we need to do some
648 // combination of zig and zag.
649 int grandfatherdepth = grandfather->Depth;
651 setDepthAdd(fatherdepth + grandfatherdepth);
652 MinOccurrence = grandfather->MinOccurrence;
653 Min = grandfather->Min;
655 ETOccurrence *greatgrandfather = grandfather->Parent;
657 if (grandfather->Left == father) {
658 if (father->Left == this) {
660 grandfather->setLeft(father->Right);
661 father->setLeft(Right);
663 father->setRight(grandfather);
665 father->setDepth(-occdepth);
668 father->Left->setDepthAdd(occdepth);
670 grandfather->setDepth(-fatherdepth);
671 if (grandfather->Left)
672 grandfather->Left->setDepthAdd(fatherdepth);
675 grandfather->setLeft(Right);
676 father->setRight(Left);
678 setRight(grandfather);
680 father->setDepth(-occdepth);
682 father->Right->setDepthAdd(occdepth);
683 grandfather->setDepth(-occdepth - fatherdepth);
684 if (grandfather->Left)
685 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
688 if (father->Left == this) {
690 grandfather->setRight(Left);
691 father->setLeft(Right);
692 setLeft(grandfather);
695 father->setDepth(-occdepth);
697 father->Left->setDepthAdd(occdepth);
698 grandfather->setDepth(-occdepth - fatherdepth);
699 if (grandfather->Right)
700 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
702 grandfather->setRight(father->Left);
703 father->setRight(Left);
705 father->setLeft(grandfather);
707 father->setDepth(-occdepth);
709 father->Right->setDepthAdd(occdepth);
710 grandfather->setDepth(-fatherdepth);
711 if (grandfather->Right)
712 grandfather->Right->setDepthAdd(fatherdepth);
716 // Might need one more rotate depending on greatgrandfather.
717 setParent(greatgrandfather);
718 if (greatgrandfather) {
719 if (greatgrandfather->Left == grandfather)
720 greatgrandfather->Left = this;
722 greatgrandfather->Right = this;
725 grandfather->recomputeMin();
726 father->recomputeMin();
730 //===----------------------------------------------------------------------===//
731 // ETNode implementation
732 //===----------------------------------------------------------------------===//
734 void ETNode::Split() {
735 ETOccurrence *right, *left;
736 ETOccurrence *rightmost = RightmostOcc;
737 ETOccurrence *parent;
739 // Update the occurrence tree first.
740 RightmostOcc->Splay();
742 // Find the leftmost occurrence in the rightmost subtree, then splay
744 for (right = rightmost->Right; right->Left; right = right->Left);
749 right->Left->Parent = NULL;
755 parent->Right->Parent = NULL;
757 right->setLeft(left);
759 right->recomputeMin();
762 rightmost->Depth = 0;
767 // Now update *our* tree
769 if (Father->Son == this)
772 if (Father->Son == this)
782 void ETNode::setFather(ETNode *NewFather) {
783 ETOccurrence *rightmost;
784 ETOccurrence *leftpart;
785 ETOccurrence *NewFatherOcc;
788 // First update the path in the splay tree
789 NewFatherOcc = new ETOccurrence(NewFather);
791 rightmost = NewFather->RightmostOcc;
794 leftpart = rightmost->Left;
799 NewFatherOcc->setLeft(leftpart);
800 NewFatherOcc->setRight(temp);
804 NewFatherOcc->recomputeMin();
806 rightmost->setLeft(NewFatherOcc);
808 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
809 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
810 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
814 ParentOcc = NewFatherOcc;
836 bool ETNode::Below(ETNode *other) {
837 ETOccurrence *up = other->RightmostOcc;
838 ETOccurrence *down = RightmostOcc;
845 ETOccurrence *left, *right;
855 right->Parent = NULL;
859 if (left == down || left->Parent != NULL) {
866 // If the two occurrences are in different trees, put things
867 // back the way they were.
868 if (right && right->Parent != NULL)
875 if (down->Depth <= 0)
878 return !down->Right || down->Right->Min + down->Depth >= 0;
881 ETNode *ETNode::NCA(ETNode *other) {
882 ETOccurrence *occ1 = RightmostOcc;
883 ETOccurrence *occ2 = other->RightmostOcc;
885 ETOccurrence *left, *right, *ret;
886 ETOccurrence *occmin;
900 right->Parent = NULL;
903 if (left == occ2 || (left && left->Parent != NULL)) {
908 right->Parent = occ1;
912 occ1->setRight(occ2);
917 if (occ2->Depth > 0) {
919 mindepth = occ1->Depth;
922 mindepth = occ2->Depth + occ1->Depth;
925 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
926 return ret->MinOccurrence->OccFor;
928 return occmin->OccFor;
931 void ETNode::assignDFSNumber(int num) {
932 std::vector<ETNode *> workStack;
933 std::set<ETNode *> visitedNodes;
935 workStack.push_back(this);
936 visitedNodes.insert(this);
937 this->DFSNumIn = num++;
939 while (!workStack.empty()) {
940 ETNode *Node = workStack.back();
942 // If this is leaf node then set DFSNumOut and pop the stack
944 Node->DFSNumOut = num++;
945 workStack.pop_back();
949 ETNode *son = Node->Son;
951 // Visit Node->Son first
952 if (visitedNodes.count(son) == 0) {
953 son->DFSNumIn = num++;
954 workStack.push_back(son);
955 visitedNodes.insert(son);
959 bool visitChild = false;
960 // Visit remaining children
961 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
962 if (visitedNodes.count(s) == 0) {
965 workStack.push_back(s);
966 visitedNodes.insert(s);
971 // If we reach here means all children are visited
972 Node->DFSNumOut = num++;
973 workStack.pop_back();
978 //===----------------------------------------------------------------------===//
979 // ETForest implementation
980 //===----------------------------------------------------------------------===//
982 char ETForest::ID = 0;
983 static RegisterPass<ETForest>
984 D("etforest", "ET Forest Construction", true);
986 void ETForestBase::reset() {
987 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
992 void ETForestBase::updateDFSNumbers()
995 // Iterate over all nodes in depth first order.
996 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
997 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
998 E = df_end(Roots[i]); I != E; ++I) {
1000 ETNode *ETN = getNode(BB);
1001 if (ETN && !ETN->hasFather())
1002 ETN->assignDFSNumber(dfsnum);
1005 DFSInfoValid = true;
1008 // dominates - Return true if A dominates B. THis performs the
1009 // special checks necessary if A and B are in the same basic block.
1010 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
1011 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
1012 if (BBA != BBB) return dominates(BBA, BBB);
1014 // It is not possible to determine dominance between two PHI nodes
1015 // based on their ordering.
1016 if (isa<PHINode>(A) && isa<PHINode>(B))
1019 // Loop through the basic block until we find A or B.
1020 BasicBlock::iterator I = BBA->begin();
1021 for (; &*I != A && &*I != B; ++I) /*empty*/;
1023 if(!IsPostDominators) {
1024 // A dominates B if it is found first in the basic block.
1027 // A post-dominates B if B is found first in the basic block.
1032 /// isReachableFromEntry - Return true if A is dominated by the entry
1033 /// block of the function containing it.
1034 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
1035 return dominates(&A->getParent()->getEntryBlock(), A);
1038 // FIXME : There is no need to make getNodeForBlock public. Fix
1039 // predicate simplifier.
1040 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
1041 ETNode *&BBNode = Nodes[BB];
1042 if (BBNode) return BBNode;
1044 // Haven't calculated this node yet? Get or calculate the node for the
1045 // immediate dominator.
1046 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1048 // If we are unreachable, we may not have an immediate dominator.
1049 if (!node || !node->getIDom())
1050 return BBNode = new ETNode(BB);
1052 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1054 // Add a new tree node for this BasicBlock, and link it as a child of
1056 BBNode = new ETNode(BB);
1057 BBNode->setFather(IDomNode);
1062 void ETForest::calculate(const DominatorTree &DT) {
1063 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1064 BasicBlock *Root = Roots[0];
1065 Nodes[Root] = new ETNode(Root); // Add a node for the root
1067 Function *F = Root->getParent();
1068 // Loop over all of the reachable blocks in the function...
1069 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1070 DomTreeNode* node = DT.getNode(I);
1071 if (node && node->getIDom()) { // Reachable block.
1072 BasicBlock* ImmDom = node->getIDom()->getBlock();
1073 ETNode *&BBNode = Nodes[I];
1074 if (!BBNode) { // Haven't calculated this node yet?
1075 // Get or calculate the node for the immediate dominator
1076 ETNode *IDomNode = getNodeForBlock(ImmDom);
1078 // Add a new ETNode for this BasicBlock, and set it's parent
1079 // to it's immediate dominator.
1080 BBNode = new ETNode(I);
1081 BBNode->setFather(IDomNode);
1086 // Make sure we've got nodes around for every block
1087 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1088 ETNode *&BBNode = Nodes[I];
1090 BBNode = new ETNode(I);
1093 updateDFSNumbers ();
1096 //===----------------------------------------------------------------------===//
1097 // ETForestBase Implementation
1098 //===----------------------------------------------------------------------===//
1100 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1101 ETNode *&BBNode = Nodes[BB];
1102 assert(!BBNode && "BasicBlock already in ET-Forest");
1104 BBNode = new ETNode(BB);
1105 BBNode->setFather(getNode(IDom));
1106 DFSInfoValid = false;
1109 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1110 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1111 assert(getNode(newIDom) && "IDom not in ET-Forest");
1113 ETNode *Node = getNode(BB);
1114 if (Node->hasFather()) {
1115 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1119 Node->setFather(getNode(newIDom));
1120 DFSInfoValid= false;
1123 void ETForestBase::print(std::ostream &o, const Module *) const {
1124 o << "=============================--------------------------------\n";
1125 o << "ET Forest:\n";
1131 o << " up to date\n";
1133 Function *F = getRoots()[0]->getParent();
1134 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1135 o << " DFS Numbers For Basic Block:";
1136 WriteAsOperand(o, I, false);
1138 if (ETNode *EN = getNode(I)) {
1139 o << "In: " << EN->getDFSNumIn();
1140 o << " Out: " << EN->getDFSNumOut() << "\n";
1142 o << "No associated ETNode";
1149 void ETForestBase::dump() {