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