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 DomTreeNode *BBNode = getNode(BB);
321 ETNode *ETN = BBNode->getETNode();
322 if (ETN && !ETN->hasFather())
323 ETN->assignDFSNumber(dfsnum);
330 /// isReachableFromEntry - Return true if A is dominated by the entry
331 /// block of the function containing it.
332 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
333 return dominates(&A->getParent()->getEntryBlock(), A);
336 // dominates - Return true if A dominates B. THis performs the
337 // special checks necessary if A and B are in the same basic block.
338 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
339 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
340 if (BBA != BBB) return dominates(BBA, BBB);
342 // It is not possible to determine dominance between two PHI nodes
343 // based on their ordering.
344 if (isa<PHINode>(A) && isa<PHINode>(B))
347 // Loop through the basic block until we find A or B.
348 BasicBlock::iterator I = BBA->begin();
349 for (; &*I != A && &*I != B; ++I) /*empty*/;
351 if(!IsPostDominators) {
352 // A dominates B if it is found first in the basic block.
355 // A post-dominates B if B is found first in the basic block.
360 // DominatorTreeBase::reset - Free all of the tree node memory.
362 void DominatorTreeBase::reset() {
363 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), E = DomTreeNodes.end(); I != E; ++I)
365 DomTreeNodes.clear();
372 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
373 assert(IDom && "No immediate dominator?");
374 if (IDom != NewIDom) {
375 std::vector<DomTreeNode*>::iterator I =
376 std::find(IDom->Children.begin(), IDom->Children.end(), this);
377 assert(I != IDom->Children.end() &&
378 "Not in immediate dominator children set!");
379 // I am no longer your child...
380 IDom->Children.erase(I);
382 // Switch to new dominator
384 IDom->Children.push_back(this);
386 if (!ETN->hasFather())
387 ETN->setFather(IDom->getETNode());
388 else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
390 ETN->setFather(IDom->getETNode());
395 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
396 DomTreeNode *&BBNode = DomTreeNodes[BB];
397 if (BBNode) return BBNode;
399 // Haven't calculated this node yet? Get or calculate the node for the
400 // immediate dominator.
401 BasicBlock *IDom = getIDom(BB);
402 DomTreeNode *IDomNode = getNodeForBlock(IDom);
404 // Add a new tree node for this BasicBlock, and link it as a child of
406 ETNode *ET = new ETNode(BB);
408 DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
409 DomTreeNodes[BB] = C;
410 return BBNode = IDomNode->addChild(C);
413 static std::ostream &operator<<(std::ostream &o,
414 const DomTreeNode *Node) {
415 if (Node->getBlock())
416 WriteAsOperand(o, Node->getBlock(), false);
418 o << " <<exit node>>";
422 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
424 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
425 for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
427 PrintDomTree(*I, o, Lev+1);
430 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
431 o << "=============================--------------------------------\n"
432 << "Inorder Dominator Tree:\n";
433 PrintDomTree(getRootNode(), o, 1);
436 void DominatorTreeBase::dump() {
440 bool DominatorTree::runOnFunction(Function &F) {
441 reset(); // Reset from the last time we were run...
442 Roots.push_back(&F.getEntryBlock());
447 //===----------------------------------------------------------------------===//
448 // DominanceFrontier Implementation
449 //===----------------------------------------------------------------------===//
451 char DominanceFrontier::ID = 0;
452 static RegisterPass<DominanceFrontier>
453 G("domfrontier", "Dominance Frontier Construction", true);
456 class DFCalculateWorkObject {
458 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
459 const DomTreeNode *N,
460 const DomTreeNode *PN)
461 : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
462 BasicBlock *currentBB;
463 BasicBlock *parentBB;
464 const DomTreeNode *Node;
465 const DomTreeNode *parentNode;
469 const DominanceFrontier::DomSetType &
470 DominanceFrontier::calculate(const DominatorTree &DT,
471 const DomTreeNode *Node) {
472 BasicBlock *BB = Node->getBlock();
473 DomSetType *Result = NULL;
475 std::vector<DFCalculateWorkObject> workList;
476 SmallPtrSet<BasicBlock *, 32> visited;
478 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
480 DFCalculateWorkObject *currentW = &workList.back();
481 assert (currentW && "Missing work object.");
483 BasicBlock *currentBB = currentW->currentBB;
484 BasicBlock *parentBB = currentW->parentBB;
485 const DomTreeNode *currentNode = currentW->Node;
486 const DomTreeNode *parentNode = currentW->parentNode;
487 assert (currentBB && "Invalid work object. Missing current Basic Block");
488 assert (currentNode && "Invalid work object. Missing current Node");
489 DomSetType &S = Frontiers[currentBB];
491 // Visit each block only once.
492 if (visited.count(currentBB) == 0) {
493 visited.insert(currentBB);
495 // Loop over CFG successors to calculate DFlocal[currentNode]
496 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
498 // Does Node immediately dominate this successor?
499 if (DT[*SI]->getIDom() != currentNode)
504 // At this point, S is DFlocal. Now we union in DFup's of our children...
505 // Loop through and visit the nodes that Node immediately dominates (Node's
506 // children in the IDomTree)
507 bool visitChild = false;
508 for (DomTreeNode::const_iterator NI = currentNode->begin(),
509 NE = currentNode->end(); NI != NE; ++NI) {
510 DomTreeNode *IDominee = *NI;
511 BasicBlock *childBB = IDominee->getBlock();
512 if (visited.count(childBB) == 0) {
513 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
514 IDominee, currentNode));
519 // If all children are visited or there is any child then pop this block
520 // from the workList.
528 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
529 DomSetType &parentSet = Frontiers[parentBB];
530 for (; CDFI != CDFE; ++CDFI) {
531 if (!DT.properlyDominates(parentNode, DT[*CDFI]))
532 parentSet.insert(*CDFI);
537 } while (!workList.empty());
542 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
543 for (const_iterator I = begin(), E = end(); I != E; ++I) {
544 o << " DomFrontier for BB";
546 WriteAsOperand(o, I->first, false);
548 o << " <<exit node>>";
549 o << " is:\t" << I->second << "\n";
553 void DominanceFrontierBase::dump() {
558 //===----------------------------------------------------------------------===//
559 // ETOccurrence Implementation
560 //===----------------------------------------------------------------------===//
562 void ETOccurrence::Splay() {
563 ETOccurrence *father;
564 ETOccurrence *grandfather;
572 fatherdepth = Parent->Depth;
573 grandfather = father->Parent;
575 // If we have no grandparent, a single zig or zag will do.
577 setDepthAdd(fatherdepth);
578 MinOccurrence = father->MinOccurrence;
581 // See what we have to rotate
582 if (father->Left == this) {
584 father->setLeft(Right);
587 father->Left->setDepthAdd(occdepth);
590 father->setRight(Left);
593 father->Right->setDepthAdd(occdepth);
595 father->setDepth(-occdepth);
598 father->recomputeMin();
602 // If we have a grandfather, we need to do some
603 // combination of zig and zag.
604 int grandfatherdepth = grandfather->Depth;
606 setDepthAdd(fatherdepth + grandfatherdepth);
607 MinOccurrence = grandfather->MinOccurrence;
608 Min = grandfather->Min;
610 ETOccurrence *greatgrandfather = grandfather->Parent;
612 if (grandfather->Left == father) {
613 if (father->Left == this) {
615 grandfather->setLeft(father->Right);
616 father->setLeft(Right);
618 father->setRight(grandfather);
620 father->setDepth(-occdepth);
623 father->Left->setDepthAdd(occdepth);
625 grandfather->setDepth(-fatherdepth);
626 if (grandfather->Left)
627 grandfather->Left->setDepthAdd(fatherdepth);
630 grandfather->setLeft(Right);
631 father->setRight(Left);
633 setRight(grandfather);
635 father->setDepth(-occdepth);
637 father->Right->setDepthAdd(occdepth);
638 grandfather->setDepth(-occdepth - fatherdepth);
639 if (grandfather->Left)
640 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
643 if (father->Left == this) {
645 grandfather->setRight(Left);
646 father->setLeft(Right);
647 setLeft(grandfather);
650 father->setDepth(-occdepth);
652 father->Left->setDepthAdd(occdepth);
653 grandfather->setDepth(-occdepth - fatherdepth);
654 if (grandfather->Right)
655 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
657 grandfather->setRight(father->Left);
658 father->setRight(Left);
660 father->setLeft(grandfather);
662 father->setDepth(-occdepth);
664 father->Right->setDepthAdd(occdepth);
665 grandfather->setDepth(-fatherdepth);
666 if (grandfather->Right)
667 grandfather->Right->setDepthAdd(fatherdepth);
671 // Might need one more rotate depending on greatgrandfather.
672 setParent(greatgrandfather);
673 if (greatgrandfather) {
674 if (greatgrandfather->Left == grandfather)
675 greatgrandfather->Left = this;
677 greatgrandfather->Right = this;
680 grandfather->recomputeMin();
681 father->recomputeMin();
685 //===----------------------------------------------------------------------===//
686 // ETNode implementation
687 //===----------------------------------------------------------------------===//
689 void ETNode::Split() {
690 ETOccurrence *right, *left;
691 ETOccurrence *rightmost = RightmostOcc;
692 ETOccurrence *parent;
694 // Update the occurrence tree first.
695 RightmostOcc->Splay();
697 // Find the leftmost occurrence in the rightmost subtree, then splay
699 for (right = rightmost->Right; right->Left; right = right->Left);
704 right->Left->Parent = NULL;
710 parent->Right->Parent = NULL;
712 right->setLeft(left);
714 right->recomputeMin();
717 rightmost->Depth = 0;
722 // Now update *our* tree
724 if (Father->Son == this)
727 if (Father->Son == this)
737 void ETNode::setFather(ETNode *NewFather) {
738 ETOccurrence *rightmost;
739 ETOccurrence *leftpart;
740 ETOccurrence *NewFatherOcc;
743 // First update the path in the splay tree
744 NewFatherOcc = new ETOccurrence(NewFather);
746 rightmost = NewFather->RightmostOcc;
749 leftpart = rightmost->Left;
754 NewFatherOcc->setLeft(leftpart);
755 NewFatherOcc->setRight(temp);
759 NewFatherOcc->recomputeMin();
761 rightmost->setLeft(NewFatherOcc);
763 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
764 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
765 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
769 ParentOcc = NewFatherOcc;
791 bool ETNode::Below(ETNode *other) {
792 ETOccurrence *up = other->RightmostOcc;
793 ETOccurrence *down = RightmostOcc;
800 ETOccurrence *left, *right;
810 right->Parent = NULL;
814 if (left == down || left->Parent != NULL) {
821 // If the two occurrences are in different trees, put things
822 // back the way they were.
823 if (right && right->Parent != NULL)
830 if (down->Depth <= 0)
833 return !down->Right || down->Right->Min + down->Depth >= 0;
836 ETNode *ETNode::NCA(ETNode *other) {
837 ETOccurrence *occ1 = RightmostOcc;
838 ETOccurrence *occ2 = other->RightmostOcc;
840 ETOccurrence *left, *right, *ret;
841 ETOccurrence *occmin;
855 right->Parent = NULL;
858 if (left == occ2 || (left && left->Parent != NULL)) {
863 right->Parent = occ1;
867 occ1->setRight(occ2);
872 if (occ2->Depth > 0) {
874 mindepth = occ1->Depth;
877 mindepth = occ2->Depth + occ1->Depth;
880 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
881 return ret->MinOccurrence->OccFor;
883 return occmin->OccFor;
886 void ETNode::assignDFSNumber(int num) {
887 std::vector<ETNode *> workStack;
888 std::set<ETNode *> visitedNodes;
890 workStack.push_back(this);
891 visitedNodes.insert(this);
892 this->DFSNumIn = num++;
894 while (!workStack.empty()) {
895 ETNode *Node = workStack.back();
897 // If this is leaf node then set DFSNumOut and pop the stack
899 Node->DFSNumOut = num++;
900 workStack.pop_back();
904 ETNode *son = Node->Son;
906 // Visit Node->Son first
907 if (visitedNodes.count(son) == 0) {
908 son->DFSNumIn = num++;
909 workStack.push_back(son);
910 visitedNodes.insert(son);
914 bool visitChild = false;
915 // Visit remaining children
916 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
917 if (visitedNodes.count(s) == 0) {
920 workStack.push_back(s);
921 visitedNodes.insert(s);
926 // If we reach here means all children are visited
927 Node->DFSNumOut = num++;
928 workStack.pop_back();
933 //===----------------------------------------------------------------------===//
934 // ETForest implementation
935 //===----------------------------------------------------------------------===//
937 char ETForest::ID = 0;
938 static RegisterPass<ETForest>
939 D("etforest", "ET Forest Construction", true);
941 void ETForestBase::reset() {
942 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
947 void ETForestBase::updateDFSNumbers()
950 // Iterate over all nodes in depth first order.
951 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
952 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
953 E = df_end(Roots[i]); I != E; ++I) {
955 ETNode *ETN = getNode(BB);
956 if (ETN && !ETN->hasFather())
957 ETN->assignDFSNumber(dfsnum);
963 // dominates - Return true if A dominates B. THis performs the
964 // special checks necessary if A and B are in the same basic block.
965 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
966 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
967 if (BBA != BBB) return dominates(BBA, BBB);
969 // It is not possible to determine dominance between two PHI nodes
970 // based on their ordering.
971 if (isa<PHINode>(A) && isa<PHINode>(B))
974 // Loop through the basic block until we find A or B.
975 BasicBlock::iterator I = BBA->begin();
976 for (; &*I != A && &*I != B; ++I) /*empty*/;
978 if(!IsPostDominators) {
979 // A dominates B if it is found first in the basic block.
982 // A post-dominates B if B is found first in the basic block.
987 /// isReachableFromEntry - Return true if A is dominated by the entry
988 /// block of the function containing it.
989 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
990 return dominates(&A->getParent()->getEntryBlock(), A);
993 // FIXME : There is no need to make getNodeForBlock public. Fix
994 // predicate simplifier.
995 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
996 ETNode *&BBNode = Nodes[BB];
997 if (BBNode) return BBNode;
999 // Haven't calculated this node yet? Get or calculate the node for the
1000 // immediate dominator.
1001 DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1003 // If we are unreachable, we may not have an immediate dominator.
1004 if (!node || !node->getIDom())
1005 return BBNode = new ETNode(BB);
1007 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1009 // Add a new tree node for this BasicBlock, and link it as a child of
1011 BBNode = new ETNode(BB);
1012 BBNode->setFather(IDomNode);
1017 void ETForest::calculate(const DominatorTree &DT) {
1018 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
1019 BasicBlock *Root = Roots[0];
1020 Nodes[Root] = new ETNode(Root); // Add a node for the root
1022 Function *F = Root->getParent();
1023 // Loop over all of the reachable blocks in the function...
1024 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1025 DomTreeNode* node = DT.getNode(I);
1026 if (node && node->getIDom()) { // Reachable block.
1027 BasicBlock* ImmDom = node->getIDom()->getBlock();
1028 ETNode *&BBNode = Nodes[I];
1029 if (!BBNode) { // Haven't calculated this node yet?
1030 // Get or calculate the node for the immediate dominator
1031 ETNode *IDomNode = getNodeForBlock(ImmDom);
1033 // Add a new ETNode for this BasicBlock, and set it's parent
1034 // to it's immediate dominator.
1035 BBNode = new ETNode(I);
1036 BBNode->setFather(IDomNode);
1041 // Make sure we've got nodes around for every block
1042 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1043 ETNode *&BBNode = Nodes[I];
1045 BBNode = new ETNode(I);
1048 updateDFSNumbers ();
1051 //===----------------------------------------------------------------------===//
1052 // ETForestBase Implementation
1053 //===----------------------------------------------------------------------===//
1055 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1056 ETNode *&BBNode = Nodes[BB];
1057 assert(!BBNode && "BasicBlock already in ET-Forest");
1059 BBNode = new ETNode(BB);
1060 BBNode->setFather(getNode(IDom));
1061 DFSInfoValid = false;
1064 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
1065 assert(getNode(BB) && "BasicBlock not in ET-Forest");
1066 assert(getNode(newIDom) && "IDom not in ET-Forest");
1068 ETNode *Node = getNode(BB);
1069 if (Node->hasFather()) {
1070 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1074 Node->setFather(getNode(newIDom));
1075 DFSInfoValid= false;
1078 void ETForestBase::print(std::ostream &o, const Module *) const {
1079 o << "=============================--------------------------------\n";
1080 o << "ET Forest:\n";
1086 o << " up to date\n";
1088 Function *F = getRoots()[0]->getParent();
1089 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1090 o << " DFS Numbers For Basic Block:";
1091 WriteAsOperand(o, I, false);
1093 if (ETNode *EN = getNode(I)) {
1094 o << "In: " << EN->getDFSNumIn();
1095 o << " Out: " << EN->getDFSNumOut() << "\n";
1097 o << "No associated ETNode";
1104 void ETForestBase::dump() {