60bdeac16b3640a34e1760c19dff42a8d9cbefee
[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/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/Analysis/DominatorInternals.h"
25 #include "llvm/Assembly/Writer.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 bool BasicBlockEdge::isSingleEdge() const {
43   const TerminatorInst *TI = Start->getTerminator();
44   unsigned NumEdgesToEnd = 0;
45   for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
46     if (TI->getSuccessor(i) == End)
47       ++NumEdgesToEnd;
48     if (NumEdgesToEnd >= 2)
49       return false;
50   }
51   assert(NumEdgesToEnd == 1);
52   return true;
53 }
54
55 //===----------------------------------------------------------------------===//
56 //  DominatorTree Implementation
57 //===----------------------------------------------------------------------===//
58 //
59 // Provide public access to DominatorTree information.  Implementation details
60 // can be found in DominatorInternals.h.
61 //
62 //===----------------------------------------------------------------------===//
63
64 TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
65 TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
66
67 char DominatorTree::ID = 0;
68 INITIALIZE_PASS(DominatorTree, "domtree",
69                 "Dominator Tree Construction", true, true)
70
71 bool DominatorTree::runOnFunction(Function &F) {
72   DT->recalculate(F);
73   return false;
74 }
75
76 void DominatorTree::verifyAnalysis() const {
77   if (!VerifyDomInfo) return;
78
79   Function &F = *getRoot()->getParent();
80
81   DominatorTree OtherDT;
82   OtherDT.getBase().recalculate(F);
83   if (compare(OtherDT)) {
84     errs() << "DominatorTree is not up to date!\nComputed:\n";
85     print(errs());
86     errs() << "\nActual:\n";
87     OtherDT.print(errs());
88     abort();
89   }
90 }
91
92 void DominatorTree::print(raw_ostream &OS, const Module *) const {
93   DT->print(OS);
94 }
95
96 // dominates - Return true if Def dominates a use in User. This performs
97 // the special checks necessary if Def and User are in the same basic block.
98 // Note that Def doesn't dominate a use in Def itself!
99 bool DominatorTree::dominates(const Instruction *Def,
100                               const Instruction *User) const {
101   const BasicBlock *UseBB = User->getParent();
102   const BasicBlock *DefBB = Def->getParent();
103
104   // Any unreachable use is dominated, even if Def == User.
105   if (!isReachableFromEntry(UseBB))
106     return true;
107
108   // Unreachable definitions don't dominate anything.
109   if (!isReachableFromEntry(DefBB))
110     return false;
111
112   // An instruction doesn't dominate a use in itself.
113   if (Def == User)
114     return false;
115
116   // The value defined by an invoke dominates an instruction only if
117   // it dominates every instruction in UseBB.
118   // A PHI is dominated only if the instruction dominates every possible use
119   // in the UseBB.
120   if (isa<InvokeInst>(Def) || isa<PHINode>(User))
121     return dominates(Def, UseBB);
122
123   if (DefBB != UseBB)
124     return dominates(DefBB, UseBB);
125
126   // Loop through the basic block until we find Def or User.
127   BasicBlock::const_iterator I = DefBB->begin();
128   for (; &*I != Def && &*I != User; ++I)
129     /*empty*/;
130
131   return &*I == Def;
132 }
133
134 // true if Def would dominate a use in any instruction in UseBB.
135 // note that dominates(Def, Def->getParent()) is false.
136 bool DominatorTree::dominates(const Instruction *Def,
137                               const BasicBlock *UseBB) const {
138   const BasicBlock *DefBB = Def->getParent();
139
140   // Any unreachable use is dominated, even if DefBB == UseBB.
141   if (!isReachableFromEntry(UseBB))
142     return true;
143
144   // Unreachable definitions don't dominate anything.
145   if (!isReachableFromEntry(DefBB))
146     return false;
147
148   if (DefBB == UseBB)
149     return false;
150
151   const InvokeInst *II = dyn_cast<InvokeInst>(Def);
152   if (!II)
153     return dominates(DefBB, UseBB);
154
155   // Invoke results are only usable in the normal destination, not in the
156   // exceptional destination.
157   BasicBlock *NormalDest = II->getNormalDest();
158   BasicBlockEdge E(DefBB, NormalDest);
159   return dominates(E, UseBB);
160 }
161
162 bool DominatorTree::dominates(const BasicBlockEdge &BBE,
163                               const BasicBlock *UseBB) const {
164   // If the BB the edge ends in doesn't dominate the use BB, then the
165   // edge also doesn't.
166   const BasicBlock *Start = BBE.getStart();
167   const BasicBlock *End = BBE.getEnd();
168   if (!dominates(End, UseBB))
169     return false;
170
171   // Simple case: if the end BB has a single predecessor, the fact that it
172   // dominates the use block implies that the edge also does.
173   if (End->getSinglePredecessor())
174     return true;
175
176   // The normal edge from the invoke is critical. Conceptually, what we would
177   // like to do is split it and check if the new block dominates the use.
178   // With X being the new block, the graph would look like:
179   //
180   //        DefBB
181   //          /\      .  .
182   //         /  \     .  .
183   //        /    \    .  .
184   //       /      \   |  |
185   //      A        X  B  C
186   //      |         \ | /
187   //      .          \|/
188   //      .      NormalDest
189   //      .
190   //
191   // Given the definition of dominance, NormalDest is dominated by X iff X
192   // dominates all of NormalDest's predecessors (X, B, C in the example). X
193   // trivially dominates itself, so we only have to find if it dominates the
194   // other predecessors. Since the only way out of X is via NormalDest, X can
195   // only properly dominate a node if NormalDest dominates that node too.
196   for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
197        PI != E; ++PI) {
198     const BasicBlock *BB = *PI;
199     if (BB == Start)
200       continue;
201
202     if (!dominates(End, BB))
203       return false;
204   }
205   return true;
206 }
207
208 bool DominatorTree::dominates(const BasicBlockEdge &BBE,
209                               const Use &U) const {
210   Instruction *UserInst = cast<Instruction>(U.getUser());
211   // A PHI in the end of the edge is dominated by it.
212   PHINode *PN = dyn_cast<PHINode>(UserInst);
213   if (PN && PN->getParent() == BBE.getEnd() &&
214       PN->getIncomingBlock(U) == BBE.getStart())
215     return true;
216
217   // Otherwise use the edge-dominates-block query, which
218   // handles the crazy critical edge cases properly.
219   const BasicBlock *UseBB;
220   if (PN)
221     UseBB = PN->getIncomingBlock(U);
222   else
223     UseBB = UserInst->getParent();
224   return dominates(BBE, UseBB);
225 }
226
227 bool DominatorTree::dominates(const Instruction *Def,
228                               const Use &U) const {
229   Instruction *UserInst = cast<Instruction>(U.getUser());
230   const BasicBlock *DefBB = Def->getParent();
231
232   // Determine the block in which the use happens. PHI nodes use
233   // their operands on edges; simulate this by thinking of the use
234   // happening at the end of the predecessor block.
235   const BasicBlock *UseBB;
236   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
237     UseBB = PN->getIncomingBlock(U);
238   else
239     UseBB = UserInst->getParent();
240
241   // Any unreachable use is dominated, even if Def == User.
242   if (!isReachableFromEntry(UseBB))
243     return true;
244
245   // Unreachable definitions don't dominate anything.
246   if (!isReachableFromEntry(DefBB))
247     return false;
248
249   // Invoke instructions define their return values on the edges
250   // to their normal successors, so we have to handle them specially.
251   // Among other things, this means they don't dominate anything in
252   // their own block, except possibly a phi, so we don't need to
253   // walk the block in any case.
254   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
255     BasicBlock *NormalDest = II->getNormalDest();
256     BasicBlockEdge E(DefBB, NormalDest);
257     return dominates(E, U);
258   }
259
260   // If the def and use are in different blocks, do a simple CFG dominator
261   // tree query.
262   if (DefBB != UseBB)
263     return dominates(DefBB, UseBB);
264
265   // Ok, def and use are in the same block. If the def is an invoke, it
266   // doesn't dominate anything in the block. If it's a PHI, it dominates
267   // everything in the block.
268   if (isa<PHINode>(UserInst))
269     return true;
270
271   // Otherwise, just loop through the basic block until we find Def or User.
272   BasicBlock::const_iterator I = DefBB->begin();
273   for (; &*I != Def && &*I != UserInst; ++I)
274     /*empty*/;
275
276   return &*I != UserInst;
277 }
278
279 bool DominatorTree::isReachableFromEntry(const Use &U) const {
280   Instruction *I = dyn_cast<Instruction>(U.getUser());
281
282   // ConstantExprs aren't really reachable from the entry block, but they
283   // don't need to be treated like unreachable code either.
284   if (!I) return true;
285
286   // PHI nodes use their operands on their incoming edges.
287   if (PHINode *PN = dyn_cast<PHINode>(I))
288     return isReachableFromEntry(PN->getIncomingBlock(U));
289
290   // Everything else uses their operands in their own block.
291   return isReachableFromEntry(I->getParent());
292 }