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