Undo previous check-in.
[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 // NewBB is split and now it has one successor. Update dominator tree to
67 // reflect this change.
68 void DominatorTree::splitBlock(BasicBlock *NewBB) {
69
70   assert(NewBB->getTerminator()->getNumSuccessors() == 1
71          && "NewBB should have a single successor!");
72   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
73
74   std::vector<BasicBlock*> PredBlocks;
75   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
76        PI != PE; ++PI)
77       PredBlocks.push_back(*PI);  
78
79   assert(!PredBlocks.empty() && "No predblocks??");
80
81   // The newly inserted basic block will dominate existing basic blocks iff the
82   // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
83   // the non-pred blocks, then they all must be the same block!
84   //
85   bool NewBBDominatesNewBBSucc = true;
86   {
87     BasicBlock *OnePred = PredBlocks[0];
88     unsigned i = 1, e = PredBlocks.size();
89     for (i = 1; !isReachableFromEntry(OnePred); ++i) {
90       assert(i != e && "Didn't find reachable pred?");
91       OnePred = PredBlocks[i];
92     }
93     
94     for (; i != e; ++i)
95       if (PredBlocks[i] != OnePred && isReachableFromEntry(OnePred)){
96         NewBBDominatesNewBBSucc = false;
97         break;
98       }
99
100     if (NewBBDominatesNewBBSucc)
101       for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
102            PI != E; ++PI)
103         if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
104           NewBBDominatesNewBBSucc = false;
105           break;
106         }
107   }
108
109   // The other scenario where the new block can dominate its successors are when
110   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
111   // already.
112   if (!NewBBDominatesNewBBSucc) {
113     NewBBDominatesNewBBSucc = true;
114     for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
115          PI != E; ++PI)
116       if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
117         NewBBDominatesNewBBSucc = false;
118         break;
119       }
120   }
121
122
123   // Find NewBB's immediate dominator and create new dominator tree node for NewBB.
124   BasicBlock *NewBBIDom = 0;
125   unsigned i = 0;
126   for (i = 0; i < PredBlocks.size(); ++i)
127     if (isReachableFromEntry(PredBlocks[i])) {
128       NewBBIDom = PredBlocks[i];
129       break;
130     }
131   assert(i != PredBlocks.size() && "No reachable preds?");
132   for (i = i + 1; i < PredBlocks.size(); ++i) {
133     if (isReachableFromEntry(PredBlocks[i]))
134       NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
135   }
136   assert(NewBBIDom && "No immediate dominator found??");
137   
138   // Create the new dominator tree node... and set the idom of NewBB.
139   DomTreeNode *NewBBNode = addNewBlock(NewBB, NewBBIDom);
140   
141   // If NewBB strictly dominates other blocks, then it is now the immediate
142   // dominator of NewBBSucc.  Update the dominator tree as appropriate.
143   if (NewBBDominatesNewBBSucc) {
144     DomTreeNode *NewBBSuccNode = getNode(NewBBSucc);
145     changeImmediateDominator(NewBBSuccNode, NewBBNode);
146   }
147 }
148
149 unsigned DominatorTree::DFSPass(BasicBlock *V, InfoRec &VInfo,
150                                       unsigned N) {
151   // This is more understandable as a recursive algorithm, but we can't use the
152   // recursive algorithm due to stack depth issues.  Keep it here for
153   // documentation purposes.
154 #if 0
155   VInfo.Semi = ++N;
156   VInfo.Label = V;
157
158   Vertex.push_back(V);        // Vertex[n] = V;
159   //Info[V].Ancestor = 0;     // Ancestor[n] = 0
160   //Info[V].Child = 0;        // Child[v] = 0
161   VInfo.Size = 1;             // Size[v] = 1
162
163   for (succ_iterator SI = succ_begin(V), E = succ_end(V); SI != E; ++SI) {
164     InfoRec &SuccVInfo = Info[*SI];
165     if (SuccVInfo.Semi == 0) {
166       SuccVInfo.Parent = V;
167       N = DFSPass(*SI, SuccVInfo, N);
168     }
169   }
170 #else
171   std::vector<std::pair<BasicBlock*, unsigned> > Worklist;
172   Worklist.push_back(std::make_pair(V, 0U));
173   while (!Worklist.empty()) {
174     BasicBlock *BB = Worklist.back().first;
175     unsigned NextSucc = Worklist.back().second;
176     
177     // First time we visited this BB?
178     if (NextSucc == 0) {
179       InfoRec &BBInfo = Info[BB];
180       BBInfo.Semi = ++N;
181       BBInfo.Label = BB;
182       
183       Vertex.push_back(BB);       // Vertex[n] = V;
184       //BBInfo[V].Ancestor = 0;   // Ancestor[n] = 0
185       //BBInfo[V].Child = 0;      // Child[v] = 0
186       BBInfo.Size = 1;            // Size[v] = 1
187     }
188     
189     // If we are done with this block, remove it from the worklist.
190     if (NextSucc == BB->getTerminator()->getNumSuccessors()) {
191       Worklist.pop_back();
192       continue;
193     }
194     
195     // Otherwise, increment the successor number for the next time we get to it.
196     ++Worklist.back().second;
197     
198     // Visit the successor next, if it isn't already visited.
199     BasicBlock *Succ = BB->getTerminator()->getSuccessor(NextSucc);
200     
201     InfoRec &SuccVInfo = Info[Succ];
202     if (SuccVInfo.Semi == 0) {
203       SuccVInfo.Parent = BB;
204       Worklist.push_back(std::make_pair(Succ, 0U));
205     }
206   }
207 #endif
208   return N;
209 }
210
211 void DominatorTree::Compress(BasicBlock *VIn) {
212
213   std::vector<BasicBlock *> Work;
214   std::set<BasicBlock *> Visited;
215   InfoRec &VInInfo = Info[VIn];
216   BasicBlock *VInAncestor = VInInfo.Ancestor;
217   InfoRec &VInVAInfo = Info[VInAncestor];
218
219   if (VInVAInfo.Ancestor != 0)
220     Work.push_back(VIn);
221   
222   while (!Work.empty()) {
223     BasicBlock *V = Work.back();
224     InfoRec &VInfo = Info[V];
225     BasicBlock *VAncestor = VInfo.Ancestor;
226     InfoRec &VAInfo = Info[VAncestor];
227
228     // Process Ancestor first
229     if (Visited.count(VAncestor) == 0 && VAInfo.Ancestor != 0) {
230       Work.push_back(VAncestor);
231       Visited.insert(VAncestor);
232       continue;
233     } 
234     Work.pop_back(); 
235
236     // Update VINfo based on Ancestor info
237     if (VAInfo.Ancestor == 0)
238       continue;
239     BasicBlock *VAncestorLabel = VAInfo.Label;
240     BasicBlock *VLabel = VInfo.Label;
241     if (Info[VAncestorLabel].Semi < Info[VLabel].Semi)
242       VInfo.Label = VAncestorLabel;
243     VInfo.Ancestor = VAInfo.Ancestor;
244   }
245 }
246
247 BasicBlock *DominatorTree::Eval(BasicBlock *V) {
248   InfoRec &VInfo = Info[V];
249 #if !BALANCE_IDOM_TREE
250   // Higher-complexity but faster implementation
251   if (VInfo.Ancestor == 0)
252     return V;
253   Compress(V);
254   return VInfo.Label;
255 #else
256   // Lower-complexity but slower implementation
257   if (VInfo.Ancestor == 0)
258     return VInfo.Label;
259   Compress(V);
260   BasicBlock *VLabel = VInfo.Label;
261
262   BasicBlock *VAncestorLabel = Info[VInfo.Ancestor].Label;
263   if (Info[VAncestorLabel].Semi >= Info[VLabel].Semi)
264     return VLabel;
265   else
266     return VAncestorLabel;
267 #endif
268 }
269
270 void DominatorTree::Link(BasicBlock *V, BasicBlock *W, InfoRec &WInfo){
271 #if !BALANCE_IDOM_TREE
272   // Higher-complexity but faster implementation
273   WInfo.Ancestor = V;
274 #else
275   // Lower-complexity but slower implementation
276   BasicBlock *WLabel = WInfo.Label;
277   unsigned WLabelSemi = Info[WLabel].Semi;
278   BasicBlock *S = W;
279   InfoRec *SInfo = &Info[S];
280
281   BasicBlock *SChild = SInfo->Child;
282   InfoRec *SChildInfo = &Info[SChild];
283
284   while (WLabelSemi < Info[SChildInfo->Label].Semi) {
285     BasicBlock *SChildChild = SChildInfo->Child;
286     if (SInfo->Size+Info[SChildChild].Size >= 2*SChildInfo->Size) {
287       SChildInfo->Ancestor = S;
288       SInfo->Child = SChild = SChildChild;
289       SChildInfo = &Info[SChild];
290     } else {
291       SChildInfo->Size = SInfo->Size;
292       S = SInfo->Ancestor = SChild;
293       SInfo = SChildInfo;
294       SChild = SChildChild;
295       SChildInfo = &Info[SChild];
296     }
297   }
298
299   InfoRec &VInfo = Info[V];
300   SInfo->Label = WLabel;
301
302   assert(V != W && "The optimization here will not work in this case!");
303   unsigned WSize = WInfo.Size;
304   unsigned VSize = (VInfo.Size += WSize);
305
306   if (VSize < 2*WSize)
307     std::swap(S, VInfo.Child);
308
309   while (S) {
310     SInfo = &Info[S];
311     SInfo->Ancestor = V;
312     S = SInfo->Child;
313   }
314 #endif
315 }
316
317 void DominatorTree::calculate(Function& F) {
318   BasicBlock* Root = Roots[0];
319
320   // Add a node for the root...
321   DomTreeNodes[Root] = RootNode = new DomTreeNode(Root, 0);
322
323   Vertex.push_back(0);
324
325   // Step #1: Number blocks in depth-first order and initialize variables used
326   // in later stages of the algorithm.
327   unsigned N = 0;
328   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
329     N = DFSPass(Roots[i], Info[Roots[i]], 0);
330
331   for (unsigned i = N; i >= 2; --i) {
332     BasicBlock *W = Vertex[i];
333     InfoRec &WInfo = Info[W];
334
335     // Step #2: Calculate the semidominators of all vertices
336     for (pred_iterator PI = pred_begin(W), E = pred_end(W); PI != E; ++PI)
337       if (Info.count(*PI)) {  // Only if this predecessor is reachable!
338         unsigned SemiU = Info[Eval(*PI)].Semi;
339         if (SemiU < WInfo.Semi)
340           WInfo.Semi = SemiU;
341       }
342
343     Info[Vertex[WInfo.Semi]].Bucket.push_back(W);
344
345     BasicBlock *WParent = WInfo.Parent;
346     Link(WParent, W, WInfo);
347
348     // Step #3: Implicitly define the immediate dominator of vertices
349     std::vector<BasicBlock*> &WParentBucket = Info[WParent].Bucket;
350     while (!WParentBucket.empty()) {
351       BasicBlock *V = WParentBucket.back();
352       WParentBucket.pop_back();
353       BasicBlock *U = Eval(V);
354       IDoms[V] = Info[U].Semi < Info[V].Semi ? U : WParent;
355     }
356   }
357
358   // Step #4: Explicitly define the immediate dominator of each vertex
359   for (unsigned i = 2; i <= N; ++i) {
360     BasicBlock *W = Vertex[i];
361     BasicBlock *&WIDom = IDoms[W];
362     if (WIDom != Vertex[Info[W].Semi])
363       WIDom = IDoms[WIDom];
364   }
365
366   // Loop over all of the reachable blocks in the function...
367   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
368     if (BasicBlock *ImmDom = getIDom(I)) {  // Reachable block.
369       DomTreeNode *&BBNode = DomTreeNodes[I];
370       if (!BBNode) {  // Haven't calculated this node yet?
371         // Get or calculate the node for the immediate dominator
372         DomTreeNode *IDomNode = getNodeForBlock(ImmDom);
373
374         // Add a new tree node for this BasicBlock, and link it as a child of
375         // IDomNode
376         DomTreeNode *C = new DomTreeNode(I, IDomNode);
377         DomTreeNodes[I] = C;
378         BBNode = IDomNode->addChild(C);
379       }
380     }
381
382   // Free temporary memory used to construct idom's
383   Info.clear();
384   IDoms.clear();
385   std::vector<BasicBlock*>().swap(Vertex);
386
387   updateDFSNumbers();
388 }
389
390 void DominatorTreeBase::updateDFSNumbers()
391 {
392   int dfsnum = 0;
393   // Iterate over all nodes in depth first order.
394   for (unsigned i = 0, e = Roots.size(); i != e; ++i)
395     for (df_iterator<BasicBlock*> I = df_begin(Roots[i]),
396            E = df_end(Roots[i]); I != E; ++I) {
397       BasicBlock *BB = *I;
398       DomTreeNode *BBNode = getNode(BB);
399       if (BBNode) {
400         if (!BBNode->getIDom())
401           BBNode->assignDFSNumber(dfsnum);
402       }
403   }
404   SlowQueries = 0;
405   DFSInfoValid = true;
406 }
407
408 /// isReachableFromEntry - Return true if A is dominated by the entry
409 /// block of the function containing it.
410 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
411   assert (!isPostDominator() 
412           && "This is not implemented for post dominators");
413   return dominates(&A->getParent()->getEntryBlock(), A);
414 }
415
416 // dominates - Return true if A dominates B. THis performs the
417 // special checks necessary if A and B are in the same basic block.
418 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
419   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
420   if (BBA != BBB) return dominates(BBA, BBB);
421   
422   // It is not possible to determine dominance between two PHI nodes 
423   // based on their ordering.
424   if (isa<PHINode>(A) && isa<PHINode>(B)) 
425     return false;
426
427   // Loop through the basic block until we find A or B.
428   BasicBlock::iterator I = BBA->begin();
429   for (; &*I != A && &*I != B; ++I) /*empty*/;
430   
431   if(!IsPostDominators) {
432     // A dominates B if it is found first in the basic block.
433     return &*I == A;
434   } else {
435     // A post-dominates B if B is found first in the basic block.
436     return &*I == B;
437   }
438 }
439
440 // DominatorTreeBase::reset - Free all of the tree node memory.
441 //
442 void DominatorTreeBase::reset() {
443   for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), 
444          E = DomTreeNodes.end(); I != E; ++I)
445     delete I->second;
446   DomTreeNodes.clear();
447   IDoms.clear();
448   Roots.clear();
449   Vertex.clear();
450   RootNode = 0;
451 }
452
453 /// findNearestCommonDominator - Find nearest common dominator basic block
454 /// for basic block A and B. If there is no such block then return NULL.
455 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A, 
456                                                           BasicBlock *B) {
457
458   assert (!isPostDominator() 
459           && "This is not implemented for post dominators");
460   assert (A->getParent() == B->getParent() 
461           && "Two blocks are not in same function");
462
463   // If either A or B is a entry block then it is nearest common dominator.
464   BasicBlock &Entry  = A->getParent()->getEntryBlock();
465   if (A == &Entry || B == &Entry)
466     return &Entry;
467
468   // If B dominates A then B is nearest common dominator.
469   if (dominates(B,A))
470     return B;
471
472   // If A dominates B then A is nearest common dominator.
473   if (dominates(A,B))
474     return A;
475
476   DomTreeNode *NodeA = getNode(A);
477   DomTreeNode *NodeB = getNode(B);
478
479   // Collect NodeA dominators set.
480   SmallPtrSet<DomTreeNode*, 16> NodeADoms;
481   NodeADoms.insert(NodeA);
482   DomTreeNode *IDomA = NodeA->getIDom();
483   while(IDomA) {
484     NodeADoms.insert(IDomA);
485     IDomA = IDomA->getIDom();
486   }
487
488   // Walk NodeB immediate dominators chain and find common dominator node.
489   DomTreeNode *IDomB = NodeB->getIDom();
490   while(IDomB) {
491     if (NodeADoms.count(IDomB) != 0)
492       return IDomB->getBlock();
493
494     IDomB = IDomB->getIDom();
495   }
496
497   return NULL;
498 }
499
500 /// assignDFSNumber - Assign In and Out numbers while walking dominator tree
501 /// in dfs order.
502 void DomTreeNode::assignDFSNumber(int num) {
503   std::vector<DomTreeNode *>  workStack;
504   std::set<DomTreeNode *> visitedNodes;
505   
506   workStack.push_back(this);
507   visitedNodes.insert(this);
508   this->DFSNumIn = num++;
509   
510   while (!workStack.empty()) {
511     DomTreeNode  *Node = workStack.back();
512     
513     bool visitChild = false;
514     for (std::vector<DomTreeNode*>::iterator DI = Node->begin(),
515            E = Node->end(); DI != E && !visitChild; ++DI) {
516       DomTreeNode *Child = *DI;
517       if (visitedNodes.count(Child) == 0) {
518         visitChild = true;
519         Child->DFSNumIn = num++;
520         workStack.push_back(Child);
521         visitedNodes.insert(Child);
522       }
523     }
524     if (!visitChild) {
525       // If we reach here means all children are visited
526       Node->DFSNumOut = num++;
527       workStack.pop_back();
528     }
529   }
530 }
531
532 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
533   assert(IDom && "No immediate dominator?");
534   if (IDom != NewIDom) {
535     std::vector<DomTreeNode*>::iterator I =
536       std::find(IDom->Children.begin(), IDom->Children.end(), this);
537     assert(I != IDom->Children.end() &&
538            "Not in immediate dominator children set!");
539     // I am no longer your child...
540     IDom->Children.erase(I);
541
542     // Switch to new dominator
543     IDom = NewIDom;
544     IDom->Children.push_back(this);
545   }
546 }
547
548 DomTreeNode *DominatorTree::getNodeForBlock(BasicBlock *BB) {
549   DomTreeNode *&BBNode = DomTreeNodes[BB];
550   if (BBNode) return BBNode;
551
552   // Haven't calculated this node yet?  Get or calculate the node for the
553   // immediate dominator.
554   BasicBlock *IDom = getIDom(BB);
555   DomTreeNode *IDomNode = getNodeForBlock(IDom);
556
557   // Add a new tree node for this BasicBlock, and link it as a child of
558   // IDomNode
559   DomTreeNode *C = new DomTreeNode(BB, IDomNode);
560   DomTreeNodes[BB] = C;
561   return BBNode = IDomNode->addChild(C);
562 }
563
564 static std::ostream &operator<<(std::ostream &o,
565                                 const DomTreeNode *Node) {
566   if (Node->getBlock())
567     WriteAsOperand(o, Node->getBlock(), false);
568   else
569     o << " <<exit node>>";
570   return o << "\n";
571 }
572
573 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
574                          unsigned Lev) {
575   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
576   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
577        I != E; ++I)
578     PrintDomTree(*I, o, Lev+1);
579 }
580
581 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
582   o << "=============================--------------------------------\n"
583     << "Inorder Dominator Tree:\n";
584   PrintDomTree(getRootNode(), o, 1);
585 }
586
587 void DominatorTreeBase::dump() {
588   print (llvm::cerr);
589 }
590
591 bool DominatorTree::runOnFunction(Function &F) {
592   reset();     // Reset from the last time we were run...
593   Roots.push_back(&F.getEntryBlock());
594   calculate(F);
595   return false;
596 }
597
598 //===----------------------------------------------------------------------===//
599 //  DominanceFrontier Implementation
600 //===----------------------------------------------------------------------===//
601
602 char DominanceFrontier::ID = 0;
603 static RegisterPass<DominanceFrontier>
604 G("domfrontier", "Dominance Frontier Construction", true);
605
606 // NewBB is split and now it has one successor. Update dominace frontier to
607 // reflect this change.
608 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
609
610   assert(NewBB->getTerminator()->getNumSuccessors() == 1
611          && "NewBB should have a single successor!");
612   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
613
614   std::vector<BasicBlock*> PredBlocks;
615   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
616        PI != PE; ++PI)
617       PredBlocks.push_back(*PI);  
618
619   if (PredBlocks.empty())
620     // If NewBB does not have any predecessors then it is a entry block.
621     // In this case, NewBB and its successor NewBBSucc dominates all
622     // other blocks.
623     return;
624
625   DominatorTree &DT = getAnalysis<DominatorTree>();
626   bool NewBBDominatesNewBBSucc = true;
627   if (!DT.dominates(NewBB, NewBBSucc))
628     NewBBDominatesNewBBSucc = false;
629
630   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
631   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
632   // a predecessor of.
633   if (NewBBDominatesNewBBSucc) {
634     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
635     if (DFI != end()) {
636       DominanceFrontier::DomSetType Set = DFI->second;
637       // Filter out stuff in Set that we do not dominate a predecessor of.
638       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
639              E = Set.end(); SetI != E;) {
640         bool DominatesPred = false;
641         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
642              PI != E; ++PI)
643           if (DT.dominates(NewBB, *PI))
644             DominatesPred = true;
645         if (!DominatesPred)
646           Set.erase(SetI++);
647         else
648           ++SetI;
649       }
650
651       DominanceFrontier::iterator NewBBI = find(NewBB);
652       if (NewBBI != end()) {
653         DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
654         NewBBSet.insert(Set.begin(), Set.end());
655       } else 
656         addBasicBlock(NewBB, Set);
657     }
658     
659   } else {
660     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
661     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
662     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
663     DominanceFrontier::DomSetType NewDFSet;
664     NewDFSet.insert(NewBBSucc);
665     addBasicBlock(NewBB, NewDFSet);
666   }
667   
668   // Now we must loop over all of the dominance frontiers in the function,
669   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
670   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
671   // their dominance frontier must be updated to contain NewBB instead.
672   //
673   for (Function::iterator FI = NewBB->getParent()->begin(),
674          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
675     DominanceFrontier::iterator DFI = find(FI);
676     if (DFI == end()) continue;  // unreachable block.
677     
678     // Only consider dominators of NewBBSucc
679     if (!DFI->second.count(NewBBSucc)) continue;
680
681     bool BlockDominatesAny = false;
682     for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
683            BE = PredBlocks.end(); BI != BE; ++BI) {
684       if (DT.dominates(FI, *BI)) {
685         BlockDominatesAny = true;
686         break;
687       }
688     }
689     
690     if (BlockDominatesAny) {
691       // If NewBBSucc should not stay in our dominator frontier, remove it.
692       // We remove it unless there is a predecessor of NewBBSucc that we
693       // dominate, but we don't strictly dominate NewBBSucc.
694       bool ShouldRemove = true;
695       if ((BasicBlock*)FI == NewBBSucc
696           || !DT.dominates(FI, NewBBSucc)) {
697         // Okay, we know that PredDom does not strictly dominate NewBBSucc.
698         // Check to see if it dominates any predecessors of NewBBSucc.
699         for (pred_iterator PI = pred_begin(NewBBSucc),
700                E = pred_end(NewBBSucc); PI != E; ++PI)
701           if (DT.dominates(FI, *PI)) {
702             ShouldRemove = false;
703             break;
704           }
705         
706         if (ShouldRemove)
707           removeFromFrontier(DFI, NewBBSucc);
708         addToFrontier(DFI, NewBB);
709         
710         break;
711       }
712     }
713   }
714 }
715
716 namespace {
717   class DFCalculateWorkObject {
718   public:
719     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
720                           const DomTreeNode *N,
721                           const DomTreeNode *PN)
722     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
723     BasicBlock *currentBB;
724     BasicBlock *parentBB;
725     const DomTreeNode *Node;
726     const DomTreeNode *parentNode;
727   };
728 }
729
730 const DominanceFrontier::DomSetType &
731 DominanceFrontier::calculate(const DominatorTree &DT,
732                              const DomTreeNode *Node) {
733   BasicBlock *BB = Node->getBlock();
734   DomSetType *Result = NULL;
735
736   std::vector<DFCalculateWorkObject> workList;
737   SmallPtrSet<BasicBlock *, 32> visited;
738
739   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
740   do {
741     DFCalculateWorkObject *currentW = &workList.back();
742     assert (currentW && "Missing work object.");
743
744     BasicBlock *currentBB = currentW->currentBB;
745     BasicBlock *parentBB = currentW->parentBB;
746     const DomTreeNode *currentNode = currentW->Node;
747     const DomTreeNode *parentNode = currentW->parentNode;
748     assert (currentBB && "Invalid work object. Missing current Basic Block");
749     assert (currentNode && "Invalid work object. Missing current Node");
750     DomSetType &S = Frontiers[currentBB];
751
752     // Visit each block only once.
753     if (visited.count(currentBB) == 0) {
754       visited.insert(currentBB);
755
756       // Loop over CFG successors to calculate DFlocal[currentNode]
757       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
758            SI != SE; ++SI) {
759         // Does Node immediately dominate this successor?
760         if (DT[*SI]->getIDom() != currentNode)
761           S.insert(*SI);
762       }
763     }
764
765     // At this point, S is DFlocal.  Now we union in DFup's of our children...
766     // Loop through and visit the nodes that Node immediately dominates (Node's
767     // children in the IDomTree)
768     bool visitChild = false;
769     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
770            NE = currentNode->end(); NI != NE; ++NI) {
771       DomTreeNode *IDominee = *NI;
772       BasicBlock *childBB = IDominee->getBlock();
773       if (visited.count(childBB) == 0) {
774         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
775                                                  IDominee, currentNode));
776         visitChild = true;
777       }
778     }
779
780     // If all children are visited or there is any child then pop this block
781     // from the workList.
782     if (!visitChild) {
783
784       if (!parentBB) {
785         Result = &S;
786         break;
787       }
788
789       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
790       DomSetType &parentSet = Frontiers[parentBB];
791       for (; CDFI != CDFE; ++CDFI) {
792         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
793           parentSet.insert(*CDFI);
794       }
795       workList.pop_back();
796     }
797
798   } while (!workList.empty());
799
800   return *Result;
801 }
802
803 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
804   for (const_iterator I = begin(), E = end(); I != E; ++I) {
805     o << "  DomFrontier for BB";
806     if (I->first)
807       WriteAsOperand(o, I->first, false);
808     else
809       o << " <<exit node>>";
810     o << " is:\t" << I->second << "\n";
811   }
812 }
813
814 void DominanceFrontierBase::dump() {
815   print (llvm::cerr);
816 }