blob: e13c47a9bde784a1eac3d281597feaf6b2a8e6fe [file] [log] [blame]
Duncan Sandse0aa0d62009-01-18 12:19:30 +00001//===--- 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
Jakub Staszak173bce32012-01-17 22:16:31 +000019#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/SmallVector.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000021#include "llvm/Analysis/AliasAnalysis.h"
Duncan Sandse0aa0d62009-01-18 12:19:30 +000022#include "llvm/Analysis/CaptureTracking.h"
Hal Finkelb0356212014-07-21 13:15:48 +000023#include "llvm/Analysis/CFG.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000024#include "llvm/IR/CallSite.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000025#include "llvm/IR/Constants.h"
Hal Finkelb0356212014-07-21 13:15:48 +000026#include "llvm/IR/Dominators.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000027#include "llvm/IR/Instructions.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000028
Duncan Sandse0aa0d62009-01-18 12:19:30 +000029using namespace llvm;
30
Nick Lewyckyaa2a00d2011-11-21 18:32:21 +000031CaptureTracker::~CaptureTracker() {}
32
Chandler Carruth64e9aa52014-03-05 10:21:48 +000033bool CaptureTracker::shouldExplore(const Use *U) { return true; }
Nick Lewycky7c3b5d92012-10-08 22:12:48 +000034
Nick Lewycky7013a192011-11-14 22:49:42 +000035namespace {
Nick Lewycky6ae03c32011-11-20 19:37:06 +000036 struct SimpleCaptureTracker : public CaptureTracker {
Nick Lewycky7013a192011-11-14 22:49:42 +000037 explicit SimpleCaptureTracker(bool ReturnCaptures)
38 : ReturnCaptures(ReturnCaptures), Captured(false) {}
39
Craig Toppere9ba7592014-03-05 07:30:04 +000040 void tooManyUses() override { Captured = true; }
Nick Lewycky7013a192011-11-14 22:49:42 +000041
Chandler Carruth64e9aa52014-03-05 10:21:48 +000042 bool captured(const Use *U) override {
Nick Lewycky4c378a42011-12-28 23:24:21 +000043 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
Chad Rosier8244b1d2012-05-10 23:38:07 +000044 return false;
Nick Lewycky7013a192011-11-14 22:49:42 +000045
46 Captured = true;
47 return true;
48 }
49
50 bool ReturnCaptures;
51
52 bool Captured;
53 };
Hal Finkelb0356212014-07-21 13:15:48 +000054
55 /// Only find pointer captures which happen before the given instruction. Uses
56 /// the dominator tree to determine whether one instruction is before another.
57 /// Only support the case where the Value is defined in the same basic block
58 /// as the given instruction and the use.
59 struct CapturesBefore : public CaptureTracker {
60 CapturesBefore(bool ReturnCaptures, const Instruction *I, DominatorTree *DT)
61 : BeforeHere(I), DT(DT), ReturnCaptures(ReturnCaptures),
62 Captured(false) {}
63
64 void tooManyUses() override { Captured = true; }
65
66 bool shouldExplore(const Use *U) override {
67 Instruction *I = cast<Instruction>(U->getUser());
68 BasicBlock *BB = I->getParent();
69 // We explore this usage only if the usage can reach "BeforeHere".
70 // If use is not reachable from entry, there is no need to explore.
71 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
72 return false;
73 // If the value is defined in the same basic block as use and BeforeHere,
74 // there is no need to explore the use if BeforeHere dominates use.
75 // Check whether there is a path from I to BeforeHere.
76 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
77 !isPotentiallyReachable(I, BeforeHere, DT))
78 return false;
79 return true;
80 }
81
82 bool captured(const Use *U) override {
83 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
84 return false;
85
86 Instruction *I = cast<Instruction>(U->getUser());
87 BasicBlock *BB = I->getParent();
88 // Same logic as in shouldExplore.
89 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
90 return false;
91 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
92 !isPotentiallyReachable(I, BeforeHere, DT))
93 return false;
94 Captured = true;
95 return true;
96 }
97
98 const Instruction *BeforeHere;
99 DominatorTree *DT;
100
101 bool ReturnCaptures;
102
103 bool Captured;
104 };
Nick Lewycky7013a192011-11-14 22:49:42 +0000105}
Dan Gohman2d27b192009-12-08 23:59:12 +0000106
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000107/// PointerMayBeCaptured - Return true if this pointer value may be captured
108/// by the enclosing function (which is required to exist). This routine can
109/// be expensive, so consider caching the results. The boolean ReturnCaptures
110/// specifies whether returning the value (or part of it) from the function
Dan Gohman94e61762009-11-19 21:57:48 +0000111/// counts as capturing it or not. The boolean StoreCaptures specified whether
112/// storing the value (or part of it) into memory anywhere automatically
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000113/// counts as capturing it or not.
Dan Gohman94e61762009-11-19 21:57:48 +0000114bool llvm::PointerMayBeCaptured(const Value *V,
115 bool ReturnCaptures, bool StoreCaptures) {
Nick Lewycky063ae582011-11-21 19:42:56 +0000116 assert(!isa<GlobalValue>(V) &&
117 "It doesn't make sense to ask whether a global is captured.");
118
Nick Lewycky7013a192011-11-14 22:49:42 +0000119 // TODO: If StoreCaptures is not true, we could do Fancy analysis
120 // to determine whether this store is not actually an escape point.
121 // In that case, BasicAliasAnalysis should be updated as well to
122 // take advantage of this.
123 (void)StoreCaptures;
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000124
Nick Lewycky7013a192011-11-14 22:49:42 +0000125 SimpleCaptureTracker SCT(ReturnCaptures);
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000126 PointerMayBeCaptured(V, &SCT);
Nick Lewycky7013a192011-11-14 22:49:42 +0000127 return SCT.Captured;
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000128}
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000129
Hal Finkelb0356212014-07-21 13:15:48 +0000130/// PointerMayBeCapturedBefore - Return true if this pointer value may be
131/// captured by the enclosing function (which is required to exist). If a
132/// DominatorTree is provided, only captures which happen before the given
133/// instruction are considered. This routine can be expensive, so consider
134/// caching the results. The boolean ReturnCaptures specifies whether
135/// returning the value (or part of it) from the function counts as capturing
136/// it or not. The boolean StoreCaptures specified whether storing the value
137/// (or part of it) into memory anywhere automatically counts as capturing it
138/// or not.
139bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
140 bool StoreCaptures, const Instruction *I,
141 DominatorTree *DT) {
142 assert(!isa<GlobalValue>(V) &&
143 "It doesn't make sense to ask whether a global is captured.");
144
145 if (!DT)
146 return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures);
147
148 // TODO: See comment in PointerMayBeCaptured regarding what could be done
149 // with StoreCaptures.
150
151 CapturesBefore CB(ReturnCaptures, I, DT);
152 PointerMayBeCaptured(V, &CB);
153 return CB.Captured;
154}
155
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000156/// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
157/// a cache. Then we can move the code from BasicAliasAnalysis into
158/// that path, and remove this threshold.
159static int const Threshold = 20;
160
161void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
162 assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
Chandler Carruth64e9aa52014-03-05 10:21:48 +0000163 SmallVector<const Use *, Threshold> Worklist;
164 SmallSet<const Use *, Threshold> Visited;
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000165 int Count = 0;
166
Chandler Carruthcdf47882014-03-09 03:16:01 +0000167 for (const Use &U : V->uses()) {
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000168 // If there are lots of uses, conservatively say that the value
169 // is captured to avoid taking too much compile time.
170 if (Count++ >= Threshold)
171 return Tracker->tooManyUses();
172
Chandler Carruthcdf47882014-03-09 03:16:01 +0000173 if (!Tracker->shouldExplore(&U)) continue;
174 Visited.insert(&U);
175 Worklist.push_back(&U);
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000176 }
177
178 while (!Worklist.empty()) {
Chandler Carruth64e9aa52014-03-05 10:21:48 +0000179 const Use *U = Worklist.pop_back_val();
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000180 Instruction *I = cast<Instruction>(U->getUser());
181 V = U->get();
182
183 switch (I->getOpcode()) {
184 case Instruction::Call:
185 case Instruction::Invoke: {
186 CallSite CS(I);
187 // Not captured if the callee is readonly, doesn't return a copy through
188 // its return value and doesn't unwind (a readonly function can leak bits
189 // by throwing an exception or not depending on the input value).
190 if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
191 break;
192
193 // Not captured if only passed via 'nocapture' arguments. Note that
194 // calling a function pointer does not in itself cause the pointer to
195 // be captured. This is a subtle point considering that (for example)
196 // the callee might return its own address. It is analogous to saying
197 // that loading a value from a pointer does not cause the pointer to be
198 // captured, even though the loaded value might be the pointer itself
199 // (think of self-referential objects).
200 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
201 for (CallSite::arg_iterator A = B; A != E; ++A)
202 if (A->get() == V && !CS.doesNotCapture(A - B))
203 // The parameter is not marked 'nocapture' - captured.
Nick Lewycky4c378a42011-12-28 23:24:21 +0000204 if (Tracker->captured(U))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000205 return;
206 break;
207 }
208 case Instruction::Load:
209 // Loading from a pointer does not cause it to be captured.
210 break;
211 case Instruction::VAArg:
212 // "va-arg" from a pointer does not cause it to be captured.
213 break;
214 case Instruction::Store:
215 if (V == I->getOperand(0))
216 // Stored the pointer - conservatively assume it may be captured.
Nick Lewycky4c378a42011-12-28 23:24:21 +0000217 if (Tracker->captured(U))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000218 return;
219 // Storing to the pointee does not cause the pointer to be captured.
220 break;
221 case Instruction::BitCast:
222 case Instruction::GetElementPtr:
223 case Instruction::PHI:
224 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000225 case Instruction::AddrSpaceCast:
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000226 // The original value is not captured via this if the new value isn't.
Benjamin Kramerd2757ba2013-10-03 13:24:02 +0000227 Count = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000228 for (Use &UU : I->uses()) {
Benjamin Kramerd2757ba2013-10-03 13:24:02 +0000229 // If there are lots of uses, conservatively say that the value
230 // is captured to avoid taking too much compile time.
231 if (Count++ >= Threshold)
232 return Tracker->tooManyUses();
233
Chandler Carruthcdf47882014-03-09 03:16:01 +0000234 if (Visited.insert(&UU))
235 if (Tracker->shouldExplore(&UU))
236 Worklist.push_back(&UU);
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000237 }
238 break;
239 case Instruction::ICmp:
240 // Don't count comparisons of a no-alias return value against null as
241 // captures. This allows us to ignore comparisons of malloc results
242 // with null, for example.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000243 if (ConstantPointerNull *CPN =
244 dyn_cast<ConstantPointerNull>(I->getOperand(1)))
245 if (CPN->getType()->getAddressSpace() == 0)
246 if (isNoAliasCall(V->stripPointerCasts()))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000247 break;
248 // Otherwise, be conservative. There are crazy ways to capture pointers
249 // using comparisons.
Nick Lewycky4c378a42011-12-28 23:24:21 +0000250 if (Tracker->captured(U))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000251 return;
252 break;
253 default:
254 // Something else - be conservative and say it is captured.
Nick Lewycky4c378a42011-12-28 23:24:21 +0000255 if (Tracker->captured(U))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000256 return;
257 break;
258 }
259 }
260
261 // All uses examined.
262}