use ArgOperand accessors
[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/Analysis/CaptureTracking.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Value.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/CallSite.h"
26 using namespace llvm;
27
28 /// As its comment mentions, PointerMayBeCaptured can be expensive.
29 /// However, it's not easy for BasicAA to cache the result, because
30 /// it's an ImmutablePass. To work around this, bound queries at a
31 /// fixed number of uses.
32 ///
33 /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
34 /// a cache. Then we can move the code from BasicAliasAnalysis into
35 /// that path, and remove this threshold.
36 static int const Threshold = 20;
37
38 /// PointerMayBeCaptured - Return true if this pointer value may be captured
39 /// by the enclosing function (which is required to exist).  This routine can
40 /// be expensive, so consider caching the results.  The boolean ReturnCaptures
41 /// specifies whether returning the value (or part of it) from the function
42 /// counts as capturing it or not.  The boolean StoreCaptures specified whether
43 /// storing the value (or part of it) into memory anywhere automatically
44 /// counts as capturing it or not.
45 bool llvm::PointerMayBeCaptured(const Value *V,
46                                 bool ReturnCaptures, bool StoreCaptures) {
47   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
48   SmallVector<Use*, Threshold> Worklist;
49   SmallSet<Use*, Threshold> Visited;
50   int Count = 0;
51
52   for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
53        UI != UE; ++UI) {
54     // If there are lots of uses, conservatively say that the value
55     // is captured to avoid taking too much compile time.
56     if (Count++ >= Threshold)
57       return true;
58
59     Use *U = &UI.getUse();
60     Visited.insert(U);
61     Worklist.push_back(U);
62   }
63
64   while (!Worklist.empty()) {
65     Use *U = Worklist.pop_back_val();
66     Instruction *I = cast<Instruction>(U->getUser());
67     V = U->get();
68
69     switch (I->getOpcode()) {
70     case Instruction::Call:
71     case Instruction::Invoke: {
72       CallSite CS = CallSite::get(I);
73       // Not captured if the callee is readonly, doesn't return a copy through
74       // its return value and doesn't unwind (a readonly function can leak bits
75       // by throwing an exception or not depending on the input value).
76       if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
77         break;
78
79       // Not captured if only passed via 'nocapture' arguments.  Note that
80       // calling a function pointer does not in itself cause the pointer to
81       // be captured.  This is a subtle point considering that (for example)
82       // the callee might return its own address.  It is analogous to saying
83       // that loading a value from a pointer does not cause the pointer to be
84       // captured, even though the loaded value might be the pointer itself
85       // (think of self-referential objects).
86       CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
87       for (CallSite::arg_iterator A = B; A != E; ++A)
88         if (A->get() == V && !CS.paramHasAttr(A - B + 1, Attribute::NoCapture))
89           // The parameter is not marked 'nocapture' - captured.
90           return true;
91       // Only passed via 'nocapture' arguments, or is the called function - not
92       // captured.
93       break;
94     }
95     case Instruction::Load:
96       // Loading from a pointer does not cause it to be captured.
97       break;
98     case Instruction::Ret:
99       if (ReturnCaptures)
100         return true;
101       break;
102     case Instruction::Store:
103       if (V == I->getOperand(0))
104         // Stored the pointer - conservatively assume it may be captured.
105         // TODO: If StoreCaptures is not true, we could do Fancy analysis
106         // to determine whether this store is not actually an escape point.
107         // In that case, BasicAliasAnalysis should be updated as well to
108         // take advantage of this.
109         return true;
110       // Storing to the pointee does not cause the pointer to be captured.
111       break;
112     case Instruction::BitCast:
113     case Instruction::GetElementPtr:
114     case Instruction::PHI:
115     case Instruction::Select:
116       // The original value is not captured via this if the new value isn't.
117       for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end();
118            UI != UE; ++UI) {
119         Use *U = &UI.getUse();
120         if (Visited.insert(U))
121           Worklist.push_back(U);
122       }
123       break;
124     case Instruction::ICmp:
125       // Don't count comparisons of a no-alias return value against null as
126       // captures. This allows us to ignore comparisons of malloc results
127       // with null, for example.
128       if (isNoAliasCall(V->stripPointerCasts()))
129         if (ConstantPointerNull *CPN =
130               dyn_cast<ConstantPointerNull>(I->getOperand(1)))
131           if (CPN->getType()->getAddressSpace() == 0)
132             break;
133       // Otherwise, be conservative. There are crazy ways to capture pointers
134       // using comparisons.
135       return true;
136     default:
137       // Something else - be conservative and say it is captured.
138       return true;
139     }
140   }
141
142   // All uses examined - not captured.
143   return false;
144 }