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