Begin the process of allowing DomTree on MBB's. Step One: template DomTreeNode by...
[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/Analysis/DominatorInternals.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Support/Streams.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 static std::ostream &operator<<(std::ostream &o, const DomTreeNode *Node) {
280   if (Node->getBlock())
281     WriteAsOperand(o, Node->getBlock(), false);
282   else
283     o << " <<exit node>>";
284   
285   o << " {" << Node->getDFSNumIn() << "," << Node->getDFSNumOut() << "}";
286   
287   return o << "\n";
288 }
289
290 static void PrintDomTree(const DomTreeNode *N, std::ostream &o,
291                          unsigned Lev) {
292   o << std::string(2*Lev, ' ') << "[" << Lev << "] " << N;
293   for (DomTreeNode::const_iterator I = N->begin(), E = N->end();
294        I != E; ++I)
295     PrintDomTree(*I, o, Lev+1);
296 }
297
298 /// eraseNode - Removes a node from  the domiantor tree. Block must not
299 /// domiante any other blocks. Removes node from its immediate dominator's
300 /// children list. Deletes dominator node associated with basic block BB.
301 void DominatorTreeBase::eraseNode(BasicBlock *BB) {
302   DomTreeNode *Node = getNode(BB);
303   assert (Node && "Removing node that isn't in dominator tree.");
304   assert (Node->getChildren().empty() && "Node is not a leaf node.");
305
306     // Remove node from immediate dominator's children list.
307   DomTreeNode *IDom = Node->getIDom();
308   if (IDom) {
309     std::vector<DomTreeNode*>::iterator I =
310       std::find(IDom->Children.begin(), IDom->Children.end(), Node);
311     assert(I != IDom->Children.end() &&
312            "Not in immediate dominator children set!");
313     // I am no longer your child...
314     IDom->Children.erase(I);
315   }
316   
317   DomTreeNodes.erase(BB);
318   delete Node;
319 }
320
321 void DominatorTreeBase::print(std::ostream &o, const Module* ) const {
322   o << "=============================--------------------------------\n";
323   o << "Inorder Dominator Tree: ";
324   if (DFSInfoValid)
325     o << "DFSNumbers invalid: " << SlowQueries << " slow queries.";
326   o << "\n";
327   
328   PrintDomTree(getRootNode(), o, 1);
329 }
330
331 void DominatorTreeBase::dump() {
332   print(llvm::cerr);
333 }
334
335 bool DominatorTree::runOnFunction(Function &F) {
336   reset();     // Reset from the last time we were run...
337   
338   // Initialize roots
339   Roots.push_back(&F.getEntryBlock());
340   IDoms[&F.getEntryBlock()] = 0;
341   DomTreeNodes[&F.getEntryBlock()] = 0;
342   Vertex.push_back(0);
343   
344   Calculate<BasicBlock*>(*this, F);
345   
346   updateDFSNumbers();
347   
348   return false;
349 }
350
351 //===----------------------------------------------------------------------===//
352 //  DominanceFrontier Implementation
353 //===----------------------------------------------------------------------===//
354
355 char DominanceFrontier::ID = 0;
356 static RegisterPass<DominanceFrontier>
357 G("domfrontier", "Dominance Frontier Construction", true);
358
359 // NewBB is split and now it has one successor. Update dominace frontier to
360 // reflect this change.
361 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
362   assert(NewBB->getTerminator()->getNumSuccessors() == 1
363          && "NewBB should have a single successor!");
364   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
365
366   std::vector<BasicBlock*> PredBlocks;
367   for (pred_iterator PI = pred_begin(NewBB), PE = pred_end(NewBB);
368        PI != PE; ++PI)
369       PredBlocks.push_back(*PI);  
370
371   if (PredBlocks.empty())
372     // If NewBB does not have any predecessors then it is a entry block.
373     // In this case, NewBB and its successor NewBBSucc dominates all
374     // other blocks.
375     return;
376
377   // NewBBSucc inherits original NewBB frontier.
378   DominanceFrontier::iterator NewBBI = find(NewBB);
379   if (NewBBI != end()) {
380     DominanceFrontier::DomSetType NewBBSet = NewBBI->second;
381     DominanceFrontier::DomSetType NewBBSuccSet;
382     NewBBSuccSet.insert(NewBBSet.begin(), NewBBSet.end());
383     addBasicBlock(NewBBSucc, NewBBSuccSet);
384   }
385
386   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
387   // DF(PredBlocks[0]) without the stuff that the new block does not dominate
388   // a predecessor of.
389   DominatorTree &DT = getAnalysis<DominatorTree>();
390   if (DT.dominates(NewBB, NewBBSucc)) {
391     DominanceFrontier::iterator DFI = find(PredBlocks[0]);
392     if (DFI != end()) {
393       DominanceFrontier::DomSetType Set = DFI->second;
394       // Filter out stuff in Set that we do not dominate a predecessor of.
395       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
396              E = Set.end(); SetI != E;) {
397         bool DominatesPred = false;
398         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
399              PI != E; ++PI)
400           if (DT.dominates(NewBB, *PI))
401             DominatesPred = true;
402         if (!DominatesPred)
403           Set.erase(SetI++);
404         else
405           ++SetI;
406       }
407
408       if (NewBBI != end()) {
409         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
410                E = Set.end(); SetI != E; ++SetI) {
411           BasicBlock *SB = *SetI;
412           addToFrontier(NewBBI, SB);
413         }
414       } else 
415         addBasicBlock(NewBB, Set);
416     }
417     
418   } else {
419     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
420     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
421     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
422     DominanceFrontier::DomSetType NewDFSet;
423     NewDFSet.insert(NewBBSucc);
424     addBasicBlock(NewBB, NewDFSet);
425   }
426   
427   // Now we must loop over all of the dominance frontiers in the function,
428   // replacing occurrences of NewBBSucc with NewBB in some cases.  All
429   // blocks that dominate a block in PredBlocks and contained NewBBSucc in
430   // their dominance frontier must be updated to contain NewBB instead.
431   //
432   for (Function::iterator FI = NewBB->getParent()->begin(),
433          FE = NewBB->getParent()->end(); FI != FE; ++FI) {
434     DominanceFrontier::iterator DFI = find(FI);
435     if (DFI == end()) continue;  // unreachable block.
436     
437     // Only consider nodes that have NewBBSucc in their dominator frontier.
438     if (!DFI->second.count(NewBBSucc)) continue;
439
440     // Verify whether this block dominates a block in predblocks.  If not, do
441     // not update it.
442     bool BlockDominatesAny = false;
443     for (std::vector<BasicBlock*>::const_iterator BI = PredBlocks.begin(), 
444            BE = PredBlocks.end(); BI != BE; ++BI) {
445       if (DT.dominates(FI, *BI)) {
446         BlockDominatesAny = true;
447         break;
448       }
449     }
450     
451     if (!BlockDominatesAny)
452       continue;
453     
454     // If NewBBSucc should not stay in our dominator frontier, remove it.
455     // We remove it unless there is a predecessor of NewBBSucc that we
456     // dominate, but we don't strictly dominate NewBBSucc.
457     bool ShouldRemove = true;
458     if ((BasicBlock*)FI == NewBBSucc || !DT.dominates(FI, NewBBSucc)) {
459       // Okay, we know that PredDom does not strictly dominate NewBBSucc.
460       // Check to see if it dominates any predecessors of NewBBSucc.
461       for (pred_iterator PI = pred_begin(NewBBSucc),
462            E = pred_end(NewBBSucc); PI != E; ++PI)
463         if (DT.dominates(FI, *PI)) {
464           ShouldRemove = false;
465           break;
466         }
467     }
468     
469     if (ShouldRemove)
470       removeFromFrontier(DFI, NewBBSucc);
471     addToFrontier(DFI, NewBB);
472   }
473 }
474
475 namespace {
476   class DFCalculateWorkObject {
477   public:
478     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
479                           const DomTreeNode *N,
480                           const DomTreeNode *PN)
481     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
482     BasicBlock *currentBB;
483     BasicBlock *parentBB;
484     const DomTreeNode *Node;
485     const DomTreeNode *parentNode;
486   };
487 }
488
489 const DominanceFrontier::DomSetType &
490 DominanceFrontier::calculate(const DominatorTree &DT,
491                              const DomTreeNode *Node) {
492   BasicBlock *BB = Node->getBlock();
493   DomSetType *Result = NULL;
494
495   std::vector<DFCalculateWorkObject> workList;
496   SmallPtrSet<BasicBlock *, 32> visited;
497
498   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
499   do {
500     DFCalculateWorkObject *currentW = &workList.back();
501     assert (currentW && "Missing work object.");
502
503     BasicBlock *currentBB = currentW->currentBB;
504     BasicBlock *parentBB = currentW->parentBB;
505     const DomTreeNode *currentNode = currentW->Node;
506     const DomTreeNode *parentNode = currentW->parentNode;
507     assert (currentBB && "Invalid work object. Missing current Basic Block");
508     assert (currentNode && "Invalid work object. Missing current Node");
509     DomSetType &S = Frontiers[currentBB];
510
511     // Visit each block only once.
512     if (visited.count(currentBB) == 0) {
513       visited.insert(currentBB);
514
515       // Loop over CFG successors to calculate DFlocal[currentNode]
516       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
517            SI != SE; ++SI) {
518         // Does Node immediately dominate this successor?
519         if (DT[*SI]->getIDom() != currentNode)
520           S.insert(*SI);
521       }
522     }
523
524     // At this point, S is DFlocal.  Now we union in DFup's of our children...
525     // Loop through and visit the nodes that Node immediately dominates (Node's
526     // children in the IDomTree)
527     bool visitChild = false;
528     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
529            NE = currentNode->end(); NI != NE; ++NI) {
530       DomTreeNode *IDominee = *NI;
531       BasicBlock *childBB = IDominee->getBlock();
532       if (visited.count(childBB) == 0) {
533         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
534                                                  IDominee, currentNode));
535         visitChild = true;
536       }
537     }
538
539     // If all children are visited or there is any child then pop this block
540     // from the workList.
541     if (!visitChild) {
542
543       if (!parentBB) {
544         Result = &S;
545         break;
546       }
547
548       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
549       DomSetType &parentSet = Frontiers[parentBB];
550       for (; CDFI != CDFE; ++CDFI) {
551         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
552           parentSet.insert(*CDFI);
553       }
554       workList.pop_back();
555     }
556
557   } while (!workList.empty());
558
559   return *Result;
560 }
561
562 void DominanceFrontierBase::print(std::ostream &o, const Module* ) const {
563   for (const_iterator I = begin(), E = end(); I != E; ++I) {
564     o << "  DomFrontier for BB";
565     if (I->first)
566       WriteAsOperand(o, I->first, false);
567     else
568       o << " <<exit node>>";
569     o << " is:\t" << I->second << "\n";
570   }
571 }
572
573 void DominanceFrontierBase::dump() {
574   print (llvm::cerr);
575 }