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