d22b30af48911205bdd221964442adb865794d32
[oota-llvm.git] / include / llvm / Support / ValueHandle.h
1 //===- llvm/Support/ValueHandle.h - Value Smart Pointer classes -*- C++ -*-===//
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 declares the ValueHandle class and its sub-classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_SUPPORT_VALUEHANDLE_H
15 #define LLVM_SUPPORT_VALUEHANDLE_H
16
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/Value.h"
20
21 namespace llvm {
22 class ValueHandleBase;
23
24 // ValueHandleBase** is only 4-byte aligned.
25 template<>
26 class PointerLikeTypeTraits<ValueHandleBase**> {
27 public:
28   static inline void *getAsVoidPointer(ValueHandleBase** P) { return P; }
29   static inline ValueHandleBase **getFromVoidPointer(void *P) {
30     return static_cast<ValueHandleBase**>(P);
31   }
32   enum { NumLowBitsAvailable = 2 };
33 };
34
35 /// ValueHandleBase - This is the common base class of value handles.
36 /// ValueHandle's are smart pointers to Value's that have special behavior when
37 /// the value is deleted or ReplaceAllUsesWith'd.  See the specific handles
38 /// below for details.
39 ///
40 class ValueHandleBase {
41   friend class Value;
42 protected:
43   /// HandleBaseKind - This indicates what sub class the handle actually is.
44   /// This is to avoid having a vtable for the light-weight handle pointers. The
45   /// fully general Callback version does have a vtable.
46   enum HandleBaseKind {
47     Assert,
48     Callback,
49     Tracking,
50     Weak
51   };
52 private:
53
54   PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
55   ValueHandleBase *Next;
56   Value *VP;
57 public:
58   explicit ValueHandleBase(HandleBaseKind Kind)
59     : PrevPair(0, Kind), Next(0), VP(0) {}
60   ValueHandleBase(HandleBaseKind Kind, Value *V)
61     : PrevPair(0, Kind), Next(0), VP(V) {
62     if (isValid(VP))
63       AddToUseList();
64   }
65   ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
66     : PrevPair(0, Kind), Next(0), VP(RHS.VP) {
67     if (isValid(VP))
68       AddToExistingUseList(RHS.getPrevPtr());
69   }
70   ~ValueHandleBase() {
71     if (isValid(VP))
72       RemoveFromUseList();
73   }
74
75   Value *operator=(Value *RHS) {
76     if (VP == RHS) return RHS;
77     if (isValid(VP)) RemoveFromUseList();
78     VP = RHS;
79     if (isValid(VP)) AddToUseList();
80     return RHS;
81   }
82
83   Value *operator=(const ValueHandleBase &RHS) {
84     if (VP == RHS.VP) return RHS.VP;
85     if (isValid(VP)) RemoveFromUseList();
86     VP = RHS.VP;
87     if (isValid(VP)) AddToExistingUseList(RHS.getPrevPtr());
88     return VP;
89   }
90
91   Value *operator->() const { return getValPtr(); }
92   Value &operator*() const { return *getValPtr(); }
93
94 protected:
95   Value *getValPtr() const { return VP; }
96   static bool isValid(Value *V) {
97     return V &&
98            V != DenseMapInfo<Value *>::getEmptyKey() &&
99            V != DenseMapInfo<Value *>::getTombstoneKey();
100   }
101
102 private:
103   // Callbacks made from Value.
104   static void ValueIsDeleted(Value *V);
105   static void ValueIsRAUWd(Value *Old, Value *New);
106
107   // Internal implementation details.
108   ValueHandleBase **getPrevPtr() const { return PrevPair.getPointer(); }
109   HandleBaseKind getKind() const { return PrevPair.getInt(); }
110   void setPrevPtr(ValueHandleBase **Ptr) { PrevPair.setPointer(Ptr); }
111
112   /// AddToExistingUseList - Add this ValueHandle to the use list for VP,
113   /// where List is known to point into the existing use list.
114   void AddToExistingUseList(ValueHandleBase **List);
115
116   /// AddToUseList - Add this ValueHandle to the use list for VP.
117   void AddToUseList();
118   /// RemoveFromUseList - Remove this ValueHandle from its current use list.
119   void RemoveFromUseList();
120 };
121
122 /// WeakVH - This is a value handle that tries hard to point to a Value, even
123 /// across RAUW operations, but will null itself out if the value is destroyed.
124 /// this is useful for advisory sorts of information, but should not be used as
125 /// the key of a map (since the map would have to rearrange itself when the
126 /// pointer changes).
127 class WeakVH : public ValueHandleBase {
128 public:
129   WeakVH() : ValueHandleBase(Weak) {}
130   WeakVH(Value *P) : ValueHandleBase(Weak, P) {}
131   WeakVH(const WeakVH &RHS)
132     : ValueHandleBase(Weak, RHS) {}
133
134   operator Value*() const {
135     return getValPtr();
136   }
137 };
138
139 // Specialize simplify_type to allow WeakVH to participate in
140 // dyn_cast, isa, etc.
141 template<typename From> struct simplify_type;
142 template<> struct simplify_type<const WeakVH> {
143   typedef Value* SimpleType;
144   static SimpleType getSimplifiedValue(const WeakVH &WVH) {
145     return static_cast<Value *>(WVH);
146   }
147 };
148 template<> struct simplify_type<WeakVH> : public simplify_type<const WeakVH> {};
149
150 /// AssertingVH - This is a Value Handle that points to a value and asserts out
151 /// if the value is destroyed while the handle is still live.  This is very
152 /// useful for catching dangling pointer bugs and other things which can be
153 /// non-obvious.  One particularly useful place to use this is as the Key of a
154 /// map.  Dangling pointer bugs often lead to really subtle bugs that only occur
155 /// if another object happens to get allocated to the same address as the old
156 /// one.  Using an AssertingVH ensures that an assert is triggered as soon as
157 /// the bad delete occurs.
158 ///
159 /// Note that an AssertingVH handle does *not* follow values across RAUW
160 /// operations.  This means that RAUW's need to explicitly update the
161 /// AssertingVH's as it moves.  This is required because in non-assert mode this
162 /// class turns into a trivial wrapper around a pointer.
163 template <typename ValueTy>
164 class AssertingVH
165 #ifndef NDEBUG
166   : public ValueHandleBase
167 #endif
168   {
169
170 #ifndef NDEBUG
171   ValueTy *getValPtr() const {
172     return static_cast<ValueTy*>(ValueHandleBase::getValPtr());
173   }
174   void setValPtr(ValueTy *P) {
175     ValueHandleBase::operator=(GetAsValue(P));
176   }
177 #else
178   ValueTy *ThePtr;
179   ValueTy *getValPtr() const { return ThePtr; }
180   void setValPtr(ValueTy *P) { ThePtr = P; }
181 #endif
182
183   // Convert a ValueTy*, which may be const, to the type the base
184   // class expects.
185   static Value *GetAsValue(Value *V) { return V; }
186   static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
187
188 public:
189 #ifndef NDEBUG
190   AssertingVH() : ValueHandleBase(Assert) {}
191   AssertingVH(ValueTy *P) : ValueHandleBase(Assert, GetAsValue(P)) {}
192   AssertingVH(const AssertingVH &RHS) : ValueHandleBase(Assert, RHS) {}
193 #else
194   AssertingVH() : ThePtr(0) {}
195   AssertingVH(ValueTy *P) : ThePtr(P) {}
196 #endif
197
198   operator ValueTy*() const {
199     return getValPtr();
200   }
201
202   ValueTy *operator=(ValueTy *RHS) {
203     setValPtr(RHS);
204     return getValPtr();
205   }
206   ValueTy *operator=(const AssertingVH<ValueTy> &RHS) {
207     setValPtr(RHS.getValPtr());
208     return getValPtr();
209   }
210
211   ValueTy *operator->() const { return getValPtr(); }
212   ValueTy &operator*() const { return *getValPtr(); }
213 };
214
215 // Specialize simplify_type to allow AssertingVH to participate in
216 // dyn_cast, isa, etc.
217 template<typename From> struct simplify_type;
218 template<> struct simplify_type<const AssertingVH<Value> > {
219   typedef Value* SimpleType;
220   static SimpleType getSimplifiedValue(const AssertingVH<Value> &AVH) {
221     return static_cast<Value *>(AVH);
222   }
223 };
224 template<> struct simplify_type<AssertingVH<Value> >
225   : public simplify_type<const AssertingVH<Value> > {};
226
227 /// TrackingVH - This is a value handle that tracks a Value (or Value subclass),
228 /// even across RAUW operations.
229 ///
230 /// TrackingVH is designed for situations where a client needs to hold a handle
231 /// to a Value (or subclass) across some operations which may move that value,
232 /// but should never destroy it or replace it with some unacceptable type.
233 ///
234 /// It is an error to do anything with a TrackingVH whose value has been
235 /// destroyed, except to destruct it.
236 ///
237 /// It is an error to attempt to replace a value with one of a type which is
238 /// incompatible with any of its outstanding TrackingVHs.
239 template<typename ValueTy>
240 class TrackingVH : public ValueHandleBase {
241   void CheckValidity() const {
242     Value *VP = ValueHandleBase::getValPtr();
243
244     // Null is always ok.
245     if (!VP)
246         return;
247
248     // Check that this value is valid (i.e., it hasn't been deleted). We
249     // explicitly delay this check until access to avoid requiring clients to be
250     // unnecessarily careful w.r.t. destruction.
251     assert(ValueHandleBase::isValid(VP) && "Tracked Value was deleted!");
252
253     // Check that the value is a member of the correct subclass. We would like
254     // to check this property on assignment for better debugging, but we don't
255     // want to require a virtual interface on this VH. Instead we allow RAUW to
256     // replace this value with a value of an invalid type, and check it here.
257     assert(isa<ValueTy>(VP) &&
258            "Tracked Value was replaced by one with an invalid type!");
259   }
260
261   ValueTy *getValPtr() const {
262     CheckValidity();
263     return static_cast<ValueTy*>(ValueHandleBase::getValPtr());
264   }
265   void setValPtr(ValueTy *P) {
266     CheckValidity();
267     ValueHandleBase::operator=(GetAsValue(P));
268   }
269
270   // Convert a ValueTy*, which may be const, to the type the base
271   // class expects.
272   static Value *GetAsValue(Value *V) { return V; }
273   static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
274
275 public:
276   TrackingVH() : ValueHandleBase(Tracking) {}
277   TrackingVH(ValueTy *P) : ValueHandleBase(Tracking, P) {}
278   TrackingVH(const TrackingVH &RHS) : ValueHandleBase(Tracking, RHS) {}
279
280   operator ValueTy*() const {
281     return getValPtr();
282   }
283
284   ValueTy *operator=(ValueTy *RHS) {
285     setValPtr(RHS);
286     return getValPtr();
287   }
288   ValueTy *operator=(const TrackingVH<ValueTy> &RHS) {
289     setValPtr(RHS.getValPtr());
290     return getValPtr();
291   }
292
293   ValueTy *operator->() const { return getValPtr(); }
294   ValueTy &operator*() const { return *getValPtr(); }
295 };
296
297 // Specialize simplify_type to allow TrackingVH to participate in
298 // dyn_cast, isa, etc.
299 template<typename From> struct simplify_type;
300 template<> struct simplify_type<const TrackingVH<Value> > {
301   typedef Value* SimpleType;
302   static SimpleType getSimplifiedValue(const TrackingVH<Value> &AVH) {
303     return static_cast<Value *>(AVH);
304   }
305 };
306 template<> struct simplify_type<TrackingVH<Value> >
307   : public simplify_type<const TrackingVH<Value> > {};
308
309 /// CallbackVH - This is a value handle that allows subclasses to define
310 /// callbacks that run when the underlying Value has RAUW called on it or is
311 /// destroyed.  This class can be used as the key of a map, as long as the user
312 /// takes it out of the map before calling setValPtr() (since the map has to
313 /// rearrange itself when the pointer changes).  Unlike ValueHandleBase, this
314 /// class has a vtable and a virtual destructor.
315 class CallbackVH : public ValueHandleBase {
316 protected:
317   CallbackVH(const CallbackVH &RHS)
318     : ValueHandleBase(Callback, RHS) {}
319
320   virtual ~CallbackVH();
321
322   void setValPtr(Value *P) {
323     ValueHandleBase::operator=(P);
324   }
325
326 public:
327   CallbackVH() : ValueHandleBase(Callback) {}
328   CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
329
330   operator Value*() const {
331     return getValPtr();
332   }
333
334   /// Called when this->getValPtr() is destroyed, inside ~Value(), so you may
335   /// call any non-virtual Value method on getValPtr(), but no subclass methods.
336   /// If WeakVH were implemented as a CallbackVH, it would use this method to
337   /// call setValPtr(NULL).  AssertingVH would use this method to cause an
338   /// assertion failure.
339   ///
340   /// All implementations must remove the reference from this object to the
341   /// Value that's being destroyed.
342   virtual void deleted() {
343     setValPtr(NULL);
344   }
345
346   /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
347   /// _before_ any of the uses have actually been replaced.  If WeakVH were
348   /// implemented as a CallbackVH, it would use this method to call
349   /// setValPtr(new_value).  AssertingVH would do nothing in this method.
350   virtual void allUsesReplacedWith(Value *new_value) {}
351 };
352
353 // Specialize simplify_type to allow CallbackVH to participate in
354 // dyn_cast, isa, etc.
355 template<typename From> struct simplify_type;
356 template<> struct simplify_type<const CallbackVH> {
357   typedef Value* SimpleType;
358   static SimpleType getSimplifiedValue(const CallbackVH &CVH) {
359     return static_cast<Value *>(CVH);
360   }
361 };
362 template<> struct simplify_type<CallbackVH>
363   : public simplify_type<const CallbackVH> {};
364
365 } // End llvm namespace
366
367 #endif