Add an assert to MDNode::deleteTemporary check that the node being deleted
[oota-llvm.git] / lib / VMCore / Dominators.cpp
1 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/SetOperations.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Analysis/DominatorInternals.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/CommandLine.h"
29 #include <algorithm>
30 using namespace llvm;
31
32 // Always verify dominfo if expensive checking is enabled.
33 #ifdef XDEBUG
34 static bool VerifyDomInfo = true;
35 #else
36 static bool VerifyDomInfo = false;
37 #endif
38 static cl::opt<bool,true>
39 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
40                cl::desc("Verify dominator info (time consuming)"));
41
42 //===----------------------------------------------------------------------===//
43 //  DominatorTree Implementation
44 //===----------------------------------------------------------------------===//
45 //
46 // Provide public access to DominatorTree information.  Implementation details
47 // can be found in DominatorCalculation.h.
48 //
49 //===----------------------------------------------------------------------===//
50
51 TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
52 TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
53
54 char DominatorTree::ID = 0;
55 INITIALIZE_PASS(DominatorTree, "domtree",
56                 "Dominator Tree Construction", true, true);
57
58 bool DominatorTree::runOnFunction(Function &F) {
59   DT->recalculate(F);
60   return false;
61 }
62
63 void DominatorTree::verifyAnalysis() const {
64   if (!VerifyDomInfo) return;
65
66   Function &F = *getRoot()->getParent();
67
68   DominatorTree OtherDT;
69   OtherDT.getBase().recalculate(F);
70   assert(!compare(OtherDT) && "Invalid DominatorTree info!");
71 }
72
73 void DominatorTree::print(raw_ostream &OS, const Module *) const {
74   DT->print(OS);
75 }
76
77 // dominates - Return true if A dominates a use in B. This performs the
78 // special checks necessary if A and B are in the same basic block.
79 bool DominatorTree::dominates(const Instruction *A, const Instruction *B) const{
80   const BasicBlock *BBA = A->getParent(), *BBB = B->getParent();
81   
82   // If A is an invoke instruction, its value is only available in this normal
83   // successor block.
84   if (const InvokeInst *II = dyn_cast<InvokeInst>(A))
85     BBA = II->getNormalDest();
86   
87   if (BBA != BBB) return dominates(BBA, BBB);
88   
89   // It is not possible to determine dominance between two PHI nodes 
90   // based on their ordering.
91   if (isa<PHINode>(A) && isa<PHINode>(B)) 
92     return false;
93   
94   // Loop through the basic block until we find A or B.
95   BasicBlock::const_iterator I = BBA->begin();
96   for (; &*I != A && &*I != B; ++I)
97     /*empty*/;
98   
99   return &*I == A;
100 }
101
102
103
104 //===----------------------------------------------------------------------===//
105 //  DominanceFrontier Implementation
106 //===----------------------------------------------------------------------===//
107
108 char DominanceFrontier::ID = 0;
109 INITIALIZE_PASS(DominanceFrontier, "domfrontier",
110                 "Dominance Frontier Construction", true, true);
111
112 void DominanceFrontier::verifyAnalysis() const {
113   if (!VerifyDomInfo) return;
114
115   DominatorTree &DT = getAnalysis<DominatorTree>();
116
117   DominanceFrontier OtherDF;
118   const std::vector<BasicBlock*> &DTRoots = DT.getRoots();
119   OtherDF.calculate(DT, DT.getNode(DTRoots[0]));
120   assert(!compare(OtherDF) && "Invalid DominanceFrontier info!");
121 }
122
123 // NewBB is split and now it has one successor. Update dominance frontier to
124 // reflect this change.
125 void DominanceFrontier::splitBlock(BasicBlock *NewBB) {
126   assert(NewBB->getTerminator()->getNumSuccessors() == 1 &&
127          "NewBB should have a single successor!");
128   BasicBlock *NewBBSucc = NewBB->getTerminator()->getSuccessor(0);
129
130   // NewBBSucc inherits original NewBB frontier.
131   DominanceFrontier::iterator NewBBI = find(NewBB);
132   if (NewBBI != end())
133     addBasicBlock(NewBBSucc, NewBBI->second);
134
135   // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
136   // DF(NewBBSucc) without the stuff that the new block does not dominate
137   // a predecessor of.
138   DominatorTree &DT = getAnalysis<DominatorTree>();
139   DomTreeNode *NewBBNode = DT.getNode(NewBB);
140   DomTreeNode *NewBBSuccNode = DT.getNode(NewBBSucc);
141   if (DT.dominates(NewBBNode, NewBBSuccNode)) {
142     DominanceFrontier::iterator DFI = find(NewBBSucc);
143     if (DFI != end()) {
144       DominanceFrontier::DomSetType Set = DFI->second;
145       // Filter out stuff in Set that we do not dominate a predecessor of.
146       for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
147              E = Set.end(); SetI != E;) {
148         bool DominatesPred = false;
149         for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
150              PI != E; ++PI)
151           if (DT.dominates(NewBBNode, DT.getNode(*PI))) {
152             DominatesPred = true;
153             break;
154           }
155         if (!DominatesPred)
156           Set.erase(SetI++);
157         else
158           ++SetI;
159       }
160
161       if (NewBBI != end()) {
162         for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
163                E = Set.end(); SetI != E; ++SetI) {
164           BasicBlock *SB = *SetI;
165           addToFrontier(NewBBI, SB);
166         }
167       } else 
168         addBasicBlock(NewBB, Set);
169     }
170     
171   } else {
172     // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
173     // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
174     // NewBBSucc)).  NewBBSucc is the single successor of NewBB.
175     DominanceFrontier::DomSetType NewDFSet;
176     NewDFSet.insert(NewBBSucc);
177     addBasicBlock(NewBB, NewDFSet);
178   }
179
180   // Now update dominance frontiers which either used to contain NewBBSucc
181   // or which now need to include NewBB.
182
183   // Collect the set of blocks which dominate a predecessor of NewBB or
184   // NewSuccBB and which don't dominate both. This is an initial
185   // approximation of the blocks whose dominance frontiers will need updates.
186   SmallVector<DomTreeNode *, 16> AllPredDoms;
187
188   // Compute the block which dominates both NewBBSucc and NewBB. This is
189   // the immediate dominator of NewBBSucc unless NewBB dominates NewBBSucc.
190   // The code below which climbs dominator trees will stop at this point,
191   // because from this point up, dominance frontiers are unaffected.
192   DomTreeNode *DominatesBoth = 0;
193   if (NewBBSuccNode) {
194     DominatesBoth = NewBBSuccNode->getIDom();
195     if (DominatesBoth == NewBBNode)
196       DominatesBoth = NewBBNode->getIDom();
197   }
198
199   // Collect the set of all blocks which dominate a predecessor of NewBB.
200   SmallPtrSet<DomTreeNode *, 8> NewBBPredDoms;
201   for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); PI != E; ++PI)
202     for (DomTreeNode *DTN = DT.getNode(*PI); DTN; DTN = DTN->getIDom()) {
203       if (DTN == DominatesBoth)
204         break;
205       if (!NewBBPredDoms.insert(DTN))
206         break;
207       AllPredDoms.push_back(DTN);
208     }
209
210   // Collect the set of all blocks which dominate a predecessor of NewSuccBB.
211   SmallPtrSet<DomTreeNode *, 8> NewBBSuccPredDoms;
212   for (pred_iterator PI = pred_begin(NewBBSucc),
213        E = pred_end(NewBBSucc); PI != E; ++PI)
214     for (DomTreeNode *DTN = DT.getNode(*PI); DTN; DTN = DTN->getIDom()) {
215       if (DTN == DominatesBoth)
216         break;
217       if (!NewBBSuccPredDoms.insert(DTN))
218         break;
219       if (!NewBBPredDoms.count(DTN))
220         AllPredDoms.push_back(DTN);
221     }
222
223   // Visit all relevant dominance frontiers and make any needed updates.
224   for (SmallVectorImpl<DomTreeNode *>::const_iterator I = AllPredDoms.begin(),
225        E = AllPredDoms.end(); I != E; ++I) {
226     DomTreeNode *DTN = *I;
227     iterator DFI = find((*I)->getBlock());
228
229     // Only consider nodes that have NewBBSucc in their dominator frontier.
230     if (DFI == end() || !DFI->second.count(NewBBSucc)) continue;
231
232     // If the block dominates a predecessor of NewBB but does not properly
233     // dominate NewBB itself, add NewBB to its dominance frontier.
234     if (NewBBPredDoms.count(DTN) &&
235         !DT.properlyDominates(DTN, NewBBNode))
236       addToFrontier(DFI, NewBB);
237
238     // If the block does not dominate a predecessor of NewBBSucc or
239     // properly dominates NewBBSucc itself, remove NewBBSucc from its
240     // dominance frontier.
241     if (!NewBBSuccPredDoms.count(DTN) ||
242         DT.properlyDominates(DTN, NewBBSuccNode))
243       removeFromFrontier(DFI, NewBBSucc);
244   }
245 }
246
247 namespace {
248   class DFCalculateWorkObject {
249   public:
250     DFCalculateWorkObject(BasicBlock *B, BasicBlock *P, 
251                           const DomTreeNode *N,
252                           const DomTreeNode *PN)
253     : currentBB(B), parentBB(P), Node(N), parentNode(PN) {}
254     BasicBlock *currentBB;
255     BasicBlock *parentBB;
256     const DomTreeNode *Node;
257     const DomTreeNode *parentNode;
258   };
259 }
260
261 const DominanceFrontier::DomSetType &
262 DominanceFrontier::calculate(const DominatorTree &DT,
263                              const DomTreeNode *Node) {
264   BasicBlock *BB = Node->getBlock();
265   DomSetType *Result = NULL;
266
267   std::vector<DFCalculateWorkObject> workList;
268   SmallPtrSet<BasicBlock *, 32> visited;
269
270   workList.push_back(DFCalculateWorkObject(BB, NULL, Node, NULL));
271   do {
272     DFCalculateWorkObject *currentW = &workList.back();
273     assert (currentW && "Missing work object.");
274
275     BasicBlock *currentBB = currentW->currentBB;
276     BasicBlock *parentBB = currentW->parentBB;
277     const DomTreeNode *currentNode = currentW->Node;
278     const DomTreeNode *parentNode = currentW->parentNode;
279     assert (currentBB && "Invalid work object. Missing current Basic Block");
280     assert (currentNode && "Invalid work object. Missing current Node");
281     DomSetType &S = Frontiers[currentBB];
282
283     // Visit each block only once.
284     if (visited.count(currentBB) == 0) {
285       visited.insert(currentBB);
286
287       // Loop over CFG successors to calculate DFlocal[currentNode]
288       for (succ_iterator SI = succ_begin(currentBB), SE = succ_end(currentBB);
289            SI != SE; ++SI) {
290         // Does Node immediately dominate this successor?
291         if (DT[*SI]->getIDom() != currentNode)
292           S.insert(*SI);
293       }
294     }
295
296     // At this point, S is DFlocal.  Now we union in DFup's of our children...
297     // Loop through and visit the nodes that Node immediately dominates (Node's
298     // children in the IDomTree)
299     bool visitChild = false;
300     for (DomTreeNode::const_iterator NI = currentNode->begin(), 
301            NE = currentNode->end(); NI != NE; ++NI) {
302       DomTreeNode *IDominee = *NI;
303       BasicBlock *childBB = IDominee->getBlock();
304       if (visited.count(childBB) == 0) {
305         workList.push_back(DFCalculateWorkObject(childBB, currentBB,
306                                                  IDominee, currentNode));
307         visitChild = true;
308       }
309     }
310
311     // If all children are visited or there is any child then pop this block
312     // from the workList.
313     if (!visitChild) {
314
315       if (!parentBB) {
316         Result = &S;
317         break;
318       }
319
320       DomSetType::const_iterator CDFI = S.begin(), CDFE = S.end();
321       DomSetType &parentSet = Frontiers[parentBB];
322       for (; CDFI != CDFE; ++CDFI) {
323         if (!DT.properlyDominates(parentNode, DT[*CDFI]))
324           parentSet.insert(*CDFI);
325       }
326       workList.pop_back();
327     }
328
329   } while (!workList.empty());
330
331   return *Result;
332 }
333
334 void DominanceFrontierBase::print(raw_ostream &OS, const Module* ) const {
335   for (const_iterator I = begin(), E = end(); I != E; ++I) {
336     OS << "  DomFrontier for BB ";
337     if (I->first)
338       WriteAsOperand(OS, I->first, false);
339     else
340       OS << " <<exit node>>";
341     OS << " is:\t";
342     
343     const std::set<BasicBlock*> &BBs = I->second;
344     
345     for (std::set<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
346          I != E; ++I) {
347       OS << ' ';
348       if (*I)
349         WriteAsOperand(OS, *I, false);
350       else
351         OS << "<<exit node>>";
352     }
353     OS << "\n";
354   }
355 }
356
357 void DominanceFrontierBase::dump() const {
358   print(dbgs());
359 }
360