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