IntrusiveRefCntPtr.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //==- llvm/ADT/IntrusiveRefCntPtr.h - Smart Refcounting Pointer --*- C++ -*-==//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file defines the RefCountedBase, ThreadSafeRefCountedBase, and
  16. /// IntrusiveRefCntPtr classes.
  17. ///
  18. /// IntrusiveRefCntPtr is a smart pointer to an object which maintains a
  19. /// reference count. (ThreadSafe)RefCountedBase is a mixin class that adds a
  20. /// refcount member variable and methods for updating the refcount. An object
  21. /// that inherits from (ThreadSafe)RefCountedBase deletes itself when its
  22. /// refcount hits zero.
  23. ///
  24. /// For example:
  25. ///
  26. /// ```
  27. /// class MyClass : public RefCountedBase<MyClass> {};
  28. ///
  29. /// void foo() {
  30. /// // Constructing an IntrusiveRefCntPtr increases the pointee's refcount
  31. /// // by 1 (from 0 in this case).
  32. /// IntrusiveRefCntPtr<MyClass> Ptr1(new MyClass());
  33. ///
  34. /// // Copying an IntrusiveRefCntPtr increases the pointee's refcount by 1.
  35. /// IntrusiveRefCntPtr<MyClass> Ptr2(Ptr1);
  36. ///
  37. /// // Constructing an IntrusiveRefCntPtr has no effect on the object's
  38. /// // refcount. After a move, the moved-from pointer is null.
  39. /// IntrusiveRefCntPtr<MyClass> Ptr3(std::move(Ptr1));
  40. /// assert(Ptr1 == nullptr);
  41. ///
  42. /// // Clearing an IntrusiveRefCntPtr decreases the pointee's refcount by 1.
  43. /// Ptr2.reset();
  44. ///
  45. /// // The object deletes itself when we return from the function, because
  46. /// // Ptr3's destructor decrements its refcount to 0.
  47. /// }
  48. /// ```
  49. ///
  50. /// You can use IntrusiveRefCntPtr with isa<T>(), dyn_cast<T>(), etc.:
  51. ///
  52. /// ```
  53. /// IntrusiveRefCntPtr<MyClass> Ptr(new MyClass());
  54. /// OtherClass *Other = dyn_cast<OtherClass>(Ptr); // Ptr.get() not required
  55. /// ```
  56. ///
  57. /// IntrusiveRefCntPtr works with any class that
  58. ///
  59. /// - inherits from (ThreadSafe)RefCountedBase,
  60. /// - has Retain() and Release() methods, or
  61. /// - specializes IntrusiveRefCntPtrInfo.
  62. ///
  63. //===----------------------------------------------------------------------===//
  64. #ifndef LLVM_ADT_INTRUSIVEREFCNTPTR_H
  65. #define LLVM_ADT_INTRUSIVEREFCNTPTR_H
  66. #include <atomic>
  67. #include <cassert>
  68. #include <cstddef>
  69. #include <memory>
  70. namespace llvm {
  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.
  77. template <class Derived> class RefCountedBase {
  78. mutable unsigned RefCount = 0;
  79. protected:
  80. RefCountedBase() = default;
  81. RefCountedBase(const RefCountedBase &) {}
  82. RefCountedBase &operator=(const RefCountedBase &) = delete;
  83. #ifndef NDEBUG
  84. ~RefCountedBase() {
  85. assert(RefCount == 0 &&
  86. "Destruction occurred when there are still references to this.");
  87. }
  88. #else
  89. // Default the destructor in release builds, A trivial destructor may enable
  90. // better codegen.
  91. ~RefCountedBase() = default;
  92. #endif
  93. public:
  94. void Retain() const { ++RefCount; }
  95. void Release() const {
  96. assert(RefCount > 0 && "Reference count is already zero.");
  97. if (--RefCount == 0)
  98. delete static_cast<const Derived *>(this);
  99. }
  100. };
  101. /// A thread-safe version of \c RefCountedBase.
  102. template <class Derived> class ThreadSafeRefCountedBase {
  103. mutable std::atomic<int> RefCount{0};
  104. protected:
  105. ThreadSafeRefCountedBase() = default;
  106. ThreadSafeRefCountedBase(const ThreadSafeRefCountedBase &) {}
  107. ThreadSafeRefCountedBase &
  108. operator=(const ThreadSafeRefCountedBase &) = delete;
  109. #ifndef NDEBUG
  110. ~ThreadSafeRefCountedBase() {
  111. assert(RefCount == 0 &&
  112. "Destruction occurred when there are still references to this.");
  113. }
  114. #else
  115. // Default the destructor in release builds, A trivial destructor may enable
  116. // better codegen.
  117. ~ThreadSafeRefCountedBase() = default;
  118. #endif
  119. public:
  120. void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); }
  121. void Release() const {
  122. int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1;
  123. assert(NewRefCount >= 0 && "Reference count was already zero.");
  124. if (NewRefCount == 0)
  125. delete static_cast<const Derived *>(this);
  126. }
  127. };
  128. /// Class you can specialize to provide custom retain/release functionality for
  129. /// a type.
  130. ///
  131. /// Usually specializing this class is not necessary, as IntrusiveRefCntPtr
  132. /// works with any type which defines Retain() and Release() functions -- you
  133. /// can define those functions yourself if RefCountedBase doesn't work for you.
  134. ///
  135. /// One case when you might want to specialize this type is if you have
  136. /// - Foo.h defines type Foo and includes Bar.h, and
  137. /// - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions.
  138. ///
  139. /// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in
  140. /// the declaration of Foo. Without the declaration of Foo, normally Bar.h
  141. /// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call
  142. /// T::Retain and T::Release.
  143. ///
  144. /// To resolve this, Bar.h could include a third header, FooFwd.h, which
  145. /// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>. Then
  146. /// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any
  147. /// functions on Foo itself, because Foo would be an incomplete type.
  148. template <typename T> struct IntrusiveRefCntPtrInfo {
  149. static void retain(T *obj) { obj->Retain(); }
  150. static void release(T *obj) { obj->Release(); }
  151. };
  152. /// A smart pointer to a reference-counted object that inherits from
  153. /// RefCountedBase or ThreadSafeRefCountedBase.
  154. ///
  155. /// This class increments its pointee's reference count when it is created, and
  156. /// decrements its refcount when it's destroyed (or is changed to point to a
  157. /// different object).
  158. template <typename T> class IntrusiveRefCntPtr {
  159. T *Obj = nullptr;
  160. public:
  161. using element_type = T;
  162. explicit IntrusiveRefCntPtr() = default;
  163. IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); }
  164. IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); }
  165. IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; }
  166. template <class X,
  167. std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
  168. IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> S) : Obj(S.get()) {
  169. S.Obj = nullptr;
  170. }
  171. template <class X,
  172. std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
  173. IntrusiveRefCntPtr(std::unique_ptr<X> S) : Obj(S.release()) {
  174. retain();
  175. }
  176. ~IntrusiveRefCntPtr() { release(); }
  177. IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) {
  178. swap(S);
  179. return *this;
  180. }
  181. T &operator*() const { return *Obj; }
  182. T *operator->() const { return Obj; }
  183. T *get() const { return Obj; }
  184. explicit operator bool() const { return Obj; }
  185. void swap(IntrusiveRefCntPtr &other) {
  186. T *tmp = other.Obj;
  187. other.Obj = Obj;
  188. Obj = tmp;
  189. }
  190. void reset() {
  191. release();
  192. Obj = nullptr;
  193. }
  194. void resetWithoutRelease() { Obj = nullptr; }
  195. private:
  196. void retain() {
  197. if (Obj)
  198. IntrusiveRefCntPtrInfo<T>::retain(Obj);
  199. }
  200. void release() {
  201. if (Obj)
  202. IntrusiveRefCntPtrInfo<T>::release(Obj);
  203. }
  204. template <typename X> friend class IntrusiveRefCntPtr;
  205. };
  206. template <class T, class U>
  207. inline bool operator==(const IntrusiveRefCntPtr<T> &A,
  208. const IntrusiveRefCntPtr<U> &B) {
  209. return A.get() == B.get();
  210. }
  211. template <class T, class U>
  212. inline bool operator!=(const IntrusiveRefCntPtr<T> &A,
  213. const IntrusiveRefCntPtr<U> &B) {
  214. return A.get() != B.get();
  215. }
  216. template <class T, class U>
  217. inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
  218. return A.get() == B;
  219. }
  220. template <class T, class U>
  221. inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
  222. return A.get() != B;
  223. }
  224. template <class T, class U>
  225. inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
  226. return A == B.get();
  227. }
  228. template <class T, class U>
  229. inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
  230. return A != B.get();
  231. }
  232. template <class T>
  233. bool operator==(std::nullptr_t, const IntrusiveRefCntPtr<T> &B) {
  234. return !B;
  235. }
  236. template <class T>
  237. bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
  238. return B == A;
  239. }
  240. template <class T>
  241. bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
  242. return !(A == B);
  243. }
  244. template <class T>
  245. bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
  246. return !(A == B);
  247. }
  248. // Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
  249. // Casting.h.
  250. template <typename From> struct simplify_type;
  251. template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
  252. using SimpleType = T *;
  253. static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) {
  254. return Val.get();
  255. }
  256. };
  257. template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
  258. using SimpleType = /*const*/ T *;
  259. static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) {
  260. return Val.get();
  261. }
  262. };
  263. /// Factory function for creating intrusive ref counted pointers.
  264. template <typename T, typename... Args>
  265. IntrusiveRefCntPtr<T> makeIntrusiveRefCnt(Args &&...A) {
  266. return IntrusiveRefCntPtr<T>(new T(std::forward<Args>(A)...));
  267. }
  268. } // end namespace llvm
  269. #endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H
  270. #ifdef __GNUC__
  271. #pragma GCC diagnostic pop
  272. #endif