Convert DFSPass into a templated friend function, in preparation for making it common...
[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/ADT/SmallVector.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/Streams.h"
26 #include "DominatorCalculation.h"
27 #include <algorithm>
28 using namespace llvm;
29
30 namespace llvm {
31 static std::ostream &operator<<(std::ostream &o,
32                                 const std::set<BasicBlock*> &BBs) {
33   for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
34        I != E; ++I)
35     if (*I)
36       WriteAsOperand(o, *I, false);
37     else
38       o << " <<exit node>>";
39   return o;
40 }
41 }
42
43 //===----------------------------------------------------------------------===//
44 //  DominatorTree Implementation
45 //===----------------------------------------------------------------------===//
46 //
47 // Provide public access to DominatorTree information.  Implementation details
48 // can be found in DominatorCalculation.h.
49 //
50 //===----------------------------------------------------------------------===//
51
52 char DominatorTree::ID = 0;
53 static RegisterPass<DominatorTree>
54 E("domtree", "Dominator Tree Construction", true);
55
56 // NewBB is split and now it has one successor. Update dominator tree to
57 // reflect this change.
58 void DominatorTree::splitBlock(BasicBlock *NewBB) {
59   assert(NewBB->getTerminator()->getNumSuccessors() == 1
60          && "NewBB should have a single successor!");
61   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
62
63   std::vector<BasicBlock*> PredBlocks;
64   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
65        PI != PE; ++PI)
66       PredBlocks.push_back(*PI);  
67
68   assert(!PredBlocks.empty() && "No predblocks??");
69
70   // The newly inserted basic block will dominate existing basic blocks iff the
71   // PredBlocks dominate all of the non-pred blocks.  If all predblocks dominate
72   // the non-pred blocks, then they all must be the same block!
73   //
74   bool NewBBDominatesNewBBSucc = true;
75   {
76     BasicBlock *OnePred = PredBlocks[0];
77     unsigned i = 1, e = PredBlocks.size();
78     for (i = 1; !isReachableFromEntry(OnePred); ++i) {
79       assert(i != e && "Didn't find reachable pred?");
80       OnePred = PredBlocks[i];
81     }
82     
83     for (; i != e; ++i)
84       if (PredBlocks[i] != OnePred && isReachableFromEntry(OnePred)) {
85         NewBBDominatesNewBBSucc = false;
86         break;
87       }
88
89     if (NewBBDominatesNewBBSucc)
90       for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
91            PI != E; ++PI)
92         if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
93           NewBBDominatesNewBBSucc = false;
94           break;
95         }
96   }
97
98   // The other scenario where the new block can dominate its successors are when
99   // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
100   // already.
101   if (!NewBBDominatesNewBBSucc) {
102     NewBBDominatesNewBBSucc = true;
103     for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
104          PI != E; ++PI)
105       if (*PI != NewBB && !dominates(NewBBSucc, *PI)) {
106         NewBBDominatesNewBBSucc = false;
107         break;
108       }
109   }
110
111   // Find NewBB's immediate dominator and create new dominator tree node for
112   // NewBB.
113   BasicBlock *NewBBIDom = 0;
114   unsigned i = 0;
115   for (i = 0; i < PredBlocks.size(); ++i)
116     if (isReachableFromEntry(PredBlocks[i])) {
117       NewBBIDom = PredBlocks[i];
118       break;
119     }
120   assert(i != PredBlocks.size() && "No reachable preds?");
121   for (i = i + 1; i < PredBlocks.size(); ++i) {
122     if (isReachableFromEntry(PredBlocks[i]))
123       NewBBIDom = findNearestCommonDominator(NewBBIDom, PredBlocks[i]);
124   }
125   assert(NewBBIDom && "No immediate dominator found??");
126   
127   // Create the new dominator tree node... and set the idom of NewBB.
128   DomTreeNode *NewBBNode = addNewBlock(NewBB, NewBBIDom);
129   
130   // If NewBB strictly dominates other blocks, then it is now the immediate
131   // dominator of NewBBSucc.  Update the dominator tree as appropriate.
132   if (NewBBDominatesNewBBSucc) {
133     DomTreeNode *NewBBSuccNode = getNode(NewBBSucc);
134     changeImmediateDominator(NewBBSuccNode, NewBBNode);
135   }
136 }
137
138 void DominatorTreeBase::updateDFSNumbers() {
139   unsigned DFSNum = 0;
140
141   SmallVector<std::pair<DomTreeNode*, DomTreeNode::iterator>, 32> WorkStack;
142   
143   for (unsigned i = 0, e = Roots.size(); i != e; ++i) {
144     DomTreeNode *ThisRoot = getNode(Roots[i]);
145     WorkStack.push_back(std::make_pair(ThisRoot, ThisRoot->begin()));
146     ThisRoot->DFSNumIn = DFSNum++;
147     
148     while (!WorkStack.empty()) {
149       DomTreeNode *Node = WorkStack.back().first;
150       DomTreeNode::iterator ChildIt = WorkStack.back().second;
151
152       // If we visited all of the children of this node, "recurse" back up the
153       // stack setting the DFOutNum.
154       if (ChildIt == Node->end()) {
155         Node->DFSNumOut = DFSNum++;
156         WorkStack.pop_back();
157       } else {
158         // Otherwise, recursively visit this child.
159         DomTreeNode *Child = *ChildIt;
160         ++WorkStack.back().second;
161         
162         WorkStack.push_back(std::make_pair(Child, Child->begin()));
163         Child->DFSNumIn = DFSNum++;
164       }
165     }
166   }
167   
168   SlowQueries = 0;
169   DFSInfoValid = true;
170 }
171
172 /// isReachableFromEntry - Return true if A is dominated by the entry
173 /// block of the function containing it.
174 const bool DominatorTreeBase::isReachableFromEntry(BasicBlock* A) {
175   assert (!isPostDominator() 
176           && "This is not implemented for post dominators");
177   return dominates(&A->getParent()->getEntryBlock(), A);
178 }
179
180 // dominates - Return true if A dominates B. THis performs the
181 // special checks necessary if A and B are in the same basic block.
182 bool DominatorTreeBase::dominates(Instruction *A, Instruction *B) {
183   BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
184   if (BBA != BBB) return dominates(BBA, BBB);
185   
186   // It is not possible to determine dominance between two PHI nodes 
187   // based on their ordering.
188   if (isa<PHINode>(A) && isa<PHINode>(B)) 
189     return false;
190
191   // Loop through the basic block until we find A or B.
192   BasicBlock::iterator I = BBA->begin();
193   for (; &*I != A && &*I != B; ++I) /*empty*/;
194   
195   if(!IsPostDominators) {
196     // A dominates B if it is found first in the basic block.
197     return &*I == A;
198   } else {
199     // A post-dominates B if B is found first in the basic block.
200     return &*I == B;
201   }
202 }
203
204 // DominatorTreeBase::reset - Free all of the tree node memory.
205 //
206 void DominatorTreeBase::reset() {
207   for (DomTreeNodeMapType::iterator I = DomTreeNodes.begin(), 
208          E = DomTreeNodes.end(); I != E; ++I)
209     delete I->second;
210   DomTreeNodes.clear();
211   IDoms.clear();
212   Roots.clear();
213   Vertex.clear();
214   RootNode = 0;
215 }
216
217 DomTreeNode *DominatorTreeBase::getNodeForBlock(BasicBlock *BB) {
218   if (DomTreeNode *BBNode = DomTreeNodes[BB])
219     return BBNode;
220
221   // Haven't calculated this node yet?  Get or calculate the node for the
222   // immediate dominator.
223   BasicBlock *IDom = getIDom(BB);
224   DomTreeNode *IDomNode = getNodeForBlock(IDom);
225
226   // Add a new tree node for this BasicBlock, and link it as a child of
227   // IDomNode
228   DomTreeNode *C = new DomTreeNode(BB, IDomNode);
229   return DomTreeNodes[BB] = IDomNode->addChild(C);
230 }
231
232 /// findNearestCommonDominator - Find nearest common dominator basic block
233 /// for basic block A and B. If there is no such block then return NULL.
234 BasicBlock *DominatorTreeBase::findNearestCommonDominator(BasicBlock *A, 
235                                                           BasicBlock *B) {
236
237   assert (!isPostDominator() 
238           && "This is not implemented for post dominators");
239   assert (A->getParent() == B->getParent() 
240           && "Two blocks are not in same function");
241
242   // If either A or B is a entry block then it is nearest common dominator.
243   BasicBlock &Entry  = A->getParent()->getEntryBlock();
244   if (A == &Entry || B == &Entry)
245     return &Entry;
246
247   // If B dominates A then B is nearest common dominator.
248   if (dominates(B, A))
249     return B;
250
251   // If A dominates B then A is nearest common dominator.
252   if (dominates(A, B))
253     return A;
254
255   DomTreeNode *NodeA = getNode(A);
256   DomTreeNode *NodeB = getNode(B);
257
258   // Collect NodeA dominators set.
259   SmallPtrSet<DomTreeNode*, 16> NodeADoms;
260   NodeADoms.insert(NodeA);
261   DomTreeNode *IDomA = NodeA->getIDom();
262   while (IDomA) {
263     NodeADoms.insert(IDomA);
264     IDomA = IDomA->getIDom();
265   }
266
267   // Walk NodeB immediate dominators chain and find common dominator node.
268   DomTreeNode *IDomB = NodeB->getIDom();
269   while(IDomB) {
270     if (NodeADoms.count(IDomB) != 0)
271       return IDomB->getBlock();
272
273     IDomB = IDomB->getIDom();
274   }
275
276   return NULL;
277 }
278
279 void DomTreeNode::setIDom(DomTreeNode *NewIDom) {
280   assert(IDom && "No immediate dominator?");
281   if (IDom != NewIDom) {
282     std::vector<DomTreeNode*>::iterator I =
283       std::find(IDom->Children.begin(), IDom->Children.end(), this);
284     assert(I != IDom->Children.end() &&
285            "Not in immediate dominator children set!");
286     // I am no longer your child...
287     IDom->Children.erase(I);
288
289     // Switch to new dominator
290     IDom = NewIDom;
291     IDom->Children.push_back(this);
292   }
293 }
294
295 static std::ostream &operator<<(std::ostream &o, const DomTreeNode *Node) {
296   if (Node->getBlock())
297     WriteAsOperand(o, Node->getBlock(), false);
298   else
299     o << " <<exit node>>";
300   
301   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
302   
303   return o << "\n";
304 }
305
306 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
307                          unsigned Lev) {
308   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
309   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
310        I != E; ++I)
311     PrintDomTree(*I, o, Lev+1);
312 }
313
314 /// eraseNode - Removes a node from  the domiantor tree. Block must not
315 /// domiante any other blocks. Removes node from its immediate dominator's
316 /// children list. Deletes dominator node associated with basic block BB.
317 void DominatorTreeBase::eraseNode(BasicBlock *BB) {
318   DomTreeNode *Node = getNode(BB);
319   assert (Node && "Removing node that isn't in dominator tree.");
320   assert (Node->getChildren().empty() && "Node is not a leaf node.");
321
322     // Remove node from immediate dominator's children list.
323   DomTreeNode *IDom = Node->getIDom();
324   if (IDom) {
325     std::vector<DomTreeNode*>::iterator I =
326       std::find(IDom->Children.begin(), IDom->Children.end(), Node);
327     assert(I != IDom->Children.end() &&
328            "Not in immediate dominator children set!");
329     // I am no longer your child...
330     IDom->Children.erase(I);
331   }
332   
333   DomTreeNodes.erase(BB);
334   delete Node;
335 }
336
337 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
338   o << "=============================--------------------------------\n";
339   o << "Inorder Dominator Tree: ";
340   if (DFSInfoValid)
341     o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
342   o << "\n";
343   
344   PrintDomTree(getRootNode(), o, 1);
345 }
346
347 void DominatorTreeBase::dump() {
348   print(llvm::cerr);
349 }
350
351 bool DominatorTree::runOnFunction(Function &F) {
352   reset();     // Reset from the last time we were run...
353   Roots.push_back(&F.getEntryBlock());
354   DTcalculate(*this, F);
355   return false;
356 }
357
358 //===----------------------------------------------------------------------===//
359 //  DominanceFrontier Implementation
360 //===----------------------------------------------------------------------===//
361
362 char DominanceFrontier::ID = 0;
363 static RegisterPass<DominanceFrontier>
364 G("domfrontier", "Dominance Frontier Construction", true);
365
366 // NewBB is split and now it has one successor. Update dominace frontier to
367 // reflect this change.
368 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
369   assert(NewBB->getTerminator()->getNumSuccessors() == 1
370          && "NewBB should have a single successor!");
371   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
372
373   std::vector<BasicBlock*> PredBlocks;
374   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
375        PI != PE; ++PI)
376       PredBlocks.push_back(*PI);  
377
378   if (PredBlocks.empty())
379     // If NewBB does not have any predecessors then it is a entry block.
380     // In this case, NewBB and its successor NewBBSucc dominates all
381     // other blocks.
382     return;
383
384   // NewBBSucc inherits original NewBB frontier.
385   DominanceFrontier::iterator NewBBI = find(NewBB);
386   if (NewBBI != end()) {
387     DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
388     DominanceFrontier::DomSetType NewBBSuccSet;
389     NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
390     addBasicBlock(NewBBSucc, NewBBSuccSet);
391   }
392
393   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
394   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
395   // a predecessor of.
396   DominatorTree &DT = getAnalysis<DominatorTree>();
397   if (DT.dominates(NewBB, NewBBSucc)) {
398     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
399     if (DFI != end()) {
400       DominanceFrontier::DomSetType Set = DFI->second;
401       // Filter out stuff in Set that we do not dominate a predecessor of.
402       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
403              E = Set.end(); SetI != E;) {
404         bool DominatesPred = false;
405         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
406              PI != E; ++PI)
407           if (DT.dominates(NewBB, *PI))
408             DominatesPred = true;
409         if (!DominatesPred)
410           Set.erase(SetI++);
411         else
412           ++SetI;
413       }
414
415       if (NewBBI != end()) {
416         DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
417         NewBBSet.insert(Set.begin(), Set.end());
418       } else 
419         addBasicBlock(NewBB, Set);
420     }
421     
422   } else {
423     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
424     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
425     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
426     DominanceFrontier::DomSetType NewDFSet;
427     NewDFSet.insert(NewBBSucc);
428     addBasicBlock(NewBB, NewDFSet);
429   }
430   
431   // Now we must loop over all of the dominance frontiers in the function,
432   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
433   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
434   // their dominance frontier must be updated to contain NewBB instead.
435   //
436   for (Function::iterator FI = NewBB->getParent()->begin(),
437          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
438     DominanceFrontier::iterator DFI = find(FI);
439     if (DFI == end()) continue;  // unreachable block.
440     
441     // Only consider nodes that have NewBBSucc in their dominator frontier.
442     if (!DFI->second.count(NewBBSucc)) continue;
443
444     // Verify whether this block dominates a block in predblocks.  If not, do
445     // not update it.
446     bool BlockDominatesAny = false;
447     for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
448            BE = PredBlocks.end(); BI != BE; ++BI) {
449       if (DT.dominates(FI, *BI)) {
450         BlockDominatesAny = true;
451         break;
452       }
453     }
454     
455     if (!BlockDominatesAny)
456       continue;
457     
458     // If NewBBSucc should not stay in our dominator frontier, remove it.
459     // We remove it unless there is a predecessor of NewBBSucc that we
460     // dominate, but we don't strictly dominate NewBBSucc.
461     bool ShouldRemove = true;
462     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
463       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
464       // Check to see if it dominates any predecessors of NewBBSucc.
465       for (pred_iterator PI = pred_begin(NewBBSucc),
466            E = pred_end(NewBBSucc); PI != E; ++PI)
467         if (DT.dominates(FI, *PI)) {
468           ShouldRemove = false;
469           break;
470         }
471     }
472     
473     if (ShouldRemove)
474       removeFromFrontier(DFI, NewBBSucc);
475     addToFrontier(DFI, NewBB);
476   }
477 }
478
479 namespace {
480   class DFCalculateWorkObject {
481   public:
482     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
483                           const DomTreeNode *N,
484                           const DomTreeNode *PN)
485     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
486     BasicBlock *currentBB;
487     BasicBlock *parentBB;
488     const DomTreeNode *Node;
489     const DomTreeNode *parentNode;
490   };
491 }
492
493 const DominanceFrontier::DomSetType &
494 DominanceFrontier::calculate(const DominatorTree &DT,
495                              const DomTreeNode *Node) {
496   BasicBlock *BB = Node->getBlock();
497   DomSetType *Result = NULL;
498
499   std::vector<DFCalculateWorkObject> workList;
500   SmallPtrSet<BasicBlock *, 32> visited;
501
502   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
503   do {
504     DFCalculateWorkObject *currentW = &workList.back();
505     assert (currentW && "Missing work object.");
506
507     BasicBlock *currentBB = currentW->currentBB;
508     BasicBlock *parentBB = currentW->parentBB;
509     const DomTreeNode *currentNode = currentW->Node;
510     const DomTreeNode *parentNode = currentW->parentNode;
511     assert (currentBB && "Invalid work object. Missing current Basic Block");
512     assert (currentNode && "Invalid work object. Missing current Node");
513     DomSetType &S = Frontiers[currentBB];
514
515     // Visit each block only once.
516     if (visited.count(currentBB) == 0) {
517       visited.insert(currentBB);
518
519       // Loop over CFG successors to calculate DFlocal[currentNode]
520       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
521            SI != SE; ++SI) {
522         // Does Node immediately dominate this successor?
523         if (DT[*SI]->getIDom() != currentNode)
524           S.insert(*SI);
525       }
526     }
527
528     // At this point, S is DFlocal.  Now we union in DFup's of our children...
529     // Loop through and visit the nodes that Node immediately dominates (Node's
530     // children in the IDomTree)
531     bool visitChild = false;
532     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
533            NE = currentNode->end(); NI != NE; ++NI) {
534       DomTreeNode *IDominee = *NI;
535       BasicBlock *childBB = IDominee->getBlock();
536       if (visited.count(childBB) == 0) {
537         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
538                                                  IDominee, currentNode));
539         visitChild = true;
540       }
541     }
542
543     // If all children are visited or there is any child then pop this block
544     // from the workList.
545     if (!visitChild) {
546
547       if (!parentBB) {
548         Result = &S;
549         break;
550       }
551
552       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
553       DomSetType &parentSet = Frontiers[parentBB];
554       for (; CDFI != CDFE; ++CDFI) {
555         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
556           parentSet.insert(*CDFI);
557       }
558       workList.pop_back();
559     }
560
561   } while (!workList.empty());
562
563   return *Result;
564 }
565
566 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
567   for (const_iterator I = begin(), E = end(); I != E; ++I) {
568     o << "  DomFrontier for BB";
569     if (I->first)
570       WriteAsOperand(o, I->first, false);
571     else
572       o << " <<exit node>>";
573     o << " is:\t" << I->second << "\n";
574   }
575 }
576
577 void DominanceFrontierBase::dump() {
578   print (llvm::cerr);
579 }