Bug 1456906 [wpt PR 10641] - Subtract scrollbar in PerpendicularContainingBlockLogica...
[gecko.git] / mfbt / RefCounted.h
blob215bf0729de834fdec0c4c3579bf7f69f257ac7b
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /* CRTP refcounting templates. Do not use unless you are an Expert. */
9 #ifndef mozilla_RefCounted_h
10 #define mozilla_RefCounted_h
12 #include "mozilla/AlreadyAddRefed.h"
13 #include "mozilla/Assertions.h"
14 #include "mozilla/Atomics.h"
15 #include "mozilla/Attributes.h"
16 #include "mozilla/Move.h"
17 #include "mozilla/RefCountType.h"
18 #include "mozilla/TypeTraits.h"
20 #include <atomic>
22 #if defined(MOZILLA_INTERNAL_API)
23 #include "nsXPCOM.h"
24 #endif
26 #if defined(MOZILLA_INTERNAL_API) && \
27 (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
28 #define MOZ_REFCOUNTED_LEAK_CHECKING
29 #endif
31 namespace mozilla {
33 /**
34 * RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
35 * manages, well, refcounting for T, and because RefCounted is
36 * parameterized on T, RefCounted<T> can call T's destructor directly.
37 * This means T doesn't need to have a virtual dtor and so doesn't
38 * need a vtable.
40 * RefCounted<T> is created with refcount == 0. Newly-allocated
41 * RefCounted<T> must immediately be assigned to a RefPtr to make the
42 * refcount > 0. It's an error to allocate and free a bare
43 * RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
44 * do so will abort DEBUG builds.
46 * Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
47 * live RefCounted<T> are controlled by RefPtr<T> and
48 * RefPtr<super/subclass of T>. Upon a transition from refcounted==1
49 * to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
50 * state is represented in DEBUG builds by refcount==0xffffdead. This
51 * state distinguishes use-before-ref (refcount==0) from
52 * use-after-destroy (refcount==0xffffdead).
54 * Note that when deriving from RefCounted or AtomicRefCounted, you
55 * should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
56 * section of your class, where ClassName is the name of your class.
58 * Note: SpiderMonkey should use js::RefCounted instead since that type
59 * will use appropriate js_delete and also not break ref-count logging.
61 namespace detail {
62 const MozRefCountType DEAD = 0xffffdead;
64 // When building code that gets compiled into Gecko, try to use the
65 // trace-refcount leak logging facilities.
66 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
67 class RefCountLogger
69 public:
70 static void logAddRef(const void* aPointer, MozRefCountType aRefCount,
71 const char* aTypeName, uint32_t aInstanceSize)
73 MOZ_ASSERT(aRefCount != DEAD);
74 NS_LogAddRef(const_cast<void*>(aPointer), aRefCount, aTypeName,
75 aInstanceSize);
78 static void logRelease(const void* aPointer, MozRefCountType aRefCount,
79 const char* aTypeName)
81 MOZ_ASSERT(aRefCount != DEAD);
82 NS_LogRelease(const_cast<void*>(aPointer), aRefCount, aTypeName);
85 #endif
87 // This is used WeakPtr.h as well as this file.
88 enum RefCountAtomicity
90 AtomicRefCount,
91 NonAtomicRefCount
94 template<typename T, RefCountAtomicity Atomicity>
95 class RC
97 public:
98 explicit RC(T aCount) : mValue(aCount) {}
100 T operator++() { return ++mValue; }
101 T operator--() { return --mValue; }
103 void operator=(const T& aValue) { mValue = aValue; }
105 operator T() const { return mValue; }
107 private:
108 T mValue;
111 template<typename T>
112 class RC<T, AtomicRefCount>
114 public:
115 explicit RC(T aCount) : mValue(aCount) {}
117 T operator++()
119 // Memory synchronization is not required when incrementing a
120 // reference count. The first increment of a reference count on a
121 // thread is not important, since the first use of the object on a
122 // thread can happen before it. What is important is the transfer
123 // of the pointer to that thread, which may happen prior to the
124 // first increment on that thread. The necessary memory
125 // synchronization is done by the mechanism that transfers the
126 // pointer between threads.
127 return mValue.fetch_add(1, std::memory_order_relaxed) + 1;
130 T operator--()
132 // Since this may be the last release on this thread, we need
133 // release semantics so that prior writes on this thread are visible
134 // to the thread that destroys the object when it reads mValue with
135 // acquire semantics.
136 T result = mValue.fetch_sub(1, std::memory_order_release) - 1;
137 if (result == 0) {
138 // We're going to destroy the object on this thread, so we need
139 // acquire semantics to synchronize with the memory released by
140 // the last release on other threads, that is, to ensure that
141 // writes prior to that release are now visible on this thread.
142 std::atomic_thread_fence(std::memory_order_acquire);
144 return result;
147 // This method is only called in debug builds, so we're not too concerned
148 // about its performance.
149 void operator=(const T& aValue) { mValue.store(aValue, std::memory_order_seq_cst); }
151 operator T() const
153 // Use acquire semantics since we're not sure what the caller is
154 // doing.
155 return mValue.load(std::memory_order_acquire);
158 private:
159 std::atomic<T> mValue;
162 template<typename T, RefCountAtomicity Atomicity>
163 class RefCounted
165 protected:
166 RefCounted() : mRefCnt(0) {}
167 ~RefCounted() { MOZ_ASSERT(mRefCnt == detail::DEAD); }
169 public:
170 // Compatibility with nsRefPtr.
171 void AddRef() const
173 // Note: this method must be thread safe for AtomicRefCounted.
174 MOZ_ASSERT(int32_t(mRefCnt) >= 0);
175 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
176 ++mRefCnt;
177 #else
178 const char* type = static_cast<const T*>(this)->typeName();
179 uint32_t size = static_cast<const T*>(this)->typeSize();
180 const void* ptr = static_cast<const T*>(this);
181 MozRefCountType cnt = ++mRefCnt;
182 detail::RefCountLogger::logAddRef(ptr, cnt, type, size);
183 #endif
186 void Release() const
188 // Note: this method must be thread safe for AtomicRefCounted.
189 MOZ_ASSERT(int32_t(mRefCnt) > 0);
190 #ifndef MOZ_REFCOUNTED_LEAK_CHECKING
191 MozRefCountType cnt = --mRefCnt;
192 #else
193 const char* type = static_cast<const T*>(this)->typeName();
194 const void* ptr = static_cast<const T*>(this);
195 MozRefCountType cnt = --mRefCnt;
196 // Note: it's not safe to touch |this| after decrementing the refcount,
197 // except for below.
198 detail::RefCountLogger::logRelease(ptr, cnt, type);
199 #endif
200 if (0 == cnt) {
201 // Because we have atomically decremented the refcount above, only
202 // one thread can get a 0 count here, so as long as we can assume that
203 // everything else in the system is accessing this object through
204 // RefPtrs, it's safe to access |this| here.
205 #ifdef DEBUG
206 mRefCnt = detail::DEAD;
207 #endif
208 delete static_cast<const T*>(this);
212 // Compatibility with wtf::RefPtr.
213 void ref() { AddRef(); }
214 void deref() { Release(); }
215 MozRefCountType refCount() const { return mRefCnt; }
216 bool hasOneRef() const
218 MOZ_ASSERT(mRefCnt > 0);
219 return mRefCnt == 1;
222 private:
223 mutable RC<MozRefCountType, Atomicity> mRefCnt;
226 #ifdef MOZ_REFCOUNTED_LEAK_CHECKING
227 // Passing override for the optional argument marks the typeName and
228 // typeSize functions defined by this macro as overrides.
229 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...) \
230 virtual const char* typeName() const __VA_ARGS__ { return #T; } \
231 virtual size_t typeSize() const __VA_ARGS__ { return sizeof(*this); }
232 #else
233 #define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T, ...)
234 #endif
236 // Note that this macro is expanded unconditionally because it declares only
237 // two small inline functions which will hopefully get eliminated by the linker
238 // in non-leak-checking builds.
239 #define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
240 const char* typeName() const { return #T; } \
241 size_t typeSize() const { return sizeof(*this); }
243 } // namespace detail
245 template<typename T>
246 class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount>
248 public:
249 ~RefCounted()
251 static_assert(IsBaseOf<RefCounted, T>::value,
252 "T must derive from RefCounted<T>");
256 namespace external {
259 * AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
260 * reference counter.
262 * NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
263 * instead.
265 template<typename T>
266 class AtomicRefCounted :
267 public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount>
269 public:
270 ~AtomicRefCounted()
272 static_assert(IsBaseOf<AtomicRefCounted, T>::value,
273 "T must derive from AtomicRefCounted<T>");
277 } // namespace external
279 } // namespace mozilla
281 #endif // mozilla_RefCounted_h