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