xref: /src/contrib/llvm-project/llvm/lib/Analysis/CaptureTracking.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1009b1c42SEd Schouten //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file contains routines that help determine which pointers are captured.
10009b1c42SEd Schouten // A pointer value is captured if the function makes a copy of any part of the
11009b1c42SEd Schouten // pointer that outlives the call.  Not being captured means, more or less, that
12009b1c42SEd Schouten // the pointer is only dereferenced and not stored in a global.  Returning part
13009b1c42SEd Schouten // of the pointer as the function return value may or may not count as capturing
14009b1c42SEd Schouten // the pointer, depending on the context.
15009b1c42SEd Schouten //
16009b1c42SEd Schouten //===----------------------------------------------------------------------===//
17009b1c42SEd Schouten 
187ab83427SDimitry Andric #include "llvm/Analysis/CaptureTracking.h"
19009b1c42SEd Schouten #include "llvm/ADT/SmallSet.h"
20009b1c42SEd Schouten #include "llvm/ADT/SmallVector.h"
21b60736ecSDimitry Andric #include "llvm/ADT/Statistic.h"
224a16efa3SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
235ca98fd9SDimitry Andric #include "llvm/Analysis/CFG.h"
24eb11fae6SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
254a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
265ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
274a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
2801095a5dSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
29cfca06d7SDimitry Andric #include "llvm/Support/CommandLine.h"
304a16efa3SDimitry Andric 
31009b1c42SEd Schouten using namespace llvm;
32009b1c42SEd Schouten 
33b60736ecSDimitry Andric #define DEBUG_TYPE "capture-tracking"
34b60736ecSDimitry Andric 
35b60736ecSDimitry Andric STATISTIC(NumCaptured,          "Number of pointers maybe captured");
36b60736ecSDimitry Andric STATISTIC(NumNotCaptured,       "Number of pointers not captured");
37b60736ecSDimitry Andric STATISTIC(NumCapturedBefore,    "Number of pointers maybe captured before");
38b60736ecSDimitry Andric STATISTIC(NumNotCapturedBefore, "Number of pointers not captured before");
39b60736ecSDimitry Andric 
40cfca06d7SDimitry Andric /// The default value for MaxUsesToExplore argument. It's relatively small to
41cfca06d7SDimitry Andric /// keep the cost of analysis reasonable for clients like BasicAliasAnalysis,
42cfca06d7SDimitry Andric /// where the results can't be cached.
43cfca06d7SDimitry Andric /// TODO: we should probably introduce a caching CaptureTracking analysis and
44cfca06d7SDimitry Andric /// use it where possible. The caching version can use much higher limit or
45cfca06d7SDimitry Andric /// don't have this cap at all.
46cfca06d7SDimitry Andric static cl::opt<unsigned>
47cfca06d7SDimitry Andric     DefaultMaxUsesToExplore("capture-tracking-max-uses-to-explore", cl::Hidden,
48cfca06d7SDimitry Andric                             cl::desc("Maximal number of uses to explore."),
49145449b1SDimitry Andric                             cl::init(100));
50cfca06d7SDimitry Andric 
getDefaultMaxUsesToExploreForCaptureTracking()51cfca06d7SDimitry Andric unsigned llvm::getDefaultMaxUsesToExploreForCaptureTracking() {
52cfca06d7SDimitry Andric   return DefaultMaxUsesToExplore;
53cfca06d7SDimitry Andric }
54cfca06d7SDimitry Andric 
55145449b1SDimitry Andric CaptureTracker::~CaptureTracker() = default;
5663faed5bSDimitry Andric 
shouldExplore(const Use * U)575ca98fd9SDimitry Andric bool CaptureTracker::shouldExplore(const Use *U) { return true; }
58522600a2SDimitry Andric 
isDereferenceableOrNull(Value * O,const DataLayout & DL)591d5ae102SDimitry Andric bool CaptureTracker::isDereferenceableOrNull(Value *O, const DataLayout &DL) {
607fa27ce4SDimitry Andric   // We want comparisons to null pointers to not be considered capturing,
617fa27ce4SDimitry Andric   // but need to guard against cases like gep(p, -ptrtoint(p2)) == null,
627fa27ce4SDimitry Andric   // which are equivalent to p == p2 and would capture the pointer.
637fa27ce4SDimitry Andric   //
647fa27ce4SDimitry Andric   // A dereferenceable pointer is a case where this is known to be safe,
657fa27ce4SDimitry Andric   // because the pointer resulting from such a construction would not be
667fa27ce4SDimitry Andric   // dereferenceable.
677fa27ce4SDimitry Andric   //
687fa27ce4SDimitry Andric   // It is not sufficient to check for inbounds GEP here, because GEP with
697fa27ce4SDimitry Andric   // zero offset is always inbounds.
70344a3780SDimitry Andric   bool CanBeNull, CanBeFreed;
71344a3780SDimitry Andric   return O->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
721d5ae102SDimitry Andric }
731d5ae102SDimitry Andric 
7463faed5bSDimitry Andric namespace {
7563faed5bSDimitry Andric struct SimpleCaptureTracker : public CaptureTracker {
SimpleCaptureTracker__anon466d5f7f0111::SimpleCaptureTracker76b1c73532SDimitry Andric   explicit SimpleCaptureTracker(bool ReturnCaptures)
77b1c73532SDimitry Andric       : ReturnCaptures(ReturnCaptures) {}
7863faed5bSDimitry Andric 
tooManyUses__anon466d5f7f0111::SimpleCaptureTracker797fa27ce4SDimitry Andric   void tooManyUses() override {
807fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "Captured due to too many uses\n");
817fa27ce4SDimitry Andric     Captured = true;
827fa27ce4SDimitry Andric   }
8363faed5bSDimitry Andric 
captured__anon466d5f7f0111::SimpleCaptureTracker845ca98fd9SDimitry Andric   bool captured(const Use *U) override {
8563faed5bSDimitry Andric     if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
8663faed5bSDimitry Andric       return false;
8763faed5bSDimitry Andric 
887fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "Captured by: " << *U->getUser() << "\n");
897fa27ce4SDimitry Andric 
9063faed5bSDimitry Andric     Captured = true;
9163faed5bSDimitry Andric     return true;
9263faed5bSDimitry Andric   }
9363faed5bSDimitry Andric 
9463faed5bSDimitry Andric   bool ReturnCaptures;
9563faed5bSDimitry Andric 
966f8fc217SDimitry Andric   bool Captured = false;
9763faed5bSDimitry Andric };
985ca98fd9SDimitry Andric 
995ca98fd9SDimitry Andric /// Only find pointer captures which happen before the given instruction. Uses
1005ca98fd9SDimitry Andric /// the dominator tree to determine whether one instruction is before another.
1015ca98fd9SDimitry Andric /// Only support the case where the Value is defined in the same basic block
1025ca98fd9SDimitry Andric /// as the given instruction and the use.
1035ca98fd9SDimitry Andric struct CapturesBefore : public CaptureTracker {
1041a82d4c0SDimitry Andric 
CapturesBefore__anon466d5f7f0111::CapturesBefore105c0981da4SDimitry Andric   CapturesBefore(bool ReturnCaptures, const Instruction *I,
106c0981da4SDimitry Andric                  const DominatorTree *DT, bool IncludeI, const LoopInfo *LI)
107c0981da4SDimitry Andric       : BeforeHere(I), DT(DT), ReturnCaptures(ReturnCaptures),
1086f8fc217SDimitry Andric         IncludeI(IncludeI), LI(LI) {}
1095ca98fd9SDimitry Andric 
tooManyUses__anon466d5f7f0111::CapturesBefore1105ca98fd9SDimitry Andric   void tooManyUses() override { Captured = true; }
1115ca98fd9SDimitry Andric 
isSafeToPrune__anon466d5f7f0111::CapturesBefore1121a82d4c0SDimitry Andric   bool isSafeToPrune(Instruction *I) {
113344a3780SDimitry Andric     if (BeforeHere == I)
114344a3780SDimitry Andric       return !IncludeI;
115344a3780SDimitry Andric 
1165ca98fd9SDimitry Andric     // We explore this usage only if the usage can reach "BeforeHere".
1175ca98fd9SDimitry Andric     // If use is not reachable from entry, there is no need to explore.
118344a3780SDimitry Andric     if (!DT->isReachableFromEntry(I->getParent()))
1191a82d4c0SDimitry Andric       return true;
1201a82d4c0SDimitry Andric 
1215ca98fd9SDimitry Andric     // Check whether there is a path from I to BeforeHere.
122c0981da4SDimitry Andric     return !isPotentiallyReachable(I, BeforeHere, nullptr, DT, LI);
1235ca98fd9SDimitry Andric   }
1245ca98fd9SDimitry Andric 
captured__anon466d5f7f0111::CapturesBefore1255ca98fd9SDimitry Andric   bool captured(const Use *U) override {
126344a3780SDimitry Andric     Instruction *I = cast<Instruction>(U->getUser());
127344a3780SDimitry Andric     if (isa<ReturnInst>(I) && !ReturnCaptures)
128344a3780SDimitry Andric       return false;
129344a3780SDimitry Andric 
130344a3780SDimitry Andric     // Check isSafeToPrune() here rather than in shouldExplore() to avoid
131344a3780SDimitry Andric     // an expensive reachability query for every instruction we look at.
132344a3780SDimitry Andric     // Instead we only do one for actual capturing candidates.
133344a3780SDimitry Andric     if (isSafeToPrune(I))
1345ca98fd9SDimitry Andric       return false;
1355ca98fd9SDimitry Andric 
1365ca98fd9SDimitry Andric     Captured = true;
1375ca98fd9SDimitry Andric     return true;
1385ca98fd9SDimitry Andric   }
1395ca98fd9SDimitry Andric 
1405ca98fd9SDimitry Andric   const Instruction *BeforeHere;
141eb11fae6SDimitry Andric   const DominatorTree *DT;
1425ca98fd9SDimitry Andric 
1435ca98fd9SDimitry Andric   bool ReturnCaptures;
1445ca98fd9SDimitry Andric   bool IncludeI;
1455ca98fd9SDimitry Andric 
1466f8fc217SDimitry Andric   bool Captured = false;
147c0981da4SDimitry Andric 
148c0981da4SDimitry Andric   const LoopInfo *LI;
149c0981da4SDimitry Andric };
150c0981da4SDimitry Andric 
151c0981da4SDimitry Andric /// Find the 'earliest' instruction before which the pointer is known not to
152c0981da4SDimitry Andric /// be captured. Here an instruction A is considered earlier than instruction
153c0981da4SDimitry Andric /// B, if A dominates B. If 2 escapes do not dominate each other, the
154c0981da4SDimitry Andric /// terminator of the common dominator is chosen. If not all uses cannot be
155c0981da4SDimitry Andric /// analyzed, the earliest escape is set to the first instruction in the
156c0981da4SDimitry Andric /// function entry block.
157c0981da4SDimitry Andric // NOTE: Users have to make sure instructions compared against the earliest
158c0981da4SDimitry Andric // escape are not in a cycle.
159c0981da4SDimitry Andric struct EarliestCaptures : public CaptureTracker {
160c0981da4SDimitry Andric 
EarliestCaptures__anon466d5f7f0111::EarliestCaptures161b1c73532SDimitry Andric   EarliestCaptures(bool ReturnCaptures, Function &F, const DominatorTree &DT)
162b1c73532SDimitry Andric       : DT(DT), ReturnCaptures(ReturnCaptures), F(F) {}
163c0981da4SDimitry Andric 
tooManyUses__anon466d5f7f0111::EarliestCaptures164c0981da4SDimitry Andric   void tooManyUses() override {
165c0981da4SDimitry Andric     Captured = true;
166c0981da4SDimitry Andric     EarliestCapture = &*F.getEntryBlock().begin();
167c0981da4SDimitry Andric   }
168c0981da4SDimitry Andric 
captured__anon466d5f7f0111::EarliestCaptures169c0981da4SDimitry Andric   bool captured(const Use *U) override {
170c0981da4SDimitry Andric     Instruction *I = cast<Instruction>(U->getUser());
171c0981da4SDimitry Andric     if (isa<ReturnInst>(I) && !ReturnCaptures)
172c0981da4SDimitry Andric       return false;
173c0981da4SDimitry Andric 
174e3b55780SDimitry Andric     if (!EarliestCapture)
175c0981da4SDimitry Andric       EarliestCapture = I;
176e3b55780SDimitry Andric     else
177e3b55780SDimitry Andric       EarliestCapture = DT.findNearestCommonDominator(EarliestCapture, I);
178c0981da4SDimitry Andric     Captured = true;
179c0981da4SDimitry Andric 
180c0981da4SDimitry Andric     // Return false to continue analysis; we need to see all potential
181c0981da4SDimitry Andric     // captures.
182c0981da4SDimitry Andric     return false;
183c0981da4SDimitry Andric   }
184c0981da4SDimitry Andric 
185c0981da4SDimitry Andric   Instruction *EarliestCapture = nullptr;
186c0981da4SDimitry Andric 
187c0981da4SDimitry Andric   const DominatorTree &DT;
188c0981da4SDimitry Andric 
189c0981da4SDimitry Andric   bool ReturnCaptures;
190c0981da4SDimitry Andric 
1916f8fc217SDimitry Andric   bool Captured = false;
192c0981da4SDimitry Andric 
193c0981da4SDimitry Andric   Function &F;
1945ca98fd9SDimitry Andric };
195ac9a064cSDimitry Andric } // namespace
196571945e6SRoman Divacky 
197009b1c42SEd Schouten /// PointerMayBeCaptured - Return true if this pointer value may be captured
198009b1c42SEd Schouten /// by the enclosing function (which is required to exist).  This routine can
199009b1c42SEd Schouten /// be expensive, so consider caching the results.  The boolean ReturnCaptures
200009b1c42SEd Schouten /// specifies whether returning the value (or part of it) from the function
20106f9d401SRoman Divacky /// counts as capturing it or not.  The boolean StoreCaptures specified whether
20206f9d401SRoman Divacky /// storing the value (or part of it) into memory anywhere automatically
203009b1c42SEd Schouten /// counts as capturing it or not.
PointerMayBeCaptured(const Value * V,bool ReturnCaptures,bool StoreCaptures,unsigned MaxUsesToExplore)204145449b1SDimitry Andric bool llvm::PointerMayBeCaptured(const Value *V, bool ReturnCaptures,
205145449b1SDimitry Andric                                 bool StoreCaptures, unsigned MaxUsesToExplore) {
20663faed5bSDimitry Andric   assert(!isa<GlobalValue>(V) &&
20763faed5bSDimitry Andric          "It doesn't make sense to ask whether a global is captured.");
20863faed5bSDimitry Andric 
20963faed5bSDimitry Andric   // TODO: If StoreCaptures is not true, we could do Fancy analysis
21063faed5bSDimitry Andric   // to determine whether this store is not actually an escape point.
21163faed5bSDimitry Andric   // In that case, BasicAliasAnalysis should be updated as well to
21263faed5bSDimitry Andric   // take advantage of this.
21363faed5bSDimitry Andric   (void)StoreCaptures;
21463faed5bSDimitry Andric 
2157fa27ce4SDimitry Andric   LLVM_DEBUG(dbgs() << "Captured?: " << *V << " = ");
2167fa27ce4SDimitry Andric 
217b1c73532SDimitry Andric   SimpleCaptureTracker SCT(ReturnCaptures);
218d8e91e46SDimitry Andric   PointerMayBeCaptured(V, &SCT, MaxUsesToExplore);
219b60736ecSDimitry Andric   if (SCT.Captured)
220b60736ecSDimitry Andric     ++NumCaptured;
2217fa27ce4SDimitry Andric   else {
222b60736ecSDimitry Andric     ++NumNotCaptured;
2237fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "not captured\n");
2247fa27ce4SDimitry Andric   }
22563faed5bSDimitry Andric   return SCT.Captured;
22663faed5bSDimitry Andric }
22763faed5bSDimitry Andric 
2285ca98fd9SDimitry Andric /// PointerMayBeCapturedBefore - Return true if this pointer value may be
2295ca98fd9SDimitry Andric /// captured by the enclosing function (which is required to exist). If a
2305ca98fd9SDimitry Andric /// DominatorTree is provided, only captures which happen before the given
2315ca98fd9SDimitry Andric /// instruction are considered. This routine can be expensive, so consider
2325ca98fd9SDimitry Andric /// caching the results.  The boolean ReturnCaptures specifies whether
2335ca98fd9SDimitry Andric /// returning the value (or part of it) from the function counts as capturing
2345ca98fd9SDimitry Andric /// it or not.  The boolean StoreCaptures specified whether storing the value
2355ca98fd9SDimitry Andric /// (or part of it) into memory anywhere automatically counts as capturing it
236cfca06d7SDimitry Andric /// or not.
PointerMayBeCapturedBefore(const Value * V,bool ReturnCaptures,bool StoreCaptures,const Instruction * I,const DominatorTree * DT,bool IncludeI,unsigned MaxUsesToExplore,const LoopInfo * LI)2375ca98fd9SDimitry Andric bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
2385ca98fd9SDimitry Andric                                       bool StoreCaptures, const Instruction *I,
239eb11fae6SDimitry Andric                                       const DominatorTree *DT, bool IncludeI,
240c0981da4SDimitry Andric                                       unsigned MaxUsesToExplore,
241c0981da4SDimitry Andric                                       const LoopInfo *LI) {
2425ca98fd9SDimitry Andric   assert(!isa<GlobalValue>(V) &&
2435ca98fd9SDimitry Andric          "It doesn't make sense to ask whether a global is captured.");
2445ca98fd9SDimitry Andric 
2455ca98fd9SDimitry Andric   if (!DT)
246d8e91e46SDimitry Andric     return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures,
247d8e91e46SDimitry Andric                                 MaxUsesToExplore);
2485ca98fd9SDimitry Andric 
2495ca98fd9SDimitry Andric   // TODO: See comment in PointerMayBeCaptured regarding what could be done
2505ca98fd9SDimitry Andric   // with StoreCaptures.
2515ca98fd9SDimitry Andric 
252c0981da4SDimitry Andric   CapturesBefore CB(ReturnCaptures, I, DT, IncludeI, LI);
253d8e91e46SDimitry Andric   PointerMayBeCaptured(V, &CB, MaxUsesToExplore);
254b60736ecSDimitry Andric   if (CB.Captured)
255b60736ecSDimitry Andric     ++NumCapturedBefore;
256b60736ecSDimitry Andric   else
257b60736ecSDimitry Andric     ++NumNotCapturedBefore;
2585ca98fd9SDimitry Andric   return CB.Captured;
2595ca98fd9SDimitry Andric }
2605ca98fd9SDimitry Andric 
FindEarliestCapture(const Value * V,Function & F,bool ReturnCaptures,bool StoreCaptures,const DominatorTree & DT,unsigned MaxUsesToExplore)261b1c73532SDimitry Andric Instruction *llvm::FindEarliestCapture(const Value *V, Function &F,
262b1c73532SDimitry Andric                                        bool ReturnCaptures, bool StoreCaptures,
263b1c73532SDimitry Andric                                        const DominatorTree &DT,
264c0981da4SDimitry Andric                                        unsigned MaxUsesToExplore) {
265c0981da4SDimitry Andric   assert(!isa<GlobalValue>(V) &&
266c0981da4SDimitry Andric          "It doesn't make sense to ask whether a global is captured.");
267c0981da4SDimitry Andric 
268b1c73532SDimitry Andric   EarliestCaptures CB(ReturnCaptures, F, DT);
269c0981da4SDimitry Andric   PointerMayBeCaptured(V, &CB, MaxUsesToExplore);
270c0981da4SDimitry Andric   if (CB.Captured)
271c0981da4SDimitry Andric     ++NumCapturedBefore;
272c0981da4SDimitry Andric   else
273c0981da4SDimitry Andric     ++NumNotCapturedBefore;
274c0981da4SDimitry Andric   return CB.EarliestCapture;
275c0981da4SDimitry Andric }
276c0981da4SDimitry Andric 
DetermineUseCaptureKind(const Use & U,function_ref<bool (Value *,const DataLayout &)> IsDereferenceableOrNull)277145449b1SDimitry Andric UseCaptureKind llvm::DetermineUseCaptureKind(
278145449b1SDimitry Andric     const Use &U,
279145449b1SDimitry Andric     function_ref<bool(Value *, const DataLayout &)> IsDereferenceableOrNull) {
280b1c73532SDimitry Andric   Instruction *I = dyn_cast<Instruction>(U.getUser());
281b1c73532SDimitry Andric 
282b1c73532SDimitry Andric   // TODO: Investigate non-instruction uses.
283b1c73532SDimitry Andric   if (!I)
284b1c73532SDimitry Andric     return UseCaptureKind::MAY_CAPTURE;
285145449b1SDimitry Andric 
286145449b1SDimitry Andric   switch (I->getOpcode()) {
287145449b1SDimitry Andric   case Instruction::Call:
288145449b1SDimitry Andric   case Instruction::Invoke: {
289145449b1SDimitry Andric     auto *Call = cast<CallBase>(I);
290145449b1SDimitry Andric     // Not captured if the callee is readonly, doesn't return a copy through
291145449b1SDimitry Andric     // its return value and doesn't unwind (a readonly function can leak bits
292145449b1SDimitry Andric     // by throwing an exception or not depending on the input value).
293145449b1SDimitry Andric     if (Call->onlyReadsMemory() && Call->doesNotThrow() &&
294145449b1SDimitry Andric         Call->getType()->isVoidTy())
295145449b1SDimitry Andric       return UseCaptureKind::NO_CAPTURE;
296145449b1SDimitry Andric 
297145449b1SDimitry Andric     // The pointer is not captured if returned pointer is not captured.
298145449b1SDimitry Andric     // NOTE: CaptureTracking users should not assume that only functions
299145449b1SDimitry Andric     // marked with nocapture do not capture. This means that places like
300145449b1SDimitry Andric     // getUnderlyingObject in ValueTracking or DecomposeGEPExpression
301145449b1SDimitry Andric     // in BasicAA also need to know about this property.
302145449b1SDimitry Andric     if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call, true))
303145449b1SDimitry Andric       return UseCaptureKind::PASSTHROUGH;
304145449b1SDimitry Andric 
305145449b1SDimitry Andric     // Volatile operations effectively capture the memory location that they
306145449b1SDimitry Andric     // load and store to.
307145449b1SDimitry Andric     if (auto *MI = dyn_cast<MemIntrinsic>(Call))
308145449b1SDimitry Andric       if (MI->isVolatile())
309145449b1SDimitry Andric         return UseCaptureKind::MAY_CAPTURE;
310145449b1SDimitry Andric 
311145449b1SDimitry Andric     // Calling a function pointer does not in itself cause the pointer to
312145449b1SDimitry Andric     // be captured.  This is a subtle point considering that (for example)
313145449b1SDimitry Andric     // the callee might return its own address.  It is analogous to saying
314145449b1SDimitry Andric     // that loading a value from a pointer does not cause the pointer to be
315145449b1SDimitry Andric     // captured, even though the loaded value might be the pointer itself
316145449b1SDimitry Andric     // (think of self-referential objects).
317145449b1SDimitry Andric     if (Call->isCallee(&U))
318145449b1SDimitry Andric       return UseCaptureKind::NO_CAPTURE;
319145449b1SDimitry Andric 
320145449b1SDimitry Andric     // Not captured if only passed via 'nocapture' arguments.
321145449b1SDimitry Andric     if (Call->isDataOperand(&U) &&
322145449b1SDimitry Andric         !Call->doesNotCapture(Call->getDataOperandNo(&U))) {
323145449b1SDimitry Andric       // The parameter is not marked 'nocapture' - captured.
324145449b1SDimitry Andric       return UseCaptureKind::MAY_CAPTURE;
325145449b1SDimitry Andric     }
326145449b1SDimitry Andric     return UseCaptureKind::NO_CAPTURE;
327145449b1SDimitry Andric   }
328145449b1SDimitry Andric   case Instruction::Load:
329145449b1SDimitry Andric     // Volatile loads make the address observable.
330145449b1SDimitry Andric     if (cast<LoadInst>(I)->isVolatile())
331145449b1SDimitry Andric       return UseCaptureKind::MAY_CAPTURE;
332145449b1SDimitry Andric     return UseCaptureKind::NO_CAPTURE;
333145449b1SDimitry Andric   case Instruction::VAArg:
334145449b1SDimitry Andric     // "va-arg" from a pointer does not cause it to be captured.
335145449b1SDimitry Andric     return UseCaptureKind::NO_CAPTURE;
336145449b1SDimitry Andric   case Instruction::Store:
337145449b1SDimitry Andric     // Stored the pointer - conservatively assume it may be captured.
338145449b1SDimitry Andric     // Volatile stores make the address observable.
339145449b1SDimitry Andric     if (U.getOperandNo() == 0 || cast<StoreInst>(I)->isVolatile())
340145449b1SDimitry Andric       return UseCaptureKind::MAY_CAPTURE;
341145449b1SDimitry Andric     return UseCaptureKind::NO_CAPTURE;
342145449b1SDimitry Andric   case Instruction::AtomicRMW: {
343145449b1SDimitry Andric     // atomicrmw conceptually includes both a load and store from
344145449b1SDimitry Andric     // the same location.
345145449b1SDimitry Andric     // As with a store, the location being accessed is not captured,
346145449b1SDimitry Andric     // but the value being stored is.
347145449b1SDimitry Andric     // Volatile stores make the address observable.
348145449b1SDimitry Andric     auto *ARMWI = cast<AtomicRMWInst>(I);
349145449b1SDimitry Andric     if (U.getOperandNo() == 1 || ARMWI->isVolatile())
350145449b1SDimitry Andric       return UseCaptureKind::MAY_CAPTURE;
351145449b1SDimitry Andric     return UseCaptureKind::NO_CAPTURE;
352145449b1SDimitry Andric   }
353145449b1SDimitry Andric   case Instruction::AtomicCmpXchg: {
354145449b1SDimitry Andric     // cmpxchg conceptually includes both a load and store from
355145449b1SDimitry Andric     // the same location.
356145449b1SDimitry Andric     // As with a store, the location being accessed is not captured,
357145449b1SDimitry Andric     // but the value being stored is.
358145449b1SDimitry Andric     // Volatile stores make the address observable.
359145449b1SDimitry Andric     auto *ACXI = cast<AtomicCmpXchgInst>(I);
360145449b1SDimitry Andric     if (U.getOperandNo() == 1 || U.getOperandNo() == 2 || ACXI->isVolatile())
361145449b1SDimitry Andric       return UseCaptureKind::MAY_CAPTURE;
362145449b1SDimitry Andric     return UseCaptureKind::NO_CAPTURE;
363145449b1SDimitry Andric   }
364145449b1SDimitry Andric   case Instruction::GetElementPtr:
365b1c73532SDimitry Andric     // AA does not support pointers of vectors, so GEP vector splats need to
366b1c73532SDimitry Andric     // be considered as captures.
367b1c73532SDimitry Andric     if (I->getType()->isVectorTy())
368b1c73532SDimitry Andric       return UseCaptureKind::MAY_CAPTURE;
369b1c73532SDimitry Andric     return UseCaptureKind::PASSTHROUGH;
370b1c73532SDimitry Andric   case Instruction::BitCast:
371145449b1SDimitry Andric   case Instruction::PHI:
372145449b1SDimitry Andric   case Instruction::Select:
373145449b1SDimitry Andric   case Instruction::AddrSpaceCast:
374145449b1SDimitry Andric     // The original value is not captured via this if the new value isn't.
375145449b1SDimitry Andric     return UseCaptureKind::PASSTHROUGH;
376145449b1SDimitry Andric   case Instruction::ICmp: {
377145449b1SDimitry Andric     unsigned Idx = U.getOperandNo();
378145449b1SDimitry Andric     unsigned OtherIdx = 1 - Idx;
379145449b1SDimitry Andric     if (auto *CPN = dyn_cast<ConstantPointerNull>(I->getOperand(OtherIdx))) {
380145449b1SDimitry Andric       // Don't count comparisons of a no-alias return value against null as
381145449b1SDimitry Andric       // captures. This allows us to ignore comparisons of malloc results
382145449b1SDimitry Andric       // with null, for example.
383145449b1SDimitry Andric       if (CPN->getType()->getAddressSpace() == 0)
384145449b1SDimitry Andric         if (isNoAliasCall(U.get()->stripPointerCasts()))
385145449b1SDimitry Andric           return UseCaptureKind::NO_CAPTURE;
386145449b1SDimitry Andric       if (!I->getFunction()->nullPointerIsDefined()) {
387145449b1SDimitry Andric         auto *O = I->getOperand(Idx)->stripPointerCastsSameRepresentation();
388145449b1SDimitry Andric         // Comparing a dereferenceable_or_null pointer against null cannot
389145449b1SDimitry Andric         // lead to pointer escapes, because if it is not null it must be a
390145449b1SDimitry Andric         // valid (in-bounds) pointer.
391ac9a064cSDimitry Andric         const DataLayout &DL = I->getDataLayout();
392145449b1SDimitry Andric         if (IsDereferenceableOrNull && IsDereferenceableOrNull(O, DL))
393145449b1SDimitry Andric           return UseCaptureKind::NO_CAPTURE;
394145449b1SDimitry Andric       }
395145449b1SDimitry Andric     }
3967fa27ce4SDimitry Andric 
397145449b1SDimitry Andric     // Otherwise, be conservative. There are crazy ways to capture pointers
398145449b1SDimitry Andric     // using comparisons.
399145449b1SDimitry Andric     return UseCaptureKind::MAY_CAPTURE;
400145449b1SDimitry Andric   }
401145449b1SDimitry Andric   default:
402145449b1SDimitry Andric     // Something else - be conservative and say it is captured.
403145449b1SDimitry Andric     return UseCaptureKind::MAY_CAPTURE;
404145449b1SDimitry Andric   }
405145449b1SDimitry Andric }
406145449b1SDimitry Andric 
PointerMayBeCaptured(const Value * V,CaptureTracker * Tracker,unsigned MaxUsesToExplore)407d8e91e46SDimitry Andric void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker,
408d8e91e46SDimitry Andric                                 unsigned MaxUsesToExplore) {
40967a71b31SRoman Divacky   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
410cfca06d7SDimitry Andric   if (MaxUsesToExplore == 0)
411cfca06d7SDimitry Andric     MaxUsesToExplore = DefaultMaxUsesToExplore;
412cfca06d7SDimitry Andric 
413cfca06d7SDimitry Andric   SmallVector<const Use *, 20> Worklist;
414cfca06d7SDimitry Andric   Worklist.reserve(getDefaultMaxUsesToExploreForCaptureTracking());
415cfca06d7SDimitry Andric   SmallSet<const Use *, 20> Visited;
416009b1c42SEd Schouten 
417eb11fae6SDimitry Andric   auto AddUses = [&](const Value *V) {
4185ca98fd9SDimitry Andric     for (const Use &U : V->uses()) {
419571945e6SRoman Divacky       // If there are lots of uses, conservatively say that the value
420571945e6SRoman Divacky       // is captured to avoid taking too much compile time.
421145449b1SDimitry Andric       if (Visited.size()  >= MaxUsesToExplore) {
422b60736ecSDimitry Andric         Tracker->tooManyUses();
423b60736ecSDimitry Andric         return false;
424b60736ecSDimitry Andric       }
425eb11fae6SDimitry Andric       if (!Visited.insert(&U).second)
426eb11fae6SDimitry Andric         continue;
427eb11fae6SDimitry Andric       if (!Tracker->shouldExplore(&U))
428eb11fae6SDimitry Andric         continue;
4295ca98fd9SDimitry Andric       Worklist.push_back(&U);
430009b1c42SEd Schouten     }
431b60736ecSDimitry Andric     return true;
432eb11fae6SDimitry Andric   };
433b60736ecSDimitry Andric   if (!AddUses(V))
434b60736ecSDimitry Andric     return;
435009b1c42SEd Schouten 
436145449b1SDimitry Andric   auto IsDereferenceableOrNull = [Tracker](Value *V, const DataLayout &DL) {
437145449b1SDimitry Andric     return Tracker->isDereferenceableOrNull(V, DL);
438145449b1SDimitry Andric   };
439009b1c42SEd Schouten   while (!Worklist.empty()) {
4405ca98fd9SDimitry Andric     const Use *U = Worklist.pop_back_val();
441145449b1SDimitry Andric     switch (DetermineUseCaptureKind(*U, IsDereferenceableOrNull)) {
442145449b1SDimitry Andric     case UseCaptureKind::NO_CAPTURE:
443145449b1SDimitry Andric       continue;
444145449b1SDimitry Andric     case UseCaptureKind::MAY_CAPTURE:
44501095a5dSDimitry Andric       if (Tracker->captured(U))
44601095a5dSDimitry Andric         return;
447145449b1SDimitry Andric       continue;
448145449b1SDimitry Andric     case UseCaptureKind::PASSTHROUGH:
449145449b1SDimitry Andric       if (!AddUses(U->getUser()))
45063faed5bSDimitry Andric         return;
451145449b1SDimitry Andric       continue;
452009b1c42SEd Schouten     }
453009b1c42SEd Schouten   }
454009b1c42SEd Schouten 
45563faed5bSDimitry Andric   // All uses examined.
456009b1c42SEd Schouten }
457b60736ecSDimitry Andric 
isNonEscapingLocalObject(const Value * V,SmallDenseMap<const Value *,bool,8> * IsCapturedCache)458b60736ecSDimitry Andric bool llvm::isNonEscapingLocalObject(
459b60736ecSDimitry Andric     const Value *V, SmallDenseMap<const Value *, bool, 8> *IsCapturedCache) {
460b60736ecSDimitry Andric   SmallDenseMap<const Value *, bool, 8>::iterator CacheIt;
461b60736ecSDimitry Andric   if (IsCapturedCache) {
462b60736ecSDimitry Andric     bool Inserted;
463b60736ecSDimitry Andric     std::tie(CacheIt, Inserted) = IsCapturedCache->insert({V, false});
464b60736ecSDimitry Andric     if (!Inserted)
465b60736ecSDimitry Andric       // Found cached result, return it!
466b60736ecSDimitry Andric       return CacheIt->second;
467b60736ecSDimitry Andric   }
468b60736ecSDimitry Andric 
469344a3780SDimitry Andric   // If this is an identified function-local object, check to see if it escapes.
470344a3780SDimitry Andric   if (isIdentifiedFunctionLocal(V)) {
471b60736ecSDimitry Andric     // Set StoreCaptures to True so that we can assume in our callers that the
472b60736ecSDimitry Andric     // pointer is not the result of a load instruction. Currently
473b60736ecSDimitry Andric     // PointerMayBeCaptured doesn't have any special analysis for the
474b60736ecSDimitry Andric     // StoreCaptures=false case; if it did, our callers could be refined to be
475b60736ecSDimitry Andric     // more precise.
476b60736ecSDimitry Andric     auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
477b60736ecSDimitry Andric     if (IsCapturedCache)
478b60736ecSDimitry Andric       CacheIt->second = Ret;
479b60736ecSDimitry Andric     return Ret;
480b60736ecSDimitry Andric   }
481b60736ecSDimitry Andric 
482b60736ecSDimitry Andric   return false;
483b60736ecSDimitry Andric }
484