LLVM 24.0.0git
IntrusiveRefCntPtr.h
Go to the documentation of this file.
1//==- llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer --*- 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/// \file
10/// This file defines the RefCountedBase, ThreadSafeRefCountedBase, and
11/// IntrusiveRefCntPtr classes.
12///
13/// IntrusiveRefCntPtr is a smart pointer to an object which maintains a
14/// reference count. (ThreadSafe)RefCountedBase is a mixin class that adds a
15/// refcount member variable and methods for updating the refcount. An object
16/// that inherits from (ThreadSafe)RefCountedBase deletes itself when its
17/// refcount hits zero.
18///
19/// For example:
20///
21/// ```
22/// class MyClass : public RefCountedBase<MyClass> {};
23///
24/// void foo() {
25/// // Constructing an IntrusiveRefCntPtr increases the pointee's refcount
26/// // by 1 (from 0 in this case).
27/// IntrusiveRefCntPtr<MyClass> Ptr1(new MyClass());
28///
29/// // Copying an IntrusiveRefCntPtr increases the pointee's refcount by 1.
30/// IntrusiveRefCntPtr<MyClass> Ptr2(Ptr1);
31///
32/// // Constructing an IntrusiveRefCntPtr has no effect on the object's
33/// // refcount. After a move, the moved-from pointer is null.
34/// IntrusiveRefCntPtr<MyClass> Ptr3(std::move(Ptr1));
35/// assert(Ptr1 == nullptr);
36///
37/// // Clearing an IntrusiveRefCntPtr decreases the pointee's refcount by 1.
38/// Ptr2.reset();
39///
40/// // The object deletes itself when we return from the function, because
41/// // Ptr3's destructor decrements its refcount to 0.
42/// }
43/// ```
44///
45/// You can use IntrusiveRefCntPtr with isa<T>(), dyn_cast<T>(), etc.:
46///
47/// ```
48/// IntrusiveRefCntPtr<MyClass> Ptr(new MyClass());
49/// OtherClass *Other = dyn_cast<OtherClass>(Ptr); // Ptr.get() not required
50/// ```
51///
52/// IntrusiveRefCntPtr works with any class that
53///
54/// - inherits from (ThreadSafe)RefCountedBase,
55/// - has Retain() and Release() methods, or
56/// - specializes IntrusiveRefCntPtrInfo.
57///
58//===----------------------------------------------------------------------===//
59
60#ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H
61#define LLVM_ADT_INTRUSIVEREFCNTPTR_H
62
64#include <atomic>
65#include <cassert>
66#include <cstddef>
67#include <memory>
68
69namespace llvm {
70
71/// A CRTP mixin class that adds reference counting to a type.
72///
73/// The lifetime of an object which inherits from RefCountedBase is managed by
74/// calls to Release() and Retain(), which increment and decrement the object's
75/// refcount, respectively. When a Release() call decrements the refcount to 0,
76/// the object deletes itself.
77template <class Derived> class RefCountedBase {
78 mutable unsigned RefCount = 0;
79
80protected:
81 RefCountedBase() = default;
84
85#ifndef NDEBUG
87 assert(RefCount == 0 &&
88 "Destruction occurred when there are still references to this.");
89 }
90#else
91 // Default the destructor in release builds, A trivial destructor may enable
92 // better codegen.
93 ~RefCountedBase() = default;
94#endif
95
96public:
97 unsigned UseCount() const { return RefCount; }
98
99 void Retain() const { ++RefCount; }
100
101 void Release() const {
102 assert(RefCount > 0 && "Reference count is already zero.");
103 if (--RefCount == 0)
104 delete static_cast<const Derived *>(this);
105 }
106};
107
108/// A thread-safe version of \c RefCountedBase.
109template <class Derived> class ThreadSafeRefCountedBase {
110 mutable std::atomic<int> RefCount{0};
111
112protected:
117
118#ifndef NDEBUG
120 assert(RefCount == 0 &&
121 "Destruction occurred when there are still references to this.");
122 }
123#else
124 // Default the destructor in release builds, A trivial destructor may enable
125 // better codegen.
126 ~ThreadSafeRefCountedBase() = default;
127#endif
128
129public:
130 unsigned UseCount() const { return RefCount.load(std::memory_order_relaxed); }
131
132 void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); }
133
134 void Release() const {
135 int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1;
136 assert(NewRefCount >= 0 && "Reference count was already zero.");
137 if (NewRefCount == 0)
138 delete static_cast<const Derived *>(this);
139 }
140};
141
142/// Class you can specialize to provide custom retain/release functionality for
143/// a type.
144///
145/// Usually specializing this class is not necessary, as IntrusiveRefCntPtr
146/// works with any type which defines Retain() and Release() functions -- you
147/// can define those functions yourself if RefCountedBase doesn't work for you.
148///
149/// One case when you might want to specialize this type is if you have
150/// - Foo.h defines type Foo and includes Bar.h, and
151/// - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions.
152///
153/// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in
154/// the declaration of Foo. Without the declaration of Foo, normally Bar.h
155/// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call
156/// T::Retain and T::Release.
157///
158/// To resolve this, Bar.h could include a third header, FooFwd.h, which
159/// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>. Then
160/// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any
161/// functions on Foo itself, because Foo would be an incomplete type.
162template <typename T> struct IntrusiveRefCntPtrInfo {
163 static unsigned useCount(const T *obj) { return obj->UseCount(); }
164 static void retain(T *obj) { obj->Retain(); }
165 static void release(T *obj) { obj->Release(); }
166};
167
168/// A smart pointer to a reference-counted object that inherits from
169/// RefCountedBase or ThreadSafeRefCountedBase.
170///
171/// This class increments its pointee's reference count when it is created, and
172/// decrements its refcount when it's destroyed (or is changed to point to a
173/// different object).
175 T *Obj = nullptr;
176
177public:
179
180 explicit IntrusiveRefCntPtr() = default;
181 IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); }
182 IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); }
183 IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; }
184
185 template <class X,
186 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
188 S.Obj = nullptr;
189 }
190
191 template <class X,
192 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
193 IntrusiveRefCntPtr(std::unique_ptr<X> S) : Obj(S.release()) {
194 retain();
195 }
196
197 ~IntrusiveRefCntPtr() { release(); }
198
200 swap(S);
201 return *this;
202 }
203
204 T &operator*() const { return *Obj; }
205 T *operator->() const { return Obj; }
206 T *get() const { return Obj; }
207 explicit operator bool() const { return Obj; }
208
210 T *tmp = other.Obj;
211 other.Obj = Obj;
212 Obj = tmp;
213 }
214
215 void reset() {
216 release();
217 Obj = nullptr;
218 }
219
220 void resetWithoutRelease() { Obj = nullptr; }
221
222 unsigned useCount() const {
223 return Obj ? IntrusiveRefCntPtrInfo<T>::useCount(Obj) : 0;
224 }
225
226private:
227 void retain() {
228 if (Obj)
230 }
231
232 void release() {
233 if (Obj)
234 IntrusiveRefCntPtrInfo<T>::release(Obj);
235 }
236
237 template <typename X> friend class IntrusiveRefCntPtr;
238};
239
240template <class T, class U>
242 const IntrusiveRefCntPtr<U> &B) {
243 return A.get() == B.get();
244}
245
246template <class T, class U>
248 const IntrusiveRefCntPtr<U> &B) {
249 return A.get() != B.get();
250}
251
252template <class T, class U>
253inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
254 return A.get() == B;
255}
256
257template <class T, class U>
258inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
259 return A.get() != B;
260}
261
262template <class T, class U>
263inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
264 return A == B.get();
265}
266
267template <class T, class U>
268inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
269 return A != B.get();
270}
271
272template <class T>
273bool operator==(std::nullptr_t, const IntrusiveRefCntPtr<T> &B) {
274 return !B;
275}
276
277template <class T>
278bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
279 return B == A;
280}
281
282template <class T>
283bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
284 return !(A == B);
285}
286
287template <class T>
288bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
289 return !(A == B);
290}
291
292// Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
293// Casting.h.
294template <typename From> struct simplify_type;
295
296template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
297 using SimpleType = T *;
298
300 return Val.get();
301 }
302};
303
304template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
305 using SimpleType = /*const*/ T *;
306
308 return Val.get();
309 }
310};
311
312/// Factory function for creating intrusive ref counted pointers.
313template <typename T, typename... Args>
315 return IntrusiveRefCntPtr<T>(new T(std::forward<Args>(A)...));
316}
317
318} // end namespace llvm
319
320#endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ATTRIBUTE_WARN_UNUSED
Definition Compiler.h:244
#define T
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
IntrusiveRefCntPtr & operator=(IntrusiveRefCntPtr S)
IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S)
IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S)
IntrusiveRefCntPtr(std::unique_ptr< X > S)
IntrusiveRefCntPtr(IntrusiveRefCntPtr< X > S)
RefCountedBase(const RefCountedBase &)
RefCountedBase & operator=(const RefCountedBase &)=delete
unsigned UseCount() const
RefCountedBase()=default
A thread-safe version of RefCountedBase.
ThreadSafeRefCountedBase(const ThreadSafeRefCountedBase &)
ThreadSafeRefCountedBase & operator=(const ThreadSafeRefCountedBase &)=delete
This is an optimization pass for GlobalISel generic memory operations.
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2144
IntrusiveRefCntPtr< T > makeIntrusiveRefCnt(Args &&...A)
Factory function for creating intrusive ref counted pointers.
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
Class you can specialize to provide custom retain/release functionality for a type.
static unsigned useCount(const T *obj)
static SimpleType getSimplifiedValue(IntrusiveRefCntPtr< T > &Val)
static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr< T > &Val)
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34