Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h
Warning:line 191, column 38
Potential leak of memory pointed to by field 'Obj'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name QueryParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/tools/extra/clang-query -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang-tools-extra/clang-query -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang-tools-extra/clang-query/QueryParser.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang-tools-extra/clang-query/QueryParser.cpp

1//===---- QueryParser.cpp - clang-query command parser --------------------===//
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#include "QueryParser.h"
10#include "Query.h"
11#include "QuerySession.h"
12#include "clang/ASTMatchers/Dynamic/Parser.h"
13#include "clang/Basic/CharInfo.h"
14#include "clang/Tooling/NodeIntrospection.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/StringSwitch.h"
17#include <set>
18
19using namespace llvm;
20using namespace clang::ast_matchers::dynamic;
21
22namespace clang {
23namespace query {
24
25// Lex any amount of whitespace followed by a "word" (any sequence of
26// non-whitespace characters) from the start of region [Begin,End). If no word
27// is found before End, return StringRef(). Begin is adjusted to exclude the
28// lexed region.
29StringRef QueryParser::lexWord() {
30 Line = Line.drop_while([](char c) {
31 // Don't trim newlines.
32 return StringRef(" \t\v\f\r").contains(c);
33 });
34
35 if (Line.empty())
36 // Even though the Line is empty, it contains a pointer and
37 // a (zero) length. The pointer is used in the LexOrCompleteWord
38 // code completion.
39 return Line;
40
41 StringRef Word;
42 if (Line.front() == '#')
43 Word = Line.substr(0, 1);
44 else
45 Word = Line.take_until(isWhitespace);
46
47 Line = Line.drop_front(Word.size());
48 return Word;
49}
50
51// This is the StringSwitch-alike used by lexOrCompleteWord below. See that
52// function for details.
53template <typename T> struct QueryParser::LexOrCompleteWord {
54 StringRef Word;
55 StringSwitch<T> Switch;
56
57 QueryParser *P;
58 // Set to the completion point offset in Word, or StringRef::npos if
59 // completion point not in Word.
60 size_t WordCompletionPos;
61
62 // Lexes a word and stores it in Word. Returns a LexOrCompleteWord<T> object
63 // that can be used like a llvm::StringSwitch<T>, but adds cases as possible
64 // completions if the lexed word contains the completion point.
65 LexOrCompleteWord(QueryParser *P, StringRef &OutWord)
66 : Word(P->lexWord()), Switch(Word), P(P),
67 WordCompletionPos(StringRef::npos) {
68 OutWord = Word;
69 if (P->CompletionPos && P->CompletionPos <= Word.data() + Word.size()) {
70 if (P->CompletionPos < Word.data())
71 WordCompletionPos = 0;
72 else
73 WordCompletionPos = P->CompletionPos - Word.data();
74 }
75 }
76
77 LexOrCompleteWord &Case(llvm::StringLiteral CaseStr, const T &Value,
78 bool IsCompletion = true) {
79
80 if (WordCompletionPos == StringRef::npos)
81 Switch.Case(CaseStr, Value);
82 else if (CaseStr.size() != 0 && IsCompletion && WordCompletionPos <= CaseStr.size() &&
83 CaseStr.substr(0, WordCompletionPos) ==
84 Word.substr(0, WordCompletionPos))
85 P->Completions.push_back(LineEditor::Completion(
86 (CaseStr.substr(WordCompletionPos) + " ").str(),
87 std::string(CaseStr)));
88 return *this;
89 }
90
91 T Default(T Value) { return Switch.Default(Value); }
92};
93
94QueryRef QueryParser::parseSetBool(bool QuerySession::*Var) {
95 StringRef ValStr;
96 unsigned Value = LexOrCompleteWord<unsigned>(this, ValStr)
97 .Case("false", 0)
98 .Case("true", 1)
99 .Default(~0u);
100 if (Value == ~0u) {
101 return new InvalidQuery("expected 'true' or 'false', got '" + ValStr + "'");
102 }
103 return new SetQuery<bool>(Var, Value);
104}
105
106template <typename QueryType> QueryRef QueryParser::parseSetOutputKind() {
107 StringRef ValStr;
108 bool HasIntrospection = tooling::NodeIntrospection::hasIntrospectionSupport();
109 unsigned OutKind =
110 LexOrCompleteWord<unsigned>(this, ValStr)
111 .Case("diag", OK_Diag)
112 .Case("print", OK_Print)
113 .Case("detailed-ast", OK_DetailedAST)
114 .Case("srcloc", OK_SrcLoc, /*IsCompletion=*/HasIntrospection)
115 .Case("dump", OK_DetailedAST)
116 .Default(~0u);
117 if (OutKind == ~0u) {
118 return new InvalidQuery("expected 'diag', 'print', 'detailed-ast'" +
119 StringRef(HasIntrospection ? ", 'srcloc'" : "") +
120 " or 'dump', got '" + ValStr + "'");
121 }
122
123 switch (OutKind) {
124 case OK_DetailedAST:
125 return new QueryType(&QuerySession::DetailedASTOutput);
126 case OK_Diag:
127 return new QueryType(&QuerySession::DiagOutput);
128 case OK_Print:
129 return new QueryType(&QuerySession::PrintOutput);
130 case OK_SrcLoc:
131 if (HasIntrospection)
132 return new QueryType(&QuerySession::SrcLocOutput);
133 return new InvalidQuery("'srcloc' output support is not available.");
134 }
135
136 llvm_unreachable("Invalid output kind")::llvm::llvm_unreachable_internal("Invalid output kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 136)
;
137}
138
139QueryRef QueryParser::parseSetTraversalKind(TraversalKind QuerySession::*Var) {
140 StringRef ValStr;
141 unsigned Value =
142 LexOrCompleteWord<unsigned>(this, ValStr)
143 .Case("AsIs", TK_AsIs)
144 .Case("IgnoreUnlessSpelledInSource", TK_IgnoreUnlessSpelledInSource)
145 .Default(~0u);
146 if (Value == ~0u) {
147 return new InvalidQuery("expected traversal kind, got '" + ValStr + "'");
148 }
149 return new SetQuery<TraversalKind>(Var, static_cast<TraversalKind>(Value));
150}
151
152QueryRef QueryParser::endQuery(QueryRef Q) {
153 StringRef Extra = Line;
154 StringRef ExtraTrimmed = Extra.drop_while(
155 [](char c) { return StringRef(" \t\v\f\r").contains(c); });
156
157 if ((!ExtraTrimmed.empty() && ExtraTrimmed[0] == '\n') ||
158 (ExtraTrimmed.size() >= 2 && ExtraTrimmed[0] == '\r' &&
159 ExtraTrimmed[1] == '\n'))
160 Q->RemainingContent = Extra;
161 else {
162 StringRef TrailingWord = lexWord();
163 if (!TrailingWord.empty() && TrailingWord.front() == '#') {
164 Line = Line.drop_until([](char c) { return c == '\n'; });
165 Line = Line.drop_while([](char c) { return c == '\n'; });
166 return endQuery(Q);
167 }
168 if (!TrailingWord.empty()) {
169 return new InvalidQuery("unexpected extra input: '" + Extra + "'");
170 }
171 }
172 return Q;
173}
174
175namespace {
176
177enum ParsedQueryKind {
178 PQK_Invalid,
179 PQK_Comment,
180 PQK_NoOp,
181 PQK_Help,
182 PQK_Let,
183 PQK_Match,
184 PQK_Set,
185 PQK_Unlet,
186 PQK_Quit,
187 PQK_Enable,
188 PQK_Disable
189};
190
191enum ParsedQueryVariable {
192 PQV_Invalid,
193 PQV_Output,
194 PQV_BindRoot,
195 PQV_PrintMatcher,
196 PQV_Traversal
197};
198
199QueryRef makeInvalidQueryFromDiagnostics(const Diagnostics &Diag) {
200 std::string ErrStr;
201 llvm::raw_string_ostream OS(ErrStr);
202 Diag.printToStreamFull(OS);
203 return new InvalidQuery(OS.str());
204}
205
206} // namespace
207
208QueryRef QueryParser::completeMatcherExpression() {
209 std::vector<MatcherCompletion> Comps = Parser::completeExpression(
210 Line, CompletionPos - Line.begin(), nullptr, &QS.NamedValues);
211 for (auto I = Comps.begin(), E = Comps.end(); I != E; ++I) {
212 Completions.push_back(LineEditor::Completion(I->TypedText, I->MatcherDecl));
213 }
214 return QueryRef();
215}
216
217QueryRef QueryParser::doParse() {
218 StringRef CommandStr;
219 ParsedQueryKind QKind = LexOrCompleteWord<ParsedQueryKind>(this, CommandStr)
220 .Case("", PQK_NoOp)
221 .Case("#", PQK_Comment, /*IsCompletion=*/false)
222 .Case("help", PQK_Help)
223 .Case("l", PQK_Let, /*IsCompletion=*/false)
224 .Case("let", PQK_Let)
225 .Case("m", PQK_Match, /*IsCompletion=*/false)
226 .Case("match", PQK_Match)
227 .Case("q", PQK_Quit, /*IsCompletion=*/false)
228 .Case("quit", PQK_Quit)
229 .Case("set", PQK_Set)
230 .Case("enable", PQK_Enable)
231 .Case("disable", PQK_Disable)
232 .Case("unlet", PQK_Unlet)
233 .Default(PQK_Invalid);
234
235 switch (QKind) {
2
Control jumps to 'case PQK_Invalid:' at line 356
236 case PQK_Comment:
237 case PQK_NoOp:
238 Line = Line.drop_until([](char c) { return c == '\n'; });
239 Line = Line.drop_while([](char c) { return c == '\n'; });
240 if (Line.empty())
241 return new NoOpQuery;
242 return doParse();
243
244 case PQK_Help:
245 return endQuery(new HelpQuery);
246
247 case PQK_Quit:
248 return endQuery(new QuitQuery);
249
250 case PQK_Let: {
251 StringRef Name = lexWord();
252
253 if (Name.empty())
254 return new InvalidQuery("expected variable name");
255
256 if (CompletionPos)
257 return completeMatcherExpression();
258
259 Diagnostics Diag;
260 ast_matchers::dynamic::VariantValue Value;
261 if (!Parser::parseExpression(Line, nullptr, &QS.NamedValues, &Value,
262 &Diag)) {
263 return makeInvalidQueryFromDiagnostics(Diag);
264 }
265
266 auto *Q = new LetQuery(Name, Value);
267 Q->RemainingContent = Line;
268 return Q;
269 }
270
271 case PQK_Match: {
272 if (CompletionPos)
273 return completeMatcherExpression();
274
275 Diagnostics Diag;
276 auto MatcherSource = Line.ltrim();
277 auto OrigMatcherSource = MatcherSource;
278 Optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
279 MatcherSource, nullptr, &QS.NamedValues, &Diag);
280 if (!Matcher) {
281 return makeInvalidQueryFromDiagnostics(Diag);
282 }
283 auto ActualSource = OrigMatcherSource.slice(0, OrigMatcherSource.size() -
284 MatcherSource.size());
285 auto *Q = new MatchQuery(ActualSource, *Matcher);
286 Q->RemainingContent = MatcherSource;
287 return Q;
288 }
289
290 case PQK_Set: {
291 StringRef VarStr;
292 ParsedQueryVariable Var =
293 LexOrCompleteWord<ParsedQueryVariable>(this, VarStr)
294 .Case("output", PQV_Output)
295 .Case("bind-root", PQV_BindRoot)
296 .Case("print-matcher", PQV_PrintMatcher)
297 .Case("traversal", PQV_Traversal)
298 .Default(PQV_Invalid);
299 if (VarStr.empty())
300 return new InvalidQuery("expected variable name");
301 if (Var == PQV_Invalid)
302 return new InvalidQuery("unknown variable: '" + VarStr + "'");
303
304 QueryRef Q;
305 switch (Var) {
306 case PQV_Output:
307 Q = parseSetOutputKind<SetExclusiveOutputQuery>();
308 break;
309 case PQV_BindRoot:
310 Q = parseSetBool(&QuerySession::BindRoot);
311 break;
312 case PQV_PrintMatcher:
313 Q = parseSetBool(&QuerySession::PrintMatcher);
314 break;
315 case PQV_Traversal:
316 Q = parseSetTraversalKind(&QuerySession::TK);
317 break;
318 case PQV_Invalid:
319 llvm_unreachable("Invalid query kind")::llvm::llvm_unreachable_internal("Invalid query kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 319)
;
320 }
321
322 return endQuery(Q);
323 }
324 case PQK_Enable:
325 case PQK_Disable: {
326 StringRef VarStr;
327 ParsedQueryVariable Var =
328 LexOrCompleteWord<ParsedQueryVariable>(this, VarStr)
329 .Case("output", PQV_Output)
330 .Default(PQV_Invalid);
331 if (VarStr.empty())
332 return new InvalidQuery("expected variable name");
333 if (Var == PQV_Invalid)
334 return new InvalidQuery("unknown variable: '" + VarStr + "'");
335
336 QueryRef Q;
337
338 if (QKind == PQK_Enable)
339 Q = parseSetOutputKind<EnableOutputQuery>();
340 else if (QKind == PQK_Disable)
341 Q = parseSetOutputKind<DisableOutputQuery>();
342 else
343 llvm_unreachable("Invalid query kind")::llvm::llvm_unreachable_internal("Invalid query kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 343)
;
344 return endQuery(Q);
345 }
346
347 case PQK_Unlet: {
348 StringRef Name = lexWord();
349
350 if (Name.empty())
351 return new InvalidQuery("expected variable name");
352
353 return endQuery(new LetQuery(Name, VariantValue()));
354 }
355
356 case PQK_Invalid:
357 return new InvalidQuery("unknown command: " + CommandStr);
3
Memory is allocated
358 }
359
360 llvm_unreachable("Invalid query kind")::llvm::llvm_unreachable_internal("Invalid query kind", "clang-tools-extra/clang-query/QueryParser.cpp"
, 360)
;
361}
362
363QueryRef QueryParser::parse(StringRef Line, const QuerySession &QS) {
364 return QueryParser(Line, QS).doParse();
365}
366
367std::vector<LineEditor::Completion>
368QueryParser::complete(StringRef Line, size_t Pos, const QuerySession &QS) {
369 QueryParser P(Line, QS);
370 P.CompletionPos = Line.data() + Pos;
371
372 P.doParse();
1
Calling 'QueryParser::doParse'
4
Returned allocated memory
5
Calling '~IntrusiveRefCntPtr'
373 return P.Completions;
374}
375
376} // namespace query
377} // namespace clang

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/ADT/IntrusiveRefCntPtr.h

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
63#include <atomic>
64#include <cassert>
65#include <cstddef>
66#include <memory>
67
68namespace llvm {
69
70/// A CRTP mixin class that adds reference counting to a type.
71///
72/// The lifetime of an object which inherits from RefCountedBase is managed by
73/// calls to Release() and Retain(), which increment and decrement the object's
74/// refcount, respectively. When a Release() call decrements the refcount to 0,
75/// the object deletes itself.
76template <class Derived> class RefCountedBase {
77 mutable unsigned RefCount = 0;
78
79protected:
80 RefCountedBase() = default;
81 RefCountedBase(const RefCountedBase &) {}
82 RefCountedBase &operator=(const RefCountedBase &) = delete;
83
84#ifndef NDEBUG
85 ~RefCountedBase() {
86 assert(RefCount == 0 &&(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 87, __extension__
__PRETTY_FUNCTION__))
87 "Destruction occurred when there are still references to this.")(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 87, __extension__
__PRETTY_FUNCTION__))
;
88 }
89#else
90 // Default the destructor in release builds, A trivial destructor may enable
91 // better codegen.
92 ~RefCountedBase() = default;
93#endif
94
95public:
96 void Retain() const { ++RefCount; }
97
98 void Release() const {
99 assert(RefCount > 0 && "Reference count is already zero.")(static_cast <bool> (RefCount > 0 && "Reference count is already zero."
) ? void (0) : __assert_fail ("RefCount > 0 && \"Reference count is already zero.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 99, __extension__
__PRETTY_FUNCTION__))
;
100 if (--RefCount == 0)
101 delete static_cast<const Derived *>(this);
102 }
103};
104
105/// A thread-safe version of \c RefCountedBase.
106template <class Derived> class ThreadSafeRefCountedBase {
107 mutable std::atomic<int> RefCount{0};
108
109protected:
110 ThreadSafeRefCountedBase() = default;
111 ThreadSafeRefCountedBase(const ThreadSafeRefCountedBase &) {}
112 ThreadSafeRefCountedBase &
113 operator=(const ThreadSafeRefCountedBase &) = delete;
114
115#ifndef NDEBUG
116 ~ThreadSafeRefCountedBase() {
117 assert(RefCount == 0 &&(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 118, __extension__
__PRETTY_FUNCTION__))
118 "Destruction occurred when there are still references to this.")(static_cast <bool> (RefCount == 0 && "Destruction occurred when there are still references to this."
) ? void (0) : __assert_fail ("RefCount == 0 && \"Destruction occurred when there are still references to this.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 118, __extension__
__PRETTY_FUNCTION__))
;
119 }
120#else
121 // Default the destructor in release builds, A trivial destructor may enable
122 // better codegen.
123 ~ThreadSafeRefCountedBase() = default;
124#endif
125
126public:
127 void Retain() const { RefCount.fetch_add(1, std::memory_order_relaxed); }
128
129 void Release() const {
130 int NewRefCount = RefCount.fetch_sub(1, std::memory_order_acq_rel) - 1;
131 assert(NewRefCount >= 0 && "Reference count was already zero.")(static_cast <bool> (NewRefCount >= 0 && "Reference count was already zero."
) ? void (0) : __assert_fail ("NewRefCount >= 0 && \"Reference count was already zero.\""
, "llvm/include/llvm/ADT/IntrusiveRefCntPtr.h", 131, __extension__
__PRETTY_FUNCTION__))
;
132 if (NewRefCount == 0)
133 delete static_cast<const Derived *>(this);
134 }
135};
136
137/// Class you can specialize to provide custom retain/release functionality for
138/// a type.
139///
140/// Usually specializing this class is not necessary, as IntrusiveRefCntPtr
141/// works with any type which defines Retain() and Release() functions -- you
142/// can define those functions yourself if RefCountedBase doesn't work for you.
143///
144/// One case when you might want to specialize this type is if you have
145/// - Foo.h defines type Foo and includes Bar.h, and
146/// - Bar.h uses IntrusiveRefCntPtr<Foo> in inline functions.
147///
148/// Because Foo.h includes Bar.h, Bar.h can't include Foo.h in order to pull in
149/// the declaration of Foo. Without the declaration of Foo, normally Bar.h
150/// wouldn't be able to use IntrusiveRefCntPtr<Foo>, which wants to call
151/// T::Retain and T::Release.
152///
153/// To resolve this, Bar.h could include a third header, FooFwd.h, which
154/// forward-declares Foo and specializes IntrusiveRefCntPtrInfo<Foo>. Then
155/// Bar.h could use IntrusiveRefCntPtr<Foo>, although it still couldn't call any
156/// functions on Foo itself, because Foo would be an incomplete type.
157template <typename T> struct IntrusiveRefCntPtrInfo {
158 static void retain(T *obj) { obj->Retain(); }
159 static void release(T *obj) { obj->Release(); }
160};
161
162/// A smart pointer to a reference-counted object that inherits from
163/// RefCountedBase or ThreadSafeRefCountedBase.
164///
165/// This class increments its pointee's reference count when it is created, and
166/// decrements its refcount when it's destroyed (or is changed to point to a
167/// different object).
168template <typename T> class IntrusiveRefCntPtr {
169 T *Obj = nullptr;
170
171public:
172 using element_type = T;
173
174 explicit IntrusiveRefCntPtr() = default;
175 IntrusiveRefCntPtr(T *obj) : Obj(obj) { retain(); }
176 IntrusiveRefCntPtr(const IntrusiveRefCntPtr &S) : Obj(S.Obj) { retain(); }
177 IntrusiveRefCntPtr(IntrusiveRefCntPtr &&S) : Obj(S.Obj) { S.Obj = nullptr; }
178
179 template <class X,
180 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
181 IntrusiveRefCntPtr(IntrusiveRefCntPtr<X> S) : Obj(S.get()) {
182 S.Obj = nullptr;
183 }
184
185 template <class X,
186 std::enable_if_t<std::is_convertible<X *, T *>::value, bool> = true>
187 IntrusiveRefCntPtr(std::unique_ptr<X> S) : Obj(S.release()) {
188 retain();
189 }
190
191 ~IntrusiveRefCntPtr() { release(); }
6
Potential leak of memory pointed to by field 'Obj'
192
193 IntrusiveRefCntPtr &operator=(IntrusiveRefCntPtr S) {
194 swap(S);
195 return *this;
196 }
197
198 T &operator*() const { return *Obj; }
199 T *operator->() const { return Obj; }
200 T *get() const { return Obj; }
201 explicit operator bool() const { return Obj; }
202
203 void swap(IntrusiveRefCntPtr &other) {
204 T *tmp = other.Obj;
205 other.Obj = Obj;
206 Obj = tmp;
207 }
208
209 void reset() {
210 release();
211 Obj = nullptr;
212 }
213
214 void resetWithoutRelease() { Obj = nullptr; }
215
216private:
217 void retain() {
218 if (Obj)
219 IntrusiveRefCntPtrInfo<T>::retain(Obj);
220 }
221
222 void release() {
223 if (Obj)
224 IntrusiveRefCntPtrInfo<T>::release(Obj);
225 }
226
227 template <typename X> friend class IntrusiveRefCntPtr;
228};
229
230template <class T, class U>
231inline bool operator==(const IntrusiveRefCntPtr<T> &A,
232 const IntrusiveRefCntPtr<U> &B) {
233 return A.get() == B.get();
234}
235
236template <class T, class U>
237inline bool operator!=(const IntrusiveRefCntPtr<T> &A,
238 const IntrusiveRefCntPtr<U> &B) {
239 return A.get() != B.get();
240}
241
242template <class T, class U>
243inline bool operator==(const IntrusiveRefCntPtr<T> &A, U *B) {
244 return A.get() == B;
245}
246
247template <class T, class U>
248inline bool operator!=(const IntrusiveRefCntPtr<T> &A, U *B) {
249 return A.get() != B;
250}
251
252template <class T, class U>
253inline bool operator==(T *A, const IntrusiveRefCntPtr<U> &B) {
254 return A == B.get();
255}
256
257template <class T, class U>
258inline bool operator!=(T *A, const IntrusiveRefCntPtr<U> &B) {
259 return A != B.get();
260}
261
262template <class T>
263bool operator==(std::nullptr_t, const IntrusiveRefCntPtr<T> &B) {
264 return !B;
265}
266
267template <class T>
268bool operator==(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
269 return B == A;
270}
271
272template <class T>
273bool operator!=(std::nullptr_t A, const IntrusiveRefCntPtr<T> &B) {
274 return !(A == B);
275}
276
277template <class T>
278bool operator!=(const IntrusiveRefCntPtr<T> &A, std::nullptr_t B) {
279 return !(A == B);
280}
281
282// Make IntrusiveRefCntPtr work with dyn_cast, isa, and the other idioms from
283// Casting.h.
284template <typename From> struct simplify_type;
285
286template <class T> struct simplify_type<IntrusiveRefCntPtr<T>> {
287 using SimpleType = T *;
288
289 static SimpleType getSimplifiedValue(IntrusiveRefCntPtr<T> &Val) {
290 return Val.get();
291 }
292};
293
294template <class T> struct simplify_type<const IntrusiveRefCntPtr<T>> {
295 using SimpleType = /*const*/ T *;
296
297 static SimpleType getSimplifiedValue(const IntrusiveRefCntPtr<T> &Val) {
298 return Val.get();
299 }
300};
301
302/// Factory function for creating intrusive ref counted pointers.
303template <typename T, typename... Args>
304IntrusiveRefCntPtr<T> makeIntrusiveRefCnt(Args &&...A) {
305 return IntrusiveRefCntPtr<T>(new T(std::forward<Args>(A)...));
306}
307
308} // end namespace llvm
309
310#endif // LLVM_ADT_INTRUSIVEREFCNTPTR_H