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