LLVM API Documentation

CaptureTracking.cpp
Go to the documentation of this file.
00001 //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains routines that help determine which pointers are captured.
00011 // A pointer value is captured if the function makes a copy of any part of the
00012 // pointer that outlives the call.  Not being captured means, more or less, that
00013 // the pointer is only dereferenced and not stored in a global.  Returning part
00014 // of the pointer as the function return value may or may not count as capturing
00015 // the pointer, depending on the context.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/ADT/SmallSet.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/Analysis/AliasAnalysis.h"
00022 #include "llvm/Analysis/CaptureTracking.h"
00023 #include "llvm/IR/Constants.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/Support/CallSite.h"
00026 
00027 using namespace llvm;
00028 
00029 CaptureTracker::~CaptureTracker() {}
00030 
00031 bool CaptureTracker::shouldExplore(Use *U) { return true; }
00032 
00033 namespace {
00034   struct SimpleCaptureTracker : public CaptureTracker {
00035     explicit SimpleCaptureTracker(bool ReturnCaptures)
00036       : ReturnCaptures(ReturnCaptures), Captured(false) {}
00037 
00038     void tooManyUses() { Captured = true; }
00039 
00040     bool captured(Use *U) {
00041       if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
00042         return false;
00043 
00044       Captured = true;
00045       return true;
00046     }
00047 
00048     bool ReturnCaptures;
00049 
00050     bool Captured;
00051   };
00052 }
00053 
00054 /// PointerMayBeCaptured - Return true if this pointer value may be captured
00055 /// by the enclosing function (which is required to exist).  This routine can
00056 /// be expensive, so consider caching the results.  The boolean ReturnCaptures
00057 /// specifies whether returning the value (or part of it) from the function
00058 /// counts as capturing it or not.  The boolean StoreCaptures specified whether
00059 /// storing the value (or part of it) into memory anywhere automatically
00060 /// counts as capturing it or not.
00061 bool llvm::PointerMayBeCaptured(const Value *V,
00062                                 bool ReturnCaptures, bool StoreCaptures) {
00063   assert(!isa<GlobalValue>(V) &&
00064          "It doesn't make sense to ask whether a global is captured.");
00065 
00066   // TODO: If StoreCaptures is not true, we could do Fancy analysis
00067   // to determine whether this store is not actually an escape point.
00068   // In that case, BasicAliasAnalysis should be updated as well to
00069   // take advantage of this.
00070   (void)StoreCaptures;
00071 
00072   SimpleCaptureTracker SCT(ReturnCaptures);
00073   PointerMayBeCaptured(V, &SCT);
00074   return SCT.Captured;
00075 }
00076 
00077 /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
00078 /// a cache. Then we can move the code from BasicAliasAnalysis into
00079 /// that path, and remove this threshold.
00080 static int const Threshold = 20;
00081 
00082 void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
00083   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
00084   SmallVector<Use*, Threshold> Worklist;
00085   SmallSet<Use*, Threshold> Visited;
00086   int Count = 0;
00087 
00088   for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
00089        UI != UE; ++UI) {
00090     // If there are lots of uses, conservatively say that the value
00091     // is captured to avoid taking too much compile time.
00092     if (Count++ >= Threshold)
00093       return Tracker->tooManyUses();
00094 
00095     Use *U = &UI.getUse();
00096     if (!Tracker->shouldExplore(U)) continue;
00097     Visited.insert(U);
00098     Worklist.push_back(U);
00099   }
00100 
00101   while (!Worklist.empty()) {
00102     Use *U = Worklist.pop_back_val();
00103     Instruction *I = cast<Instruction>(U->getUser());
00104     V = U->get();
00105 
00106     switch (I->getOpcode()) {
00107     case Instruction::Call:
00108     case Instruction::Invoke: {
00109       CallSite CS(I);
00110       // Not captured if the callee is readonly, doesn't return a copy through
00111       // its return value and doesn't unwind (a readonly function can leak bits
00112       // by throwing an exception or not depending on the input value).
00113       if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
00114         break;
00115 
00116       // Not captured if only passed via 'nocapture' arguments.  Note that
00117       // calling a function pointer does not in itself cause the pointer to
00118       // be captured.  This is a subtle point considering that (for example)
00119       // the callee might return its own address.  It is analogous to saying
00120       // that loading a value from a pointer does not cause the pointer to be
00121       // captured, even though the loaded value might be the pointer itself
00122       // (think of self-referential objects).
00123       CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
00124       for (CallSite::arg_iterator A = B; A != E; ++A)
00125         if (A->get() == V && !CS.doesNotCapture(A - B))
00126           // The parameter is not marked 'nocapture' - captured.
00127           if (Tracker->captured(U))
00128             return;
00129       break;
00130     }
00131     case Instruction::Load:
00132       // Loading from a pointer does not cause it to be captured.
00133       break;
00134     case Instruction::VAArg:
00135       // "va-arg" from a pointer does not cause it to be captured.
00136       break;
00137     case Instruction::Store:
00138       if (V == I->getOperand(0))
00139         // Stored the pointer - conservatively assume it may be captured.
00140         if (Tracker->captured(U))
00141           return;
00142       // Storing to the pointee does not cause the pointer to be captured.
00143       break;
00144     case Instruction::BitCast:
00145     case Instruction::GetElementPtr:
00146     case Instruction::PHI:
00147     case Instruction::Select:
00148       // The original value is not captured via this if the new value isn't.
00149       for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end();
00150            UI != UE; ++UI) {
00151         Use *U = &UI.getUse();
00152         if (Visited.insert(U))
00153           if (Tracker->shouldExplore(U))
00154             Worklist.push_back(U);
00155       }
00156       break;
00157     case Instruction::ICmp:
00158       // Don't count comparisons of a no-alias return value against null as
00159       // captures. This allows us to ignore comparisons of malloc results
00160       // with null, for example.
00161       if (isNoAliasCall(V->stripPointerCasts()))
00162         if (ConstantPointerNull *CPN =
00163               dyn_cast<ConstantPointerNull>(I->getOperand(1)))
00164           if (CPN->getType()->getAddressSpace() == 0)
00165             break;
00166       // Otherwise, be conservative. There are crazy ways to capture pointers
00167       // using comparisons.
00168       if (Tracker->captured(U))
00169         return;
00170       break;
00171     default:
00172       // Something else - be conservative and say it is captured.
00173       if (Tracker->captured(U))
00174         return;
00175       break;
00176     }
00177   }
00178 
00179   // All uses examined.
00180 }