8b2c1a45e223a5c799003100a5348fe510ebfc7e
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
25 #include <algorithm>
26 #include <set>
27 using namespace llvm;
28
29 namespace llvm {
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();
33        I != E; ++I)
34     if (*I)
35       WriteAsOperand(o, *I, false);
36     else
37       o << " <<exit node>>";
38   return o;
39 }
40 }
41
42 //===----------------------------------------------------------------------===//
43 //  DominatorTree Implementation
44 //===----------------------------------------------------------------------===//
45 //
46 // DominatorTree construction - This pass constructs immediate dominator
47 // information for a flow-graph based on the algorithm described in this
48 // document:
49 //
50 //   A Fast Algorithm for Finding Dominators in a Flowgraph
51 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
52 //
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:
58 //
59 #define BALANCE_IDOM_TREE 0
60 //
61 //===----------------------------------------------------------------------===//
62
63 char DominatorTree::ID = 0;
64 static RegisterPass<DominatorTree>
65 E("domtree", "Dominator Tree Construction", true);
66
67 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
68                                       unsigned N) {
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.
72 #if 0
73   VInfo.Semi = ++N;
74   VInfo.Label = V;
75
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
80
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) {
84       SuccVInfo.Parent = V;
85       N = DFSPass(*SI, SuccVInfo, N);
86     }
87   }
88 #else
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;
94     
95     // First time we visited this BB?
96     if (NextSucc == 0) {
97       InfoRec &BBInfo = Info[BB];
98       BBInfo.Semi = ++N;
99       BBInfo.Label = BB;
100       
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
105     }
106     
107     // If we are done with this block, remove it from the worklist.
108     if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
109       Worklist.pop_back();
110       continue;
111     }
112     
113     // Otherwise, increment the successor number for the next time we get to it.
114     ++Worklist.back().second;
115     
116     // Visit the successor next, if it isn't already visited.
117     BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
118     
119     InfoRec &SuccVInfo = Info[Succ];
120     if (SuccVInfo.Semi == 0) {
121       SuccVInfo.Parent = BB;
122       Worklist.push_back(std::make_pair(Succ, 0U));
123     }
124   }
125 #endif
126   return N;
127 }
128
129 void DominatorTree::Compress(BasicBlock *VIn) {
130
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];
136
137   if (VInVAInfo.Ancestor != 0)
138     Work.push_back(VIn);
139   
140   while (!Work.empty()) {
141     BasicBlock *V = Work.back();
142     InfoRec &VInfo = Info[V];
143     BasicBlock *VAncestor = VInfo.Ancestor;
144     InfoRec &VAInfo = Info[VAncestor];
145
146     // Process Ancestor first
147     if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
148       Work.push_back(VAncestor);
149       Visited.insert(VAncestor);
150       continue;
151     } 
152     Work.pop_back(); 
153
154     // Update VINfo based on Ancestor info
155     if (VAInfo.Ancestor == 0)
156       continue;
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;
162   }
163 }
164
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)
170     return V;
171   Compress(V);
172   return VInfo.Label;
173 #else
174   // Lower-complexity but slower implementation
175   if (VInfo.Ancestor == 0)
176     return VInfo.Label;
177   Compress(V);
178   BasicBlock *VLabel = VInfo.Label;
179
180   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
181   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
182     return VLabel;
183   else
184     return VAncestorLabel;
185 #endif
186 }
187
188 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
189 #if !BALANCE_IDOM_TREE
190   // Higher-complexity but faster implementation
191   WInfo.Ancestor = V;
192 #else
193   // Lower-complexity but slower implementation
194   BasicBlock *WLabel = WInfo.Label;
195   unsigned WLabelSemi = Info[WLabel].Semi;
196   BasicBlock *S = W;
197   InfoRec *SInfo = &Info[S];
198
199   BasicBlock *SChild = SInfo->Child;
200   InfoRec *SChildInfo = &Info[SChild];
201
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];
208     } else {
209       SChildInfo->Size = SInfo->Size;
210       S = SInfo->Ancestor = SChild;
211       SInfo = SChildInfo;
212       SChild = SChildChild;
213       SChildInfo = &Info[SChild];
214     }
215   }
216
217   InfoRec &VInfo = Info[V];
218   SInfo->Label = WLabel;
219
220   assert(V != W && "The optimization here will not work in this case!");
221   unsigned WSize = WInfo.Size;
222   unsigned VSize = (VInfo.Size += WSize);
223
224   if (VSize < 2*WSize)
225     std::swap(S, VInfo.Child);
226
227   while (S) {
228     SInfo = &Info[S];
229     SInfo->Ancestor = V;
230     S = SInfo->Child;
231   }
232 #endif
233 }
234
235 void DominatorTree::calculate(Function& F) {
236   BasicBlock* Root = Roots[0];
237
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);
242
243   Vertex.push_back(0);
244
245   // Step #1: Number blocks in depth-first order and initialize variables used
246   // in later stages of the algorithm.
247   unsigned N = 0;
248   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
249     N = DFSPass(Roots[i], Info[Roots[i]], 0);
250
251   for (unsigned i = N; i >= 2; --i) {
252     BasicBlock *W = Vertex[i];
253     InfoRec &WInfo = Info[W];
254
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)
260           WInfo.Semi = SemiU;
261       }
262
263     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
264
265     BasicBlock *WParent = WInfo.Parent;
266     Link(WParent, W, WInfo);
267
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;
275     }
276   }
277
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];
284   }
285
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);
293
294         // Add a new tree node for this BasicBlock, and link it as a child of
295         // IDomNode
296         ETNode *ET = new ETNode(I);
297         ETNodes[I] = ET;
298         DomTreeNode *C = new DomTreeNode(I, IDomNode, ET);
299         DomTreeNodes[I] = C;
300         BBNode = IDomNode->addChild(C);
301       }
302     }
303
304   // Free temporary memory used to construct idom's
305   Info.clear();
306   IDoms.clear();
307   std::vector<BasicBlock*>().swap(Vertex);
308
309   updateDFSNumbers();
310 }
311
312 void DominatorTreeBase::updateDFSNumbers()
313 {
314   int dfsnum = 0;
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) {
319       BasicBlock *BB = *I;
320       DomTreeNode *BBNode = getNode(BB);
321       if (BBNode) {
322         ETNode *ETN = BBNode->getETNode();
323         if (ETN && !ETN->hasFather())
324           ETN->assignDFSNumber(dfsnum);
325       }
326   }
327   SlowQueries = 0;
328   DFSInfoValid = true;
329 }
330
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);
335 }
336
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);
342   
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)) 
346     return false;
347
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*/;
351   
352   if(!IsPostDominators) {
353     // A dominates B if it is found first in the basic block.
354     return &*I == A;
355   } else {
356     // A post-dominates B if B is found first in the basic block.
357     return &*I == B;
358   }
359 }
360
361 // DominatorTreeBase::reset - Free all of the tree node memory.
362 //
363 void DominatorTreeBase::reset() {
364   for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), E = DomTreeNodes.end(); I != E; ++I)
365     delete I->second;
366   DomTreeNodes.clear();
367   IDoms.clear();
368   Roots.clear();
369   Vertex.clear();
370   RootNode = 0;
371 }
372
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) {
376
377   assert (!isPostDominator()  && "This is not implemented for post dominators");
378   assert (A->getParent() == B->getParent()  && "Two blocks are not in same function");
379
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)
383     return &Entry;
384
385   // If A and B are same then A is nearest common dominator.
386   DomTreeNode *NodeA = getNode(A);
387   if (A != 0 && A == B)
388     return A;
389
390   DomTreeNode *NodeB = getNode(B);
391
392   // Collect NodeA dominators set.
393   std::set<DomTreeNode *> NodeADoms;
394   NodeADoms.insert(NodeA);
395   DomTreeNode *IDomA = NodeA->getIDom();
396   while(IDomA) {
397     NodeADoms.insert(IDomA);
398     IDomA = IDomA->getIDom();
399   }
400
401   // If B dominates A then B is nearest common dominator.
402   if (NodeADoms.count(NodeB) != 0)
403     return B;
404
405   // Walk NodeB immediate dominators chain and find common dominator node.
406   DomTreeNode *IDomB = NodeB->getIDom();
407   while(IDomB) {
408     if (NodeADoms.count(IDomB) != 0)
409       return IDomB->getBlock();
410
411     IDomB = IDomB->getIDom();
412   }
413
414   return NULL;
415 }
416
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);
426
427     // Switch to new dominator
428     IDom = NewIDom;
429     IDom->Children.push_back(this);
430
431     if (!ETN->hasFather())
432       ETN->setFather(IDom->getETNode());
433     else if (ETN->getFather()->getData<BasicBlock>() != IDom->getBlock()) {
434         ETN->Split();
435         ETN->setFather(IDom->getETNode());
436     }
437   }
438 }
439
440 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
441   DomTreeNode *&BBNode = DomTreeNodes[BB];
442   if (BBNode) return BBNode;
443
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);
448
449   // Add a new tree node for this BasicBlock, and link it as a child of
450   // IDomNode
451   ETNode *ET = new ETNode(BB);
452   ETNodes[BB] = ET;
453   DomTreeNode *C = new DomTreeNode(BB, IDomNode, ET);
454   DomTreeNodes[BB] = C;
455   return BBNode = IDomNode->addChild(C);
456 }
457
458 static std::ostream &operator<<(std::ostream &o,
459                                 const DomTreeNode *Node) {
460   if (Node->getBlock())
461     WriteAsOperand(o, Node->getBlock(), false);
462   else
463     o << " <<exit node>>";
464   return o << "\n";
465 }
466
467 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
468                          unsigned Lev) {
469   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
470   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
471        I != E; ++I)
472     PrintDomTree(*I, o, Lev+1);
473 }
474
475 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
476   o << "=============================--------------------------------\n"
477     << "Inorder Dominator Tree:\n";
478   PrintDomTree(getRootNode(), o, 1);
479 }
480
481 void DominatorTreeBase::dump() {
482   print (llvm::cerr);
483 }
484
485 bool DominatorTree::runOnFunction(Function &F) {
486   reset();     // Reset from the last time we were run...
487   Roots.push_back(&F.getEntryBlock());
488   calculate(F);
489   return false;
490 }
491
492 //===----------------------------------------------------------------------===//
493 //  DominanceFrontier Implementation
494 //===----------------------------------------------------------------------===//
495
496 char DominanceFrontier::ID = 0;
497 static RegisterPass<DominanceFrontier>
498 G("domfrontier", "Dominance Frontier Construction", true);
499
500 namespace {
501   class DFCalculateWorkObject {
502   public:
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;
511   };
512 }
513
514 const DominanceFrontier::DomSetType &
515 DominanceFrontier::calculate(const DominatorTree &DT,
516                              const DomTreeNode *Node) {
517   BasicBlock *BB = Node->getBlock();
518   DomSetType *Result = NULL;
519
520   std::vector<DFCalculateWorkObject> workList;
521   SmallPtrSet<BasicBlock *, 32> visited;
522
523   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
524   do {
525     DFCalculateWorkObject *currentW = &workList.back();
526     assert (currentW && "Missing work object.");
527
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];
535
536     // Visit each block only once.
537     if (visited.count(currentBB) == 0) {
538       visited.insert(currentBB);
539
540       // Loop over CFG successors to calculate DFlocal[currentNode]
541       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
542            SI != SE; ++SI) {
543         // Does Node immediately dominate this successor?
544         if (DT[*SI]->getIDom() != currentNode)
545           S.insert(*SI);
546       }
547     }
548
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));
560         visitChild = true;
561       }
562     }
563
564     // If all children are visited or there is any child then pop this block
565     // from the workList.
566     if (!visitChild) {
567
568       if (!parentBB) {
569         Result = &S;
570         break;
571       }
572
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);
578       }
579       workList.pop_back();
580     }
581
582   } while (!workList.empty());
583
584   return *Result;
585 }
586
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";
590     if (I->first)
591       WriteAsOperand(o, I->first, false);
592     else
593       o << " <<exit node>>";
594     o << " is:\t" << I->second << "\n";
595   }
596 }
597
598 void DominanceFrontierBase::dump() {
599   print (llvm::cerr);
600 }
601
602
603 //===----------------------------------------------------------------------===//
604 // ETOccurrence Implementation
605 //===----------------------------------------------------------------------===//
606
607 void ETOccurrence::Splay() {
608   ETOccurrence *father;
609   ETOccurrence *grandfather;
610   int occdepth;
611   int fatherdepth;
612   
613   while (Parent) {
614     occdepth = Depth;
615     
616     father = Parent;
617     fatherdepth = Parent->Depth;
618     grandfather = father->Parent;
619     
620     // If we have no grandparent, a single zig or zag will do.
621     if (!grandfather) {
622       setDepthAdd(fatherdepth);
623       MinOccurrence = father->MinOccurrence;
624       Min = father->Min;
625       
626       // See what we have to rotate
627       if (father->Left == this) {
628         // Zig
629         father->setLeft(Right);
630         setRight(father);
631         if (father->Left)
632           father->Left->setDepthAdd(occdepth);
633       } else {
634         // Zag
635         father->setRight(Left);
636         setLeft(father);
637         if (father->Right)
638           father->Right->setDepthAdd(occdepth);
639       }
640       father->setDepth(-occdepth);
641       Parent = NULL;
642       
643       father->recomputeMin();
644       return;
645     }
646     
647     // If we have a grandfather, we need to do some
648     // combination of zig and zag.
649     int grandfatherdepth = grandfather->Depth;
650     
651     setDepthAdd(fatherdepth + grandfatherdepth);
652     MinOccurrence = grandfather->MinOccurrence;
653     Min = grandfather->Min;
654     
655     ETOccurrence *greatgrandfather = grandfather->Parent;
656     
657     if (grandfather->Left == father) {
658       if (father->Left == this) {
659         // Zig zig
660         grandfather->setLeft(father->Right);
661         father->setLeft(Right);
662         setRight(father);
663         father->setRight(grandfather);
664         
665         father->setDepth(-occdepth);
666         
667         if (father->Left)
668           father->Left->setDepthAdd(occdepth);
669         
670         grandfather->setDepth(-fatherdepth);
671         if (grandfather->Left)
672           grandfather->Left->setDepthAdd(fatherdepth);
673       } else {
674         // Zag zig
675         grandfather->setLeft(Right);
676         father->setRight(Left);
677         setLeft(father);
678         setRight(grandfather);
679         
680         father->setDepth(-occdepth);
681         if (father->Right)
682           father->Right->setDepthAdd(occdepth);
683         grandfather->setDepth(-occdepth - fatherdepth);
684         if (grandfather->Left)
685           grandfather->Left->setDepthAdd(occdepth + fatherdepth);
686       }
687     } else {
688       if (father->Left == this) {
689         // Zig zag
690         grandfather->setRight(Left);
691         father->setLeft(Right);
692         setLeft(grandfather);
693         setRight(father);
694         
695         father->setDepth(-occdepth);
696         if (father->Left)
697           father->Left->setDepthAdd(occdepth);
698         grandfather->setDepth(-occdepth - fatherdepth);
699         if (grandfather->Right)
700           grandfather->Right->setDepthAdd(occdepth + fatherdepth);
701       } else {              // Zag Zag
702         grandfather->setRight(father->Left);
703         father->setRight(Left);
704         setLeft(father);
705         father->setLeft(grandfather);
706         
707         father->setDepth(-occdepth);
708         if (father->Right)
709           father->Right->setDepthAdd(occdepth);
710         grandfather->setDepth(-fatherdepth);
711         if (grandfather->Right)
712           grandfather->Right->setDepthAdd(fatherdepth);
713       }
714     }
715     
716     // Might need one more rotate depending on greatgrandfather.
717     setParent(greatgrandfather);
718     if (greatgrandfather) {
719       if (greatgrandfather->Left == grandfather)
720         greatgrandfather->Left = this;
721       else
722         greatgrandfather->Right = this;
723       
724     }
725     grandfather->recomputeMin();
726     father->recomputeMin();
727   }
728 }
729
730 //===----------------------------------------------------------------------===//
731 // ETNode implementation
732 //===----------------------------------------------------------------------===//
733
734 void ETNode::Split() {
735   ETOccurrence *right, *left;
736   ETOccurrence *rightmost = RightmostOcc;
737   ETOccurrence *parent;
738
739   // Update the occurrence tree first.
740   RightmostOcc->Splay();
741
742   // Find the leftmost occurrence in the rightmost subtree, then splay
743   // around it.
744   for (right = rightmost->Right; right->Left; right = right->Left);
745
746   right->Splay();
747
748   // Start splitting
749   right->Left->Parent = NULL;
750   parent = ParentOcc;
751   parent->Splay();
752   ParentOcc = NULL;
753
754   left = parent->Left;
755   parent->Right->Parent = NULL;
756
757   right->setLeft(left);
758
759   right->recomputeMin();
760
761   rightmost->Splay();
762   rightmost->Depth = 0;
763   rightmost->Min = 0;
764
765   delete parent;
766
767   // Now update *our* tree
768
769   if (Father->Son == this)
770     Father->Son = Right;
771
772   if (Father->Son == this)
773     Father->Son = NULL;
774   else {
775     Left->Right = Right;
776     Right->Left = Left;
777   }
778   Left = Right = NULL;
779   Father = NULL;
780 }
781
782 void ETNode::setFather(ETNode *NewFather) {
783   ETOccurrence *rightmost;
784   ETOccurrence *leftpart;
785   ETOccurrence *NewFatherOcc;
786   ETOccurrence *temp;
787
788   // First update the path in the splay tree
789   NewFatherOcc = new ETOccurrence(NewFather);
790
791   rightmost = NewFather->RightmostOcc;
792   rightmost->Splay();
793
794   leftpart = rightmost->Left;
795
796   temp = RightmostOcc;
797   temp->Splay();
798
799   NewFatherOcc->setLeft(leftpart);
800   NewFatherOcc->setRight(temp);
801
802   temp->Depth++;
803   temp->Min++;
804   NewFatherOcc->recomputeMin();
805
806   rightmost->setLeft(NewFatherOcc);
807
808   if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
809     rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
810     rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
811   }
812
813   delete ParentOcc;
814   ParentOcc = NewFatherOcc;
815
816   // Update *our* tree
817   ETNode *left;
818   ETNode *right;
819
820   Father = NewFather;
821   right = Father->Son;
822
823   if (right)
824     left = right->Left;
825   else
826     left = right = this;
827
828   left->Right = this;
829   right->Left = this;
830   Left = left;
831   Right = right;
832
833   Father->Son = this;
834 }
835
836 bool ETNode::Below(ETNode *other) {
837   ETOccurrence *up = other->RightmostOcc;
838   ETOccurrence *down = RightmostOcc;
839
840   if (this == other)
841     return true;
842
843   up->Splay();
844
845   ETOccurrence *left, *right;
846   left = up->Left;
847   right = up->Right;
848
849   if (!left)
850     return false;
851
852   left->Parent = NULL;
853
854   if (right)
855     right->Parent = NULL;
856
857   down->Splay();
858
859   if (left == down || left->Parent != NULL) {
860     if (right)
861       right->Parent = up;
862     up->setLeft(down);
863   } else {
864     left->Parent = up;
865
866     // If the two occurrences are in different trees, put things
867     // back the way they were.
868     if (right && right->Parent != NULL)
869       up->setRight(down);
870     else
871       up->setRight(right);
872     return false;
873   }
874
875   if (down->Depth <= 0)
876     return false;
877
878   return !down->Right || down->Right->Min + down->Depth >= 0;
879 }
880
881 ETNode *ETNode::NCA(ETNode *other) {
882   ETOccurrence *occ1 = RightmostOcc;
883   ETOccurrence *occ2 = other->RightmostOcc;
884   
885   ETOccurrence *left, *right, *ret;
886   ETOccurrence *occmin;
887   int mindepth;
888   
889   if (this == other)
890     return this;
891   
892   occ1->Splay();
893   left = occ1->Left;
894   right = occ1->Right;
895   
896   if (left)
897     left->Parent = NULL;
898   
899   if (right)
900     right->Parent = NULL;
901   occ2->Splay();
902
903   if (left == occ2 || (left && left->Parent != NULL)) {
904     ret = occ2->Right;
905     
906     occ1->setLeft(occ2);
907     if (right)
908       right->Parent = occ1;
909   } else {
910     ret = occ2->Left;
911     
912     occ1->setRight(occ2);
913     if (left)
914       left->Parent = occ1;
915   }
916
917   if (occ2->Depth > 0) {
918     occmin = occ1;
919     mindepth = occ1->Depth;
920   } else {
921     occmin = occ2;
922     mindepth = occ2->Depth + occ1->Depth;
923   }
924   
925   if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
926     return ret->MinOccurrence->OccFor;
927   else
928     return occmin->OccFor;
929 }
930
931 void ETNode::assignDFSNumber(int num) {
932   std::vector<ETNode *>  workStack;
933   std::set<ETNode *> visitedNodes;
934   
935   workStack.push_back(this);
936   visitedNodes.insert(this);
937   this->DFSNumIn = num++;
938
939   while (!workStack.empty()) {
940     ETNode  *Node = workStack.back();
941     
942     // If this is leaf node then set DFSNumOut and pop the stack
943     if (!Node->Son) {
944       Node->DFSNumOut = num++;
945       workStack.pop_back();
946       continue;
947     }
948     
949     ETNode *son = Node->Son;
950     
951     // Visit Node->Son first
952     if (visitedNodes.count(son) == 0) {
953       son->DFSNumIn = num++;
954       workStack.push_back(son);
955       visitedNodes.insert(son);
956       continue;
957     }
958     
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) {
963         visitChild = true;
964         s->DFSNumIn = num++;
965         workStack.push_back(s);
966         visitedNodes.insert(s);
967       }
968     }
969     
970     if (!visitChild) {
971       // If we reach here means all children are visited
972       Node->DFSNumOut = num++;
973       workStack.pop_back();
974     }
975   }
976 }
977
978 //===----------------------------------------------------------------------===//
979 // ETForest implementation
980 //===----------------------------------------------------------------------===//
981
982 char ETForest::ID = 0;
983 static RegisterPass<ETForest>
984 D("etforest", "ET Forest Construction", true);
985
986 void ETForestBase::reset() {
987   for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
988     delete I->second;
989   Nodes.clear();
990 }
991
992 void ETForestBase::updateDFSNumbers()
993 {
994   int dfsnum = 0;
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) {
999       BasicBlock *BB = *I;
1000       ETNode *ETN = getNode(BB);
1001       if (ETN && !ETN->hasFather())
1002         ETN->assignDFSNumber(dfsnum);    
1003   }
1004   SlowQueries = 0;
1005   DFSInfoValid = true;
1006 }
1007
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);
1013   
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)) 
1017     return false;
1018
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*/;
1022   
1023   if(!IsPostDominators) {
1024     // A dominates B if it is found first in the basic block.
1025     return &*I == A;
1026   } else {
1027     // A post-dominates B if B is found first in the basic block.
1028     return &*I == B;
1029   }
1030 }
1031
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);
1036 }
1037
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;
1043
1044   // Haven't calculated this node yet?  Get or calculate the node for the
1045   // immediate dominator.
1046   DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
1047
1048   // If we are unreachable, we may not have an immediate dominator.
1049   if (!node || !node->getIDom())
1050     return BBNode = new ETNode(BB);
1051   else {
1052     ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
1053     
1054     // Add a new tree node for this BasicBlock, and link it as a child of
1055     // IDomNode
1056     BBNode = new ETNode(BB);
1057     BBNode->setFather(IDomNode);
1058     return BBNode;
1059   }
1060 }
1061
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
1066
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);
1077
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);
1082       }
1083     }
1084   }
1085
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];
1089     if (!BBNode)
1090       BBNode = new ETNode(I);
1091   }
1092
1093   updateDFSNumbers ();
1094 }
1095
1096 //===----------------------------------------------------------------------===//
1097 // ETForestBase Implementation
1098 //===----------------------------------------------------------------------===//
1099
1100 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
1101   ETNode *&BBNode = Nodes[BB];
1102   assert(!BBNode && "BasicBlock already in ET-Forest");
1103
1104   BBNode = new ETNode(BB);
1105   BBNode->setFather(getNode(IDom));
1106   DFSInfoValid = false;
1107 }
1108
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");
1112   
1113   ETNode *Node = getNode(BB);
1114   if (Node->hasFather()) {
1115     if (Node->getFather()->getData<BasicBlock>() == newIDom)
1116       return;
1117     Node->Split();
1118   }
1119   Node->setFather(getNode(newIDom));
1120   DFSInfoValid= false;
1121 }
1122
1123 void ETForestBase::print(std::ostream &o, const Module *) const {
1124   o << "=============================--------------------------------\n";
1125   o << "ET Forest:\n";
1126   o << "DFS Info ";
1127   if (DFSInfoValid)
1128     o << "is";
1129   else
1130     o << "is not";
1131   o << " up to date\n";
1132
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);
1137     o << " are:";
1138     if (ETNode *EN = getNode(I)) {
1139       o << "In: " << EN->getDFSNumIn();
1140       o << " Out: " << EN->getDFSNumOut() << "\n";
1141     } else {
1142       o << "No associated ETNode";
1143     }
1144     o << "\n";
1145   }
1146   o << "\n";
1147 }
1148
1149 void ETForestBase::dump() {
1150   print (llvm::cerr);
1151 }