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