[InstCombine] Signed saturation patterns
[llvm-core.git] / include / llvm / IR / ValueHandle.h
blob1135d796f7ed7def28191f78d224c03a9a3e2c13
1 //===- ValueHandle.h - Value Smart Pointer classes --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file declares the ValueHandle class and its sub-classes.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_IR_VALUEHANDLE_H
14 #define LLVM_IR_VALUEHANDLE_H
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/ADT/PointerIntPair.h"
18 #include "llvm/IR/Value.h"
19 #include "llvm/Support/Casting.h"
20 #include <cassert>
22 namespace llvm {
24 /// This is the common base class of value handles.
25 ///
26 /// ValueHandle's are smart pointers to Value's that have special behavior when
27 /// the value is deleted or ReplaceAllUsesWith'd. See the specific handles
28 /// below for details.
29 class ValueHandleBase {
30 friend class Value;
32 protected:
33 /// This indicates what sub class the handle actually is.
34 ///
35 /// This is to avoid having a vtable for the light-weight handle pointers. The
36 /// fully general Callback version does have a vtable.
37 enum HandleBaseKind { Assert, Callback, Weak, WeakTracking };
39 ValueHandleBase(const ValueHandleBase &RHS)
40 : ValueHandleBase(RHS.PrevPair.getInt(), RHS) {}
42 ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
43 : PrevPair(nullptr, Kind), Val(RHS.getValPtr()) {
44 if (isValid(getValPtr()))
45 AddToExistingUseList(RHS.getPrevPtr());
48 private:
49 PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
50 ValueHandleBase *Next = nullptr;
51 Value *Val = nullptr;
53 void setValPtr(Value *V) { Val = V; }
55 public:
56 explicit ValueHandleBase(HandleBaseKind Kind)
57 : PrevPair(nullptr, Kind) {}
58 ValueHandleBase(HandleBaseKind Kind, Value *V)
59 : PrevPair(nullptr, Kind), Val(V) {
60 if (isValid(getValPtr()))
61 AddToUseList();
64 ~ValueHandleBase() {
65 if (isValid(getValPtr()))
66 RemoveFromUseList();
69 Value *operator=(Value *RHS) {
70 if (getValPtr() == RHS)
71 return RHS;
72 if (isValid(getValPtr()))
73 RemoveFromUseList();
74 setValPtr(RHS);
75 if (isValid(getValPtr()))
76 AddToUseList();
77 return RHS;
80 Value *operator=(const ValueHandleBase &RHS) {
81 if (getValPtr() == RHS.getValPtr())
82 return RHS.getValPtr();
83 if (isValid(getValPtr()))
84 RemoveFromUseList();
85 setValPtr(RHS.getValPtr());
86 if (isValid(getValPtr()))
87 AddToExistingUseList(RHS.getPrevPtr());
88 return getValPtr();
91 Value *operator->() const { return getValPtr(); }
92 Value &operator*() const { return *getValPtr(); }
94 protected:
95 Value *getValPtr() const { return Val; }
97 static bool isValid(Value *V) {
98 return V &&
99 V != DenseMapInfo<Value *>::getEmptyKey() &&
100 V != DenseMapInfo<Value *>::getTombstoneKey();
103 /// Remove this ValueHandle from its current use list.
104 void RemoveFromUseList();
106 /// Clear the underlying pointer without clearing the use list.
108 /// This should only be used if a derived class has manually removed the
109 /// handle from the use list.
110 void clearValPtr() { setValPtr(nullptr); }
112 public:
113 // Callbacks made from Value.
114 static void ValueIsDeleted(Value *V);
115 static void ValueIsRAUWd(Value *Old, Value *New);
117 private:
118 // Internal implementation details.
119 ValueHandleBase **getPrevPtr() const { return PrevPair.getPointer(); }
120 HandleBaseKind getKind() const { return PrevPair.getInt(); }
121 void setPrevPtr(ValueHandleBase **Ptr) { PrevPair.setPointer(Ptr); }
123 /// Add this ValueHandle to the use list for V.
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);
129 /// Add this ValueHandle to the use list after Node.
130 void AddToExistingUseListAfter(ValueHandleBase *Node);
132 /// Add this ValueHandle to the use list for V.
133 void AddToUseList();
136 /// A nullable Value handle that is nullable.
138 /// This is a value handle that points to a value, and nulls itself
139 /// out if that value is deleted.
140 class WeakVH : public ValueHandleBase {
141 public:
142 WeakVH() : ValueHandleBase(Weak) {}
143 WeakVH(Value *P) : ValueHandleBase(Weak, P) {}
144 WeakVH(const WeakVH &RHS)
145 : ValueHandleBase(Weak, RHS) {}
147 WeakVH &operator=(const WeakVH &RHS) = default;
149 Value *operator=(Value *RHS) {
150 return ValueHandleBase::operator=(RHS);
152 Value *operator=(const ValueHandleBase &RHS) {
153 return ValueHandleBase::operator=(RHS);
156 operator Value*() const {
157 return getValPtr();
161 // Specialize simplify_type to allow WeakVH to participate in
162 // dyn_cast, isa, etc.
163 template <> struct simplify_type<WeakVH> {
164 using SimpleType = Value *;
166 static SimpleType getSimplifiedValue(WeakVH &WVH) { return WVH; }
168 template <> struct simplify_type<const WeakVH> {
169 using SimpleType = Value *;
171 static SimpleType getSimplifiedValue(const WeakVH &WVH) { return WVH; }
174 /// Value handle that is nullable, but tries to track the Value.
176 /// This is a value handle that tries hard to point to a Value, even across
177 /// RAUW operations, but will null itself out if the value is destroyed. this
178 /// is useful for advisory sorts of information, but should not be used as the
179 /// key of a map (since the map would have to rearrange itself when the pointer
180 /// changes).
181 class WeakTrackingVH : public ValueHandleBase {
182 public:
183 WeakTrackingVH() : ValueHandleBase(WeakTracking) {}
184 WeakTrackingVH(Value *P) : ValueHandleBase(WeakTracking, P) {}
185 WeakTrackingVH(const WeakTrackingVH &RHS)
186 : ValueHandleBase(WeakTracking, RHS) {}
188 WeakTrackingVH &operator=(const WeakTrackingVH &RHS) = default;
190 Value *operator=(Value *RHS) {
191 return ValueHandleBase::operator=(RHS);
193 Value *operator=(const ValueHandleBase &RHS) {
194 return ValueHandleBase::operator=(RHS);
197 operator Value*() const {
198 return getValPtr();
201 bool pointsToAliveValue() const {
202 return ValueHandleBase::isValid(getValPtr());
206 // Specialize simplify_type to allow WeakTrackingVH to participate in
207 // dyn_cast, isa, etc.
208 template <> struct simplify_type<WeakTrackingVH> {
209 using SimpleType = Value *;
211 static SimpleType getSimplifiedValue(WeakTrackingVH &WVH) { return WVH; }
213 template <> struct simplify_type<const WeakTrackingVH> {
214 using SimpleType = Value *;
216 static SimpleType getSimplifiedValue(const WeakTrackingVH &WVH) {
217 return WVH;
221 /// Value handle that asserts if the Value is deleted.
223 /// This is a Value Handle that points to a value and asserts out if the value
224 /// is destroyed while the handle is still live. This is very useful for
225 /// catching dangling pointer bugs and other things which can be non-obvious.
226 /// One particularly useful place to use this is as the Key of a map. Dangling
227 /// pointer bugs often lead to really subtle bugs that only occur if another
228 /// object happens to get allocated to the same address as the old one. Using
229 /// an AssertingVH ensures that an assert is triggered as soon as the bad
230 /// delete occurs.
232 /// Note that an AssertingVH handle does *not* follow values across RAUW
233 /// operations. This means that RAUW's need to explicitly update the
234 /// AssertingVH's as it moves. This is required because in non-assert mode this
235 /// class turns into a trivial wrapper around a pointer.
236 template <typename ValueTy>
237 class AssertingVH
238 #ifndef NDEBUG
239 : public ValueHandleBase
240 #endif
242 friend struct DenseMapInfo<AssertingVH<ValueTy>>;
244 #ifndef NDEBUG
245 Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
246 void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
247 #else
248 Value *ThePtr;
249 Value *getRawValPtr() const { return ThePtr; }
250 void setRawValPtr(Value *P) { ThePtr = P; }
251 #endif
252 // Convert a ValueTy*, which may be const, to the raw Value*.
253 static Value *GetAsValue(Value *V) { return V; }
254 static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
256 ValueTy *getValPtr() const { return static_cast<ValueTy *>(getRawValPtr()); }
257 void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
259 public:
260 #ifndef NDEBUG
261 AssertingVH() : ValueHandleBase(Assert) {}
262 AssertingVH(ValueTy *P) : ValueHandleBase(Assert, GetAsValue(P)) {}
263 AssertingVH(const AssertingVH &RHS) : ValueHandleBase(Assert, RHS) {}
264 #else
265 AssertingVH() : ThePtr(nullptr) {}
266 AssertingVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
267 #endif
269 operator ValueTy*() const {
270 return getValPtr();
273 ValueTy *operator=(ValueTy *RHS) {
274 setValPtr(RHS);
275 return getValPtr();
277 ValueTy *operator=(const AssertingVH<ValueTy> &RHS) {
278 setValPtr(RHS.getValPtr());
279 return getValPtr();
282 ValueTy *operator->() const { return getValPtr(); }
283 ValueTy &operator*() const { return *getValPtr(); }
286 // Specialize DenseMapInfo to allow AssertingVH to participate in DenseMap.
287 template<typename T>
288 struct DenseMapInfo<AssertingVH<T>> {
289 static inline AssertingVH<T> getEmptyKey() {
290 AssertingVH<T> Res;
291 Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
292 return Res;
295 static inline AssertingVH<T> getTombstoneKey() {
296 AssertingVH<T> Res;
297 Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
298 return Res;
301 static unsigned getHashValue(const AssertingVH<T> &Val) {
302 return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
305 static bool isEqual(const AssertingVH<T> &LHS, const AssertingVH<T> &RHS) {
306 return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
307 RHS.getRawValPtr());
311 /// Value handle that tracks a Value across RAUW.
313 /// TrackingVH is designed for situations where a client needs to hold a handle
314 /// to a Value (or subclass) across some operations which may move that value,
315 /// but should never destroy it or replace it with some unacceptable type.
317 /// It is an error to attempt to replace a value with one of a type which is
318 /// incompatible with any of its outstanding TrackingVHs.
320 /// It is an error to read from a TrackingVH that does not point to a valid
321 /// value. A TrackingVH is said to not point to a valid value if either it
322 /// hasn't yet been assigned a value yet or because the value it was tracking
323 /// has since been deleted.
325 /// Assigning a value to a TrackingVH is always allowed, even if said TrackingVH
326 /// no longer points to a valid value.
327 template <typename ValueTy> class TrackingVH {
328 WeakTrackingVH InnerHandle;
330 public:
331 ValueTy *getValPtr() const {
332 assert(InnerHandle.pointsToAliveValue() &&
333 "TrackingVH must be non-null and valid on dereference!");
335 // Check that the value is a member of the correct subclass. We would like
336 // to check this property on assignment for better debugging, but we don't
337 // want to require a virtual interface on this VH. Instead we allow RAUW to
338 // replace this value with a value of an invalid type, and check it here.
339 assert(isa<ValueTy>(InnerHandle) &&
340 "Tracked Value was replaced by one with an invalid type!");
341 return cast<ValueTy>(InnerHandle);
344 void setValPtr(ValueTy *P) {
345 // Assigning to non-valid TrackingVH's are fine so we just unconditionally
346 // assign here.
347 InnerHandle = GetAsValue(P);
350 // Convert a ValueTy*, which may be const, to the type the base
351 // class expects.
352 static Value *GetAsValue(Value *V) { return V; }
353 static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
355 public:
356 TrackingVH() = default;
357 TrackingVH(ValueTy *P) { setValPtr(P); }
359 operator ValueTy*() const {
360 return getValPtr();
363 ValueTy *operator=(ValueTy *RHS) {
364 setValPtr(RHS);
365 return getValPtr();
368 ValueTy *operator->() const { return getValPtr(); }
369 ValueTy &operator*() const { return *getValPtr(); }
372 /// Value handle with callbacks on RAUW and destruction.
374 /// This is a value handle that allows subclasses to define callbacks that run
375 /// when the underlying Value has RAUW called on it or is destroyed. This
376 /// class can be used as the key of a map, as long as the user takes it out of
377 /// the map before calling setValPtr() (since the map has to rearrange itself
378 /// when the pointer changes). Unlike ValueHandleBase, this class has a vtable.
379 class CallbackVH : public ValueHandleBase {
380 virtual void anchor();
381 protected:
382 ~CallbackVH() = default;
383 CallbackVH(const CallbackVH &) = default;
384 CallbackVH &operator=(const CallbackVH &) = default;
386 void setValPtr(Value *P) {
387 ValueHandleBase::operator=(P);
390 public:
391 CallbackVH() : ValueHandleBase(Callback) {}
392 CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
394 operator Value*() const {
395 return getValPtr();
398 /// Callback for Value destruction.
400 /// Called when this->getValPtr() is destroyed, inside ~Value(), so you
401 /// may call any non-virtual Value method on getValPtr(), but no subclass
402 /// methods. If WeakTrackingVH were implemented as a CallbackVH, it would use
403 /// this
404 /// method to call setValPtr(NULL). AssertingVH would use this method to
405 /// cause an assertion failure.
407 /// All implementations must remove the reference from this object to the
408 /// Value that's being destroyed.
409 virtual void deleted() { setValPtr(nullptr); }
411 /// Callback for Value RAUW.
413 /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
414 /// _before_ any of the uses have actually been replaced. If WeakTrackingVH
415 /// were
416 /// implemented as a CallbackVH, it would use this method to call
417 /// setValPtr(new_value). AssertingVH would do nothing in this method.
418 virtual void allUsesReplacedWith(Value *) {}
421 /// Value handle that poisons itself if the Value is deleted.
423 /// This is a Value Handle that points to a value and poisons itself if the
424 /// value is destroyed while the handle is still live. This is very useful for
425 /// catching dangling pointer bugs where an \c AssertingVH cannot be used
426 /// because the dangling handle needs to outlive the value without ever being
427 /// used.
429 /// One particularly useful place to use this is as the Key of a map. Dangling
430 /// pointer bugs often lead to really subtle bugs that only occur if another
431 /// object happens to get allocated to the same address as the old one. Using
432 /// a PoisoningVH ensures that an assert is triggered if looking up a new value
433 /// in the map finds a handle from the old value.
435 /// Note that a PoisoningVH handle does *not* follow values across RAUW
436 /// operations. This means that RAUW's need to explicitly update the
437 /// PoisoningVH's as it moves. This is required because in non-assert mode this
438 /// class turns into a trivial wrapper around a pointer.
439 template <typename ValueTy>
440 class PoisoningVH
441 #ifndef NDEBUG
442 final : public CallbackVH
443 #endif
445 friend struct DenseMapInfo<PoisoningVH<ValueTy>>;
447 // Convert a ValueTy*, which may be const, to the raw Value*.
448 static Value *GetAsValue(Value *V) { return V; }
449 static Value *GetAsValue(const Value *V) { return const_cast<Value *>(V); }
451 #ifndef NDEBUG
452 /// A flag tracking whether this value has been poisoned.
454 /// On delete and RAUW, we leave the value pointer alone so that as a raw
455 /// pointer it produces the same value (and we fit into the same key of
456 /// a hash table, etc), but we poison the handle so that any top-level usage
457 /// will fail.
458 bool Poisoned = false;
460 Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
461 void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
463 /// Handle deletion by poisoning the handle.
464 void deleted() override {
465 assert(!Poisoned && "Tried to delete an already poisoned handle!");
466 Poisoned = true;
467 RemoveFromUseList();
470 /// Handle RAUW by poisoning the handle.
471 void allUsesReplacedWith(Value *) override {
472 assert(!Poisoned && "Tried to RAUW an already poisoned handle!");
473 Poisoned = true;
474 RemoveFromUseList();
476 #else // NDEBUG
477 Value *ThePtr = nullptr;
479 Value *getRawValPtr() const { return ThePtr; }
480 void setRawValPtr(Value *P) { ThePtr = P; }
481 #endif
483 ValueTy *getValPtr() const {
484 assert(!Poisoned && "Accessed a poisoned value handle!");
485 return static_cast<ValueTy *>(getRawValPtr());
487 void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
489 public:
490 PoisoningVH() = default;
491 #ifndef NDEBUG
492 PoisoningVH(ValueTy *P) : CallbackVH(GetAsValue(P)) {}
493 PoisoningVH(const PoisoningVH &RHS)
494 : CallbackVH(RHS), Poisoned(RHS.Poisoned) {}
496 ~PoisoningVH() {
497 if (Poisoned)
498 clearValPtr();
501 PoisoningVH &operator=(const PoisoningVH &RHS) {
502 if (Poisoned)
503 clearValPtr();
504 CallbackVH::operator=(RHS);
505 Poisoned = RHS.Poisoned;
506 return *this;
508 #else
509 PoisoningVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
510 #endif
512 operator ValueTy *() const { return getValPtr(); }
514 ValueTy *operator->() const { return getValPtr(); }
515 ValueTy &operator*() const { return *getValPtr(); }
518 // Specialize DenseMapInfo to allow PoisoningVH to participate in DenseMap.
519 template <typename T> struct DenseMapInfo<PoisoningVH<T>> {
520 static inline PoisoningVH<T> getEmptyKey() {
521 PoisoningVH<T> Res;
522 Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
523 return Res;
526 static inline PoisoningVH<T> getTombstoneKey() {
527 PoisoningVH<T> Res;
528 Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
529 return Res;
532 static unsigned getHashValue(const PoisoningVH<T> &Val) {
533 return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
536 static bool isEqual(const PoisoningVH<T> &LHS, const PoisoningVH<T> &RHS) {
537 return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
538 RHS.getRawValPtr());
542 } // end namespace llvm
544 #endif // LLVM_IR_VALUEHANDLE_H