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