Call the version of ConvertCostTableLookup that takes a statically sized array rather...
[oota-llvm.git] / lib / Analysis / CaptureTracking.cpp
1 //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
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 contains routines that help determine which pointers are captured.
11 // A pointer value is captured if the function makes a copy of any part of the
12 // pointer that outlives the call.  Not being captured means, more or less, that
13 // the pointer is only dereferenced and not stored in a global.  Returning part
14 // of the pointer as the function return value may or may not count as capturing
15 // the pointer, depending on the context.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/CFG.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/OrderedBasicBlock.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Instructions.h"
29
30 using namespace llvm;
31
32 CaptureTracker::~CaptureTracker() {}
33
34 bool CaptureTracker::shouldExplore(const Use *U) { return true; }
35
36 namespace {
37   struct SimpleCaptureTracker : public CaptureTracker {
38     explicit SimpleCaptureTracker(bool ReturnCaptures)
39       : ReturnCaptures(ReturnCaptures), Captured(false) {}
40
41     void tooManyUses() override { Captured = true; }
42
43     bool captured(const Use *U) override {
44       if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
45         return false;
46
47       Captured = true;
48       return true;
49     }
50
51     bool ReturnCaptures;
52
53     bool Captured;
54   };
55
56   /// Only find pointer captures which happen before the given instruction. Uses
57   /// the dominator tree to determine whether one instruction is before another.
58   /// Only support the case where the Value is defined in the same basic block
59   /// as the given instruction and the use.
60   struct CapturesBefore : public CaptureTracker {
61
62     CapturesBefore(bool ReturnCaptures, const Instruction *I, DominatorTree *DT,
63                    bool IncludeI, OrderedBasicBlock *IC)
64       : OrderedBB(IC), BeforeHere(I), DT(DT),
65         ReturnCaptures(ReturnCaptures), IncludeI(IncludeI), Captured(false) {}
66
67     void tooManyUses() override { Captured = true; }
68
69     bool isSafeToPrune(Instruction *I) {
70       BasicBlock *BB = I->getParent();
71       // We explore this usage only if the usage can reach "BeforeHere".
72       // If use is not reachable from entry, there is no need to explore.
73       if (BeforeHere != I && !DT->isReachableFromEntry(BB))
74         return true;
75
76       // Compute the case where both instructions are inside the same basic
77       // block. Since instructions in the same BB as BeforeHere are numbered in
78       // 'OrderedBB', avoid using 'dominates' and 'isPotentiallyReachable'
79       // which are very expensive for large basic blocks.
80       if (BB == BeforeHere->getParent()) {
81         // 'I' dominates 'BeforeHere' => not safe to prune.
82         //
83         // The value defined by an invoke/catchpad dominates an instruction only
84         // if it dominates every instruction in UseBB. A PHI is dominated only
85         // if the instruction dominates every possible use in the UseBB. Since
86         // UseBB == BB, avoid pruning.
87         if (isa<InvokeInst>(BeforeHere) || isa<CatchPadInst>(BeforeHere) ||
88             isa<PHINode>(I) || I == BeforeHere)
89           return false;
90         if (!OrderedBB->dominates(BeforeHere, I))
91           return false;
92
93         // 'BeforeHere' comes before 'I', it's safe to prune if we also
94         // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or
95         // by its successors, i.e, prune if:
96         //
97         //  (1) BB is an entry block or have no sucessors.
98         //  (2) There's no path coming back through BB sucessors.
99         if (BB == &BB->getParent()->getEntryBlock() ||
100             !BB->getTerminator()->getNumSuccessors())
101           return true;
102
103         SmallVector<BasicBlock*, 32> Worklist;
104         Worklist.append(succ_begin(BB), succ_end(BB));
105         if (!isPotentiallyReachableFromMany(Worklist, BB, DT))
106           return true;
107
108         return false;
109       }
110
111       // If the value is defined in the same basic block as use and BeforeHere,
112       // there is no need to explore the use if BeforeHere dominates use.
113       // Check whether there is a path from I to BeforeHere.
114       if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
115           !isPotentiallyReachable(I, BeforeHere, DT))
116         return true;
117
118       return false;
119     }
120
121     bool shouldExplore(const Use *U) override {
122       Instruction *I = cast<Instruction>(U->getUser());
123
124       if (BeforeHere == I && !IncludeI)
125         return false;
126
127       if (isSafeToPrune(I))
128         return false;
129
130       return true;
131     }
132
133     bool captured(const Use *U) override {
134       if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
135         return false;
136
137       if (!shouldExplore(U))
138         return false;
139
140       Captured = true;
141       return true;
142     }
143
144     OrderedBasicBlock *OrderedBB;
145     const Instruction *BeforeHere;
146     DominatorTree *DT;
147
148     bool ReturnCaptures;
149     bool IncludeI;
150
151     bool Captured;
152   };
153 }
154
155 /// PointerMayBeCaptured - Return true if this pointer value may be captured
156 /// by the enclosing function (which is required to exist).  This routine can
157 /// be expensive, so consider caching the results.  The boolean ReturnCaptures
158 /// specifies whether returning the value (or part of it) from the function
159 /// counts as capturing it or not.  The boolean StoreCaptures specified whether
160 /// storing the value (or part of it) into memory anywhere automatically
161 /// counts as capturing it or not.
162 bool llvm::PointerMayBeCaptured(const Value *V,
163                                 bool ReturnCaptures, bool StoreCaptures) {
164   assert(!isa<GlobalValue>(V) &&
165          "It doesn't make sense to ask whether a global is captured.");
166
167   // TODO: If StoreCaptures is not true, we could do Fancy analysis
168   // to determine whether this store is not actually an escape point.
169   // In that case, BasicAliasAnalysis should be updated as well to
170   // take advantage of this.
171   (void)StoreCaptures;
172
173   SimpleCaptureTracker SCT(ReturnCaptures);
174   PointerMayBeCaptured(V, &SCT);
175   return SCT.Captured;
176 }
177
178 /// PointerMayBeCapturedBefore - Return true if this pointer value may be
179 /// captured by the enclosing function (which is required to exist). If a
180 /// DominatorTree is provided, only captures which happen before the given
181 /// instruction are considered. This routine can be expensive, so consider
182 /// caching the results.  The boolean ReturnCaptures specifies whether
183 /// returning the value (or part of it) from the function counts as capturing
184 /// it or not.  The boolean StoreCaptures specified whether storing the value
185 /// (or part of it) into memory anywhere automatically counts as capturing it
186 /// or not. A ordered basic block \p OBB can be used in order to speed up
187 /// queries about relative order among instructions in the same basic block.
188 bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
189                                       bool StoreCaptures, const Instruction *I,
190                                       DominatorTree *DT, bool IncludeI,
191                                       OrderedBasicBlock *OBB) {
192   assert(!isa<GlobalValue>(V) &&
193          "It doesn't make sense to ask whether a global is captured.");
194   bool UseNewOBB = OBB == nullptr;
195
196   if (!DT)
197     return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures);
198   if (UseNewOBB)
199     OBB = new OrderedBasicBlock(I->getParent());
200
201   // TODO: See comment in PointerMayBeCaptured regarding what could be done
202   // with StoreCaptures.
203
204   CapturesBefore CB(ReturnCaptures, I, DT, IncludeI, OBB);
205   PointerMayBeCaptured(V, &CB);
206
207   if (UseNewOBB)
208     delete OBB;
209   return CB.Captured;
210 }
211
212 /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
213 /// a cache. Then we can move the code from BasicAliasAnalysis into
214 /// that path, and remove this threshold.
215 static int const Threshold = 20;
216
217 void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
218   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
219   SmallVector<const Use *, Threshold> Worklist;
220   SmallSet<const Use *, Threshold> Visited;
221   int Count = 0;
222
223   for (const Use &U : V->uses()) {
224     // If there are lots of uses, conservatively say that the value
225     // is captured to avoid taking too much compile time.
226     if (Count++ >= Threshold)
227       return Tracker->tooManyUses();
228
229     if (!Tracker->shouldExplore(&U)) continue;
230     Visited.insert(&U);
231     Worklist.push_back(&U);
232   }
233
234   while (!Worklist.empty()) {
235     const Use *U = Worklist.pop_back_val();
236     Instruction *I = cast<Instruction>(U->getUser());
237     V = U->get();
238
239     switch (I->getOpcode()) {
240     case Instruction::Call:
241     case Instruction::Invoke: {
242       CallSite CS(I);
243       // Not captured if the callee is readonly, doesn't return a copy through
244       // its return value and doesn't unwind (a readonly function can leak bits
245       // by throwing an exception or not depending on the input value).
246       if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
247         break;
248
249       // Not captured if only passed via 'nocapture' arguments.  Note that
250       // calling a function pointer does not in itself cause the pointer to
251       // be captured.  This is a subtle point considering that (for example)
252       // the callee might return its own address.  It is analogous to saying
253       // that loading a value from a pointer does not cause the pointer to be
254       // captured, even though the loaded value might be the pointer itself
255       // (think of self-referential objects).
256       CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
257       for (CallSite::arg_iterator A = B; A != E; ++A)
258         if (A->get() == V && !CS.doesNotCapture(A - B))
259           // The parameter is not marked 'nocapture' - captured.
260           if (Tracker->captured(U))
261             return;
262       break;
263     }
264     case Instruction::Load:
265       // Loading from a pointer does not cause it to be captured.
266       break;
267     case Instruction::VAArg:
268       // "va-arg" from a pointer does not cause it to be captured.
269       break;
270     case Instruction::Store:
271       if (V == I->getOperand(0))
272         // Stored the pointer - conservatively assume it may be captured.
273         if (Tracker->captured(U))
274           return;
275       // Storing to the pointee does not cause the pointer to be captured.
276       break;
277     case Instruction::BitCast:
278     case Instruction::GetElementPtr:
279     case Instruction::PHI:
280     case Instruction::Select:
281     case Instruction::AddrSpaceCast:
282       // The original value is not captured via this if the new value isn't.
283       Count = 0;
284       for (Use &UU : I->uses()) {
285         // If there are lots of uses, conservatively say that the value
286         // is captured to avoid taking too much compile time.
287         if (Count++ >= Threshold)
288           return Tracker->tooManyUses();
289
290         if (Visited.insert(&UU).second)
291           if (Tracker->shouldExplore(&UU))
292             Worklist.push_back(&UU);
293       }
294       break;
295     case Instruction::ICmp:
296       // Don't count comparisons of a no-alias return value against null as
297       // captures. This allows us to ignore comparisons of malloc results
298       // with null, for example.
299       if (ConstantPointerNull *CPN =
300           dyn_cast<ConstantPointerNull>(I->getOperand(1)))
301         if (CPN->getType()->getAddressSpace() == 0)
302           if (isNoAliasCall(V->stripPointerCasts()))
303             break;
304       // Otherwise, be conservative. There are crazy ways to capture pointers
305       // using comparisons.
306       if (Tracker->captured(U))
307         return;
308       break;
309     default:
310       // Something else - be conservative and say it is captured.
311       if (Tracker->captured(U))
312         return;
313       break;
314     }
315   }
316
317   // All uses examined.
318 }