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