Fix an et-forest memory leak. Patch by Daniel Berlin.
[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 <algorithm>
23 #include <iostream>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //  ImmediateDominators Implementation
28 //===----------------------------------------------------------------------===//
29 //
30 // Immediate Dominators construction - This pass constructs immediate dominator
31 // information for a flow-graph based on the algorithm described in this
32 // document:
33 //
34 //   A Fast Algorithm for Finding Dominators in a Flowgraph
35 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
36 //
37 // This implements both the O(n*ack(n)) and the O(n*log(n)) versions of EVAL and
38 // LINK, but it turns out that the theoretically slower O(n*log(n))
39 // implementation is actually faster than the "efficient" algorithm (even for
40 // large CFGs) because the constant overheads are substantially smaller.  The
41 // lower-complexity version can be enabled with the following #define:
42 //
43 #define BALANCE_IDOM_TREE 0
44 //
45 //===----------------------------------------------------------------------===//
46
47 static RegisterAnalysis<ImmediateDominators>
48 C("idom", "Immediate Dominators Construction", true);
49
50 unsigned ImmediateDominators::DFSPass(BasicBlock *V, InfoRec &VInfo,
51                                       unsigned N) {
52   VInfo.Semi = ++N;
53   VInfo.Label = V;
54
55   Vertex.push_back(V);        // Vertex[n] = V;
56   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
57   //Child[V] = 0;             // Child[v] = 0
58   VInfo.Size = 1;             // Size[v] = 1
59
60   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
61     InfoRec &SuccVInfo = Info[*SI];
62     if (SuccVInfo.Semi == 0) {
63       SuccVInfo.Parent = V;
64       N = DFSPass(*SI, SuccVInfo, N);
65     }
66   }
67   return N;
68 }
69
70 void ImmediateDominators::Compress(BasicBlock *V, InfoRec &VInfo) {
71   BasicBlock *VAncestor = VInfo.Ancestor;
72   InfoRec &VAInfo = Info[VAncestor];
73   if (VAInfo.Ancestor == 0)
74     return;
75
76   Compress(VAncestor, VAInfo);
77
78   BasicBlock *VAncestorLabel = VAInfo.Label;
79   BasicBlock *VLabel = VInfo.Label;
80   if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
81     VInfo.Label = VAncestorLabel;
82
83   VInfo.Ancestor = VAInfo.Ancestor;
84 }
85
86 BasicBlock *ImmediateDominators::Eval(BasicBlock *V) {
87   InfoRec &VInfo = Info[V];
88 #if !BALANCE_IDOM_TREE
89   // Higher-complexity but faster implementation
90   if (VInfo.Ancestor == 0)
91     return V;
92   Compress(V, VInfo);
93   return VInfo.Label;
94 #else
95   // Lower-complexity but slower implementation
96   if (VInfo.Ancestor == 0)
97     return VInfo.Label;
98   Compress(V, VInfo);
99   BasicBlock *VLabel = VInfo.Label;
100
101   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
102   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
103     return VLabel;
104   else
105     return VAncestorLabel;
106 #endif
107 }
108
109 void ImmediateDominators::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
110 #if !BALANCE_IDOM_TREE
111   // Higher-complexity but faster implementation
112   WInfo.Ancestor = V;
113 #else
114   // Lower-complexity but slower implementation
115   BasicBlock *WLabel = WInfo.Label;
116   unsigned WLabelSemi = Info[WLabel].Semi;
117   BasicBlock *S = W;
118   InfoRec *SInfo = &Info[S];
119
120   BasicBlock *SChild = SInfo->Child;
121   InfoRec *SChildInfo = &Info[SChild];
122
123   while (WLabelSemi < Info[SChildInfo->Label].Semi) {
124     BasicBlock *SChildChild = SChildInfo->Child;
125     if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
126       SChildInfo->Ancestor = S;
127       SInfo->Child = SChild = SChildChild;
128       SChildInfo = &Info[SChild];
129     } else {
130       SChildInfo->Size = SInfo->Size;
131       S = SInfo->Ancestor = SChild;
132       SInfo = SChildInfo;
133       SChild = SChildChild;
134       SChildInfo = &Info[SChild];
135     }
136   }
137
138   InfoRec &VInfo = Info[V];
139   SInfo->Label = WLabel;
140
141   assert(V != W && "The optimization here will not work in this case!");
142   unsigned WSize = WInfo.Size;
143   unsigned VSize = (VInfo.Size += WSize);
144
145   if (VSize < 2*WSize)
146     std::swap(S, VInfo.Child);
147
148   while (S) {
149     SInfo = &Info[S];
150     SInfo->Ancestor = V;
151     S = SInfo->Child;
152   }
153 #endif
154 }
155
156
157
158 bool ImmediateDominators::runOnFunction(Function &F) {
159   IDoms.clear();     // Reset from the last time we were run...
160   BasicBlock *Root = &F.getEntryBlock();
161   Roots.clear();
162   Roots.push_back(Root);
163
164   Vertex.push_back(0);
165
166   // Step #1: Number blocks in depth-first order and initialize variables used
167   // in later stages of the algorithm.
168   unsigned N = 0;
169   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
170     N = DFSPass(Roots[i], Info[Roots[i]], 0);
171
172   for (unsigned i = N; i >= 2; --i) {
173     BasicBlock *W = Vertex[i];
174     InfoRec &WInfo = Info[W];
175
176     // Step #2: Calculate the semidominators of all vertices
177     for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
178       if (Info.count(*PI)) {  // Only if this predecessor is reachable!
179         unsigned SemiU = Info[Eval(*PI)].Semi;
180         if (SemiU < WInfo.Semi)
181           WInfo.Semi = SemiU;
182       }
183
184     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
185
186     BasicBlock *WParent = WInfo.Parent;
187     Link(WParent, W, WInfo);
188
189     // Step #3: Implicitly define the immediate dominator of vertices
190     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
191     while (!WParentBucket.empty()) {
192       BasicBlock *V = WParentBucket.back();
193       WParentBucket.pop_back();
194       BasicBlock *U = Eval(V);
195       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
196     }
197   }
198
199   // Step #4: Explicitly define the immediate dominator of each vertex
200   for (unsigned i = 2; i <= N; ++i) {
201     BasicBlock *W = Vertex[i];
202     BasicBlock *&WIDom = IDoms[W];
203     if (WIDom != Vertex[Info[W].Semi])
204       WIDom = IDoms[WIDom];
205   }
206
207   // Free temporary memory used to construct idom's
208   Info.clear();
209   std::vector<BasicBlock*>().swap(Vertex);
210
211   return false;
212 }
213
214 void ImmediateDominatorsBase::print(std::ostream &o, const Module* ) const {
215   Function *F = getRoots()[0]->getParent();
216   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
217     o << "  Immediate Dominator For Basic Block:";
218     WriteAsOperand(o, I, false);
219     o << " is:";
220     if (BasicBlock *ID = get(I))
221       WriteAsOperand(o, ID, false);
222     else
223       o << " <<exit node>>";
224     o << "\n";
225   }
226   o << "\n";
227 }
228
229
230
231 //===----------------------------------------------------------------------===//
232 //  DominatorSet Implementation
233 //===----------------------------------------------------------------------===//
234
235 static RegisterAnalysis<DominatorSet>
236 B("domset", "Dominator Set Construction", true);
237
238 // dominates - Return true if A dominates B.  This performs the special checks
239 // necessary if A and B are in the same basic block.
240 //
241 bool DominatorSetBase::dominates(Instruction *A, Instruction *B) const {
242   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
243   if (BBA != BBB) return dominates(BBA, BBB);
244
245   // Loop through the basic block until we find A or B.
246   BasicBlock::iterator I = BBA->begin();
247   for (; &*I != A && &*I != B; ++I) /*empty*/;
248
249   if(!IsPostDominators) {
250     // A dominates B if it is found first in the basic block.
251     return &*I == A;
252   } else {
253     // A post-dominates B if B is found first in the basic block.
254     return &*I == B;
255   }
256 }
257
258
259 // runOnFunction - This method calculates the forward dominator sets for the
260 // specified function.
261 //
262 bool DominatorSet::runOnFunction(Function &F) {
263   BasicBlock *Root = &F.getEntryBlock();
264   Roots.clear();
265   Roots.push_back(Root);
266   assert(pred_begin(Root) == pred_end(Root) &&
267          "Root node has predecessors in function!");
268
269   ImmediateDominators &ID = getAnalysis<ImmediateDominators>();
270   Doms.clear();
271   if (Roots.empty()) return false;
272
273   // Root nodes only dominate themselves.
274   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
275     Doms[Roots[i]].insert(Roots[i]);
276
277   // Loop over all of the blocks in the function, calculating dominator sets for
278   // each function.
279   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
280     if (BasicBlock *IDom = ID[I]) {   // Get idom if block is reachable
281       DomSetType &DS = Doms[I];
282       assert(DS.empty() && "Domset already filled in for this block?");
283       DS.insert(I);  // Blocks always dominate themselves
284
285       // Insert all dominators into the set...
286       while (IDom) {
287         // If we have already computed the dominator sets for our immediate
288         // dominator, just use it instead of walking all the way up to the root.
289         DomSetType &IDS = Doms[IDom];
290         if (!IDS.empty()) {
291           DS.insert(IDS.begin(), IDS.end());
292           break;
293         } else {
294           DS.insert(IDom);
295           IDom = ID[IDom];
296         }
297       }
298     } else {
299       // Ensure that every basic block has at least an empty set of nodes.  This
300       // is important for the case when there is unreachable blocks.
301       Doms[I];
302     }
303
304   return false;
305 }
306
307 void DominatorSet::stub() {}
308
309 namespace llvm {
310 static std::ostream &operator<<(std::ostream &o,
311                                 const std::set<BasicBlock*> &BBs) {
312   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
313        I != E; ++I)
314     if (*I)
315       WriteAsOperand(o, *I, false);
316     else
317       o << " <<exit node>>";
318   return o;
319 }
320 }
321
322 void DominatorSetBase::print(std::ostream &o, const Module* ) const {
323   for (const_iterator I = begin(), E = end(); I != E; ++I) {
324     o << "  DomSet For BB: ";
325     if (I->first)
326       WriteAsOperand(o, I->first, false);
327     else
328       o << " <<exit node>>";
329     o << " is:\t" << I->second << "\n";
330   }
331 }
332
333 //===----------------------------------------------------------------------===//
334 //  DominatorTree Implementation
335 //===----------------------------------------------------------------------===//
336
337 static RegisterAnalysis<DominatorTree>
338 E("domtree", "Dominator Tree Construction", true);
339
340 // DominatorTreeBase::reset - Free all of the tree node memory.
341 //
342 void DominatorTreeBase::reset() {
343   for (NodeMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
344     delete I->second;
345   Nodes.clear();
346   RootNode = 0;
347 }
348
349 void DominatorTreeBase::Node::setIDom(Node *NewIDom) {
350   assert(IDom && "No immediate dominator?");
351   if (IDom != NewIDom) {
352     std::vector<Node*>::iterator I =
353       std::find(IDom->Children.begin(), IDom->Children.end(), this);
354     assert(I != IDom->Children.end() &&
355            "Not in immediate dominator children set!");
356     // I am no longer your child...
357     IDom->Children.erase(I);
358
359     // Switch to new dominator
360     IDom = NewIDom;
361     IDom->Children.push_back(this);
362   }
363 }
364
365 DominatorTreeBase::Node *DominatorTree::getNodeForBlock(BasicBlock *BB) {
366   Node *&BBNode = Nodes[BB];
367   if (BBNode) return BBNode;
368
369   // Haven't calculated this node yet?  Get or calculate the node for the
370   // immediate dominator.
371   BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
372   Node *IDomNode = getNodeForBlock(IDom);
373
374   // Add a new tree node for this BasicBlock, and link it as a child of
375   // IDomNode
376   return BBNode = IDomNode->addChild(new Node(BB, IDomNode));
377 }
378
379 void DominatorTree::calculate(const ImmediateDominators &ID) {
380   assert(Roots.size() == 1 && "DominatorTree should have 1 root block!");
381   BasicBlock *Root = Roots[0];
382   Nodes[Root] = RootNode = new Node(Root, 0); // Add a node for the root...
383
384   Function *F = Root->getParent();
385   // Loop over all of the reachable blocks in the function...
386   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
387     if (BasicBlock *ImmDom = ID.get(I)) {  // Reachable block.
388       Node *&BBNode = Nodes[I];
389       if (!BBNode) {  // Haven't calculated this node yet?
390         // Get or calculate the node for the immediate dominator
391         Node *IDomNode = getNodeForBlock(ImmDom);
392
393         // Add a new tree node for this BasicBlock, and link it as a child of
394         // IDomNode
395         BBNode = IDomNode->addChild(new Node(I, IDomNode));
396       }
397     }
398 }
399
400 static std::ostream &operator<<(std::ostream &o,
401                                 const DominatorTreeBase::Node *Node) {
402   if (Node->getBlock())
403     WriteAsOperand(o, Node->getBlock(), false);
404   else
405     o << " <<exit node>>";
406   return o << "\n";
407 }
408
409 static void PrintDomTree(const DominatorTreeBase::Node *N, std::ostream &o,
410                          unsigned Lev) {
411   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
412   for (DominatorTreeBase::Node::const_iterator I = N->begin(), E = N->end();
413        I != E; ++I)
414     PrintDomTree(*I, o, Lev+1);
415 }
416
417 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
418   o << "=============================--------------------------------\n"
419     << "Inorder Dominator Tree:\n";
420   PrintDomTree(getRootNode(), o, 1);
421 }
422
423
424 //===----------------------------------------------------------------------===//
425 //  DominanceFrontier Implementation
426 //===----------------------------------------------------------------------===//
427
428 static RegisterAnalysis<DominanceFrontier>
429 G("domfrontier", "Dominance Frontier Construction", true);
430
431 const DominanceFrontier::DomSetType &
432 DominanceFrontier::calculate(const DominatorTree &DT,
433                              const DominatorTree::Node *Node) {
434   // Loop over CFG successors to calculate DFlocal[Node]
435   BasicBlock *BB = Node->getBlock();
436   DomSetType &S = Frontiers[BB];       // The new set to fill in...
437
438   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
439        SI != SE; ++SI) {
440     // Does Node immediately dominate this successor?
441     if (DT[*SI]->getIDom() != Node)
442       S.insert(*SI);
443   }
444
445   // At this point, S is DFlocal.  Now we union in DFup's of our children...
446   // Loop through and visit the nodes that Node immediately dominates (Node's
447   // children in the IDomTree)
448   //
449   for (DominatorTree::Node::const_iterator NI = Node->begin(), NE = Node->end();
450        NI != NE; ++NI) {
451     DominatorTree::Node *IDominee = *NI;
452     const DomSetType &ChildDF = calculate(DT, IDominee);
453
454     DomSetType::const_iterator CDFI = ChildDF.begin(), CDFE = ChildDF.end();
455     for (; CDFI != CDFE; ++CDFI) {
456       if (!Node->properlyDominates(DT[*CDFI]))
457         S.insert(*CDFI);
458     }
459   }
460
461   return S;
462 }
463
464 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
465   for (const_iterator I = begin(), E = end(); I != E; ++I) {
466     o << "  DomFrontier for BB";
467     if (I->first)
468       WriteAsOperand(o, I->first, false);
469     else
470       o << " <<exit node>>";
471     o << " is:\t" << I->second << "\n";
472   }
473 }
474
475 //===----------------------------------------------------------------------===//
476 // ETOccurrence Implementation
477 //===----------------------------------------------------------------------===//
478
479 void ETOccurrence::Splay() {
480   ETOccurrence *father;
481   ETOccurrence *grandfather;
482   int occdepth;
483   int fatherdepth;
484   
485   while (Parent) {
486     occdepth = Depth;
487     
488     father = Parent;
489     fatherdepth = Parent->Depth;
490     grandfather = father->Parent;
491     
492     // If we have no grandparent, a single zig or zag will do.
493     if (!grandfather) {
494       setDepthAdd(fatherdepth);
495       MinOccurrence = father->MinOccurrence;
496       Min = father->Min;
497       
498       // See what we have to rotate
499       if (father->Left == this) {
500         // Zig
501         father->setLeft(Right);
502         setRight(father);
503         if (father->Left)
504           father->Left->setDepthAdd(occdepth);
505       } else {
506         // Zag
507         father->setRight(Left);
508         setLeft(father);
509         if (father->Right)
510           father->Right->setDepthAdd(occdepth);
511       }
512       father->setDepth(-occdepth);
513       Parent = NULL;
514       
515       father->recomputeMin();
516       return;
517     }
518     
519     // If we have a grandfather, we need to do some
520     // combination of zig and zag.
521     int grandfatherdepth = grandfather->Depth;
522     
523     setDepthAdd(fatherdepth + grandfatherdepth);
524     MinOccurrence = grandfather->MinOccurrence;
525     Min = grandfather->Min;
526     
527     ETOccurrence *greatgrandfather = grandfather->Parent;
528     
529     if (grandfather->Left == father) {
530       if (father->Left == this) {
531         // Zig zig
532         grandfather->setLeft(father->Right);
533         father->setLeft(Right);
534         setRight(father);
535         father->setRight(grandfather);
536         
537         father->setDepth(-occdepth);
538         
539         if (father->Left)
540           father->Left->setDepthAdd(occdepth);
541         
542         grandfather->setDepth(-fatherdepth);
543         if (grandfather->Left)
544           grandfather->Left->setDepthAdd(fatherdepth);
545       } else {
546         // Zag zig
547         grandfather->setLeft(Right);
548         father->setRight(Left);
549         setLeft(father);
550         setRight(grandfather);
551         
552         father->setDepth(-occdepth);
553         if (father->Right)
554           father->Right->setDepthAdd(occdepth);
555         grandfather->setDepth(-occdepth - fatherdepth);
556         if (grandfather->Left)
557           grandfather->Left->setDepthAdd(occdepth + fatherdepth);
558       }
559     } else {
560       if (father->Left == this) {
561         // Zig zag
562         grandfather->setRight(Left);
563         father->setLeft(Right);
564         setLeft(grandfather);
565         setRight(father);
566         
567         father->setDepth(-occdepth);
568         if (father->Left)
569           father->Left->setDepthAdd(occdepth);
570         grandfather->setDepth(-occdepth - fatherdepth);
571         if (grandfather->Right)
572           grandfather->Right->setDepthAdd(occdepth + fatherdepth);
573       } else {              // Zag Zag
574         grandfather->setRight(father->Left);
575         father->setRight(Left);
576         setLeft(father);
577         father->setLeft(grandfather);
578         
579         father->setDepth(-occdepth);
580         if (father->Right)
581           father->Right->setDepthAdd(occdepth);
582         grandfather->setDepth(-fatherdepth);
583         if (grandfather->Right)
584           grandfather->Right->setDepthAdd(fatherdepth);
585       }
586     }
587     
588     // Might need one more rotate depending on greatgrandfather.
589     setParent(greatgrandfather);
590     if (greatgrandfather) {
591       if (greatgrandfather->Left == grandfather)
592         greatgrandfather->Left = this;
593       else
594         greatgrandfather->Right = this;
595       
596     }
597     grandfather->recomputeMin();
598     father->recomputeMin();
599   }
600 }
601
602 //===----------------------------------------------------------------------===//
603 // ETNode implementation
604 //===----------------------------------------------------------------------===//
605
606 void ETNode::Split() {
607   ETOccurrence *right, *left;
608   ETOccurrence *rightmost = RightmostOcc;
609   ETOccurrence *parent;
610
611   // Update the occurrence tree first.
612   RightmostOcc->Splay();
613
614   // Find the leftmost occurrence in the rightmost subtree, then splay
615   // around it.
616   for (right = rightmost->Right; right->Left; right = right->Left);
617
618   right->Splay();
619
620   // Start splitting
621   right->Left->Parent = NULL;
622   parent = ParentOcc;
623   parent->Splay();
624   ParentOcc = NULL;
625
626   left = parent->Left;
627   parent->Right->Parent = NULL;
628
629   right->setLeft(left);
630
631   right->recomputeMin();
632
633   rightmost->Splay();
634   rightmost->Depth = 0;
635   rightmost->Min = 0;
636
637   delete parent;
638
639   // Now update *our* tree
640
641   if (Father->Son == this)
642     Father->Son = Right;
643
644   if (Father->Son == this)
645     Father->Son = NULL;
646   else {
647     Left->Right = Right;
648     Right->Left = Left;
649   }
650   Left = Right = NULL;
651   Father = NULL;
652 }
653
654 void ETNode::setFather(ETNode *NewFather) {
655   ETOccurrence *rightmost;
656   ETOccurrence *leftpart;
657   ETOccurrence *NewFatherOcc;
658   ETOccurrence *temp;
659
660   // First update the path in the splay tree
661   NewFatherOcc = new ETOccurrence(NewFather);
662
663   rightmost = NewFather->RightmostOcc;
664   rightmost->Splay();
665
666   leftpart = rightmost->Left;
667
668   temp = RightmostOcc;
669   temp->Splay();
670
671   NewFatherOcc->setLeft(leftpart);
672   NewFatherOcc->setRight(temp);
673
674   temp->Depth++;
675   temp->Min++;
676   NewFatherOcc->recomputeMin();
677
678   rightmost->setLeft(NewFatherOcc);
679
680   if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
681     rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
682     rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
683   }
684
685   delete ParentOcc;
686   ParentOcc = NewFatherOcc;
687
688   // Update *our* tree
689   ETNode *left;
690   ETNode *right;
691
692   Father = NewFather;
693   right = Father->Son;
694
695   if (right)
696     left = right->Left;
697   else
698     left = right = this;
699
700   left->Right = this;
701   right->Left = this;
702   Left = left;
703   Right = right;
704
705   Father->Son = this;
706 }
707
708 bool ETNode::Below(ETNode *other) {
709   ETOccurrence *up = other->RightmostOcc;
710   ETOccurrence *down = RightmostOcc;
711
712   if (this == other)
713     return true;
714
715   up->Splay();
716
717   ETOccurrence *left, *right;
718   left = up->Left;
719   right = up->Right;
720
721   if (!left)
722     return false;
723
724   left->Parent = NULL;
725
726   if (right)
727     right->Parent = NULL;
728
729   down->Splay();
730
731   if (left == down || left->Parent != NULL) {
732     if (right)
733       right->Parent = up;
734     up->setLeft(down);
735   } else {
736     left->Parent = up;
737
738     // If the two occurrences are in different trees, put things
739     // back the way they were.
740     if (right && right->Parent != NULL)
741       up->setRight(down);
742     else
743       up->setRight(right);
744     return false;
745   }
746
747   if (down->Depth <= 0)
748     return false;
749
750   return !down->Right || down->Right->Min + down->Depth >= 0;
751 }
752
753 ETNode *ETNode::NCA(ETNode *other) {
754   ETOccurrence *occ1 = RightmostOcc;
755   ETOccurrence *occ2 = other->RightmostOcc;
756   
757   ETOccurrence *left, *right, *ret;
758   ETOccurrence *occmin;
759   int mindepth;
760   
761   if (this == other)
762     return this;
763   
764   occ1->Splay();
765   left = occ1->Left;
766   right = occ1->Right;
767   
768   if (left)
769     left->Parent = NULL;
770   
771   if (right)
772     right->Parent = NULL;
773   occ2->Splay();
774
775   if (left == occ2 || (left && left->Parent != NULL)) {
776     ret = occ2->Right;
777     
778     occ1->setLeft(occ2);
779     if (right)
780       right->Parent = occ1;
781   } else {
782     ret = occ2->Left;
783     
784     occ1->setRight(occ2);
785     if (left)
786       left->Parent = occ1;
787   }
788
789   if (occ2->Depth > 0) {
790     occmin = occ1;
791     mindepth = occ1->Depth;
792   } else {
793     occmin = occ2;
794     mindepth = occ2->Depth + occ1->Depth;
795   }
796   
797   if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
798     return ret->MinOccurrence->OccFor;
799   else
800     return occmin->OccFor;
801 }
802
803 //===----------------------------------------------------------------------===//
804 // ETForest implementation
805 //===----------------------------------------------------------------------===//
806
807 static RegisterAnalysis<ETForest>
808 D("etforest", "ET Forest Construction", true);
809
810 void ETForestBase::reset() {
811   for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
812     delete I->second;
813   Nodes.clear();
814 }
815
816 void ETForestBase::updateDFSNumbers()
817 {
818   int dfsnum = 0;
819   // Iterate over all nodes in depth first order.
820   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
821     for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
822            E = df_end(Roots[i]); I != E; ++I) {
823       BasicBlock *BB = *I;
824       if (!getNode(BB)->hasFather())
825         getNode(BB)->assignDFSNumber(dfsnum);    
826   }
827   SlowQueries = 0;
828   DFSInfoValid = true;
829 }
830
831 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
832   ETNode *&BBNode = Nodes[BB];
833   if (BBNode) return BBNode;
834
835   // Haven't calculated this node yet?  Get or calculate the node for the
836   // immediate dominator.
837   BasicBlock *IDom = getAnalysis<ImmediateDominators>()[BB];
838
839   // If we are unreachable, we may not have an immediate dominator.
840   if (!IDom)
841     return BBNode = new ETNode(BB);
842   else {
843     ETNode *IDomNode = getNodeForBlock(IDom);
844     
845     // Add a new tree node for this BasicBlock, and link it as a child of
846     // IDomNode
847     BBNode = new ETNode(BB);
848     BBNode->setFather(IDomNode);
849     return BBNode;
850   }
851 }
852
853 void ETForest::calculate(const ImmediateDominators &ID) {
854   assert(Roots.size() == 1 && "ETForest should have 1 root block!");
855   BasicBlock *Root = Roots[0];
856   Nodes[Root] = new ETNode(Root); // Add a node for the root
857
858   Function *F = Root->getParent();
859   // Loop over all of the reachable blocks in the function...
860   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
861     if (BasicBlock *ImmDom = ID.get(I)) {  // Reachable block.
862       ETNode *&BBNode = Nodes[I];
863       if (!BBNode) {  // Haven't calculated this node yet?
864         // Get or calculate the node for the immediate dominator
865         ETNode *IDomNode =  getNodeForBlock(ImmDom);
866
867         // Add a new ETNode for this BasicBlock, and set it's parent
868         // to it's immediate dominator.
869         BBNode = new ETNode(I);
870         BBNode->setFather(IDomNode);
871       }
872     }
873
874   // Make sure we've got nodes around for every block
875   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
876     ETNode *&BBNode = Nodes[I];
877     if (!BBNode)
878       BBNode = new ETNode(I);
879   }
880
881   updateDFSNumbers ();
882 }
883
884 //===----------------------------------------------------------------------===//
885 // ETForestBase Implementation
886 //===----------------------------------------------------------------------===//
887
888 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
889   ETNode *&BBNode = Nodes[BB];
890   assert(!BBNode && "BasicBlock already in ET-Forest");
891
892   BBNode = new ETNode(BB);
893   BBNode->setFather(getNode(IDom));
894   DFSInfoValid = false;
895 }
896
897 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
898   assert(getNode(BB) && "BasicBlock not in ET-Forest");
899   assert(getNode(newIDom) && "IDom not in ET-Forest");
900   
901   ETNode *Node = getNode(BB);
902   if (Node->hasFather()) {
903     if (Node->getFather()->getData<BasicBlock>() == newIDom)
904       return;
905     Node->Split();
906   }
907   Node->setFather(getNode(newIDom));
908   DFSInfoValid= false;
909 }
910
911 void ETForestBase::print(std::ostream &o, const Module *) const {
912   o << "=============================--------------------------------\n";
913   o << "ET Forest:\n";
914   o << "DFS Info ";
915   if (DFSInfoValid)
916     o << "is";
917   else
918     o << "is not";
919   o << " up to date\n";
920
921   Function *F = getRoots()[0]->getParent();
922   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
923     o << "  DFS Numbers For Basic Block:";
924     WriteAsOperand(o, I, false);
925     o << " are:";
926     if (ETNode *EN = getNode(I)) {
927       o << "In: " << EN->getDFSNumIn();
928       o << " Out: " << EN->getDFSNumOut() << "\n";
929     } else {
930       o << "No associated ETNode";
931     }
932     o << "\n";
933   }
934   o << "\n";
935 }