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