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