Add FIXMEs.
[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 using namespace llvm;
27
28 namespace llvm {
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();
32        I != E; ++I)
33     if (*I)
34       WriteAsOperand(o, *I, false);
35     else
36       o << " <<exit node>>";
37   return o;
38 }
39 }
40
41 //===----------------------------------------------------------------------===//
42 //  DominatorTree Implementation
43 //===----------------------------------------------------------------------===//
44 //
45 // DominatorTree construction - This pass constructs immediate dominator
46 // information for a flow-graph based on the algorithm described in this
47 // document:
48 //
49 //   A Fast Algorithm for Finding Dominators in a Flowgraph
50 //   T. Lengauer & R. Tarjan, ACM TOPLAS July 1979, pgs 121-141.
51 //
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:
57 //
58 #define BALANCE_IDOM_TREE 0
59 //
60 //===----------------------------------------------------------------------===//
61
62 char DominatorTree::ID = 0;
63 static RegisterPass<DominatorTree>
64 E("domtree", "Dominator Tree Construction", true);
65
66 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
67                                       unsigned N) {
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.
71 #if 0
72   VInfo.Semi = ++N;
73   VInfo.Label = V;
74
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
79
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) {
83       SuccVInfo.Parent = V;
84       N = DFSPass(*SI, SuccVInfo, N);
85     }
86   }
87 #else
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;
93     
94     // First time we visited this BB?
95     if (NextSucc == 0) {
96       InfoRec &BBInfo = Info[BB];
97       BBInfo.Semi = ++N;
98       BBInfo.Label = BB;
99       
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
104     }
105     
106     // If we are done with this block, remove it from the worklist.
107     if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
108       Worklist.pop_back();
109       continue;
110     }
111     
112     // Otherwise, increment the successor number for the next time we get to it.
113     ++Worklist.back().second;
114     
115     // Visit the successor next, if it isn't already visited.
116     BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
117     
118     InfoRec &SuccVInfo = Info[Succ];
119     if (SuccVInfo.Semi == 0) {
120       SuccVInfo.Parent = BB;
121       Worklist.push_back(std::make_pair(Succ, 0U));
122     }
123   }
124 #endif
125   return N;
126 }
127
128 void DominatorTree::Compress(BasicBlock *VIn) {
129
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];
135
136   if (VInVAInfo.Ancestor != 0)
137     Work.push_back(VIn);
138   
139   while (!Work.empty()) {
140     BasicBlock *V = Work.back();
141     InfoRec &VInfo = Info[V];
142     BasicBlock *VAncestor = VInfo.Ancestor;
143     InfoRec &VAInfo = Info[VAncestor];
144
145     // Process Ancestor first
146     if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
147       Work.push_back(VAncestor);
148       Visited.insert(VAncestor);
149       continue;
150     } 
151     Work.pop_back(); 
152
153     // Update VINfo based on Ancestor info
154     if (VAInfo.Ancestor == 0)
155       continue;
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;
161   }
162 }
163
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)
169     return V;
170   Compress(V);
171   return VInfo.Label;
172 #else
173   // Lower-complexity but slower implementation
174   if (VInfo.Ancestor == 0)
175     return VInfo.Label;
176   Compress(V);
177   BasicBlock *VLabel = VInfo.Label;
178
179   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
180   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
181     return VLabel;
182   else
183     return VAncestorLabel;
184 #endif
185 }
186
187 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
188 #if !BALANCE_IDOM_TREE
189   // Higher-complexity but faster implementation
190   WInfo.Ancestor = V;
191 #else
192   // Lower-complexity but slower implementation
193   BasicBlock *WLabel = WInfo.Label;
194   unsigned WLabelSemi = Info[WLabel].Semi;
195   BasicBlock *S = W;
196   InfoRec *SInfo = &Info[S];
197
198   BasicBlock *SChild = SInfo->Child;
199   InfoRec *SChildInfo = &Info[SChild];
200
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];
207     } else {
208       SChildInfo->Size = SInfo->Size;
209       S = SInfo->Ancestor = SChild;
210       SInfo = SChildInfo;
211       SChild = SChildChild;
212       SChildInfo = &Info[SChild];
213     }
214   }
215
216   InfoRec &VInfo = Info[V];
217   SInfo->Label = WLabel;
218
219   assert(V != W && "The optimization here will not work in this case!");
220   unsigned WSize = WInfo.Size;
221   unsigned VSize = (VInfo.Size += WSize);
222
223   if (VSize < 2*WSize)
224     std::swap(S, VInfo.Child);
225
226   while (S) {
227     SInfo = &Info[S];
228     SInfo->Ancestor = V;
229     S = SInfo->Child;
230   }
231 #endif
232 }
233
234 void DominatorTree::calculate(Function& F) {
235   BasicBlock* Root = Roots[0];
236   
237   DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0); // Add a node for the root...
238
239   Vertex.push_back(0);
240
241   // Step #1: Number blocks in depth-first order and initialize variables used
242   // in later stages of the algorithm.
243   unsigned N = 0;
244   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
245     N = DFSPass(Roots[i], Info[Roots[i]], 0);
246
247   for (unsigned i = N; i >= 2; --i) {
248     BasicBlock *W = Vertex[i];
249     InfoRec &WInfo = Info[W];
250
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)
256           WInfo.Semi = SemiU;
257       }
258
259     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
260
261     BasicBlock *WParent = WInfo.Parent;
262     Link(WParent, W, WInfo);
263
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;
271     }
272   }
273
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];
280   }
281
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);
289
290         // Add a new tree node for this BasicBlock, and link it as a child of
291         // IDomNode
292         BBNode = IDomNode->addChild(new DomTreeNode(I, IDomNode));
293       }
294     }
295
296   // Free temporary memory used to construct idom's
297   Info.clear();
298   IDoms.clear();
299   std::vector<BasicBlock*>().swap(Vertex);
300 }
301
302 // DominatorTreeBase::reset - Free all of the tree node memory.
303 //
304 void DominatorTreeBase::reset() {
305   for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), E = DomTreeNodes.end(); I != E; ++I)
306     delete I->second;
307   DomTreeNodes.clear();
308   IDoms.clear();
309   Roots.clear();
310   Vertex.clear();
311   RootNode = 0;
312 }
313
314 void 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);
323
324     // Switch to new dominator
325     IDom = NewIDom;
326     IDom->Children.push_back(this);
327   }
328 }
329
330 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
331   DomTreeNode *&BBNode = DomTreeNodes[BB];
332   if (BBNode) return BBNode;
333
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);
338
339   // Add a new tree node for this BasicBlock, and link it as a child of
340   // IDomNode
341   return BBNode = IDomNode->addChild(new DomTreeNode(BB, IDomNode));
342 }
343
344 static std::ostream &operator<<(std::ostream &o,
345                                 const DomTreeNode *Node) {
346   if (Node->getBlock())
347     WriteAsOperand(o, Node->getBlock(), false);
348   else
349     o << " <<exit node>>";
350   return o << "\n";
351 }
352
353 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
354                          unsigned Lev) {
355   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
356   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
357        I != E; ++I)
358     PrintDomTree(*I, o, Lev+1);
359 }
360
361 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
362   o << "=============================--------------------------------\n"
363     << "Inorder Dominator Tree:\n";
364   PrintDomTree(getRootNode(), o, 1);
365 }
366
367 void DominatorTreeBase::dump() {
368   print (llvm::cerr);
369 }
370
371 bool DominatorTree::runOnFunction(Function &F) {
372   reset();     // Reset from the last time we were run...
373   Roots.push_back(&F.getEntryBlock());
374   calculate(F);
375   return false;
376 }
377
378 //===----------------------------------------------------------------------===//
379 //  DominanceFrontier Implementation
380 //===----------------------------------------------------------------------===//
381
382 char DominanceFrontier::ID = 0;
383 static RegisterPass<DominanceFrontier>
384 G("domfrontier", "Dominance Frontier Construction", true);
385
386 namespace {
387   class DFCalculateWorkObject {
388   public:
389     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
390                           const DomTreeNode *N,
391                           const DomTreeNode *PN)
392     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
393     BasicBlock *currentBB;
394     BasicBlock *parentBB;
395     const DomTreeNode *Node;
396     const DomTreeNode *parentNode;
397   };
398 }
399
400 const DominanceFrontier::DomSetType &
401 DominanceFrontier::calculate(const DominatorTree &DT,
402                              const DomTreeNode *Node) {
403   BasicBlock *BB = Node->getBlock();
404   DomSetType *Result = NULL;
405
406   std::vector<DFCalculateWorkObject> workList;
407   SmallPtrSet<BasicBlock *, 32> visited;
408
409   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
410   do {
411     DFCalculateWorkObject *currentW = &workList.back();
412     assert (currentW && "Missing work object.");
413
414     BasicBlock *currentBB = currentW->currentBB;
415     BasicBlock *parentBB = currentW->parentBB;
416     const DomTreeNode *currentNode = currentW->Node;
417     const 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];
421
422     // Visit each block only once.
423     if (visited.count(currentBB) == 0) {
424       visited.insert(currentBB);
425
426       // Loop over CFG successors to calculate DFlocal[currentNode]
427       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
428            SI != SE; ++SI) {
429         // Does Node immediately dominate this successor?
430         if (DT[*SI]->getIDom() != currentNode)
431           S.insert(*SI);
432       }
433     }
434
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 (DomTreeNode::const_iterator NI = currentNode->begin(), 
440            NE = currentNode->end(); NI != NE; ++NI) {
441       DomTreeNode *IDominee = *NI;
442       BasicBlock *childBB = IDominee->getBlock();
443       if (visited.count(childBB) == 0) {
444         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
445                                                  IDominee, currentNode));
446         visitChild = true;
447       }
448     }
449
450     // If all children are visited or there is any child then pop this block
451     // from the workList.
452     if (!visitChild) {
453
454       if (!parentBB) {
455         Result = &S;
456         break;
457       }
458
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);
464       }
465       workList.pop_back();
466     }
467
468   } while (!workList.empty());
469
470   return *Result;
471 }
472
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";
476     if (I->first)
477       WriteAsOperand(o, I->first, false);
478     else
479       o << " <<exit node>>";
480     o << " is:\t" << I->second << "\n";
481   }
482 }
483
484 void DominanceFrontierBase::dump() {
485   print (llvm::cerr);
486 }
487
488
489 //===----------------------------------------------------------------------===//
490 // ETOccurrence Implementation
491 //===----------------------------------------------------------------------===//
492
493 void ETOccurrence::Splay() {
494   ETOccurrence *father;
495   ETOccurrence *grandfather;
496   int occdepth;
497   int fatherdepth;
498   
499   while (Parent) {
500     occdepth = Depth;
501     
502     father = Parent;
503     fatherdepth = Parent->Depth;
504     grandfather = father->Parent;
505     
506     // If we have no grandparent, a single zig or zag will do.
507     if (!grandfather) {
508       setDepthAdd(fatherdepth);
509       MinOccurrence = father->MinOccurrence;
510       Min = father->Min;
511       
512       // See what we have to rotate
513       if (father->Left == this) {
514         // Zig
515         father->setLeft(Right);
516         setRight(father);
517         if (father->Left)
518           father->Left->setDepthAdd(occdepth);
519       } else {
520         // Zag
521         father->setRight(Left);
522         setLeft(father);
523         if (father->Right)
524           father->Right->setDepthAdd(occdepth);
525       }
526       father->setDepth(-occdepth);
527       Parent = NULL;
528       
529       father->recomputeMin();
530       return;
531     }
532     
533     // If we have a grandfather, we need to do some
534     // combination of zig and zag.
535     int grandfatherdepth = grandfather->Depth;
536     
537     setDepthAdd(fatherdepth + grandfatherdepth);
538     MinOccurrence = grandfather->MinOccurrence;
539     Min = grandfather->Min;
540     
541     ETOccurrence *greatgrandfather = grandfather->Parent;
542     
543     if (grandfather->Left == father) {
544       if (father->Left == this) {
545         // Zig zig
546         grandfather->setLeft(father->Right);
547         father->setLeft(Right);
548         setRight(father);
549         father->setRight(grandfather);
550         
551         father->setDepth(-occdepth);
552         
553         if (father->Left)
554           father->Left->setDepthAdd(occdepth);
555         
556         grandfather->setDepth(-fatherdepth);
557         if (grandfather->Left)
558           grandfather->Left->setDepthAdd(fatherdepth);
559       } else {
560         // Zag zig
561         grandfather->setLeft(Right);
562         father->setRight(Left);
563         setLeft(father);
564         setRight(grandfather);
565         
566         father->setDepth(-occdepth);
567         if (father->Right)
568           father->Right->setDepthAdd(occdepth);
569         grandfather->setDepth(-occdepth - fatherdepth);
570         if (grandfather->Left)
571           grandfather->Left->setDepthAdd(occdepth + fatherdepth);
572       }
573     } else {
574       if (father->Left == this) {
575         // Zig zag
576         grandfather->setRight(Left);
577         father->setLeft(Right);
578         setLeft(grandfather);
579         setRight(father);
580         
581         father->setDepth(-occdepth);
582         if (father->Left)
583           father->Left->setDepthAdd(occdepth);
584         grandfather->setDepth(-occdepth - fatherdepth);
585         if (grandfather->Right)
586           grandfather->Right->setDepthAdd(occdepth + fatherdepth);
587       } else {              // Zag Zag
588         grandfather->setRight(father->Left);
589         father->setRight(Left);
590         setLeft(father);
591         father->setLeft(grandfather);
592         
593         father->setDepth(-occdepth);
594         if (father->Right)
595           father->Right->setDepthAdd(occdepth);
596         grandfather->setDepth(-fatherdepth);
597         if (grandfather->Right)
598           grandfather->Right->setDepthAdd(fatherdepth);
599       }
600     }
601     
602     // Might need one more rotate depending on greatgrandfather.
603     setParent(greatgrandfather);
604     if (greatgrandfather) {
605       if (greatgrandfather->Left == grandfather)
606         greatgrandfather->Left = this;
607       else
608         greatgrandfather->Right = this;
609       
610     }
611     grandfather->recomputeMin();
612     father->recomputeMin();
613   }
614 }
615
616 //===----------------------------------------------------------------------===//
617 // ETNode implementation
618 //===----------------------------------------------------------------------===//
619
620 void ETNode::Split() {
621   ETOccurrence *right, *left;
622   ETOccurrence *rightmost = RightmostOcc;
623   ETOccurrence *parent;
624
625   // Update the occurrence tree first.
626   RightmostOcc->Splay();
627
628   // Find the leftmost occurrence in the rightmost subtree, then splay
629   // around it.
630   for (right = rightmost->Right; right->Left; right = right->Left);
631
632   right->Splay();
633
634   // Start splitting
635   right->Left->Parent = NULL;
636   parent = ParentOcc;
637   parent->Splay();
638   ParentOcc = NULL;
639
640   left = parent->Left;
641   parent->Right->Parent = NULL;
642
643   right->setLeft(left);
644
645   right->recomputeMin();
646
647   rightmost->Splay();
648   rightmost->Depth = 0;
649   rightmost->Min = 0;
650
651   delete parent;
652
653   // Now update *our* tree
654
655   if (Father->Son == this)
656     Father->Son = Right;
657
658   if (Father->Son == this)
659     Father->Son = NULL;
660   else {
661     Left->Right = Right;
662     Right->Left = Left;
663   }
664   Left = Right = NULL;
665   Father = NULL;
666 }
667
668 void ETNode::setFather(ETNode *NewFather) {
669   ETOccurrence *rightmost;
670   ETOccurrence *leftpart;
671   ETOccurrence *NewFatherOcc;
672   ETOccurrence *temp;
673
674   // First update the path in the splay tree
675   NewFatherOcc = new ETOccurrence(NewFather);
676
677   rightmost = NewFather->RightmostOcc;
678   rightmost->Splay();
679
680   leftpart = rightmost->Left;
681
682   temp = RightmostOcc;
683   temp->Splay();
684
685   NewFatherOcc->setLeft(leftpart);
686   NewFatherOcc->setRight(temp);
687
688   temp->Depth++;
689   temp->Min++;
690   NewFatherOcc->recomputeMin();
691
692   rightmost->setLeft(NewFatherOcc);
693
694   if (NewFatherOcc->Min + rightmost->Depth < rightmost->Min) {
695     rightmost->Min = NewFatherOcc->Min + rightmost->Depth;
696     rightmost->MinOccurrence = NewFatherOcc->MinOccurrence;
697   }
698
699   delete ParentOcc;
700   ParentOcc = NewFatherOcc;
701
702   // Update *our* tree
703   ETNode *left;
704   ETNode *right;
705
706   Father = NewFather;
707   right = Father->Son;
708
709   if (right)
710     left = right->Left;
711   else
712     left = right = this;
713
714   left->Right = this;
715   right->Left = this;
716   Left = left;
717   Right = right;
718
719   Father->Son = this;
720 }
721
722 bool ETNode::Below(ETNode *other) {
723   ETOccurrence *up = other->RightmostOcc;
724   ETOccurrence *down = RightmostOcc;
725
726   if (this == other)
727     return true;
728
729   up->Splay();
730
731   ETOccurrence *left, *right;
732   left = up->Left;
733   right = up->Right;
734
735   if (!left)
736     return false;
737
738   left->Parent = NULL;
739
740   if (right)
741     right->Parent = NULL;
742
743   down->Splay();
744
745   if (left == down || left->Parent != NULL) {
746     if (right)
747       right->Parent = up;
748     up->setLeft(down);
749   } else {
750     left->Parent = up;
751
752     // If the two occurrences are in different trees, put things
753     // back the way they were.
754     if (right && right->Parent != NULL)
755       up->setRight(down);
756     else
757       up->setRight(right);
758     return false;
759   }
760
761   if (down->Depth <= 0)
762     return false;
763
764   return !down->Right || down->Right->Min + down->Depth >= 0;
765 }
766
767 ETNode *ETNode::NCA(ETNode *other) {
768   ETOccurrence *occ1 = RightmostOcc;
769   ETOccurrence *occ2 = other->RightmostOcc;
770   
771   ETOccurrence *left, *right, *ret;
772   ETOccurrence *occmin;
773   int mindepth;
774   
775   if (this == other)
776     return this;
777   
778   occ1->Splay();
779   left = occ1->Left;
780   right = occ1->Right;
781   
782   if (left)
783     left->Parent = NULL;
784   
785   if (right)
786     right->Parent = NULL;
787   occ2->Splay();
788
789   if (left == occ2 || (left && left->Parent != NULL)) {
790     ret = occ2->Right;
791     
792     occ1->setLeft(occ2);
793     if (right)
794       right->Parent = occ1;
795   } else {
796     ret = occ2->Left;
797     
798     occ1->setRight(occ2);
799     if (left)
800       left->Parent = occ1;
801   }
802
803   if (occ2->Depth > 0) {
804     occmin = occ1;
805     mindepth = occ1->Depth;
806   } else {
807     occmin = occ2;
808     mindepth = occ2->Depth + occ1->Depth;
809   }
810   
811   if (ret && ret->Min + occ1->Depth + occ2->Depth < mindepth)
812     return ret->MinOccurrence->OccFor;
813   else
814     return occmin->OccFor;
815 }
816
817 void ETNode::assignDFSNumber(int num) {
818   std::vector<ETNode *>  workStack;
819   std::set<ETNode *> visitedNodes;
820   
821   workStack.push_back(this);
822   visitedNodes.insert(this);
823   this->DFSNumIn = num++;
824
825   while (!workStack.empty()) {
826     ETNode  *Node = workStack.back();
827     
828     // If this is leaf node then set DFSNumOut and pop the stack
829     if (!Node->Son) {
830       Node->DFSNumOut = num++;
831       workStack.pop_back();
832       continue;
833     }
834     
835     ETNode *son = Node->Son;
836     
837     // Visit Node->Son first
838     if (visitedNodes.count(son) == 0) {
839       son->DFSNumIn = num++;
840       workStack.push_back(son);
841       visitedNodes.insert(son);
842       continue;
843     }
844     
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) {
849         visitChild = true;
850         s->DFSNumIn = num++;
851         workStack.push_back(s);
852         visitedNodes.insert(s);
853       }
854     }
855     
856     if (!visitChild) {
857       // If we reach here means all children are visited
858       Node->DFSNumOut = num++;
859       workStack.pop_back();
860     }
861   }
862 }
863
864 //===----------------------------------------------------------------------===//
865 // ETForest implementation
866 //===----------------------------------------------------------------------===//
867
868 char ETForest::ID = 0;
869 static RegisterPass<ETForest>
870 D("etforest", "ET Forest Construction", true);
871
872 void ETForestBase::reset() {
873   for (ETMapType::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I)
874     delete I->second;
875   Nodes.clear();
876 }
877
878 void ETForestBase::updateDFSNumbers()
879 {
880   int dfsnum = 0;
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) {
885       BasicBlock *BB = *I;
886       ETNode *ETN = getNode(BB);
887       if (ETN && !ETN->hasFather())
888         ETN->assignDFSNumber(dfsnum);    
889   }
890   SlowQueries = 0;
891   DFSInfoValid = true;
892 }
893
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);
899   
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)) 
903     return false;
904
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*/;
908   
909   if(!IsPostDominators) {
910     // A dominates B if it is found first in the basic block.
911     return &*I == A;
912   } else {
913     // A post-dominates B if B is found first in the basic block.
914     return &*I == B;
915   }
916 }
917
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);
922 }
923
924 // FIXME : There is no need to make getNodeForBlock public. Fix
925 // predicate simplifier.
926 ETNode *ETForest::getNodeForBlock(BasicBlock *BB) {
927   ETNode *&BBNode = Nodes[BB];
928   if (BBNode) return BBNode;
929
930   // Haven't calculated this node yet?  Get or calculate the node for the
931   // immediate dominator.
932   DomTreeNode *node= getAnalysis<DominatorTree>().getNode(BB);
933
934   // If we are unreachable, we may not have an immediate dominator.
935   if (!node || !node->getIDom())
936     return BBNode = new ETNode(BB);
937   else {
938     ETNode *IDomNode = getNodeForBlock(node->getIDom()->getBlock());
939     
940     // Add a new tree node for this BasicBlock, and link it as a child of
941     // IDomNode
942     BBNode = new ETNode(BB);
943     BBNode->setFather(IDomNode);
944     return BBNode;
945   }
946 }
947
948 void ETForest::calculate(const DominatorTree &DT) {
949   assert(Roots.size() == 1 && "ETForest should have 1 root block!");
950   BasicBlock *Root = Roots[0];
951   Nodes[Root] = new ETNode(Root); // Add a node for the root
952
953   Function *F = Root->getParent();
954   // Loop over all of the reachable blocks in the function...
955   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
956     DomTreeNode* node = DT.getNode(I);
957     if (node && node->getIDom()) {  // Reachable block.
958       BasicBlock* ImmDom = node->getIDom()->getBlock();
959       ETNode *&BBNode = Nodes[I];
960       if (!BBNode) {  // Haven't calculated this node yet?
961         // Get or calculate the node for the immediate dominator
962         ETNode *IDomNode =  getNodeForBlock(ImmDom);
963
964         // Add a new ETNode for this BasicBlock, and set it's parent
965         // to it's immediate dominator.
966         BBNode = new ETNode(I);
967         BBNode->setFather(IDomNode);
968       }
969     }
970   }
971
972   // Make sure we've got nodes around for every block
973   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
974     ETNode *&BBNode = Nodes[I];
975     if (!BBNode)
976       BBNode = new ETNode(I);
977   }
978
979   updateDFSNumbers ();
980 }
981
982 //===----------------------------------------------------------------------===//
983 // ETForestBase Implementation
984 //===----------------------------------------------------------------------===//
985
986 void ETForestBase::addNewBlock(BasicBlock *BB, BasicBlock *IDom) {
987   ETNode *&BBNode = Nodes[BB];
988   assert(!BBNode && "BasicBlock already in ET-Forest");
989
990   BBNode = new ETNode(BB);
991   BBNode->setFather(getNode(IDom));
992   DFSInfoValid = false;
993 }
994
995 void ETForestBase::setImmediateDominator(BasicBlock *BB, BasicBlock *newIDom) {
996   assert(getNode(BB) && "BasicBlock not in ET-Forest");
997   assert(getNode(newIDom) && "IDom not in ET-Forest");
998   
999   ETNode *Node = getNode(BB);
1000   if (Node->hasFather()) {
1001     if (Node->getFather()->getData<BasicBlock>() == newIDom)
1002       return;
1003     Node->Split();
1004   }
1005   Node->setFather(getNode(newIDom));
1006   DFSInfoValid= false;
1007 }
1008
1009 void ETForestBase::print(std::ostream &o, const Module *) const {
1010   o << "=============================--------------------------------\n";
1011   o << "ET Forest:\n";
1012   o << "DFS Info ";
1013   if (DFSInfoValid)
1014     o << "is";
1015   else
1016     o << "is not";
1017   o << " up to date\n";
1018
1019   Function *F = getRoots()[0]->getParent();
1020   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
1021     o << "  DFS Numbers For Basic Block:";
1022     WriteAsOperand(o, I, false);
1023     o << " are:";
1024     if (ETNode *EN = getNode(I)) {
1025       o << "In: " << EN->getDFSNumIn();
1026       o << " Out: " << EN->getDFSNumOut() << "\n";
1027     } else {
1028       o << "No associated ETNode";
1029     }
1030     o << "\n";
1031   }
1032   o << "\n";
1033 }
1034
1035 void ETForestBase::dump() {
1036   print (llvm::cerr);
1037 }