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 DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0); // Add a node for the root...
241 // Step #1: Number blocks in depth-first order and initialize variables used
242 // in later stages of the algorithm.
244 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
245 N = DFSPass(Roots[i], Info[Roots[i]], 0);
247 for (unsigned i = N; i >= 2; --i) {
248 BasicBlock *W = Vertex[i];
249 InfoRec &WInfo = Info[W];
251 // Step #2: Calculate the semidominators of all vertices
252 for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
253 if (Info.count(*PI)) { // Only if this predecessor is reachable!
254 unsigned SemiU = Info[Eval(*PI)].Semi;
255 if (SemiU < WInfo.Semi)
259 Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
261 BasicBlock *WParent = WInfo.Parent;
262 Link(WParent, W, WInfo);
264 // Step #3: Implicitly define the immediate dominator of vertices
265 std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
266 while (!WParentBucket.empty()) {
267 BasicBlock *V = WParentBucket.back();
268 WParentBucket.pop_back();
269 BasicBlock *U = Eval(V);
270 IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
274 // Step #4: Explicitly define the immediate dominator of each vertex
275 for (unsigned i = 2; i <= N; ++i) {
276 BasicBlock *W = Vertex[i];
277 BasicBlock *&WIDom = IDoms[W];
278 if (WIDom != Vertex[Info[W].Semi])
279 WIDom = IDoms[WIDom];
282 // Loop over all of the reachable blocks in the function...
283 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
284 if (BasicBlock *ImmDom = getIDom(I)) { // Reachable block.
285 DomTreeNode *&BBNode = DomTreeNodes[I];
286 if (!BBNode) { // Haven't calculated this node yet?
287 // Get or calculate the node for the immediate dominator
288 DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
290 // Add a new tree node for this BasicBlock, and link it as a child of
292 BBNode = IDomNode->addChild(new DomTreeNode(I, IDomNode));
296 // Free temporary memory used to construct idom's
299 std::vector<BasicBlock*>().swap(Vertex);
302 // DominatorTreeBase::reset - Free all of the tree node memory.
304 void DominatorTreeBase::reset() {
305 for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), E = DomTreeNodes.end(); I != E; ++I)
307 DomTreeNodes.clear();
314 void DominatorTreeBase::DomTreeNode::setIDom(DomTreeNode *NewIDom) {
315 assert(IDom && "No immediate dominator?");
316 if (IDom != NewIDom) {
317 std::vector<DomTreeNode*>::iterator I =
318 std::find(IDom->Children.begin(), IDom->Children.end(), this);
319 assert(I != IDom->Children.end() &&
320 "Not in immediate dominator children set!");
321 // I am no longer your child...
322 IDom->Children.erase(I);
324 // Switch to new dominator
326 IDom->Children.push_back(this);
330 DominatorTreeBase::DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
331 DomTreeNode *&BBNode = DomTreeNodes[BB];
332 if (BBNode) return BBNode;
334 // Haven't calculated this node yet? Get or calculate the node for the
335 // immediate dominator.
336 BasicBlock *IDom = getIDom(BB);
337 DomTreeNode *IDomNode = getNodeForBlock(IDom);
339 // Add a new tree node for this BasicBlock, and link it as a child of
341 return BBNode = IDomNode->addChild(new DomTreeNode(BB, IDomNode));
344 static std::ostream &operator<<(std::ostream &o,
345 const DominatorTreeBase::DomTreeNode *Node) {
346 if (Node->getBlock())
347 WriteAsOperand(o, Node->getBlock(), false);
349 o << " <<exit node>>";
353 static void PrintDomTree(const DominatorTreeBase::DomTreeNode *N, std::ostream &o,
355 o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
356 for (DominatorTreeBase::DomTreeNode::const_iterator I = N->begin(), E = N->end();
358 PrintDomTree(*I, o, Lev+1);
361 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
362 o << "=============================--------------------------------\n"
363 << "Inorder Dominator Tree:\n";
364 PrintDomTree(getRootNode(), o, 1);
367 void DominatorTreeBase::dump() {
371 bool DominatorTree::runOnFunction(Function &F) {
372 reset(); // Reset from the last time we were run...
373 Roots.push_back(&F.getEntryBlock());
378 //===----------------------------------------------------------------------===//
379 // DominanceFrontier Implementation
380 //===----------------------------------------------------------------------===//
382 char DominanceFrontier::ID = 0;
383 static RegisterPass<DominanceFrontier>
384 G("domfrontier", "Dominance Frontier Construction", true);
387 class DFCalculateWorkObject {
389 DFCalculateWorkObject(BasicBlock *B, BasicBlock *P,
390 const DominatorTree::DomTreeNode *N,
391 const DominatorTree::DomTreeNode *PN)
392 : currentBB(B), parentBB(P), DomTreeNode(N), parentNode(PN) {}
393 BasicBlock *currentBB;
394 BasicBlock *parentBB;
395 const DominatorTree::DomTreeNode *DomTreeNode;
396 const DominatorTree::DomTreeNode *parentNode;
400 const DominanceFrontier::DomSetType &
401 DominanceFrontier::calculate(const DominatorTree &DT,
402 const DominatorTree::DomTreeNode *Node) {
403 BasicBlock *BB = Node->getBlock();
404 DomSetType *Result = NULL;
406 std::vector<DFCalculateWorkObject> workList;
407 SmallPtrSet<BasicBlock *, 32> visited;
409 workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
411 DFCalculateWorkObject *currentW = &workList.back();
412 assert (currentW && "Missing work object.");
414 BasicBlock *currentBB = currentW->currentBB;
415 BasicBlock *parentBB = currentW->parentBB;
416 const DominatorTree::DomTreeNode *currentNode = currentW->DomTreeNode;
417 const DominatorTree::DomTreeNode *parentNode = currentW->parentNode;
418 assert (currentBB && "Invalid work object. Missing current Basic Block");
419 assert (currentNode && "Invalid work object. Missing current Node");
420 DomSetType &S = Frontiers[currentBB];
422 // Visit each block only once.
423 if (visited.count(currentBB) == 0) {
424 visited.insert(currentBB);
426 // Loop over CFG successors to calculate DFlocal[currentNode]
427 for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
429 // Does Node immediately dominate this successor?
430 if (DT[*SI]->getIDom() != currentNode)
435 // At this point, S is DFlocal. Now we union in DFup's of our children...
436 // Loop through and visit the nodes that Node immediately dominates (Node's
437 // children in the IDomTree)
438 bool visitChild = false;
439 for (DominatorTree::DomTreeNode::const_iterator NI = currentNode->begin(),
440 NE = currentNode->end(); NI != NE; ++NI) {
441 DominatorTree::DomTreeNode *IDominee = *NI;
442 BasicBlock *childBB = IDominee->getBlock();
443 if (visited.count(childBB) == 0) {
444 workList.push_back(DFCalculateWorkObject(childBB, currentBB,
445 IDominee, currentNode));
450 // If all children are visited or there is any child then pop this block
451 // from the workList.
459 DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
460 DomSetType &parentSet = Frontiers[parentBB];
461 for (; CDFI != CDFE; ++CDFI) {
462 if (!parentNode->properlyDominates(DT[*CDFI]))
463 parentSet.insert(*CDFI);
468 } while (!workList.empty());
473 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
474 for (const_iterator I = begin(), E = end(); I != E; ++I) {
475 o << " DomFrontier for BB";
477 WriteAsOperand(o, I->first, false);
479 o << " <<exit node>>";
480 o << " is:\t" << I->second << "\n";
484 void DominanceFrontierBase::dump() {
489 //===----------------------------------------------------------------------===//
490 // ETOccurrence Implementation
491 //===----------------------------------------------------------------------===//
493 void ETOccurrence::Splay() {
494 ETOccurrence *father;
495 ETOccurrence *grandfather;
503 fatherdepth = Parent->Depth;
504 grandfather = father->Parent;
506 // If we have no grandparent, a single zig or zag will do.
508 setDepthAdd(fatherdepth);
509 MinOccurrence = father->MinOccurrence;
512 // See what we have to rotate
513 if (father->Left == this) {
515 father->setLeft(Right);
518 father->Left->setDepthAdd(occdepth);
521 father->setRight(Left);
524 father->Right->setDepthAdd(occdepth);
526 father->setDepth(-occdepth);
529 father->recomputeMin();
533 // If we have a grandfather, we need to do some
534 // combination of zig and zag.
535 int grandfatherdepth = grandfather->Depth;
537 setDepthAdd(fatherdepth + grandfatherdepth);
538 MinOccurrence = grandfather->MinOccurrence;
539 Min = grandfather->Min;
541 ETOccurrence *greatgrandfather = grandfather->Parent;
543 if (grandfather->Left == father) {
544 if (father->Left == this) {
546 grandfather->setLeft(father->Right);
547 father->setLeft(Right);
549 father->setRight(grandfather);
551 father->setDepth(-occdepth);
554 father->Left->setDepthAdd(occdepth);
556 grandfather->setDepth(-fatherdepth);
557 if (grandfather->Left)
558 grandfather->Left->setDepthAdd(fatherdepth);
561 grandfather->setLeft(Right);
562 father->setRight(Left);
564 setRight(grandfather);
566 father->setDepth(-occdepth);
568 father->Right->setDepthAdd(occdepth);
569 grandfather->setDepth(-occdepth - fatherdepth);
570 if (grandfather->Left)
571 grandfather->Left->setDepthAdd(occdepth + fatherdepth);
574 if (father->Left == this) {
576 grandfather->setRight(Left);
577 father->setLeft(Right);
578 setLeft(grandfather);
581 father->setDepth(-occdepth);
583 father->Left->setDepthAdd(occdepth);
584 grandfather->setDepth(-occdepth - fatherdepth);
585 if (grandfather->Right)
586 grandfather->Right->setDepthAdd(occdepth + fatherdepth);
588 grandfather->setRight(father->Left);
589 father->setRight(Left);
591 father->setLeft(grandfather);
593 father->setDepth(-occdepth);
595 father->Right->setDepthAdd(occdepth);
596 grandfather->setDepth(-fatherdepth);
597 if (grandfather->Right)
598 grandfather->Right->setDepthAdd(fatherdepth);
602 // Might need one more rotate depending on greatgrandfather.
603 setParent(greatgrandfather);
604 if (greatgrandfather) {
605 if (greatgrandfather->Left == grandfather)
606 greatgrandfather->Left = this;
608 greatgrandfather->Right = this;
611 grandfather->recomputeMin();
612 father->recomputeMin();
616 //===----------------------------------------------------------------------===//
617 // ETNode implementation
618 //===----------------------------------------------------------------------===//
620 void ETNode::Split() {
621 ETOccurrence *right, *left;
622 ETOccurrence *rightmost = RightmostOcc;
623 ETOccurrence *parent;
625 // Update the occurrence tree first.
626 RightmostOcc->Splay();
628 // Find the leftmost occurrence in the rightmost subtree, then splay
630 for (right = rightmost->Right; right->Left; right = right->Left);
635 right->Left->Parent = NULL;
641 parent->Right->Parent = NULL;
643 right->setLeft(left);
645 right->recomputeMin();
648 rightmost->Depth = 0;
653 // Now update *our* tree
655 if (Father->Son == this)
658 if (Father->Son == this)
668 void ETNode::setFather(ETNode *NewFather) {
669 ETOccurrence *rightmost;
670 ETOccurrence *leftpart;
671 ETOccurrence *NewFatherOcc;
674 // First update the path in the splay tree
675 NewFatherOcc = new ETOccurrence(NewFather);
677 rightmost = NewFather->RightmostOcc;
680 leftpart = rightmost->Left;
685 NewFatherOcc->setLeft(leftpart);
686 NewFatherOcc->setRight(temp);
690 NewFatherOcc->recomputeMin();
692 rightmost->setLeft(NewFatherOcc);
694 if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
695 rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
696 rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
700 ParentOcc = NewFatherOcc;
722 bool ETNode::Below(ETNode *other) {
723 ETOccurrence *up = other->RightmostOcc;
724 ETOccurrence *down = RightmostOcc;
731 ETOccurrence *left, *right;
741 right->Parent = NULL;
745 if (left == down || left->Parent != NULL) {
752 // If the two occurrences are in different trees, put things
753 // back the way they were.
754 if (right && right->Parent != NULL)
761 if (down->Depth <= 0)
764 return !down->Right || down->Right->Min + down->Depth >= 0;
767 ETNode *ETNode::NCA(ETNode *other) {
768 ETOccurrence *occ1 = RightmostOcc;
769 ETOccurrence *occ2 = other->RightmostOcc;
771 ETOccurrence *left, *right, *ret;
772 ETOccurrence *occmin;
786 right->Parent = NULL;
789 if (left == occ2 || (left && left->Parent != NULL)) {
794 right->Parent = occ1;
798 occ1->setRight(occ2);
803 if (occ2->Depth > 0) {
805 mindepth = occ1->Depth;
808 mindepth = occ2->Depth + occ1->Depth;
811 if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
812 return ret->MinOccurrence->OccFor;
814 return occmin->OccFor;
817 void ETNode::assignDFSNumber(int num) {
818 std::vector<ETNode *> workStack;
819 std::set<ETNode *> visitedNodes;
821 workStack.push_back(this);
822 visitedNodes.insert(this);
823 this->DFSNumIn = num++;
825 while (!workStack.empty()) {
826 ETNode *Node = workStack.back();
828 // If this is leaf node then set DFSNumOut and pop the stack
830 Node->DFSNumOut = num++;
831 workStack.pop_back();
835 ETNode *son = Node->Son;
837 // Visit Node->Son first
838 if (visitedNodes.count(son) == 0) {
839 son->DFSNumIn = num++;
840 workStack.push_back(son);
841 visitedNodes.insert(son);
845 bool visitChild = false;
846 // Visit remaining children
847 for (ETNode *s = son->Right; s != son && !visitChild; s = s->Right) {
848 if (visitedNodes.count(s) == 0) {
851 workStack.push_back(s);
852 visitedNodes.insert(s);
857 // If we reach here means all children are visited
858 Node->DFSNumOut = num++;
859 workStack.pop_back();
864 //===----------------------------------------------------------------------===//
865 // ETForest implementation
866 //===----------------------------------------------------------------------===//
868 char ETForest::ID = 0;
869 static RegisterPass<ETForest>
870 D("etforest", "ET Forest Construction", true);
872 void ETForestBase::reset() {
873 for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
878 void ETForestBase::updateDFSNumbers()
881 // Iterate over all nodes in depth first order.
882 for (unsigned i = 0, e = Roots.size(); i != e; ++i)
883 for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
884 E = df_end(Roots[i]); I != E; ++I) {
886 ETNode *ETN = getNode(BB);
887 if (ETN && !ETN->hasFather())
888 ETN->assignDFSNumber(dfsnum);
894 // dominates - Return true if A dominates B. THis performs the
895 // special checks necessary if A and B are in the same basic block.
896 bool ETForestBase::dominates(Instruction *A, Instruction *B) {
897 BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
898 if (BBA != BBB) return dominates(BBA, BBB);
900 // It is not possible to determine dominance between two PHI nodes
901 // based on their ordering.
902 if (isa<PHINode>(A) && isa<PHINode>(B))
905 // Loop through the basic block until we find A or B.
906 BasicBlock::iterator I = BBA->begin();
907 for (; &*I != A && &*I != B; ++I) /*empty*/;
909 if(!IsPostDominators) {
910 // A dominates B if it is found first in the basic block.
913 // A post-dominates B if B is found first in the basic block.
918 /// isReachableFromEntry - Return true if A is dominated by the entry
919 /// block of the function containing it.
920 const bool ETForestBase::isReachableFromEntry(BasicBlock* A) {
921 return dominates(&A->getParent()->getEntryBlock(), A);
924 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
925 ETNode *&BBNode = Nodes[BB];
926 if (BBNode) return BBNode;
928 // Haven't calculated this node yet? Get or calculate the node for the
929 // immediate dominator.
930 DominatorTree::DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
932 // If we are unreachable, we may not have an immediate dominator.
933 if (!node || !node->getIDom())
934 return BBNode = new ETNode(BB);
936 ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
938 // Add a new tree node for this BasicBlock, and link it as a child of
940 BBNode = new ETNode(BB);
941 BBNode->setFather(IDomNode);
946 void ETForest::calculate(const DominatorTree &DT) {
947 assert(Roots.size() == 1 && "ETForest should have 1 root block!");
948 BasicBlock *Root = Roots[0];
949 Nodes[Root] = new ETNode(Root); // Add a node for the root
951 Function *F = Root->getParent();
952 // Loop over all of the reachable blocks in the function...
953 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
954 DominatorTree::DomTreeNode* node = DT.getNode(I);
955 if (node && node->getIDom()) { // Reachable block.
956 BasicBlock* ImmDom = node->getIDom()->getBlock();
957 ETNode *&BBNode = Nodes[I];
958 if (!BBNode) { // Haven't calculated this node yet?
959 // Get or calculate the node for the immediate dominator
960 ETNode *IDomNode = getNodeForBlock(ImmDom);
962 // Add a new ETNode for this BasicBlock, and set it's parent
963 // to it's immediate dominator.
964 BBNode = new ETNode(I);
965 BBNode->setFather(IDomNode);
970 // Make sure we've got nodes around for every block
971 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
972 ETNode *&BBNode = Nodes[I];
974 BBNode = new ETNode(I);
980 //===----------------------------------------------------------------------===//
981 // ETForestBase Implementation
982 //===----------------------------------------------------------------------===//
984 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
985 ETNode *&BBNode = Nodes[BB];
986 assert(!BBNode && "BasicBlock already in ET-Forest");
988 BBNode = new ETNode(BB);
989 BBNode->setFather(getNode(IDom));
990 DFSInfoValid = false;
993 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
994 assert(getNode(BB) && "BasicBlock not in ET-Forest");
995 assert(getNode(newIDom) && "IDom not in ET-Forest");
997 ETNode *Node = getNode(BB);
998 if (Node->hasFather()) {
999 if (Node->getFather()->getData<BasicBlock>() == newIDom)
1003 Node->setFather(getNode(newIDom));
1004 DFSInfoValid= false;
1007 void ETForestBase::print(std::ostream &o, const Module *) const {
1008 o << "=============================--------------------------------\n";
1009 o << "ET Forest:\n";
1015 o << " up to date\n";
1017 Function *F = getRoots()[0]->getParent();
1018 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1019 o << " DFS Numbers For Basic Block:";
1020 WriteAsOperand(o, I, false);
1022 if (ETNode *EN = getNode(I)) {
1023 o << "In: " << EN->getDFSNumIn();
1024 o << " Out: " << EN->getDFSNumOut() << "\n";
1026 o << "No associated ETNode";
1033 void ETForestBase::dump() {