1//===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help determine which pointers are captured.
10// A pointer value is captured if the function makes a copy of any part of the
11// pointer that outlives the call.  Not being captured means, more or less, that
12// the pointer is only dereferenced and not stored in a global.  Returning part
13// of the pointer as the function return value may or may not count as capturing
14// the pointer, depending on the context.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Analysis/CaptureTracking.h"
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/ValueTracking.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/IntrinsicInst.h"
28#include "llvm/Support/CommandLine.h"
29
30using namespace llvm;
31
32/// The default value for MaxUsesToExplore argument. It's relatively small to
33/// keep the cost of analysis reasonable for clients like BasicAliasAnalysis,
34/// where the results can't be cached.
35/// TODO: we should probably introduce a caching CaptureTracking analysis and
36/// use it where possible. The caching version can use much higher limit or
37/// don't have this cap at all.
38static cl::opt<unsigned>
39DefaultMaxUsesToExplore("capture-tracking-max-uses-to-explore", cl::Hidden,
40                        cl::desc("Maximal number of uses to explore."),
41                        cl::init(20));
42
43unsigned llvm::getDefaultMaxUsesToExploreForCaptureTracking() {
44  return DefaultMaxUsesToExplore;
45}
46
47CaptureTracker::~CaptureTracker() {}
48
49bool CaptureTracker::shouldExplore(const Use *U) { return true; }
50
51bool CaptureTracker::isDereferenceableOrNull(Value *O, const DataLayout &DL) {
52  // An inbounds GEP can either be a valid pointer (pointing into
53  // or to the end of an allocation), or be null in the default
54  // address space. So for an inbounds GEP there is no way to let
55  // the pointer escape using clever GEP hacking because doing so
56  // would make the pointer point outside of the allocated object
57  // and thus make the GEP result a poison value. Similarly, other
58  // dereferenceable pointers cannot be manipulated without producing
59  // poison.
60  if (auto *GEP = dyn_cast<GetElementPtrInst>(O))
61    if (GEP->isInBounds())
62      return true;
63  bool CanBeNull;
64  return O->getPointerDereferenceableBytes(DL, CanBeNull);
65}
66
67namespace {
68  struct SimpleCaptureTracker : public CaptureTracker {
69    explicit SimpleCaptureTracker(bool ReturnCaptures)
70      : ReturnCaptures(ReturnCaptures), Captured(false) {}
71
72    void tooManyUses() override { Captured = true; }
73
74    bool captured(const Use *U) override {
75      if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
76        return false;
77
78      Captured = true;
79      return true;
80    }
81
82    bool ReturnCaptures;
83
84    bool Captured;
85  };
86
87  /// Only find pointer captures which happen before the given instruction. Uses
88  /// the dominator tree to determine whether one instruction is before another.
89  /// Only support the case where the Value is defined in the same basic block
90  /// as the given instruction and the use.
91  struct CapturesBefore : public CaptureTracker {
92
93    CapturesBefore(bool ReturnCaptures, const Instruction *I, const DominatorTree *DT,
94                   bool IncludeI)
95      : BeforeHere(I), DT(DT),
96        ReturnCaptures(ReturnCaptures), IncludeI(IncludeI), Captured(false) {}
97
98    void tooManyUses() override { Captured = true; }
99
100    bool isSafeToPrune(Instruction *I) {
101      BasicBlock *BB = I->getParent();
102      // We explore this usage only if the usage can reach "BeforeHere".
103      // If use is not reachable from entry, there is no need to explore.
104      if (BeforeHere != I && !DT->isReachableFromEntry(BB))
105        return true;
106
107      // Compute the case where both instructions are inside the same basic
108      // block.
109      if (BB == BeforeHere->getParent()) {
110        // 'I' dominates 'BeforeHere' => not safe to prune.
111        //
112        // The value defined by an invoke dominates an instruction only
113        // if it dominates every instruction in UseBB. A PHI is dominated only
114        // if the instruction dominates every possible use in the UseBB. Since
115        // UseBB == BB, avoid pruning.
116        if (isa<InvokeInst>(BeforeHere) || isa<PHINode>(I) || I == BeforeHere)
117          return false;
118        if (!BeforeHere->comesBefore(I))
119          return false;
120
121        // 'BeforeHere' comes before 'I', it's safe to prune if we also
122        // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or
123        // by its successors, i.e, prune if:
124        //
125        //  (1) BB is an entry block or have no successors.
126        //  (2) There's no path coming back through BB successors.
127        if (BB == &BB->getParent()->getEntryBlock() ||
128            !BB->getTerminator()->getNumSuccessors())
129          return true;
130
131        SmallVector<BasicBlock*, 32> Worklist;
132        Worklist.append(succ_begin(BB), succ_end(BB));
133        return !isPotentiallyReachableFromMany(Worklist, BB, nullptr, DT);
134      }
135
136      // If the value is defined in the same basic block as use and BeforeHere,
137      // there is no need to explore the use if BeforeHere dominates use.
138      // Check whether there is a path from I to BeforeHere.
139      if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
140          !isPotentiallyReachable(I, BeforeHere, nullptr, DT))
141        return true;
142
143      return false;
144    }
145
146    bool shouldExplore(const Use *U) override {
147      Instruction *I = cast<Instruction>(U->getUser());
148
149      if (BeforeHere == I && !IncludeI)
150        return false;
151
152      if (isSafeToPrune(I))
153        return false;
154
155      return true;
156    }
157
158    bool captured(const Use *U) override {
159      if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
160        return false;
161
162      if (!shouldExplore(U))
163        return false;
164
165      Captured = true;
166      return true;
167    }
168
169    const Instruction *BeforeHere;
170    const DominatorTree *DT;
171
172    bool ReturnCaptures;
173    bool IncludeI;
174
175    bool Captured;
176  };
177}
178
179/// PointerMayBeCaptured - Return true if this pointer value may be captured
180/// by the enclosing function (which is required to exist).  This routine can
181/// be expensive, so consider caching the results.  The boolean ReturnCaptures
182/// specifies whether returning the value (or part of it) from the function
183/// counts as capturing it or not.  The boolean StoreCaptures specified whether
184/// storing the value (or part of it) into memory anywhere automatically
185/// counts as capturing it or not.
186bool llvm::PointerMayBeCaptured(const Value *V,
187                                bool ReturnCaptures, bool StoreCaptures,
188                                unsigned MaxUsesToExplore) {
189  assert(!isa<GlobalValue>(V) &&
190         "It doesn't make sense to ask whether a global is captured.");
191
192  // TODO: If StoreCaptures is not true, we could do Fancy analysis
193  // to determine whether this store is not actually an escape point.
194  // In that case, BasicAliasAnalysis should be updated as well to
195  // take advantage of this.
196  (void)StoreCaptures;
197
198  SimpleCaptureTracker SCT(ReturnCaptures);
199  PointerMayBeCaptured(V, &SCT, MaxUsesToExplore);
200  return SCT.Captured;
201}
202
203/// PointerMayBeCapturedBefore - Return true if this pointer value may be
204/// captured by the enclosing function (which is required to exist). If a
205/// DominatorTree is provided, only captures which happen before the given
206/// instruction are considered. This routine can be expensive, so consider
207/// caching the results.  The boolean ReturnCaptures specifies whether
208/// returning the value (or part of it) from the function counts as capturing
209/// it or not.  The boolean StoreCaptures specified whether storing the value
210/// (or part of it) into memory anywhere automatically counts as capturing it
211/// or not.
212bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
213                                      bool StoreCaptures, const Instruction *I,
214                                      const DominatorTree *DT, bool IncludeI,
215                                      unsigned MaxUsesToExplore) {
216  assert(!isa<GlobalValue>(V) &&
217         "It doesn't make sense to ask whether a global is captured.");
218
219  if (!DT)
220    return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures,
221                                MaxUsesToExplore);
222
223  // TODO: See comment in PointerMayBeCaptured regarding what could be done
224  // with StoreCaptures.
225
226  CapturesBefore CB(ReturnCaptures, I, DT, IncludeI);
227  PointerMayBeCaptured(V, &CB, MaxUsesToExplore);
228  return CB.Captured;
229}
230
231void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker,
232                                unsigned MaxUsesToExplore) {
233  assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
234  if (MaxUsesToExplore == 0)
235    MaxUsesToExplore = DefaultMaxUsesToExplore;
236
237  SmallVector<const Use *, 20> Worklist;
238  Worklist.reserve(getDefaultMaxUsesToExploreForCaptureTracking());
239  SmallSet<const Use *, 20> Visited;
240
241  auto AddUses = [&](const Value *V) {
242    unsigned Count = 0;
243    for (const Use &U : V->uses()) {
244      // If there are lots of uses, conservatively say that the value
245      // is captured to avoid taking too much compile time.
246      if (Count++ >= MaxUsesToExplore)
247        return Tracker->tooManyUses();
248      if (!Visited.insert(&U).second)
249        continue;
250      if (!Tracker->shouldExplore(&U))
251        continue;
252      Worklist.push_back(&U);
253    }
254  };
255  AddUses(V);
256
257  while (!Worklist.empty()) {
258    const Use *U = Worklist.pop_back_val();
259    Instruction *I = cast<Instruction>(U->getUser());
260    V = U->get();
261
262    switch (I->getOpcode()) {
263    case Instruction::Call:
264    case Instruction::Invoke: {
265      auto *Call = cast<CallBase>(I);
266      // Not captured if the callee is readonly, doesn't return a copy through
267      // its return value and doesn't unwind (a readonly function can leak bits
268      // by throwing an exception or not depending on the input value).
269      if (Call->onlyReadsMemory() && Call->doesNotThrow() &&
270          Call->getType()->isVoidTy())
271        break;
272
273      // The pointer is not captured if returned pointer is not captured.
274      // NOTE: CaptureTracking users should not assume that only functions
275      // marked with nocapture do not capture. This means that places like
276      // GetUnderlyingObject in ValueTracking or DecomposeGEPExpression
277      // in BasicAA also need to know about this property.
278      if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call,
279                                                                      true)) {
280        AddUses(Call);
281        break;
282      }
283
284      // Volatile operations effectively capture the memory location that they
285      // load and store to.
286      if (auto *MI = dyn_cast<MemIntrinsic>(Call))
287        if (MI->isVolatile())
288          if (Tracker->captured(U))
289            return;
290
291      // Not captured if only passed via 'nocapture' arguments.  Note that
292      // calling a function pointer does not in itself cause the pointer to
293      // be captured.  This is a subtle point considering that (for example)
294      // the callee might return its own address.  It is analogous to saying
295      // that loading a value from a pointer does not cause the pointer to be
296      // captured, even though the loaded value might be the pointer itself
297      // (think of self-referential objects).
298      for (auto IdxOpPair : enumerate(Call->data_ops())) {
299        int Idx = IdxOpPair.index();
300        Value *A = IdxOpPair.value();
301        if (A == V && !Call->doesNotCapture(Idx))
302          // The parameter is not marked 'nocapture' - captured.
303          if (Tracker->captured(U))
304            return;
305      }
306      break;
307    }
308    case Instruction::Load:
309      // Volatile loads make the address observable.
310      if (cast<LoadInst>(I)->isVolatile())
311        if (Tracker->captured(U))
312          return;
313      break;
314    case Instruction::VAArg:
315      // "va-arg" from a pointer does not cause it to be captured.
316      break;
317    case Instruction::Store:
318        // Stored the pointer - conservatively assume it may be captured.
319        // Volatile stores make the address observable.
320      if (V == I->getOperand(0) || cast<StoreInst>(I)->isVolatile())
321        if (Tracker->captured(U))
322          return;
323      break;
324    case Instruction::AtomicRMW: {
325      // atomicrmw conceptually includes both a load and store from
326      // the same location.
327      // As with a store, the location being accessed is not captured,
328      // but the value being stored is.
329      // Volatile stores make the address observable.
330      auto *ARMWI = cast<AtomicRMWInst>(I);
331      if (ARMWI->getValOperand() == V || ARMWI->isVolatile())
332        if (Tracker->captured(U))
333          return;
334      break;
335    }
336    case Instruction::AtomicCmpXchg: {
337      // cmpxchg conceptually includes both a load and store from
338      // the same location.
339      // As with a store, the location being accessed is not captured,
340      // but the value being stored is.
341      // Volatile stores make the address observable.
342      auto *ACXI = cast<AtomicCmpXchgInst>(I);
343      if (ACXI->getCompareOperand() == V || ACXI->getNewValOperand() == V ||
344          ACXI->isVolatile())
345        if (Tracker->captured(U))
346          return;
347      break;
348    }
349    case Instruction::BitCast:
350    case Instruction::GetElementPtr:
351    case Instruction::PHI:
352    case Instruction::Select:
353    case Instruction::AddrSpaceCast:
354      // The original value is not captured via this if the new value isn't.
355      AddUses(I);
356      break;
357    case Instruction::ICmp: {
358      unsigned Idx = (I->getOperand(0) == V) ? 0 : 1;
359      unsigned OtherIdx = 1 - Idx;
360      if (auto *CPN = dyn_cast<ConstantPointerNull>(I->getOperand(OtherIdx))) {
361        // Don't count comparisons of a no-alias return value against null as
362        // captures. This allows us to ignore comparisons of malloc results
363        // with null, for example.
364        if (CPN->getType()->getAddressSpace() == 0)
365          if (isNoAliasCall(V->stripPointerCasts()))
366            break;
367        if (!I->getFunction()->nullPointerIsDefined()) {
368          auto *O = I->getOperand(Idx)->stripPointerCastsSameRepresentation();
369          // Comparing a dereferenceable_or_null pointer against null cannot
370          // lead to pointer escapes, because if it is not null it must be a
371          // valid (in-bounds) pointer.
372          if (Tracker->isDereferenceableOrNull(O, I->getModule()->getDataLayout()))
373            break;
374        }
375      }
376      // Comparison against value stored in global variable. Given the pointer
377      // does not escape, its value cannot be guessed and stored separately in a
378      // global variable.
379      auto *LI = dyn_cast<LoadInst>(I->getOperand(OtherIdx));
380      if (LI && isa<GlobalVariable>(LI->getPointerOperand()))
381        break;
382      // Otherwise, be conservative. There are crazy ways to capture pointers
383      // using comparisons.
384      if (Tracker->captured(U))
385        return;
386      break;
387    }
388    default:
389      // Something else - be conservative and say it is captured.
390      if (Tracker->captured(U))
391        return;
392      break;
393    }
394  }
395
396  // All uses examined.
397}
398