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