Bug Summary

File:clang/lib/AST/DeclCXX.cpp
Warning:line 1537, column 9
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DeclCXX.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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include -I /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-04-143208-9200-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp

/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp

1//===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===//
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 implements the C++ related Decl classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/ASTUnresolvedSet.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/LambdaCapture.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/ODRHash.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/Diagnostic.h"
32#include "clang/Basic/IdentifierTable.h"
33#include "clang/Basic/LLVM.h"
34#include "clang/Basic/LangOptions.h"
35#include "clang/Basic/OperatorKinds.h"
36#include "clang/Basic/PartialDiagnostic.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "llvm/ADT/None.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/Format.h"
46#include "llvm/Support/raw_ostream.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdint>
51
52using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Decl Allocation/Deallocation Method Implementations
56//===----------------------------------------------------------------------===//
57
58void AccessSpecDecl::anchor() {}
59
60AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
61 return new (C, ID) AccessSpecDecl(EmptyShell());
62}
63
64void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {
65 ExternalASTSource *Source = C.getExternalSource();
66 assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set")((Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set"
) ? static_cast<void> (0) : __assert_fail ("Impl.Decls.isLazy() && \"getFromExternalSource for non-lazy set\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 66, __PRETTY_FUNCTION__))
;
67 assert(Source && "getFromExternalSource with no external source")((Source && "getFromExternalSource with no external source"
) ? static_cast<void> (0) : __assert_fail ("Source && \"getFromExternalSource with no external source\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 67, __PRETTY_FUNCTION__))
;
68
69 for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)
70 I.setDecl(cast<NamedDecl>(Source->GetExternalDecl(
71 reinterpret_cast<uintptr_t>(I.getDecl()) >> 2)));
72 Impl.Decls.setLazy(false);
73}
74
75CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
76 : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
77 Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
78 Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true),
79 HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false),
80 HasPrivateFields(false), HasProtectedFields(false),
81 HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),
82 HasOnlyCMembers(true), HasInClassInitializer(false),
83 HasUninitializedReferenceMember(false), HasUninitializedFields(false),
84 HasInheritedConstructor(false), HasInheritedAssignment(false),
85 NeedOverloadResolutionForCopyConstructor(false),
86 NeedOverloadResolutionForMoveConstructor(false),
87 NeedOverloadResolutionForCopyAssignment(false),
88 NeedOverloadResolutionForMoveAssignment(false),
89 NeedOverloadResolutionForDestructor(false),
90 DefaultedCopyConstructorIsDeleted(false),
91 DefaultedMoveConstructorIsDeleted(false),
92 DefaultedCopyAssignmentIsDeleted(false),
93 DefaultedMoveAssignmentIsDeleted(false),
94 DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All),
95 HasTrivialSpecialMembersForCall(SMF_All),
96 DeclaredNonTrivialSpecialMembers(0),
97 DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true),
98 HasConstexprNonCopyMoveConstructor(false),
99 HasDefaultedDefaultConstructor(false),
100 DefaultedDefaultConstructorIsConstexpr(true),
101 HasConstexprDefaultConstructor(false),
102 DefaultedDestructorIsConstexpr(true),
103 HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true),
104 UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
105 ImplicitCopyConstructorCanHaveConstParamForVBase(true),
106 ImplicitCopyConstructorCanHaveConstParamForNonVBase(true),
107 ImplicitCopyAssignmentHasConstParam(true),
108 HasDeclaredCopyConstructorWithConstParam(false),
109 HasDeclaredCopyAssignmentWithConstParam(false), IsLambda(false),
110 IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false),
111 HasODRHash(false), Definition(D) {}
112
113CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
114 return Bases.get(Definition->getASTContext().getExternalSource());
115}
116
117CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
118 return VBases.get(Definition->getASTContext().getExternalSource());
119}
120
121CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,
122 DeclContext *DC, SourceLocation StartLoc,
123 SourceLocation IdLoc, IdentifierInfo *Id,
124 CXXRecordDecl *PrevDecl)
125 : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),
126 DefinitionData(PrevDecl ? PrevDecl->DefinitionData
127 : nullptr) {}
128
129CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
130 DeclContext *DC, SourceLocation StartLoc,
131 SourceLocation IdLoc, IdentifierInfo *Id,
132 CXXRecordDecl *PrevDecl,
133 bool DelayTypeCreation) {
134 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id,
135 PrevDecl);
136 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
137
138 // FIXME: DelayTypeCreation seems like such a hack
139 if (!DelayTypeCreation)
140 C.getTypeDeclType(R, PrevDecl);
141 return R;
142}
143
144CXXRecordDecl *
145CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
146 TypeSourceInfo *Info, SourceLocation Loc,
147 bool Dependent, bool IsGeneric,
148 LambdaCaptureDefault CaptureDefault) {
149 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TTK_Class, C, DC, Loc, Loc,
150 nullptr, nullptr);
151 R->setBeingDefined(true);
152 R->DefinitionData =
153 new (C) struct LambdaDefinitionData(R, Info, Dependent, IsGeneric,
154 CaptureDefault);
155 R->setMayHaveOutOfDateDef(false);
156 R->setImplicit(true);
157 C.getTypeDeclType(R, /*PrevDecl=*/nullptr);
158 return R;
159}
160
161CXXRecordDecl *
162CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
163 auto *R = new (C, ID) CXXRecordDecl(
164 CXXRecord, TTK_Struct, C, nullptr, SourceLocation(), SourceLocation(),
165 nullptr, nullptr);
166 R->setMayHaveOutOfDateDef(false);
167 return R;
168}
169
170/// Determine whether a class has a repeated base class. This is intended for
171/// use when determining if a class is standard-layout, so makes no attempt to
172/// handle virtual bases.
173static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {
174 llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;
175 SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};
176 while (!WorkList.empty()) {
177 const CXXRecordDecl *RD = WorkList.pop_back_val();
178 for (const CXXBaseSpecifier &BaseSpec : RD->bases()) {
179 if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) {
180 if (!SeenBaseTypes.insert(B).second)
181 return true;
182 WorkList.push_back(B);
183 }
184 }
185 }
186 return false;
187}
188
189void
190CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
191 unsigned NumBases) {
192 ASTContext &C = getASTContext();
193
194 if (!data().Bases.isOffset() && data().NumBases > 0)
195 C.Deallocate(data().getBases());
196
197 if (NumBases) {
198 if (!C.getLangOpts().CPlusPlus17) {
199 // C++ [dcl.init.aggr]p1:
200 // An aggregate is [...] a class with [...] no base classes [...].
201 data().Aggregate = false;
202 }
203
204 // C++ [class]p4:
205 // A POD-struct is an aggregate class...
206 data().PlainOldData = false;
207 }
208
209 // The set of seen virtual base types.
210 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
211
212 // The virtual bases of this class.
213 SmallVector<const CXXBaseSpecifier *, 8> VBases;
214
215 data().Bases = new(C) CXXBaseSpecifier [NumBases];
216 data().NumBases = NumBases;
217 for (unsigned i = 0; i < NumBases; ++i) {
218 data().getBases()[i] = *Bases[i];
219 // Keep track of inherited vbases for this base class.
220 const CXXBaseSpecifier *Base = Bases[i];
221 QualType BaseType = Base->getType();
222 // Skip dependent types; we can't do any checking on them now.
223 if (BaseType->isDependentType())
224 continue;
225 auto *BaseClassDecl =
226 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
227
228 // C++2a [class]p7:
229 // A standard-layout class is a class that:
230 // [...]
231 // -- has all non-static data members and bit-fields in the class and
232 // its base classes first declared in the same class
233 if (BaseClassDecl->data().HasBasesWithFields ||
234 !BaseClassDecl->field_empty()) {
235 if (data().HasBasesWithFields)
236 // Two bases have members or bit-fields: not standard-layout.
237 data().IsStandardLayout = false;
238 data().HasBasesWithFields = true;
239 }
240
241 // C++11 [class]p7:
242 // A standard-layout class is a class that:
243 // -- [...] has [...] at most one base class with non-static data
244 // members
245 if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers ||
246 BaseClassDecl->hasDirectFields()) {
247 if (data().HasBasesWithNonStaticDataMembers)
248 data().IsCXX11StandardLayout = false;
249 data().HasBasesWithNonStaticDataMembers = true;
250 }
251
252 if (!BaseClassDecl->isEmpty()) {
253 // C++14 [meta.unary.prop]p4:
254 // T is a class type [...] with [...] no base class B for which
255 // is_empty<B>::value is false.
256 data().Empty = false;
257 }
258
259 // C++1z [dcl.init.agg]p1:
260 // An aggregate is a class with [...] no private or protected base classes
261 if (Base->getAccessSpecifier() != AS_public) {
262 data().Aggregate = false;
263
264 // C++20 [temp.param]p7:
265 // A structural type is [...] a literal class type with [...] all base
266 // classes [...] public
267 data().StructuralIfLiteral = false;
268 }
269
270 // C++ [class.virtual]p1:
271 // A class that declares or inherits a virtual function is called a
272 // polymorphic class.
273 if (BaseClassDecl->isPolymorphic()) {
274 data().Polymorphic = true;
275
276 // An aggregate is a class with [...] no virtual functions.
277 data().Aggregate = false;
278 }
279
280 // C++0x [class]p7:
281 // A standard-layout class is a class that: [...]
282 // -- has no non-standard-layout base classes
283 if (!BaseClassDecl->isStandardLayout())
284 data().IsStandardLayout = false;
285 if (!BaseClassDecl->isCXX11StandardLayout())
286 data().IsCXX11StandardLayout = false;
287
288 // Record if this base is the first non-literal field or base.
289 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))
290 data().HasNonLiteralTypeFieldsOrBases = true;
291
292 // Now go through all virtual bases of this base and add them.
293 for (const auto &VBase : BaseClassDecl->vbases()) {
294 // Add this base if it's not already in the list.
295 if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) {
296 VBases.push_back(&VBase);
297
298 // C++11 [class.copy]p8:
299 // The implicitly-declared copy constructor for a class X will have
300 // the form 'X::X(const X&)' if each [...] virtual base class B of X
301 // has a copy constructor whose first parameter is of type
302 // 'const B&' or 'const volatile B&' [...]
303 if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl())
304 if (!VBaseDecl->hasCopyConstructorWithConstParam())
305 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
306
307 // C++1z [dcl.init.agg]p1:
308 // An aggregate is a class with [...] no virtual base classes
309 data().Aggregate = false;
310 }
311 }
312
313 if (Base->isVirtual()) {
314 // Add this base if it's not already in the list.
315 if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second)
316 VBases.push_back(Base);
317
318 // C++14 [meta.unary.prop] is_empty:
319 // T is a class type, but not a union type, with ... no virtual base
320 // classes
321 data().Empty = false;
322
323 // C++1z [dcl.init.agg]p1:
324 // An aggregate is a class with [...] no virtual base classes
325 data().Aggregate = false;
326
327 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
328 // A [default constructor, copy/move constructor, or copy/move assignment
329 // operator for a class X] is trivial [...] if:
330 // -- class X has [...] no virtual base classes
331 data().HasTrivialSpecialMembers &= SMF_Destructor;
332 data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
333
334 // C++0x [class]p7:
335 // A standard-layout class is a class that: [...]
336 // -- has [...] no virtual base classes
337 data().IsStandardLayout = false;
338 data().IsCXX11StandardLayout = false;
339
340 // C++20 [dcl.constexpr]p3:
341 // In the definition of a constexpr function [...]
342 // -- if the function is a constructor or destructor,
343 // its class shall not have any virtual base classes
344 data().DefaultedDefaultConstructorIsConstexpr = false;
345 data().DefaultedDestructorIsConstexpr = false;
346
347 // C++1z [class.copy]p8:
348 // The implicitly-declared copy constructor for a class X will have
349 // the form 'X::X(const X&)' if each potentially constructed subobject
350 // has a copy constructor whose first parameter is of type
351 // 'const B&' or 'const volatile B&' [...]
352 if (!BaseClassDecl->hasCopyConstructorWithConstParam())
353 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
354 } else {
355 // C++ [class.ctor]p5:
356 // A default constructor is trivial [...] if:
357 // -- all the direct base classes of its class have trivial default
358 // constructors.
359 if (!BaseClassDecl->hasTrivialDefaultConstructor())
360 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
361
362 // C++0x [class.copy]p13:
363 // A copy/move constructor for class X is trivial if [...]
364 // [...]
365 // -- the constructor selected to copy/move each direct base class
366 // subobject is trivial, and
367 if (!BaseClassDecl->hasTrivialCopyConstructor())
368 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
369
370 if (!BaseClassDecl->hasTrivialCopyConstructorForCall())
371 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
372
373 // If the base class doesn't have a simple move constructor, we'll eagerly
374 // declare it and perform overload resolution to determine which function
375 // it actually calls. If it does have a simple move constructor, this
376 // check is correct.
377 if (!BaseClassDecl->hasTrivialMoveConstructor())
378 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
379
380 if (!BaseClassDecl->hasTrivialMoveConstructorForCall())
381 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
382
383 // C++0x [class.copy]p27:
384 // A copy/move assignment operator for class X is trivial if [...]
385 // [...]
386 // -- the assignment operator selected to copy/move each direct base
387 // class subobject is trivial, and
388 if (!BaseClassDecl->hasTrivialCopyAssignment())
389 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
390 // If the base class doesn't have a simple move assignment, we'll eagerly
391 // declare it and perform overload resolution to determine which function
392 // it actually calls. If it does have a simple move assignment, this
393 // check is correct.
394 if (!BaseClassDecl->hasTrivialMoveAssignment())
395 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
396
397 // C++11 [class.ctor]p6:
398 // If that user-written default constructor would satisfy the
399 // requirements of a constexpr constructor, the implicitly-defined
400 // default constructor is constexpr.
401 if (!BaseClassDecl->hasConstexprDefaultConstructor())
402 data().DefaultedDefaultConstructorIsConstexpr = false;
403
404 // C++1z [class.copy]p8:
405 // The implicitly-declared copy constructor for a class X will have
406 // the form 'X::X(const X&)' if each potentially constructed subobject
407 // has a copy constructor whose first parameter is of type
408 // 'const B&' or 'const volatile B&' [...]
409 if (!BaseClassDecl->hasCopyConstructorWithConstParam())
410 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
411 }
412
413 // C++ [class.ctor]p3:
414 // A destructor is trivial if all the direct base classes of its class
415 // have trivial destructors.
416 if (!BaseClassDecl->hasTrivialDestructor())
417 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
418
419 if (!BaseClassDecl->hasTrivialDestructorForCall())
420 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
421
422 if (!BaseClassDecl->hasIrrelevantDestructor())
423 data().HasIrrelevantDestructor = false;
424
425 // C++11 [class.copy]p18:
426 // The implicitly-declared copy assignment operator for a class X will
427 // have the form 'X& X::operator=(const X&)' if each direct base class B
428 // of X has a copy assignment operator whose parameter is of type 'const
429 // B&', 'const volatile B&', or 'B' [...]
430 if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
431 data().ImplicitCopyAssignmentHasConstParam = false;
432
433 // A class has an Objective-C object member if... or any of its bases
434 // has an Objective-C object member.
435 if (BaseClassDecl->hasObjectMember())
436 setHasObjectMember(true);
437
438 if (BaseClassDecl->hasVolatileMember())
439 setHasVolatileMember(true);
440
441 if (BaseClassDecl->getArgPassingRestrictions() ==
442 RecordDecl::APK_CanNeverPassInRegs)
443 setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
444
445 // Keep track of the presence of mutable fields.
446 if (BaseClassDecl->hasMutableFields())
447 data().HasMutableFields = true;
448
449 if (BaseClassDecl->hasUninitializedReferenceMember())
450 data().HasUninitializedReferenceMember = true;
451
452 if (!BaseClassDecl->allowConstDefaultInit())
453 data().HasUninitializedFields = true;
454
455 addedClassSubobject(BaseClassDecl);
456 }
457
458 // C++2a [class]p7:
459 // A class S is a standard-layout class if it:
460 // -- has at most one base class subobject of any given type
461 //
462 // Note that we only need to check this for classes with more than one base
463 // class. If there's only one base class, and it's standard layout, then
464 // we know there are no repeated base classes.
465 if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this))
466 data().IsStandardLayout = false;
467
468 if (VBases.empty()) {
469 data().IsParsingBaseSpecifiers = false;
470 return;
471 }
472
473 // Create base specifier for any direct or indirect virtual bases.
474 data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
475 data().NumVBases = VBases.size();
476 for (int I = 0, E = VBases.size(); I != E; ++I) {
477 QualType Type = VBases[I]->getType();
478 if (!Type->isDependentType())
479 addedClassSubobject(Type->getAsCXXRecordDecl());
480 data().getVBases()[I] = *VBases[I];
481 }
482
483 data().IsParsingBaseSpecifiers = false;
484}
485
486unsigned CXXRecordDecl::getODRHash() const {
487 assert(hasDefinition() && "ODRHash only for records with definitions")((hasDefinition() && "ODRHash only for records with definitions"
) ? static_cast<void> (0) : __assert_fail ("hasDefinition() && \"ODRHash only for records with definitions\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 487, __PRETTY_FUNCTION__))
;
488
489 // Previously calculated hash is stored in DefinitionData.
490 if (DefinitionData->HasODRHash)
491 return DefinitionData->ODRHash;
492
493 // Only calculate hash on first call of getODRHash per record.
494 ODRHash Hash;
495 Hash.AddCXXRecordDecl(getDefinition());
496 DefinitionData->HasODRHash = true;
497 DefinitionData->ODRHash = Hash.CalculateHash();
498
499 return DefinitionData->ODRHash;
500}
501
502void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
503 // C++11 [class.copy]p11:
504 // A defaulted copy/move constructor for a class X is defined as
505 // deleted if X has:
506 // -- a direct or virtual base class B that cannot be copied/moved [...]
507 // -- a non-static data member of class type M (or array thereof)
508 // that cannot be copied or moved [...]
509 if (!Subobj->hasSimpleCopyConstructor())
510 data().NeedOverloadResolutionForCopyConstructor = true;
511 if (!Subobj->hasSimpleMoveConstructor())
512 data().NeedOverloadResolutionForMoveConstructor = true;
513
514 // C++11 [class.copy]p23:
515 // A defaulted copy/move assignment operator for a class X is defined as
516 // deleted if X has:
517 // -- a direct or virtual base class B that cannot be copied/moved [...]
518 // -- a non-static data member of class type M (or array thereof)
519 // that cannot be copied or moved [...]
520 if (!Subobj->hasSimpleCopyAssignment())
521 data().NeedOverloadResolutionForCopyAssignment = true;
522 if (!Subobj->hasSimpleMoveAssignment())
523 data().NeedOverloadResolutionForMoveAssignment = true;
524
525 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
526 // A defaulted [ctor or dtor] for a class X is defined as
527 // deleted if X has:
528 // -- any direct or virtual base class [...] has a type with a destructor
529 // that is deleted or inaccessible from the defaulted [ctor or dtor].
530 // -- any non-static data member has a type with a destructor
531 // that is deleted or inaccessible from the defaulted [ctor or dtor].
532 if (!Subobj->hasSimpleDestructor()) {
533 data().NeedOverloadResolutionForCopyConstructor = true;
534 data().NeedOverloadResolutionForMoveConstructor = true;
535 data().NeedOverloadResolutionForDestructor = true;
536 }
537
538 // C++2a [dcl.constexpr]p4:
539 // The definition of a constexpr destructor [shall] satisfy the
540 // following requirement:
541 // -- for every subobject of class type or (possibly multi-dimensional)
542 // array thereof, that class type shall have a constexpr destructor
543 if (!Subobj->hasConstexprDestructor())
544 data().DefaultedDestructorIsConstexpr = false;
545
546 // C++20 [temp.param]p7:
547 // A structural type is [...] a literal class type [for which] the types
548 // of all base classes and non-static data members are structural types or
549 // (possibly multi-dimensional) array thereof
550 if (!Subobj->data().StructuralIfLiteral)
551 data().StructuralIfLiteral = false;
552}
553
554bool CXXRecordDecl::hasConstexprDestructor() const {
555 auto *Dtor = getDestructor();
556 return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();
557}
558
559bool CXXRecordDecl::hasAnyDependentBases() const {
560 if (!isDependentContext())
561 return false;
562
563 return !forallBases([](const CXXRecordDecl *) { return true; });
564}
565
566bool CXXRecordDecl::isTriviallyCopyable() const {
567 // C++0x [class]p5:
568 // A trivially copyable class is a class that:
569 // -- has no non-trivial copy constructors,
570 if (hasNonTrivialCopyConstructor()) return false;
571 // -- has no non-trivial move constructors,
572 if (hasNonTrivialMoveConstructor()) return false;
573 // -- has no non-trivial copy assignment operators,
574 if (hasNonTrivialCopyAssignment()) return false;
575 // -- has no non-trivial move assignment operators, and
576 if (hasNonTrivialMoveAssignment()) return false;
577 // -- has a trivial destructor.
578 if (!hasTrivialDestructor()) return false;
579
580 return true;
581}
582
583void CXXRecordDecl::markedVirtualFunctionPure() {
584 // C++ [class.abstract]p2:
585 // A class is abstract if it has at least one pure virtual function.
586 data().Abstract = true;
587}
588
589bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType(
590 ASTContext &Ctx, const CXXRecordDecl *XFirst) {
591 if (!getNumBases())
592 return false;
593
594 llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases;
595 llvm::SmallPtrSet<const CXXRecordDecl*, 8> M;
596 SmallVector<const CXXRecordDecl*, 8> WorkList;
597
598 // Visit a type that we have determined is an element of M(S).
599 auto Visit = [&](const CXXRecordDecl *RD) -> bool {
600 RD = RD->getCanonicalDecl();
601
602 // C++2a [class]p8:
603 // A class S is a standard-layout class if it [...] has no element of the
604 // set M(S) of types as a base class.
605 //
606 // If we find a subobject of an empty type, it might also be a base class,
607 // so we'll need to walk the base classes to check.
608 if (!RD->data().HasBasesWithFields) {
609 // Walk the bases the first time, stopping if we find the type. Build a
610 // set of them so we don't need to walk them again.
611 if (Bases.empty()) {
612 bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool {
613 Base = Base->getCanonicalDecl();
614 if (RD == Base)
615 return false;
616 Bases.insert(Base);
617 return true;
618 });
619 if (RDIsBase)
620 return true;
621 } else {
622 if (Bases.count(RD))
623 return true;
624 }
625 }
626
627 if (M.insert(RD).second)
628 WorkList.push_back(RD);
629 return false;
630 };
631
632 if (Visit(XFirst))
633 return true;
634
635 while (!WorkList.empty()) {
636 const CXXRecordDecl *X = WorkList.pop_back_val();
637
638 // FIXME: We don't check the bases of X. That matches the standard, but
639 // that sure looks like a wording bug.
640
641 // -- If X is a non-union class type with a non-static data member
642 // [recurse to each field] that is either of zero size or is the
643 // first non-static data member of X
644 // -- If X is a union type, [recurse to union members]
645 bool IsFirstField = true;
646 for (auto *FD : X->fields()) {
647 // FIXME: Should we really care about the type of the first non-static
648 // data member of a non-union if there are preceding unnamed bit-fields?
649 if (FD->isUnnamedBitfield())
650 continue;
651
652 if (!IsFirstField && !FD->isZeroSize(Ctx))
653 continue;
654
655 // -- If X is n array type, [visit the element type]
656 QualType T = Ctx.getBaseElementType(FD->getType());
657 if (auto *RD = T->getAsCXXRecordDecl())
658 if (Visit(RD))
659 return true;
660
661 if (!X->isUnion())
662 IsFirstField = false;
663 }
664 }
665
666 return false;
667}
668
669bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {
670 assert(isLambda() && "not a lambda")((isLambda() && "not a lambda") ? static_cast<void
> (0) : __assert_fail ("isLambda() && \"not a lambda\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 670, __PRETTY_FUNCTION__))
;
671
672 // C++2a [expr.prim.lambda.capture]p11:
673 // The closure type associated with a lambda-expression has no default
674 // constructor if the lambda-expression has a lambda-capture and a
675 // defaulted default constructor otherwise. It has a deleted copy
676 // assignment operator if the lambda-expression has a lambda-capture and
677 // defaulted copy and move assignment operators otherwise.
678 //
679 // C++17 [expr.prim.lambda]p21:
680 // The closure type associated with a lambda-expression has no default
681 // constructor and a deleted copy assignment operator.
682 if (getLambdaCaptureDefault() != LCD_None || capture_size() != 0)
683 return false;
684 return getASTContext().getLangOpts().CPlusPlus20;
685}
686
687void CXXRecordDecl::addedMember(Decl *D) {
688 if (!D->isImplicit() &&
689 !isa<FieldDecl>(D) &&
690 !isa<IndirectFieldDecl>(D) &&
691 (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class ||
692 cast<TagDecl>(D)->getTagKind() == TTK_Interface))
693 data().HasOnlyCMembers = false;
694
695 // Ignore friends and invalid declarations.
696 if (D->getFriendObjectKind() || D->isInvalidDecl())
697 return;
698
699 auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
700 if (FunTmpl)
701 D = FunTmpl->getTemplatedDecl();
702
703 // FIXME: Pass NamedDecl* to addedMember?
704 Decl *DUnderlying = D;
705 if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) {
706 DUnderlying = ND->getUnderlyingDecl();
707 if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying))
708 DUnderlying = UnderlyingFunTmpl->getTemplatedDecl();
709 }
710
711 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
712 if (Method->isVirtual()) {
713 // C++ [dcl.init.aggr]p1:
714 // An aggregate is an array or a class with [...] no virtual functions.
715 data().Aggregate = false;
716
717 // C++ [class]p4:
718 // A POD-struct is an aggregate class...
719 data().PlainOldData = false;
720
721 // C++14 [meta.unary.prop]p4:
722 // T is a class type [...] with [...] no virtual member functions...
723 data().Empty = false;
724
725 // C++ [class.virtual]p1:
726 // A class that declares or inherits a virtual function is called a
727 // polymorphic class.
728 data().Polymorphic = true;
729
730 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
731 // A [default constructor, copy/move constructor, or copy/move
732 // assignment operator for a class X] is trivial [...] if:
733 // -- class X has no virtual functions [...]
734 data().HasTrivialSpecialMembers &= SMF_Destructor;
735 data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
736
737 // C++0x [class]p7:
738 // A standard-layout class is a class that: [...]
739 // -- has no virtual functions
740 data().IsStandardLayout = false;
741 data().IsCXX11StandardLayout = false;
742 }
743 }
744
745 // Notify the listener if an implicit member was added after the definition
746 // was completed.
747 if (!isBeingDefined() && D->isImplicit())
748 if (ASTMutationListener *L = getASTMutationListener())
749 L->AddedCXXImplicitMember(data().Definition, D);
750
751 // The kind of special member this declaration is, if any.
752 unsigned SMKind = 0;
753
754 // Handle constructors.
755 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
756 if (Constructor->isInheritingConstructor()) {
757 // Ignore constructor shadow declarations. They are lazily created and
758 // so shouldn't affect any properties of the class.
759 } else {
760 if (!Constructor->isImplicit()) {
761 // Note that we have a user-declared constructor.
762 data().UserDeclaredConstructor = true;
763
764 // C++ [class]p4:
765 // A POD-struct is an aggregate class [...]
766 // Since the POD bit is meant to be C++03 POD-ness, clear it even if
767 // the type is technically an aggregate in C++0x since it wouldn't be
768 // in 03.
769 data().PlainOldData = false;
770 }
771
772 if (Constructor->isDefaultConstructor()) {
773 SMKind |= SMF_DefaultConstructor;
774
775 if (Constructor->isUserProvided())
776 data().UserProvidedDefaultConstructor = true;
777 if (Constructor->isConstexpr())
778 data().HasConstexprDefaultConstructor = true;
779 if (Constructor->isDefaulted())
780 data().HasDefaultedDefaultConstructor = true;
781 }
782
783 if (!FunTmpl) {
784 unsigned Quals;
785 if (Constructor->isCopyConstructor(Quals)) {
786 SMKind |= SMF_CopyConstructor;
787
788 if (Quals & Qualifiers::Const)
789 data().HasDeclaredCopyConstructorWithConstParam = true;
790 } else if (Constructor->isMoveConstructor())
791 SMKind |= SMF_MoveConstructor;
792 }
793
794 // C++11 [dcl.init.aggr]p1: DR1518
795 // An aggregate is an array or a class with no user-provided [or]
796 // explicit [...] constructors
797 // C++20 [dcl.init.aggr]p1:
798 // An aggregate is an array or a class with no user-declared [...]
799 // constructors
800 if (getASTContext().getLangOpts().CPlusPlus20
801 ? !Constructor->isImplicit()
802 : (Constructor->isUserProvided() || Constructor->isExplicit()))
803 data().Aggregate = false;
804 }
805 }
806
807 // Handle constructors, including those inherited from base classes.
808 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) {
809 // Record if we see any constexpr constructors which are neither copy
810 // nor move constructors.
811 // C++1z [basic.types]p10:
812 // [...] has at least one constexpr constructor or constructor template
813 // (possibly inherited from a base class) that is not a copy or move
814 // constructor [...]
815 if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
816 data().HasConstexprNonCopyMoveConstructor = true;
817 }
818
819 // Handle destructors.
820 if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
821 SMKind |= SMF_Destructor;
822
823 if (DD->isUserProvided())
824 data().HasIrrelevantDestructor = false;
825 // If the destructor is explicitly defaulted and not trivial or not public
826 // or if the destructor is deleted, we clear HasIrrelevantDestructor in
827 // finishedDefaultedOrDeletedMember.
828
829 // C++11 [class.dtor]p5:
830 // A destructor is trivial if [...] the destructor is not virtual.
831 if (DD->isVirtual()) {
832 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
833 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
834 }
835 }
836
837 // Handle member functions.
838 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
839 if (Method->isCopyAssignmentOperator()) {
840 SMKind |= SMF_CopyAssignment;
841
842 const auto *ParamTy =
843 Method->getParamDecl(0)->getType()->getAs<ReferenceType>();
844 if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
845 data().HasDeclaredCopyAssignmentWithConstParam = true;
846 }
847
848 if (Method->isMoveAssignmentOperator())
849 SMKind |= SMF_MoveAssignment;
850
851 // Keep the list of conversion functions up-to-date.
852 if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) {
853 // FIXME: We use the 'unsafe' accessor for the access specifier here,
854 // because Sema may not have set it yet. That's really just a misdesign
855 // in Sema. However, LLDB *will* have set the access specifier correctly,
856 // and adds declarations after the class is technically completed,
857 // so completeDefinition()'s overriding of the access specifiers doesn't
858 // work.
859 AccessSpecifier AS = Conversion->getAccessUnsafe();
860
861 if (Conversion->getPrimaryTemplate()) {
862 // We don't record specializations.
863 } else {
864 ASTContext &Ctx = getASTContext();
865 ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx);
866 NamedDecl *Primary =
867 FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion);
868 if (Primary->getPreviousDecl())
869 Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()),
870 Primary, AS);
871 else
872 Conversions.addDecl(Ctx, Primary, AS);
873 }
874 }
875
876 if (SMKind) {
877 // If this is the first declaration of a special member, we no longer have
878 // an implicit trivial special member.
879 data().HasTrivialSpecialMembers &=
880 data().DeclaredSpecialMembers | ~SMKind;
881 data().HasTrivialSpecialMembersForCall &=
882 data().DeclaredSpecialMembers | ~SMKind;
883
884 if (!Method->isImplicit() && !Method->isUserProvided()) {
885 // This method is user-declared but not user-provided. We can't work out
886 // whether it's trivial yet (not until we get to the end of the class).
887 // We'll handle this method in finishedDefaultedOrDeletedMember.
888 } else if (Method->isTrivial()) {
889 data().HasTrivialSpecialMembers |= SMKind;
890 data().HasTrivialSpecialMembersForCall |= SMKind;
891 } else if (Method->isTrivialForCall()) {
892 data().HasTrivialSpecialMembersForCall |= SMKind;
893 data().DeclaredNonTrivialSpecialMembers |= SMKind;
894 } else {
895 data().DeclaredNonTrivialSpecialMembers |= SMKind;
896 // If this is a user-provided function, do not set
897 // DeclaredNonTrivialSpecialMembersForCall here since we don't know
898 // yet whether the method would be considered non-trivial for the
899 // purpose of calls (attribute "trivial_abi" can be dropped from the
900 // class later, which can change the special method's triviality).
901 if (!Method->isUserProvided())
902 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
903 }
904
905 // Note when we have declared a declared special member, and suppress the
906 // implicit declaration of this special member.
907 data().DeclaredSpecialMembers |= SMKind;
908
909 if (!Method->isImplicit()) {
910 data().UserDeclaredSpecialMembers |= SMKind;
911
912 // C++03 [class]p4:
913 // A POD-struct is an aggregate class that has [...] no user-defined
914 // copy assignment operator and no user-defined destructor.
915 //
916 // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
917 // aggregates could not have any constructors, clear it even for an
918 // explicitly defaulted or deleted constructor.
919 // type is technically an aggregate in C++0x since it wouldn't be in 03.
920 //
921 // Also, a user-declared move assignment operator makes a class non-POD.
922 // This is an extension in C++03.
923 data().PlainOldData = false;
924 }
925 }
926
927 return;
928 }
929
930 // Handle non-static data members.
931 if (const auto *Field = dyn_cast<FieldDecl>(D)) {
932 ASTContext &Context = getASTContext();
933
934 // C++2a [class]p7:
935 // A standard-layout class is a class that:
936 // [...]
937 // -- has all non-static data members and bit-fields in the class and
938 // its base classes first declared in the same class
939 if (data().HasBasesWithFields)
940 data().IsStandardLayout = false;
941
942 // C++ [class.bit]p2:
943 // A declaration for a bit-field that omits the identifier declares an
944 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
945 // initialized.
946 if (Field->isUnnamedBitfield()) {
947 // C++ [meta.unary.prop]p4: [LWG2358]
948 // T is a class type [...] with [...] no unnamed bit-fields of non-zero
949 // length
950 if (data().Empty && !Field->isZeroLengthBitField(Context) &&
951 Context.getLangOpts().getClangABICompat() >
952 LangOptions::ClangABI::Ver6)
953 data().Empty = false;
954 return;
955 }
956
957 // C++11 [class]p7:
958 // A standard-layout class is a class that:
959 // -- either has no non-static data members in the most derived class
960 // [...] or has no base classes with non-static data members
961 if (data().HasBasesWithNonStaticDataMembers)
962 data().IsCXX11StandardLayout = false;
963
964 // C++ [dcl.init.aggr]p1:
965 // An aggregate is an array or a class (clause 9) with [...] no
966 // private or protected non-static data members (clause 11).
967 //
968 // A POD must be an aggregate.
969 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
970 data().Aggregate = false;
971 data().PlainOldData = false;
972
973 // C++20 [temp.param]p7:
974 // A structural type is [...] a literal class type [for which] all
975 // non-static data members are public
976 data().StructuralIfLiteral = false;
977 }
978
979 // Track whether this is the first field. We use this when checking
980 // whether the class is standard-layout below.
981 bool IsFirstField = !data().HasPrivateFields &&
982 !data().HasProtectedFields && !data().HasPublicFields;
983
984 // C++0x [class]p7:
985 // A standard-layout class is a class that:
986 // [...]
987 // -- has the same access control for all non-static data members,
988 switch (D->getAccess()) {
989 case AS_private: data().HasPrivateFields = true; break;
990 case AS_protected: data().HasProtectedFields = true; break;
991 case AS_public: data().HasPublicFields = true; break;
992 case AS_none: llvm_unreachable("Invalid access specifier")::llvm::llvm_unreachable_internal("Invalid access specifier",
"/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 992)
;
993 };
994 if ((data().HasPrivateFields + data().HasProtectedFields +
995 data().HasPublicFields) > 1) {
996 data().IsStandardLayout = false;
997 data().IsCXX11StandardLayout = false;
998 }
999
1000 // Keep track of the presence of mutable fields.
1001 if (Field->isMutable()) {
1002 data().HasMutableFields = true;
1003
1004 // C++20 [temp.param]p7:
1005 // A structural type is [...] a literal class type [for which] all
1006 // non-static data members are public
1007 data().StructuralIfLiteral = false;
1008 }
1009
1010 // C++11 [class.union]p8, DR1460:
1011 // If X is a union, a non-static data member of X that is not an anonymous
1012 // union is a variant member of X.
1013 if (isUnion() && !Field->isAnonymousStructOrUnion())
1014 data().HasVariantMembers = true;
1015
1016 // C++0x [class]p9:
1017 // A POD struct is a class that is both a trivial class and a
1018 // standard-layout class, and has no non-static data members of type
1019 // non-POD struct, non-POD union (or array of such types).
1020 //
1021 // Automatic Reference Counting: the presence of a member of Objective-C pointer type
1022 // that does not explicitly have no lifetime makes the class a non-POD.
1023 QualType T = Context.getBaseElementType(Field->getType());
1024 if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
1025 if (T.hasNonTrivialObjCLifetime()) {
1026 // Objective-C Automatic Reference Counting:
1027 // If a class has a non-static data member of Objective-C pointer
1028 // type (or array thereof), it is a non-POD type and its
1029 // default constructor (if any), copy constructor, move constructor,
1030 // copy assignment operator, move assignment operator, and destructor are
1031 // non-trivial.
1032 setHasObjectMember(true);
1033 struct DefinitionData &Data = data();
1034 Data.PlainOldData = false;
1035 Data.HasTrivialSpecialMembers = 0;
1036
1037 // __strong or __weak fields do not make special functions non-trivial
1038 // for the purpose of calls.
1039 Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime();
1040 if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak)
1041 data().HasTrivialSpecialMembersForCall = 0;
1042
1043 // Structs with __weak fields should never be passed directly.
1044 if (LT == Qualifiers::OCL_Weak)
1045 setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
1046
1047 Data.HasIrrelevantDestructor = false;
1048
1049 if (isUnion()) {
1050 data().DefaultedCopyConstructorIsDeleted = true;
1051 data().DefaultedMoveConstructorIsDeleted = true;
1052 data().DefaultedCopyAssignmentIsDeleted = true;
1053 data().DefaultedMoveAssignmentIsDeleted = true;
1054 data().DefaultedDestructorIsDeleted = true;
1055 data().NeedOverloadResolutionForCopyConstructor = true;
1056 data().NeedOverloadResolutionForMoveConstructor = true;
1057 data().NeedOverloadResolutionForCopyAssignment = true;
1058 data().NeedOverloadResolutionForMoveAssignment = true;
1059 data().NeedOverloadResolutionForDestructor = true;
1060 }
1061 } else if (!Context.getLangOpts().ObjCAutoRefCount) {
1062 setHasObjectMember(true);
1063 }
1064 } else if (!T.isCXX98PODType(Context))
1065 data().PlainOldData = false;
1066
1067 if (T->isReferenceType()) {
1068 if (!Field->hasInClassInitializer())
1069 data().HasUninitializedReferenceMember = true;
1070
1071 // C++0x [class]p7:
1072 // A standard-layout class is a class that:
1073 // -- has no non-static data members of type [...] reference,
1074 data().IsStandardLayout = false;
1075 data().IsCXX11StandardLayout = false;
1076
1077 // C++1z [class.copy.ctor]p10:
1078 // A defaulted copy constructor for a class X is defined as deleted if X has:
1079 // -- a non-static data member of rvalue reference type
1080 if (T->isRValueReferenceType())
1081 data().DefaultedCopyConstructorIsDeleted = true;
1082 }
1083
1084 if (!Field->hasInClassInitializer() && !Field->isMutable()) {
1085 if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {
1086 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())
1087 data().HasUninitializedFields = true;
1088 } else {
1089 data().HasUninitializedFields = true;
1090 }
1091 }
1092
1093 // Record if this field is the first non-literal or volatile field or base.
1094 if (!T->isLiteralType(Context) || T.isVolatileQualified())
1095 data().HasNonLiteralTypeFieldsOrBases = true;
1096
1097 if (Field->hasInClassInitializer() ||
1098 (Field->isAnonymousStructOrUnion() &&
1099 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
1100 data().HasInClassInitializer = true;
1101
1102 // C++11 [class]p5:
1103 // A default constructor is trivial if [...] no non-static data member
1104 // of its class has a brace-or-equal-initializer.
1105 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1106
1107 // C++11 [dcl.init.aggr]p1:
1108 // An aggregate is a [...] class with [...] no
1109 // brace-or-equal-initializers for non-static data members.
1110 //
1111 // This rule was removed in C++14.
1112 if (!getASTContext().getLangOpts().CPlusPlus14)
1113 data().Aggregate = false;
1114
1115 // C++11 [class]p10:
1116 // A POD struct is [...] a trivial class.
1117 data().PlainOldData = false;
1118 }
1119
1120 // C++11 [class.copy]p23:
1121 // A defaulted copy/move assignment operator for a class X is defined
1122 // as deleted if X has:
1123 // -- a non-static data member of reference type
1124 if (T->isReferenceType()) {
1125 data().DefaultedCopyAssignmentIsDeleted = true;
1126 data().DefaultedMoveAssignmentIsDeleted = true;
1127 }
1128
1129 // Bitfields of length 0 are also zero-sized, but we already bailed out for
1130 // those because they are always unnamed.
1131 bool IsZeroSize = Field->isZeroSize(Context);
1132
1133 if (const auto *RecordTy = T->getAs<RecordType>()) {
1134 auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
1135 if (FieldRec->getDefinition()) {
1136 addedClassSubobject(FieldRec);
1137
1138 // We may need to perform overload resolution to determine whether a
1139 // field can be moved if it's const or volatile qualified.
1140 if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) {
1141 // We need to care about 'const' for the copy constructor because an
1142 // implicit copy constructor might be declared with a non-const
1143 // parameter.
1144 data().NeedOverloadResolutionForCopyConstructor = true;
1145 data().NeedOverloadResolutionForMoveConstructor = true;
1146 data().NeedOverloadResolutionForCopyAssignment = true;
1147 data().NeedOverloadResolutionForMoveAssignment = true;
1148 }
1149
1150 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
1151 // A defaulted [special member] for a class X is defined as
1152 // deleted if:
1153 // -- X is a union-like class that has a variant member with a
1154 // non-trivial [corresponding special member]
1155 if (isUnion()) {
1156 if (FieldRec->hasNonTrivialCopyConstructor())
1157 data().DefaultedCopyConstructorIsDeleted = true;
1158 if (FieldRec->hasNonTrivialMoveConstructor())
1159 data().DefaultedMoveConstructorIsDeleted = true;
1160 if (FieldRec->hasNonTrivialCopyAssignment())
1161 data().DefaultedCopyAssignmentIsDeleted = true;
1162 if (FieldRec->hasNonTrivialMoveAssignment())
1163 data().DefaultedMoveAssignmentIsDeleted = true;
1164 if (FieldRec->hasNonTrivialDestructor())
1165 data().DefaultedDestructorIsDeleted = true;
1166 }
1167
1168 // For an anonymous union member, our overload resolution will perform
1169 // overload resolution for its members.
1170 if (Field->isAnonymousStructOrUnion()) {
1171 data().NeedOverloadResolutionForCopyConstructor |=
1172 FieldRec->data().NeedOverloadResolutionForCopyConstructor;
1173 data().NeedOverloadResolutionForMoveConstructor |=
1174 FieldRec->data().NeedOverloadResolutionForMoveConstructor;
1175 data().NeedOverloadResolutionForCopyAssignment |=
1176 FieldRec->data().NeedOverloadResolutionForCopyAssignment;
1177 data().NeedOverloadResolutionForMoveAssignment |=
1178 FieldRec->data().NeedOverloadResolutionForMoveAssignment;
1179 data().NeedOverloadResolutionForDestructor |=
1180 FieldRec->data().NeedOverloadResolutionForDestructor;
1181 }
1182
1183 // C++0x [class.ctor]p5:
1184 // A default constructor is trivial [...] if:
1185 // -- for all the non-static data members of its class that are of
1186 // class type (or array thereof), each such class has a trivial
1187 // default constructor.
1188 if (!FieldRec->hasTrivialDefaultConstructor())
1189 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1190
1191 // C++0x [class.copy]p13:
1192 // A copy/move constructor for class X is trivial if [...]
1193 // [...]
1194 // -- for each non-static data member of X that is of class type (or
1195 // an array thereof), the constructor selected to copy/move that
1196 // member is trivial;
1197 if (!FieldRec->hasTrivialCopyConstructor())
1198 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
1199
1200 if (!FieldRec->hasTrivialCopyConstructorForCall())
1201 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
1202
1203 // If the field doesn't have a simple move constructor, we'll eagerly
1204 // declare the move constructor for this class and we'll decide whether
1205 // it's trivial then.
1206 if (!FieldRec->hasTrivialMoveConstructor())
1207 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
1208
1209 if (!FieldRec->hasTrivialMoveConstructorForCall())
1210 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
1211
1212 // C++0x [class.copy]p27:
1213 // A copy/move assignment operator for class X is trivial if [...]
1214 // [...]
1215 // -- for each non-static data member of X that is of class type (or
1216 // an array thereof), the assignment operator selected to
1217 // copy/move that member is trivial;
1218 if (!FieldRec->hasTrivialCopyAssignment())
1219 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
1220 // If the field doesn't have a simple move assignment, we'll eagerly
1221 // declare the move assignment for this class and we'll decide whether
1222 // it's trivial then.
1223 if (!FieldRec->hasTrivialMoveAssignment())
1224 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
1225
1226 if (!FieldRec->hasTrivialDestructor())
1227 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
1228 if (!FieldRec->hasTrivialDestructorForCall())
1229 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
1230 if (!FieldRec->hasIrrelevantDestructor())
1231 data().HasIrrelevantDestructor = false;
1232 if (FieldRec->hasObjectMember())
1233 setHasObjectMember(true);
1234 if (FieldRec->hasVolatileMember())
1235 setHasVolatileMember(true);
1236 if (FieldRec->getArgPassingRestrictions() ==
1237 RecordDecl::APK_CanNeverPassInRegs)
1238 setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
1239
1240 // C++0x [class]p7:
1241 // A standard-layout class is a class that:
1242 // -- has no non-static data members of type non-standard-layout
1243 // class (or array of such types) [...]
1244 if (!FieldRec->isStandardLayout())
1245 data().IsStandardLayout = false;
1246 if (!FieldRec->isCXX11StandardLayout())
1247 data().IsCXX11StandardLayout = false;
1248
1249 // C++2a [class]p7:
1250 // A standard-layout class is a class that:
1251 // [...]
1252 // -- has no element of the set M(S) of types as a base class.
1253 if (data().IsStandardLayout &&
1254 (isUnion() || IsFirstField || IsZeroSize) &&
1255 hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec))
1256 data().IsStandardLayout = false;
1257
1258 // C++11 [class]p7:
1259 // A standard-layout class is a class that:
1260 // -- has no base classes of the same type as the first non-static
1261 // data member
1262 if (data().IsCXX11StandardLayout && IsFirstField) {
1263 // FIXME: We should check all base classes here, not just direct
1264 // base classes.
1265 for (const auto &BI : bases()) {
1266 if (Context.hasSameUnqualifiedType(BI.getType(), T)) {
1267 data().IsCXX11StandardLayout = false;
1268 break;
1269 }
1270 }
1271 }
1272
1273 // Keep track of the presence of mutable fields.
1274 if (FieldRec->hasMutableFields())
1275 data().HasMutableFields = true;
1276
1277 if (Field->isMutable()) {
1278 // Our copy constructor/assignment might call something other than
1279 // the subobject's copy constructor/assignment if it's mutable and of
1280 // class type.
1281 data().NeedOverloadResolutionForCopyConstructor = true;
1282 data().NeedOverloadResolutionForCopyAssignment = true;
1283 }
1284
1285 // C++11 [class.copy]p13:
1286 // If the implicitly-defined constructor would satisfy the
1287 // requirements of a constexpr constructor, the implicitly-defined
1288 // constructor is constexpr.
1289 // C++11 [dcl.constexpr]p4:
1290 // -- every constructor involved in initializing non-static data
1291 // members [...] shall be a constexpr constructor
1292 if (!Field->hasInClassInitializer() &&
1293 !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
1294 // The standard requires any in-class initializer to be a constant
1295 // expression. We consider this to be a defect.
1296 data().DefaultedDefaultConstructorIsConstexpr = false;
1297
1298 // C++11 [class.copy]p8:
1299 // The implicitly-declared copy constructor for a class X will have
1300 // the form 'X::X(const X&)' if each potentially constructed subobject
1301 // of a class type M (or array thereof) has a copy constructor whose
1302 // first parameter is of type 'const M&' or 'const volatile M&'.
1303 if (!FieldRec->hasCopyConstructorWithConstParam())
1304 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
1305
1306 // C++11 [class.copy]p18:
1307 // The implicitly-declared copy assignment oeprator for a class X will
1308 // have the form 'X& X::operator=(const X&)' if [...] for all the
1309 // non-static data members of X that are of a class type M (or array
1310 // thereof), each such class type has a copy assignment operator whose
1311 // parameter is of type 'const M&', 'const volatile M&' or 'M'.
1312 if (!FieldRec->hasCopyAssignmentWithConstParam())
1313 data().ImplicitCopyAssignmentHasConstParam = false;
1314
1315 if (FieldRec->hasUninitializedReferenceMember() &&
1316 !Field->hasInClassInitializer())
1317 data().HasUninitializedReferenceMember = true;
1318
1319 // C++11 [class.union]p8, DR1460:
1320 // a non-static data member of an anonymous union that is a member of
1321 // X is also a variant member of X.
1322 if (FieldRec->hasVariantMembers() &&
1323 Field->isAnonymousStructOrUnion())
1324 data().HasVariantMembers = true;
1325 }
1326 } else {
1327 // Base element type of field is a non-class type.
1328 if (!T->isLiteralType(Context) ||
1329 (!Field->hasInClassInitializer() && !isUnion() &&
1330 !Context.getLangOpts().CPlusPlus20))
1331 data().DefaultedDefaultConstructorIsConstexpr = false;
1332
1333 // C++11 [class.copy]p23:
1334 // A defaulted copy/move assignment operator for a class X is defined
1335 // as deleted if X has:
1336 // -- a non-static data member of const non-class type (or array
1337 // thereof)
1338 if (T.isConstQualified()) {
1339 data().DefaultedCopyAssignmentIsDeleted = true;
1340 data().DefaultedMoveAssignmentIsDeleted = true;
1341 }
1342
1343 // C++20 [temp.param]p7:
1344 // A structural type is [...] a literal class type [for which] the
1345 // types of all non-static data members are structural types or
1346 // (possibly multidimensional) array thereof
1347 // We deal with class types elsewhere.
1348 if (!T->isStructuralType())
1349 data().StructuralIfLiteral = false;
1350 }
1351
1352 // C++14 [meta.unary.prop]p4:
1353 // T is a class type [...] with [...] no non-static data members other
1354 // than subobjects of zero size
1355 if (data().Empty && !IsZeroSize)
1356 data().Empty = false;
1357 }
1358
1359 // Handle using declarations of conversion functions.
1360 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) {
1361 if (Shadow->getDeclName().getNameKind()
1362 == DeclarationName::CXXConversionFunctionName) {
1363 ASTContext &Ctx = getASTContext();
1364 data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess());
1365 }
1366 }
1367
1368 if (const auto *Using = dyn_cast<UsingDecl>(D)) {
1369 if (Using->getDeclName().getNameKind() ==
1370 DeclarationName::CXXConstructorName) {
1371 data().HasInheritedConstructor = true;
1372 // C++1z [dcl.init.aggr]p1:
1373 // An aggregate is [...] a class [...] with no inherited constructors
1374 data().Aggregate = false;
1375 }
1376
1377 if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal)
1378 data().HasInheritedAssignment = true;
1379 }
1380}
1381
1382void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
1383 assert(!D->isImplicit() && !D->isUserProvided())((!D->isImplicit() && !D->isUserProvided()) ? static_cast
<void> (0) : __assert_fail ("!D->isImplicit() && !D->isUserProvided()"
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1383, __PRETTY_FUNCTION__))
;
1384
1385 // The kind of special member this declaration is, if any.
1386 unsigned SMKind = 0;
1387
1388 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1389 if (Constructor->isDefaultConstructor()) {
1390 SMKind |= SMF_DefaultConstructor;
1391 if (Constructor->isConstexpr())
1392 data().HasConstexprDefaultConstructor = true;
1393 }
1394 if (Constructor->isCopyConstructor())
1395 SMKind |= SMF_CopyConstructor;
1396 else if (Constructor->isMoveConstructor())
1397 SMKind |= SMF_MoveConstructor;
1398 else if (Constructor->isConstexpr())
1399 // We may now know that the constructor is constexpr.
1400 data().HasConstexprNonCopyMoveConstructor = true;
1401 } else if (isa<CXXDestructorDecl>(D)) {
1402 SMKind |= SMF_Destructor;
1403 if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted())
1404 data().HasIrrelevantDestructor = false;
1405 } else if (D->isCopyAssignmentOperator())
1406 SMKind |= SMF_CopyAssignment;
1407 else if (D->isMoveAssignmentOperator())
1408 SMKind |= SMF_MoveAssignment;
1409
1410 // Update which trivial / non-trivial special members we have.
1411 // addedMember will have skipped this step for this member.
1412 if (D->isTrivial())
1413 data().HasTrivialSpecialMembers |= SMKind;
1414 else
1415 data().DeclaredNonTrivialSpecialMembers |= SMKind;
1416}
1417
1418void CXXRecordDecl::setCaptures(ASTContext &Context,
1419 ArrayRef<LambdaCapture> Captures) {
1420 CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData();
1421
1422 // Copy captures.
1423 Data.NumCaptures = Captures.size();
1424 Data.NumExplicitCaptures = 0;
1425 Data.Captures = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) *
1426 Captures.size());
1427 LambdaCapture *ToCapture = Data.Captures;
1428 for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
1429 if (Captures[I].isExplicit())
1430 ++Data.NumExplicitCaptures;
1431
1432 *ToCapture++ = Captures[I];
1433 }
1434
1435 if (!lambdaIsDefaultConstructibleAndAssignable())
1436 Data.DefaultedCopyAssignmentIsDeleted = true;
1437}
1438
1439void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) {
1440 unsigned SMKind = 0;
1441
1442 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1443 if (Constructor->isCopyConstructor())
1444 SMKind = SMF_CopyConstructor;
1445 else if (Constructor->isMoveConstructor())
1446 SMKind = SMF_MoveConstructor;
1447 } else if (isa<CXXDestructorDecl>(D))
1448 SMKind = SMF_Destructor;
1449
1450 if (D->isTrivialForCall())
1451 data().HasTrivialSpecialMembersForCall |= SMKind;
1452 else
1453 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
1454}
1455
1456bool CXXRecordDecl::isCLike() const {
1457 if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface ||
1458 !TemplateOrInstantiation.isNull())
1459 return false;
1460 if (!hasDefinition())
1461 return true;
1462
1463 return isPOD() && data().HasOnlyCMembers;
1464}
1465
1466bool CXXRecordDecl::isGenericLambda() const {
1467 if (!isLambda()) return false;
1468 return getLambdaData().IsGenericLambda;
1469}
1470
1471#ifndef NDEBUG
1472static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {
1473 for (auto *D : R)
1474 if (!declaresSameEntity(D, R.front()))
1475 return false;
1476 return true;
1477}
1478#endif
1479
1480static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) {
1481 if (!RD.isLambda()) return nullptr;
1482 DeclarationName Name =
1483 RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
1484 DeclContext::lookup_result Calls = RD.lookup(Name);
1485
1486 assert(!Calls.empty() && "Missing lambda call operator!")((!Calls.empty() && "Missing lambda call operator!") ?
static_cast<void> (0) : __assert_fail ("!Calls.empty() && \"Missing lambda call operator!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1486, __PRETTY_FUNCTION__))
;
1487 assert(allLookupResultsAreTheSame(Calls) &&((allLookupResultsAreTheSame(Calls) && "More than one lambda call operator!"
) ? static_cast<void> (0) : __assert_fail ("allLookupResultsAreTheSame(Calls) && \"More than one lambda call operator!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1488, __PRETTY_FUNCTION__))
1488 "More than one lambda call operator!")((allLookupResultsAreTheSame(Calls) && "More than one lambda call operator!"
) ? static_cast<void> (0) : __assert_fail ("allLookupResultsAreTheSame(Calls) && \"More than one lambda call operator!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1488, __PRETTY_FUNCTION__))
;
1489 return Calls.front();
1490}
1491
1492FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {
1493 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
1494 return dyn_cast_or_null<FunctionTemplateDecl>(CallOp);
1495}
1496
1497CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const {
1498 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
1499
1500 if (CallOp == nullptr)
1501 return nullptr;
1502
1503 if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp))
1504 return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl());
1505
1506 return cast<CXXMethodDecl>(CallOp);
1507}
1508
1509CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {
1510 CXXMethodDecl *CallOp = getLambdaCallOperator();
1511 CallingConv CC = CallOp->getType()->getAs<FunctionType>()->getCallConv();
1
Assuming the object is a 'FunctionType'
1512 return getLambdaStaticInvoker(CC);
2
Calling 'CXXRecordDecl::getLambdaStaticInvoker'
1513}
1514
1515static DeclContext::lookup_result
1516getLambdaStaticInvokers(const CXXRecordDecl &RD) {
1517 assert(RD.isLambda() && "Must be a lambda")((RD.isLambda() && "Must be a lambda") ? static_cast<
void> (0) : __assert_fail ("RD.isLambda() && \"Must be a lambda\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1517, __PRETTY_FUNCTION__))
;
1518 DeclarationName Name =
1519 &RD.getASTContext().Idents.get(getLambdaStaticInvokerName());
1520 return RD.lookup(Name);
1521}
1522
1523static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) {
1524 if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND))
1525 return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl());
1526 return cast<CXXMethodDecl>(ND);
1527}
1528
1529CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const {
1530 if (!isLambda())
3
Calling 'CXXRecordDecl::isLambda'
6
Returning from 'CXXRecordDecl::isLambda'
7
Assuming the condition is false
8
Taking false branch
1531 return nullptr;
1532 DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this);
1533
1534 for (NamedDecl *ND : Invoker) {
1535 const FunctionType *FTy =
11
'FTy' initialized to a null pointer value
1536 cast<ValueDecl>(ND->getAsFunction())->getType()->getAs<FunctionType>();
9
The object is a 'ValueDecl'
10
Assuming the object is not a 'FunctionType'
1537 if (FTy->getCallConv() == CC)
12
Called C++ object pointer is null
1538 return getInvokerAsMethod(ND);
1539 }
1540
1541 return nullptr;
1542}
1543
1544void CXXRecordDecl::getCaptureFields(
1545 llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1546 FieldDecl *&ThisCapture) const {
1547 Captures.clear();
1548 ThisCapture = nullptr;
1549
1550 LambdaDefinitionData &Lambda = getLambdaData();
1551 RecordDecl::field_iterator Field = field_begin();
1552 for (const LambdaCapture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures;
1553 C != CEnd; ++C, ++Field) {
1554 if (C->capturesThis())
1555 ThisCapture = *Field;
1556 else if (C->capturesVariable())
1557 Captures[C->getCapturedVar()] = *Field;
1558 }
1559 assert(Field == field_end())((Field == field_end()) ? static_cast<void> (0) : __assert_fail
("Field == field_end()", "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1559, __PRETTY_FUNCTION__))
;
1560}
1561
1562TemplateParameterList *
1563CXXRecordDecl::getGenericLambdaTemplateParameterList() const {
1564 if (!isGenericLambda()) return nullptr;
1565 CXXMethodDecl *CallOp = getLambdaCallOperator();
1566 if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())
1567 return Tmpl->getTemplateParameters();
1568 return nullptr;
1569}
1570
1571ArrayRef<NamedDecl *>
1572CXXRecordDecl::getLambdaExplicitTemplateParameters() const {
1573 TemplateParameterList *List = getGenericLambdaTemplateParameterList();
1574 if (!List)
1575 return {};
1576
1577 assert(std::is_partitioned(List->begin(), List->end(),((std::is_partitioned(List->begin(), List->end(), [](const
NamedDecl *D) { return !D->isImplicit(); }) && "Explicit template params should be ordered before implicit ones"
) ? static_cast<void> (0) : __assert_fail ("std::is_partitioned(List->begin(), List->end(), [](const NamedDecl *D) { return !D->isImplicit(); }) && \"Explicit template params should be ordered before implicit ones\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1579, __PRETTY_FUNCTION__))
1578 [](const NamedDecl *D) { return !D->isImplicit(); })((std::is_partitioned(List->begin(), List->end(), [](const
NamedDecl *D) { return !D->isImplicit(); }) && "Explicit template params should be ordered before implicit ones"
) ? static_cast<void> (0) : __assert_fail ("std::is_partitioned(List->begin(), List->end(), [](const NamedDecl *D) { return !D->isImplicit(); }) && \"Explicit template params should be ordered before implicit ones\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1579, __PRETTY_FUNCTION__))
1579 && "Explicit template params should be ordered before implicit ones")((std::is_partitioned(List->begin(), List->end(), [](const
NamedDecl *D) { return !D->isImplicit(); }) && "Explicit template params should be ordered before implicit ones"
) ? static_cast<void> (0) : __assert_fail ("std::is_partitioned(List->begin(), List->end(), [](const NamedDecl *D) { return !D->isImplicit(); }) && \"Explicit template params should be ordered before implicit ones\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1579, __PRETTY_FUNCTION__))
;
1580
1581 const auto ExplicitEnd = llvm::partition_point(
1582 *List, [](const NamedDecl *D) { return !D->isImplicit(); });
1583 return llvm::makeArrayRef(List->begin(), ExplicitEnd);
1584}
1585
1586Decl *CXXRecordDecl::getLambdaContextDecl() const {
1587 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1587, __PRETTY_FUNCTION__))
;
1588 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1589 return getLambdaData().ContextDecl.get(Source);
1590}
1591
1592static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
1593 QualType T =
1594 cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction())
1595 ->getConversionType();
1596 return Context.getCanonicalType(T);
1597}
1598
1599/// Collect the visible conversions of a base class.
1600///
1601/// \param Record a base class of the class we're considering
1602/// \param InVirtual whether this base class is a virtual base (or a base
1603/// of a virtual base)
1604/// \param Access the access along the inheritance path to this base
1605/// \param ParentHiddenTypes the conversions provided by the inheritors
1606/// of this base
1607/// \param Output the set to which to add conversions from non-virtual bases
1608/// \param VOutput the set to which to add conversions from virtual bases
1609/// \param HiddenVBaseCs the set of conversions which were hidden in a
1610/// virtual base along some inheritance path
1611static void CollectVisibleConversions(
1612 ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual,
1613 AccessSpecifier Access,
1614 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
1615 ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput,
1616 llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) {
1617 // The set of types which have conversions in this class or its
1618 // subclasses. As an optimization, we don't copy the derived set
1619 // unless it might change.
1620 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
1621 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
1622
1623 // Collect the direct conversions and figure out which conversions
1624 // will be hidden in the subclasses.
1625 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1626 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1627 if (ConvI != ConvE) {
1628 HiddenTypesBuffer = ParentHiddenTypes;
1629 HiddenTypes = &HiddenTypesBuffer;
1630
1631 for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
1632 CanQualType ConvType(GetConversionType(Context, I.getDecl()));
1633 bool Hidden = ParentHiddenTypes.count(ConvType);
1634 if (!Hidden)
1635 HiddenTypesBuffer.insert(ConvType);
1636
1637 // If this conversion is hidden and we're in a virtual base,
1638 // remember that it's hidden along some inheritance path.
1639 if (Hidden && InVirtual)
1640 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1641
1642 // If this conversion isn't hidden, add it to the appropriate output.
1643 else if (!Hidden) {
1644 AccessSpecifier IAccess
1645 = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1646
1647 if (InVirtual)
1648 VOutput.addDecl(I.getDecl(), IAccess);
1649 else
1650 Output.addDecl(Context, I.getDecl(), IAccess);
1651 }
1652 }
1653 }
1654
1655 // Collect information recursively from any base classes.
1656 for (const auto &I : Record->bases()) {
1657 const auto *RT = I.getType()->getAs<RecordType>();
1658 if (!RT) continue;
1659
1660 AccessSpecifier BaseAccess
1661 = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier());
1662 bool BaseInVirtual = InVirtual || I.isVirtual();
1663
1664 auto *Base = cast<CXXRecordDecl>(RT->getDecl());
1665 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1666 *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1667 }
1668}
1669
1670/// Collect the visible conversions of a class.
1671///
1672/// This would be extremely straightforward if it weren't for virtual
1673/// bases. It might be worth special-casing that, really.
1674static void CollectVisibleConversions(ASTContext &Context,
1675 const CXXRecordDecl *Record,
1676 ASTUnresolvedSet &Output) {
1677 // The collection of all conversions in virtual bases that we've
1678 // found. These will be added to the output as long as they don't
1679 // appear in the hidden-conversions set.
1680 UnresolvedSet<8> VBaseCs;
1681
1682 // The set of conversions in virtual bases that we've determined to
1683 // be hidden.
1684 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1685
1686 // The set of types hidden by classes derived from this one.
1687 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1688
1689 // Go ahead and collect the direct conversions and add them to the
1690 // hidden-types set.
1691 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1692 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1693 Output.append(Context, ConvI, ConvE);
1694 for (; ConvI != ConvE; ++ConvI)
1695 HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));
1696
1697 // Recursively collect conversions from base classes.
1698 for (const auto &I : Record->bases()) {
1699 const auto *RT = I.getType()->getAs<RecordType>();
1700 if (!RT) continue;
1701
1702 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1703 I.isVirtual(), I.getAccessSpecifier(),
1704 HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1705 }
1706
1707 // Add any unhidden conversions provided by virtual bases.
1708 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1709 I != E; ++I) {
1710 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1711 Output.addDecl(Context, I.getDecl(), I.getAccess());
1712 }
1713}
1714
1715/// getVisibleConversionFunctions - get all conversion functions visible
1716/// in current class; including conversion function templates.
1717llvm::iterator_range<CXXRecordDecl::conversion_iterator>
1718CXXRecordDecl::getVisibleConversionFunctions() const {
1719 ASTContext &Ctx = getASTContext();
1720
1721 ASTUnresolvedSet *Set;
1722 if (bases_begin() == bases_end()) {
1723 // If root class, all conversions are visible.
1724 Set = &data().Conversions.get(Ctx);
1725 } else {
1726 Set = &data().VisibleConversions.get(Ctx);
1727 // If visible conversion list is not evaluated, evaluate it.
1728 if (!data().ComputedVisibleConversions) {
1729 CollectVisibleConversions(Ctx, this, *Set);
1730 data().ComputedVisibleConversions = true;
1731 }
1732 }
1733 return llvm::make_range(Set->begin(), Set->end());
1734}
1735
1736void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1737 // This operation is O(N) but extremely rare. Sema only uses it to
1738 // remove UsingShadowDecls in a class that were followed by a direct
1739 // declaration, e.g.:
1740 // class A : B {
1741 // using B::operator int;
1742 // operator int();
1743 // };
1744 // This is uncommon by itself and even more uncommon in conjunction
1745 // with sufficiently large numbers of directly-declared conversions
1746 // that asymptotic behavior matters.
1747
1748 ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext());
1749 for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1750 if (Convs[I].getDecl() == ConvDecl) {
1751 Convs.erase(I);
1752 assert(llvm::find(Convs, ConvDecl) == Convs.end() &&((llvm::find(Convs, ConvDecl) == Convs.end() && "conversion was found multiple times in unresolved set"
) ? static_cast<void> (0) : __assert_fail ("llvm::find(Convs, ConvDecl) == Convs.end() && \"conversion was found multiple times in unresolved set\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1753, __PRETTY_FUNCTION__))
1753 "conversion was found multiple times in unresolved set")((llvm::find(Convs, ConvDecl) == Convs.end() && "conversion was found multiple times in unresolved set"
) ? static_cast<void> (0) : __assert_fail ("llvm::find(Convs, ConvDecl) == Convs.end() && \"conversion was found multiple times in unresolved set\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1753, __PRETTY_FUNCTION__))
;
1754 return;
1755 }
1756 }
1757
1758 llvm_unreachable("conversion not found in set!")::llvm::llvm_unreachable_internal("conversion not found in set!"
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1758)
;
1759}
1760
1761CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1762 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1763 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1764
1765 return nullptr;
1766}
1767
1768MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
1769 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
1770}
1771
1772void
1773CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1774 TemplateSpecializationKind TSK) {
1775 assert(TemplateOrInstantiation.isNull() &&((TemplateOrInstantiation.isNull() && "Previous template or instantiation?"
) ? static_cast<void> (0) : __assert_fail ("TemplateOrInstantiation.isNull() && \"Previous template or instantiation?\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1776, __PRETTY_FUNCTION__))
1776 "Previous template or instantiation?")((TemplateOrInstantiation.isNull() && "Previous template or instantiation?"
) ? static_cast<void> (0) : __assert_fail ("TemplateOrInstantiation.isNull() && \"Previous template or instantiation?\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1776, __PRETTY_FUNCTION__))
;
1777 assert(!isa<ClassTemplatePartialSpecializationDecl>(this))((!isa<ClassTemplatePartialSpecializationDecl>(this)) ?
static_cast<void> (0) : __assert_fail ("!isa<ClassTemplatePartialSpecializationDecl>(this)"
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1777, __PRETTY_FUNCTION__))
;
1778 TemplateOrInstantiation
1779 = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1780}
1781
1782ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {
1783 return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>();
1784}
1785
1786void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {
1787 TemplateOrInstantiation = Template;
1788}
1789
1790TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1791 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this))
1792 return Spec->getSpecializationKind();
1793
1794 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1795 return MSInfo->getTemplateSpecializationKind();
1796
1797 return TSK_Undeclared;
1798}
1799
1800void
1801CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1802 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1803 Spec->setSpecializationKind(TSK);
1804 return;
1805 }
1806
1807 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1808 MSInfo->setTemplateSpecializationKind(TSK);
1809 return;
1810 }
1811
1812 llvm_unreachable("Not a class template or member class specialization")::llvm::llvm_unreachable_internal("Not a class template or member class specialization"
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1812)
;
1813}
1814
1815const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {
1816 auto GetDefinitionOrSelf =
1817 [](const CXXRecordDecl *D) -> const CXXRecordDecl * {
1818 if (auto *Def = D->getDefinition())
1819 return Def;
1820 return D;
1821 };
1822
1823 // If it's a class template specialization, find the template or partial
1824 // specialization from which it was instantiated.
1825 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1826 auto From = TD->getInstantiatedFrom();
1827 if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) {
1828 while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {
1829 if (NewCTD->isMemberSpecialization())
1830 break;
1831 CTD = NewCTD;
1832 }
1833 return GetDefinitionOrSelf(CTD->getTemplatedDecl());
1834 }
1835 if (auto *CTPSD =
1836 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
1837 while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {
1838 if (NewCTPSD->isMemberSpecialization())
1839 break;
1840 CTPSD = NewCTPSD;
1841 }
1842 return GetDefinitionOrSelf(CTPSD);
1843 }
1844 }
1845
1846 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1847 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
1848 const CXXRecordDecl *RD = this;
1849 while (auto *NewRD = RD->getInstantiatedFromMemberClass())
1850 RD = NewRD;
1851 return GetDefinitionOrSelf(RD);
1852 }
1853 }
1854
1855 assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) &&((!isTemplateInstantiation(this->getTemplateSpecializationKind
()) && "couldn't find pattern for class template instantiation"
) ? static_cast<void> (0) : __assert_fail ("!isTemplateInstantiation(this->getTemplateSpecializationKind()) && \"couldn't find pattern for class template instantiation\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1856, __PRETTY_FUNCTION__))
1856 "couldn't find pattern for class template instantiation")((!isTemplateInstantiation(this->getTemplateSpecializationKind
()) && "couldn't find pattern for class template instantiation"
) ? static_cast<void> (0) : __assert_fail ("!isTemplateInstantiation(this->getTemplateSpecializationKind()) && \"couldn't find pattern for class template instantiation\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1856, __PRETTY_FUNCTION__))
;
1857 return nullptr;
1858}
1859
1860CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1861 ASTContext &Context = getASTContext();
1862 QualType ClassType = Context.getTypeDeclType(this);
1863
1864 DeclarationName Name
1865 = Context.DeclarationNames.getCXXDestructorName(
1866 Context.getCanonicalType(ClassType));
1867
1868 DeclContext::lookup_result R = lookup(Name);
1869
1870 return R.empty() ? nullptr : dyn_cast<CXXDestructorDecl>(R.front());
1871}
1872
1873bool CXXRecordDecl::isAnyDestructorNoReturn() const {
1874 // Destructor is noreturn.
1875 if (const CXXDestructorDecl *Destructor = getDestructor())
1876 if (Destructor->isNoReturn())
1877 return true;
1878
1879 // Check base classes destructor for noreturn.
1880 for (const auto &Base : bases())
1881 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl())
1882 if (RD->isAnyDestructorNoReturn())
1883 return true;
1884
1885 // Check fields for noreturn.
1886 for (const auto *Field : fields())
1887 if (const CXXRecordDecl *RD =
1888 Field->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
1889 if (RD->isAnyDestructorNoReturn())
1890 return true;
1891
1892 // All destructors are not noreturn.
1893 return false;
1894}
1895
1896static bool isDeclContextInNamespace(const DeclContext *DC) {
1897 while (!DC->isTranslationUnit()) {
1898 if (DC->isNamespace())
1899 return true;
1900 DC = DC->getParent();
1901 }
1902 return false;
1903}
1904
1905bool CXXRecordDecl::isInterfaceLike() const {
1906 assert(hasDefinition() && "checking for interface-like without a definition")((hasDefinition() && "checking for interface-like without a definition"
) ? static_cast<void> (0) : __assert_fail ("hasDefinition() && \"checking for interface-like without a definition\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1906, __PRETTY_FUNCTION__))
;
1907 // All __interfaces are inheritently interface-like.
1908 if (isInterface())
1909 return true;
1910
1911 // Interface-like types cannot have a user declared constructor, destructor,
1912 // friends, VBases, conversion functions, or fields. Additionally, lambdas
1913 // cannot be interface types.
1914 if (isLambda() || hasUserDeclaredConstructor() ||
1915 hasUserDeclaredDestructor() || !field_empty() || hasFriends() ||
1916 getNumVBases() > 0 || conversion_end() - conversion_begin() > 0)
1917 return false;
1918
1919 // No interface-like type can have a method with a definition.
1920 for (const auto *const Method : methods())
1921 if (Method->isDefined() && !Method->isImplicit())
1922 return false;
1923
1924 // Check "Special" types.
1925 const auto *Uuid = getAttr<UuidAttr>();
1926 // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an
1927 // extern C++ block directly in the TU. These are only valid if in one
1928 // of these two situations.
1929 if (Uuid && isStruct() && !getDeclContext()->isExternCContext() &&
1930 !isDeclContextInNamespace(getDeclContext()) &&
1931 ((getName() == "IUnknown" &&
1932 Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") ||
1933 (getName() == "IDispatch" &&
1934 Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) {
1935 if (getNumBases() > 0)
1936 return false;
1937 return true;
1938 }
1939
1940 // FIXME: Any access specifiers is supposed to make this no longer interface
1941 // like.
1942
1943 // If this isn't a 'special' type, it must have a single interface-like base.
1944 if (getNumBases() != 1)
1945 return false;
1946
1947 const auto BaseSpec = *bases_begin();
1948 if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public)
1949 return false;
1950 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
1951 if (Base->isInterface() || !Base->isInterfaceLike())
1952 return false;
1953 return true;
1954}
1955
1956void CXXRecordDecl::completeDefinition() {
1957 completeDefinition(nullptr);
1958}
1959
1960void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1961 RecordDecl::completeDefinition();
1962
1963 // If the class may be abstract (but hasn't been marked as such), check for
1964 // any pure final overriders.
1965 if (mayBeAbstract()) {
1966 CXXFinalOverriderMap MyFinalOverriders;
1967 if (!FinalOverriders) {
1968 getFinalOverriders(MyFinalOverriders);
1969 FinalOverriders = &MyFinalOverriders;
1970 }
1971
1972 bool Done = false;
1973 for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
1974 MEnd = FinalOverriders->end();
1975 M != MEnd && !Done; ++M) {
1976 for (OverridingMethods::iterator SO = M->second.begin(),
1977 SOEnd = M->second.end();
1978 SO != SOEnd && !Done; ++SO) {
1979 assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "All virtual functions have overriding virtual functions"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"All virtual functions have overriding virtual functions\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1980, __PRETTY_FUNCTION__))
1980 "All virtual functions have overriding virtual functions")((SO->second.size() > 0 && "All virtual functions have overriding virtual functions"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"All virtual functions have overriding virtual functions\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 1980, __PRETTY_FUNCTION__))
;
1981
1982 // C++ [class.abstract]p4:
1983 // A class is abstract if it contains or inherits at least one
1984 // pure virtual function for which the final overrider is pure
1985 // virtual.
1986 if (SO->second.front().Method->isPure()) {
1987 data().Abstract = true;
1988 Done = true;
1989 break;
1990 }
1991 }
1992 }
1993 }
1994
1995 // Set access bits correctly on the directly-declared conversions.
1996 for (conversion_iterator I = conversion_begin(), E = conversion_end();
1997 I != E; ++I)
1998 I.setAccess((*I)->getAccess());
1999}
2000
2001bool CXXRecordDecl::mayBeAbstract() const {
2002 if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
2003 isDependentContext())
2004 return false;
2005
2006 for (const auto &B : bases()) {
2007 const auto *BaseDecl =
2008 cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl());
2009 if (BaseDecl->isAbstract())
2010 return true;
2011 }
2012
2013 return false;
2014}
2015
2016bool CXXRecordDecl::isEffectivelyFinal() const {
2017 auto *Def = getDefinition();
2018 if (!Def)
2019 return false;
2020 if (Def->hasAttr<FinalAttr>())
2021 return true;
2022 if (const auto *Dtor = Def->getDestructor())
2023 if (Dtor->hasAttr<FinalAttr>())
2024 return true;
2025 return false;
2026}
2027
2028void CXXDeductionGuideDecl::anchor() {}
2029
2030bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const {
2031 if ((getKind() != Other.getKind() ||
2032 getKind() == ExplicitSpecKind::Unresolved)) {
2033 if (getKind() == ExplicitSpecKind::Unresolved &&
2034 Other.getKind() == ExplicitSpecKind::Unresolved) {
2035 ODRHash SelfHash, OtherHash;
2036 SelfHash.AddStmt(getExpr());
2037 OtherHash.AddStmt(Other.getExpr());
2038 return SelfHash.CalculateHash() == OtherHash.CalculateHash();
2039 } else
2040 return false;
2041 }
2042 return true;
2043}
2044
2045ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) {
2046 switch (Function->getDeclKind()) {
2047 case Decl::Kind::CXXConstructor:
2048 return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier();
2049 case Decl::Kind::CXXConversion:
2050 return cast<CXXConversionDecl>(Function)->getExplicitSpecifier();
2051 case Decl::Kind::CXXDeductionGuide:
2052 return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier();
2053 default:
2054 return {};
2055 }
2056}
2057
2058CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create(
2059 ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2060 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
2061 TypeSourceInfo *TInfo, SourceLocation EndLocation) {
2062 return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T,
2063 TInfo, EndLocation);
2064}
2065
2066CXXDeductionGuideDecl *CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C,
2067 unsigned ID) {
2068 return new (C, ID) CXXDeductionGuideDecl(
2069 C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(),
2070 QualType(), nullptr, SourceLocation());
2071}
2072
2073RequiresExprBodyDecl *RequiresExprBodyDecl::Create(
2074 ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {
2075 return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);
2076}
2077
2078RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C,
2079 unsigned ID) {
2080 return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());
2081}
2082
2083void CXXMethodDecl::anchor() {}
2084
2085bool CXXMethodDecl::isStatic() const {
2086 const CXXMethodDecl *MD = getCanonicalDecl();
2087
2088 if (MD->getStorageClass() == SC_Static)
2089 return true;
2090
2091 OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();
2092 return isStaticOverloadedOperator(OOK);
2093}
2094
2095static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
2096 const CXXMethodDecl *BaseMD) {
2097 for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) {
2098 if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
2099 return true;
2100 if (recursivelyOverrides(MD, BaseMD))
2101 return true;
2102 }
2103 return false;
2104}
2105
2106CXXMethodDecl *
2107CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2108 bool MayBeBase) {
2109 if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
2110 return this;
2111
2112 // Lookup doesn't work for destructors, so handle them separately.
2113 if (isa<CXXDestructorDecl>(this)) {
2114 CXXMethodDecl *MD = RD->getDestructor();
2115 if (MD) {
2116 if (recursivelyOverrides(MD, this))
2117 return MD;
2118 if (MayBeBase && recursivelyOverrides(this, MD))
2119 return MD;
2120 }
2121 return nullptr;
2122 }
2123
2124 for (auto *ND : RD->lookup(getDeclName())) {
2125 auto *MD = dyn_cast<CXXMethodDecl>(ND);
2126 if (!MD)
2127 continue;
2128 if (recursivelyOverrides(MD, this))
2129 return MD;
2130 if (MayBeBase && recursivelyOverrides(this, MD))
2131 return MD;
2132 }
2133
2134 return nullptr;
2135}
2136
2137CXXMethodDecl *
2138CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2139 bool MayBeBase) {
2140 if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase))
2141 return MD;
2142
2143 llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders;
2144 auto AddFinalOverrider = [&](CXXMethodDecl *D) {
2145 // If this function is overridden by a candidate final overrider, it is not
2146 // a final overrider.
2147 for (CXXMethodDecl *OtherD : FinalOverriders) {
2148 if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D))
2149 return;
2150 }
2151
2152 // Other candidate final overriders might be overridden by this function.
2153 FinalOverriders.erase(
2154 std::remove_if(FinalOverriders.begin(), FinalOverriders.end(),
2155 [&](CXXMethodDecl *OtherD) {
2156 return recursivelyOverrides(D, OtherD);
2157 }),
2158 FinalOverriders.end());
2159
2160 FinalOverriders.push_back(D);
2161 };
2162
2163 for (const auto &I : RD->bases()) {
2164 const RecordType *RT = I.getType()->getAs<RecordType>();
2165 if (!RT)
2166 continue;
2167 const auto *Base = cast<CXXRecordDecl>(RT->getDecl());
2168 if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base))
2169 AddFinalOverrider(D);
2170 }
2171
2172 return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr;
2173}
2174
2175CXXMethodDecl *CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
2176 SourceLocation StartLoc,
2177 const DeclarationNameInfo &NameInfo,
2178 QualType T, TypeSourceInfo *TInfo,
2179 StorageClass SC, bool isInline,
2180 ConstexprSpecKind ConstexprKind,
2181 SourceLocation EndLocation,
2182 Expr *TrailingRequiresClause) {
2183 return new (C, RD)
2184 CXXMethodDecl(CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC,
2185 isInline, ConstexprKind, EndLocation,
2186 TrailingRequiresClause);
2187}
2188
2189CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2190 return new (C, ID)
2191 CXXMethodDecl(CXXMethod, C, nullptr, SourceLocation(),
2192 DeclarationNameInfo(), QualType(), nullptr, SC_None, false,
2193 ConstexprSpecKind::Unspecified, SourceLocation(), nullptr);
2194}
2195
2196CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,
2197 bool IsAppleKext) {
2198 assert(isVirtual() && "this method is expected to be virtual")((isVirtual() && "this method is expected to be virtual"
) ? static_cast<void> (0) : __assert_fail ("isVirtual() && \"this method is expected to be virtual\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2198, __PRETTY_FUNCTION__))
;
2199
2200 // When building with -fapple-kext, all calls must go through the vtable since
2201 // the kernel linker can do runtime patching of vtables.
2202 if (IsAppleKext)
2203 return nullptr;
2204
2205 // If the member function is marked 'final', we know that it can't be
2206 // overridden and can therefore devirtualize it unless it's pure virtual.
2207 if (hasAttr<FinalAttr>())
2208 return isPure() ? nullptr : this;
2209
2210 // If Base is unknown, we cannot devirtualize.
2211 if (!Base)
2212 return nullptr;
2213
2214 // If the base expression (after skipping derived-to-base conversions) is a
2215 // class prvalue, then we can devirtualize.
2216 Base = Base->getBestDynamicClassTypeExpr();
2217 if (Base->isRValue() && Base->getType()->isRecordType())
2218 return this;
2219
2220 // If we don't even know what we would call, we can't devirtualize.
2221 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2222 if (!BestDynamicDecl)
2223 return nullptr;
2224
2225 // There may be a method corresponding to MD in a derived class.
2226 CXXMethodDecl *DevirtualizedMethod =
2227 getCorrespondingMethodInClass(BestDynamicDecl);
2228
2229 // If there final overrider in the dynamic type is ambiguous, we can't
2230 // devirtualize this call.
2231 if (!DevirtualizedMethod)
2232 return nullptr;
2233
2234 // If that method is pure virtual, we can't devirtualize. If this code is
2235 // reached, the result would be UB, not a direct call to the derived class
2236 // function, and we can't assume the derived class function is defined.
2237 if (DevirtualizedMethod->isPure())
2238 return nullptr;
2239
2240 // If that method is marked final, we can devirtualize it.
2241 if (DevirtualizedMethod->hasAttr<FinalAttr>())
2242 return DevirtualizedMethod;
2243
2244 // Similarly, if the class itself or its destructor is marked 'final',
2245 // the class can't be derived from and we can therefore devirtualize the
2246 // member function call.
2247 if (BestDynamicDecl->isEffectivelyFinal())
2248 return DevirtualizedMethod;
2249
2250 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
2251 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2252 if (VD->getType()->isRecordType())
2253 // This is a record decl. We know the type and can devirtualize it.
2254 return DevirtualizedMethod;
2255
2256 return nullptr;
2257 }
2258
2259 // We can devirtualize calls on an object accessed by a class member access
2260 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2261 // a derived class object constructed in the same location.
2262 if (const auto *ME = dyn_cast<MemberExpr>(Base)) {
2263 const ValueDecl *VD = ME->getMemberDecl();
2264 return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;
2265 }
2266
2267 // Likewise for calls on an object accessed by a (non-reference) pointer to
2268 // member access.
2269 if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
2270 if (BO->isPtrMemOp()) {
2271 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2272 if (MPT->getPointeeType()->isRecordType())
2273 return DevirtualizedMethod;
2274 }
2275 }
2276
2277 // We can't devirtualize the call.
2278 return nullptr;
2279}
2280
2281bool CXXMethodDecl::isUsualDeallocationFunction(
2282 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {
2283 assert(PreventedBy.empty() && "PreventedBy is expected to be empty")((PreventedBy.empty() && "PreventedBy is expected to be empty"
) ? static_cast<void> (0) : __assert_fail ("PreventedBy.empty() && \"PreventedBy is expected to be empty\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2283, __PRETTY_FUNCTION__))
;
2284 if (getOverloadedOperator() != OO_Delete &&
2285 getOverloadedOperator() != OO_Array_Delete)
2286 return false;
2287
2288 // C++ [basic.stc.dynamic.deallocation]p2:
2289 // A template instance is never a usual deallocation function,
2290 // regardless of its signature.
2291 if (getPrimaryTemplate())
2292 return false;
2293
2294 // C++ [basic.stc.dynamic.deallocation]p2:
2295 // If a class T has a member deallocation function named operator delete
2296 // with exactly one parameter, then that function is a usual (non-placement)
2297 // deallocation function. [...]
2298 if (getNumParams() == 1)
2299 return true;
2300 unsigned UsualParams = 1;
2301
2302 // C++ P0722:
2303 // A destroying operator delete is a usual deallocation function if
2304 // removing the std::destroying_delete_t parameter and changing the
2305 // first parameter type from T* to void* results in the signature of
2306 // a usual deallocation function.
2307 if (isDestroyingOperatorDelete())
2308 ++UsualParams;
2309
2310 // C++ <=14 [basic.stc.dynamic.deallocation]p2:
2311 // [...] If class T does not declare such an operator delete but does
2312 // declare a member deallocation function named operator delete with
2313 // exactly two parameters, the second of which has type std::size_t (18.1),
2314 // then this function is a usual deallocation function.
2315 //
2316 // C++17 says a usual deallocation function is one with the signature
2317 // (void* [, size_t] [, std::align_val_t] [, ...])
2318 // and all such functions are usual deallocation functions. It's not clear
2319 // that allowing varargs functions was intentional.
2320 ASTContext &Context = getASTContext();
2321 if (UsualParams < getNumParams() &&
2322 Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(),
2323 Context.getSizeType()))
2324 ++UsualParams;
2325
2326 if (UsualParams < getNumParams() &&
2327 getParamDecl(UsualParams)->getType()->isAlignValT())
2328 ++UsualParams;
2329
2330 if (UsualParams != getNumParams())
2331 return false;
2332
2333 // In C++17 onwards, all potential usual deallocation functions are actual
2334 // usual deallocation functions. Honor this behavior when post-C++14
2335 // deallocation functions are offered as extensions too.
2336 // FIXME(EricWF): Destrying Delete should be a language option. How do we
2337 // handle when destroying delete is used prior to C++17?
2338 if (Context.getLangOpts().CPlusPlus17 ||
2339 Context.getLangOpts().AlignedAllocation ||
2340 isDestroyingOperatorDelete())
2341 return true;
2342
2343 // This function is a usual deallocation function if there are no
2344 // single-parameter deallocation functions of the same kind.
2345 DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());
2346 bool Result = true;
2347 for (const auto *D : R) {
2348 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2349 if (FD->getNumParams() == 1) {
2350 PreventedBy.push_back(FD);
2351 Result = false;
2352 }
2353 }
2354 }
2355 return Result;
2356}
2357
2358bool CXXMethodDecl::isCopyAssignmentOperator() const {
2359 // C++0x [class.copy]p17:
2360 // A user-declared copy assignment operator X::operator= is a non-static
2361 // non-template member function of class X with exactly one parameter of
2362 // type X, X&, const X&, volatile X& or const volatile X&.
2363 if (/*operator=*/getOverloadedOperator() != OO_Equal ||
2364 /*non-static*/ isStatic() ||
2365 /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2366 getNumParams() != 1)
2367 return false;
2368
2369 QualType ParamType = getParamDecl(0)->getType();
2370 if (const auto *Ref = ParamType->getAs<LValueReferenceType>())
2371 ParamType = Ref->getPointeeType();
2372
2373 ASTContext &Context = getASTContext();
2374 QualType ClassType
2375 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2376 return Context.hasSameUnqualifiedType(ClassType, ParamType);
2377}
2378
2379bool CXXMethodDecl::isMoveAssignmentOperator() const {
2380 // C++0x [class.copy]p19:
2381 // A user-declared move assignment operator X::operator= is a non-static
2382 // non-template member function of class X with exactly one parameter of type
2383 // X&&, const X&&, volatile X&&, or const volatile X&&.
2384 if (getOverloadedOperator() != OO_Equal || isStatic() ||
2385 getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2386 getNumParams() != 1)
2387 return false;
2388
2389 QualType ParamType = getParamDecl(0)->getType();
2390 if (!isa<RValueReferenceType>(ParamType))
2391 return false;
2392 ParamType = ParamType->getPointeeType();
2393
2394 ASTContext &Context = getASTContext();
2395 QualType ClassType
2396 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2397 return Context.hasSameUnqualifiedType(ClassType, ParamType);
2398}
2399
2400void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
2401 assert(MD->isCanonicalDecl() && "Method is not canonical!")((MD->isCanonicalDecl() && "Method is not canonical!"
) ? static_cast<void> (0) : __assert_fail ("MD->isCanonicalDecl() && \"Method is not canonical!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2401, __PRETTY_FUNCTION__))
;
2402 assert(!MD->getParent()->isDependentContext() &&((!MD->getParent()->isDependentContext() && "Can't add an overridden method to a class template!"
) ? static_cast<void> (0) : __assert_fail ("!MD->getParent()->isDependentContext() && \"Can't add an overridden method to a class template!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2403, __PRETTY_FUNCTION__))
2403 "Can't add an overridden method to a class template!")((!MD->getParent()->isDependentContext() && "Can't add an overridden method to a class template!"
) ? static_cast<void> (0) : __assert_fail ("!MD->getParent()->isDependentContext() && \"Can't add an overridden method to a class template!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2403, __PRETTY_FUNCTION__))
;
2404 assert(MD->isVirtual() && "Method is not virtual!")((MD->isVirtual() && "Method is not virtual!") ? static_cast
<void> (0) : __assert_fail ("MD->isVirtual() && \"Method is not virtual!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2404, __PRETTY_FUNCTION__))
;
2405
2406 getASTContext().addOverriddenMethod(this, MD);
2407}
2408
2409CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
2410 if (isa<CXXConstructorDecl>(this)) return nullptr;
2411 return getASTContext().overridden_methods_begin(this);
2412}
2413
2414CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
2415 if (isa<CXXConstructorDecl>(this)) return nullptr;
2416 return getASTContext().overridden_methods_end(this);
2417}
2418
2419unsigned CXXMethodDecl::size_overridden_methods() const {
2420 if (isa<CXXConstructorDecl>(this)) return 0;
2421 return getASTContext().overridden_methods_size(this);
2422}
2423
2424CXXMethodDecl::overridden_method_range
2425CXXMethodDecl::overridden_methods() const {
2426 if (isa<CXXConstructorDecl>(this))
2427 return overridden_method_range(nullptr, nullptr);
2428 return getASTContext().overridden_methods(this);
2429}
2430
2431static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,
2432 const CXXRecordDecl *Decl) {
2433 QualType ClassTy = C.getTypeDeclType(Decl);
2434 return C.getQualifiedType(ClassTy, FPT->getMethodQuals());
2435}
2436
2437QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,
2438 const CXXRecordDecl *Decl) {
2439 ASTContext &C = Decl->getASTContext();
2440 QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);
2441 return C.getPointerType(ObjectTy);
2442}
2443
2444QualType CXXMethodDecl::getThisObjectType(const FunctionProtoType *FPT,
2445 const CXXRecordDecl *Decl) {
2446 ASTContext &C = Decl->getASTContext();
2447 return ::getThisObjectType(C, FPT, Decl);
2448}
2449
2450QualType CXXMethodDecl::getThisType() const {
2451 // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
2452 // If the member function is declared const, the type of this is const X*,
2453 // if the member function is declared volatile, the type of this is
2454 // volatile X*, and if the member function is declared const volatile,
2455 // the type of this is const volatile X*.
2456 assert(isInstance() && "No 'this' for static methods!")((isInstance() && "No 'this' for static methods!") ? static_cast
<void> (0) : __assert_fail ("isInstance() && \"No 'this' for static methods!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2456, __PRETTY_FUNCTION__))
;
2457 return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),
2458 getParent());
2459}
2460
2461QualType CXXMethodDecl::getThisObjectType() const {
2462 // Ditto getThisType.
2463 assert(isInstance() && "No 'this' for static methods!")((isInstance() && "No 'this' for static methods!") ? static_cast
<void> (0) : __assert_fail ("isInstance() && \"No 'this' for static methods!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2463, __PRETTY_FUNCTION__))
;
2464 return CXXMethodDecl::getThisObjectType(
2465 getType()->castAs<FunctionProtoType>(), getParent());
2466}
2467
2468bool CXXMethodDecl::hasInlineBody() const {
2469 // If this function is a template instantiation, look at the template from
2470 // which it was instantiated.
2471 const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
2472 if (!CheckFn)
2473 CheckFn = this;
2474
2475 const FunctionDecl *fn;
2476 return CheckFn->isDefined(fn) && !fn->isOutOfLine() &&
2477 (fn->doesThisDeclarationHaveABody() || fn->willHaveBody());
2478}
2479
2480bool CXXMethodDecl::isLambdaStaticInvoker() const {
2481 const CXXRecordDecl *P = getParent();
2482 return P->isLambda() && getDeclName().isIdentifier() &&
2483 getName() == getLambdaStaticInvokerName();
2484}
2485
2486CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2487 TypeSourceInfo *TInfo, bool IsVirtual,
2488 SourceLocation L, Expr *Init,
2489 SourceLocation R,
2490 SourceLocation EllipsisLoc)
2491 : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
2492 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
2493 IsWritten(false), SourceOrder(0) {}
2494
2495CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2496 FieldDecl *Member,
2497 SourceLocation MemberLoc,
2498 SourceLocation L, Expr *Init,
2499 SourceLocation R)
2500 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
2501 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2502 IsWritten(false), SourceOrder(0) {}
2503
2504CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2505 IndirectFieldDecl *Member,
2506 SourceLocation MemberLoc,
2507 SourceLocation L, Expr *Init,
2508 SourceLocation R)
2509 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
2510 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2511 IsWritten(false), SourceOrder(0) {}
2512
2513CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2514 TypeSourceInfo *TInfo,
2515 SourceLocation L, Expr *Init,
2516 SourceLocation R)
2517 : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),
2518 IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}
2519
2520int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {
2521 return Context.getAllocator()
2522 .identifyKnownAlignedObject<CXXCtorInitializer>(this);
2523}
2524
2525TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
2526 if (isBaseInitializer())
2527 return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
2528 else
2529 return {};
2530}
2531
2532const Type *CXXCtorInitializer::getBaseClass() const {
2533 if (isBaseInitializer())
2534 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
2535 else
2536 return nullptr;
2537}
2538
2539SourceLocation CXXCtorInitializer::getSourceLocation() const {
2540 if (isInClassMemberInitializer())
2541 return getAnyMember()->getLocation();
2542
2543 if (isAnyMemberInitializer())
2544 return getMemberLocation();
2545
2546 if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>())
2547 return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
2548
2549 return {};
2550}
2551
2552SourceRange CXXCtorInitializer::getSourceRange() const {
2553 if (isInClassMemberInitializer()) {
2554 FieldDecl *D = getAnyMember();
2555 if (Expr *I = D->getInClassInitializer())
2556 return I->getSourceRange();
2557 return {};
2558 }
2559
2560 return SourceRange(getSourceLocation(), getRParenLoc());
2561}
2562
2563CXXConstructorDecl::CXXConstructorDecl(
2564 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2565 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2566 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2567 ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited,
2568 Expr *TrailingRequiresClause)
2569 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
2570 SC_None, isInline, ConstexprKind, SourceLocation(),
2571 TrailingRequiresClause) {
2572 setNumCtorInitializers(0);
2573 setInheritingConstructor(static_cast<bool>(Inherited));
2574 setImplicit(isImplicitlyDeclared);
2575 CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;
2576 if (Inherited)
2577 *getTrailingObjects<InheritedConstructor>() = Inherited;
2578 setExplicitSpecifier(ES);
2579}
2580
2581void CXXConstructorDecl::anchor() {}
2582
2583CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,
2584 unsigned ID,
2585 uint64_t AllocKind) {
2586 bool hasTraillingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);
2587 bool isInheritingConstructor =
2588 static_cast<bool>(AllocKind & TAKInheritsConstructor);
2589 unsigned Extra =
2590 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2591 isInheritingConstructor, hasTraillingExplicit);
2592 auto *Result = new (C, ID, Extra) CXXConstructorDecl(
2593 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2594 ExplicitSpecifier(), false, false, ConstexprSpecKind::Unspecified,
2595 InheritedConstructor(), nullptr);
2596 Result->setInheritingConstructor(isInheritingConstructor);
2597 Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =
2598 hasTraillingExplicit;
2599 Result->setExplicitSpecifier(ExplicitSpecifier());
2600 return Result;
2601}
2602
2603CXXConstructorDecl *CXXConstructorDecl::Create(
2604 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2605 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2606 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2607 ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited,
2608 Expr *TrailingRequiresClause) {
2609 assert(NameInfo.getName().getNameKind()((NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName
&& "Name must refer to a constructor") ? static_cast
<void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName && \"Name must refer to a constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2611, __PRETTY_FUNCTION__))
2610 == DeclarationName::CXXConstructorName &&((NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName
&& "Name must refer to a constructor") ? static_cast
<void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName && \"Name must refer to a constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2611, __PRETTY_FUNCTION__))
2611 "Name must refer to a constructor")((NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName
&& "Name must refer to a constructor") ? static_cast
<void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName && \"Name must refer to a constructor\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2611, __PRETTY_FUNCTION__))
;
2612 unsigned Extra =
2613 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2614 Inherited ? 1 : 0, ES.getExpr() ? 1 : 0);
2615 return new (C, RD, Extra)
2616 CXXConstructorDecl(C, RD, StartLoc, NameInfo, T, TInfo, ES, isInline,
2617 isImplicitlyDeclared, ConstexprKind, Inherited,
2618 TrailingRequiresClause);
2619}
2620
2621CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {
2622 return CtorInitializers.get(getASTContext().getExternalSource());
2623}
2624
2625CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
2626 assert(isDelegatingConstructor() && "Not a delegating constructor!")((isDelegatingConstructor() && "Not a delegating constructor!"
) ? static_cast<void> (0) : __assert_fail ("isDelegatingConstructor() && \"Not a delegating constructor!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2626, __PRETTY_FUNCTION__))
;
2627 Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
2628 if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
2629 return Construct->getConstructor();
2630
2631 return nullptr;
2632}
2633
2634bool CXXConstructorDecl::isDefaultConstructor() const {
2635 // C++ [class.default.ctor]p1:
2636 // A default constructor for a class X is a constructor of class X for
2637 // which each parameter that is not a function parameter pack has a default
2638 // argument (including the case of a constructor with no parameters)
2639 return getMinRequiredArguments() == 0;
2640}
2641
2642bool
2643CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
2644 return isCopyOrMoveConstructor(TypeQuals) &&
2645 getParamDecl(0)->getType()->isLValueReferenceType();
2646}
2647
2648bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
2649 return isCopyOrMoveConstructor(TypeQuals) &&
2650 getParamDecl(0)->getType()->isRValueReferenceType();
2651}
2652
2653/// Determine whether this is a copy or move constructor.
2654bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
2655 // C++ [class.copy]p2:
2656 // A non-template constructor for class X is a copy constructor
2657 // if its first parameter is of type X&, const X&, volatile X& or
2658 // const volatile X&, and either there are no other parameters
2659 // or else all other parameters have default arguments (8.3.6).
2660 // C++0x [class.copy]p3:
2661 // A non-template constructor for class X is a move constructor if its
2662 // first parameter is of type X&&, const X&&, volatile X&&, or
2663 // const volatile X&&, and either there are no other parameters or else
2664 // all other parameters have default arguments.
2665 if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||
2666 getDescribedFunctionTemplate() != nullptr)
2667 return false;
2668
2669 const ParmVarDecl *Param = getParamDecl(0);
2670
2671 // Do we have a reference type?
2672 const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();
2673 if (!ParamRefType)
2674 return false;
2675
2676 // Is it a reference to our class type?
2677 ASTContext &Context = getASTContext();
2678
2679 CanQualType PointeeType
2680 = Context.getCanonicalType(ParamRefType->getPointeeType());
2681 CanQualType ClassTy
2682 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2683 if (PointeeType.getUnqualifiedType() != ClassTy)
2684 return false;
2685
2686 // FIXME: other qualifiers?
2687
2688 // We have a copy or move constructor.
2689 TypeQuals = PointeeType.getCVRQualifiers();
2690 return true;
2691}
2692
2693bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
2694 // C++ [class.conv.ctor]p1:
2695 // A constructor declared without the function-specifier explicit
2696 // that can be called with a single parameter specifies a
2697 // conversion from the type of its first parameter to the type of
2698 // its class. Such a constructor is called a converting
2699 // constructor.
2700 if (isExplicit() && !AllowExplicit)
2701 return false;
2702
2703 // FIXME: This has nothing to do with the definition of converting
2704 // constructor, but is convenient for how we use this function in overload
2705 // resolution.
2706 return getNumParams() == 0
2707 ? getType()->castAs<FunctionProtoType>()->isVariadic()
2708 : getMinRequiredArguments() <= 1;
2709}
2710
2711bool CXXConstructorDecl::isSpecializationCopyingObject() const {
2712 if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)
2713 return false;
2714
2715 const ParmVarDecl *Param = getParamDecl(0);
2716
2717 ASTContext &Context = getASTContext();
2718 CanQualType ParamType = Context.getCanonicalType(Param->getType());
2719
2720 // Is it the same as our class type?
2721 CanQualType ClassTy
2722 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2723 if (ParamType.getUnqualifiedType() != ClassTy)
2724 return false;
2725
2726 return true;
2727}
2728
2729void CXXDestructorDecl::anchor() {}
2730
2731CXXDestructorDecl *
2732CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2733 return new (C, ID) CXXDestructorDecl(
2734 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2735 false, false, ConstexprSpecKind::Unspecified, nullptr);
2736}
2737
2738CXXDestructorDecl *CXXDestructorDecl::Create(
2739 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2740 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2741 bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2742 Expr *TrailingRequiresClause) {
2743 assert(NameInfo.getName().getNameKind()((NameInfo.getName().getNameKind() == DeclarationName::CXXDestructorName
&& "Name must refer to a destructor") ? static_cast<
void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXDestructorName && \"Name must refer to a destructor\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2745, __PRETTY_FUNCTION__))
2744 == DeclarationName::CXXDestructorName &&((NameInfo.getName().getNameKind() == DeclarationName::CXXDestructorName
&& "Name must refer to a destructor") ? static_cast<
void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXDestructorName && \"Name must refer to a destructor\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2745, __PRETTY_FUNCTION__))
2745 "Name must refer to a destructor")((NameInfo.getName().getNameKind() == DeclarationName::CXXDestructorName
&& "Name must refer to a destructor") ? static_cast<
void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXDestructorName && \"Name must refer to a destructor\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2745, __PRETTY_FUNCTION__))
;
2746 return new (C, RD)
2747 CXXDestructorDecl(C, RD, StartLoc, NameInfo, T, TInfo, isInline,
2748 isImplicitlyDeclared, ConstexprKind,
2749 TrailingRequiresClause);
2750}
2751
2752void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {
2753 auto *First = cast<CXXDestructorDecl>(getFirstDecl());
2754 if (OD && !First->OperatorDelete) {
2755 First->OperatorDelete = OD;
2756 First->OperatorDeleteThisArg = ThisArg;
2757 if (auto *L = getASTMutationListener())
2758 L->ResolvedOperatorDelete(First, OD, ThisArg);
2759 }
2760}
2761
2762void CXXConversionDecl::anchor() {}
2763
2764CXXConversionDecl *
2765CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2766 return new (C, ID) CXXConversionDecl(
2767 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2768 false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
2769 SourceLocation(), nullptr);
2770}
2771
2772CXXConversionDecl *CXXConversionDecl::Create(
2773 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2774 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2775 bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2776 SourceLocation EndLocation, Expr *TrailingRequiresClause) {
2777 assert(NameInfo.getName().getNameKind()((NameInfo.getName().getNameKind() == DeclarationName::CXXConversionFunctionName
&& "Name must refer to a conversion function") ? static_cast
<void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXConversionFunctionName && \"Name must refer to a conversion function\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2779, __PRETTY_FUNCTION__))
2778 == DeclarationName::CXXConversionFunctionName &&((NameInfo.getName().getNameKind() == DeclarationName::CXXConversionFunctionName
&& "Name must refer to a conversion function") ? static_cast
<void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXConversionFunctionName && \"Name must refer to a conversion function\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2779, __PRETTY_FUNCTION__))
2779 "Name must refer to a conversion function")((NameInfo.getName().getNameKind() == DeclarationName::CXXConversionFunctionName
&& "Name must refer to a conversion function") ? static_cast
<void> (0) : __assert_fail ("NameInfo.getName().getNameKind() == DeclarationName::CXXConversionFunctionName && \"Name must refer to a conversion function\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2779, __PRETTY_FUNCTION__))
;
2780 return new (C, RD)
2781 CXXConversionDecl(C, RD, StartLoc, NameInfo, T, TInfo, isInline, ES,
2782 ConstexprKind, EndLocation, TrailingRequiresClause);
2783}
2784
2785bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
2786 return isImplicit() && getParent()->isLambda() &&
2787 getConversionType()->isBlockPointerType();
2788}
2789
2790LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2791 SourceLocation LangLoc, LanguageIDs lang,
2792 bool HasBraces)
2793 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
2794 ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {
2795 setLanguage(lang);
2796 LinkageSpecDeclBits.HasBraces = HasBraces;
2797}
2798
2799void LinkageSpecDecl::anchor() {}
2800
2801LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
2802 DeclContext *DC,
2803 SourceLocation ExternLoc,
2804 SourceLocation LangLoc,
2805 LanguageIDs Lang,
2806 bool HasBraces) {
2807 return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
2808}
2809
2810LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,
2811 unsigned ID) {
2812 return new (C, ID) LinkageSpecDecl(nullptr, SourceLocation(),
2813 SourceLocation(), lang_c, false);
2814}
2815
2816void UsingDirectiveDecl::anchor() {}
2817
2818UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
2819 SourceLocation L,
2820 SourceLocation NamespaceLoc,
2821 NestedNameSpecifierLoc QualifierLoc,
2822 SourceLocation IdentLoc,
2823 NamedDecl *Used,
2824 DeclContext *CommonAncestor) {
2825 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used))
2826 Used = NS->getOriginalNamespace();
2827 return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
2828 IdentLoc, Used, CommonAncestor);
2829}
2830
2831UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,
2832 unsigned ID) {
2833 return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),
2834 SourceLocation(),
2835 NestedNameSpecifierLoc(),
2836 SourceLocation(), nullptr, nullptr);
2837}
2838
2839NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
2840 if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
2841 return NA->getNamespace();
2842 return cast_or_null<NamespaceDecl>(NominatedNamespace);
2843}
2844
2845NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
2846 SourceLocation StartLoc, SourceLocation IdLoc,
2847 IdentifierInfo *Id, NamespaceDecl *PrevDecl)
2848 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
2849 redeclarable_base(C), LocStart(StartLoc),
2850 AnonOrFirstNamespaceAndInline(nullptr, Inline) {
2851 setPreviousDecl(PrevDecl);
2852
2853 if (PrevDecl)
2854 AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
2855}
2856
2857NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
2858 bool Inline, SourceLocation StartLoc,
2859 SourceLocation IdLoc, IdentifierInfo *Id,
2860 NamespaceDecl *PrevDecl) {
2861 return new (C, DC) NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id,
2862 PrevDecl);
2863}
2864
2865NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2866 return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),
2867 SourceLocation(), nullptr, nullptr);
2868}
2869
2870NamespaceDecl *NamespaceDecl::getOriginalNamespace() {
2871 if (isFirstDecl())
2872 return this;
2873
2874 return AnonOrFirstNamespaceAndInline.getPointer();
2875}
2876
2877const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const {
2878 if (isFirstDecl())
2879 return this;
2880
2881 return AnonOrFirstNamespaceAndInline.getPointer();
2882}
2883
2884bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); }
2885
2886NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {
2887 return getNextRedeclaration();
2888}
2889
2890NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {
2891 return getPreviousDecl();
2892}
2893
2894NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {
2895 return getMostRecentDecl();
2896}
2897
2898void NamespaceAliasDecl::anchor() {}
2899
2900NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {
2901 return getNextRedeclaration();
2902}
2903
2904NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {
2905 return getPreviousDecl();
2906}
2907
2908NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {
2909 return getMostRecentDecl();
2910}
2911
2912NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
2913 SourceLocation UsingLoc,
2914 SourceLocation AliasLoc,
2915 IdentifierInfo *Alias,
2916 NestedNameSpecifierLoc QualifierLoc,
2917 SourceLocation IdentLoc,
2918 NamedDecl *Namespace) {
2919 // FIXME: Preserve the aliased namespace as written.
2920 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
2921 Namespace = NS->getOriginalNamespace();
2922 return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,
2923 QualifierLoc, IdentLoc, Namespace);
2924}
2925
2926NamespaceAliasDecl *
2927NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2928 return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),
2929 SourceLocation(), nullptr,
2930 NestedNameSpecifierLoc(),
2931 SourceLocation(), nullptr);
2932}
2933
2934void LifetimeExtendedTemporaryDecl::anchor() {}
2935
2936/// Retrieve the storage duration for the materialized temporary.
2937StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {
2938 const ValueDecl *ExtendingDecl = getExtendingDecl();
2939 if (!ExtendingDecl)
2940 return SD_FullExpression;
2941 // FIXME: This is not necessarily correct for a temporary materialized
2942 // within a default initializer.
2943 if (isa<FieldDecl>(ExtendingDecl))
2944 return SD_Automatic;
2945 // FIXME: This only works because storage class specifiers are not allowed
2946 // on decomposition declarations.
2947 if (isa<BindingDecl>(ExtendingDecl))
2948 return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic
2949 : SD_Static;
2950 return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
2951}
2952
2953APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {
2954 assert(getStorageDuration() == SD_Static &&((getStorageDuration() == SD_Static && "don't need to cache the computed value for this temporary"
) ? static_cast<void> (0) : __assert_fail ("getStorageDuration() == SD_Static && \"don't need to cache the computed value for this temporary\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2955, __PRETTY_FUNCTION__))
2955 "don't need to cache the computed value for this temporary")((getStorageDuration() == SD_Static && "don't need to cache the computed value for this temporary"
) ? static_cast<void> (0) : __assert_fail ("getStorageDuration() == SD_Static && \"don't need to cache the computed value for this temporary\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2955, __PRETTY_FUNCTION__))
;
2956 if (MayCreate && !Value) {
2957 Value = (new (getASTContext()) APValue);
2958 getASTContext().addDestruction(Value);
2959 }
2960 assert(Value && "may not be null")((Value && "may not be null") ? static_cast<void>
(0) : __assert_fail ("Value && \"may not be null\"",
"/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 2960, __PRETTY_FUNCTION__))
;
2961 return Value;
2962}
2963
2964void UsingShadowDecl::anchor() {}
2965
2966UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,
2967 SourceLocation Loc, UsingDecl *Using,
2968 NamedDecl *Target)
2969 : NamedDecl(K, DC, Loc, Using ? Using->getDeclName() : DeclarationName()),
2970 redeclarable_base(C), UsingOrNextShadow(cast<NamedDecl>(Using)) {
2971 if (Target)
2972 setTargetDecl(Target);
2973 setImplicit();
2974}
2975
2976UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)
2977 : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),
2978 redeclarable_base(C) {}
2979
2980UsingShadowDecl *
2981UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2982 return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());
2983}
2984
2985UsingDecl *UsingShadowDecl::getUsingDecl() const {
2986 const UsingShadowDecl *Shadow = this;
2987 while (const auto *NextShadow =
2988 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
2989 Shadow = NextShadow;
2990 return cast<UsingDecl>(Shadow->UsingOrNextShadow);
2991}
2992
2993void ConstructorUsingShadowDecl::anchor() {}
2994
2995ConstructorUsingShadowDecl *
2996ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,
2997 SourceLocation Loc, UsingDecl *Using,
2998 NamedDecl *Target, bool IsVirtual) {
2999 return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,
3000 IsVirtual);
3001}
3002
3003ConstructorUsingShadowDecl *
3004ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3005 return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());
3006}
3007
3008CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {
3009 return getUsingDecl()->getQualifier()->getAsRecordDecl();
3010}
3011
3012void UsingDecl::anchor() {}
3013
3014void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
3015 assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&((std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
"declaration already in set") ? static_cast<void> (0) :
__assert_fail ("std::find(shadow_begin(), shadow_end(), S) == shadow_end() && \"declaration already in set\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3016, __PRETTY_FUNCTION__))
3016 "declaration already in set")((std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
"declaration already in set") ? static_cast<void> (0) :
__assert_fail ("std::find(shadow_begin(), shadow_end(), S) == shadow_end() && \"declaration already in set\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3016, __PRETTY_FUNCTION__))
;
3017 assert(S->getUsingDecl() == this)((S->getUsingDecl() == this) ? static_cast<void> (0)
: __assert_fail ("S->getUsingDecl() == this", "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3017, __PRETTY_FUNCTION__))
;
3018
3019 if (FirstUsingShadow.getPointer())
3020 S->UsingOrNextShadow = FirstUsingShadow.getPointer();
3021 FirstUsingShadow.setPointer(S);
3022}
3023
3024void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
3025 assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&((std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
"declaration not in set") ? static_cast<void> (0) : __assert_fail
("std::find(shadow_begin(), shadow_end(), S) != shadow_end() && \"declaration not in set\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3026, __PRETTY_FUNCTION__))
3026 "declaration not in set")((std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
"declaration not in set") ? static_cast<void> (0) : __assert_fail
("std::find(shadow_begin(), shadow_end(), S) != shadow_end() && \"declaration not in set\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3026, __PRETTY_FUNCTION__))
;
3027 assert(S->getUsingDecl() == this)((S->getUsingDecl() == this) ? static_cast<void> (0)
: __assert_fail ("S->getUsingDecl() == this", "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3027, __PRETTY_FUNCTION__))
;
3028
3029 // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
3030
3031 if (FirstUsingShadow.getPointer() == S) {
3032 FirstUsingShadow.setPointer(
3033 dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
3034 S->UsingOrNextShadow = this;
3035 return;
3036 }
3037
3038 UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
3039 while (Prev->UsingOrNextShadow != S)
3040 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
3041 Prev->UsingOrNextShadow = S->UsingOrNextShadow;
3042 S->UsingOrNextShadow = this;
3043}
3044
3045UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
3046 NestedNameSpecifierLoc QualifierLoc,
3047 const DeclarationNameInfo &NameInfo,
3048 bool HasTypename) {
3049 return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);
3050}
3051
3052UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3053 return new (C, ID) UsingDecl(nullptr, SourceLocation(),
3054 NestedNameSpecifierLoc(), DeclarationNameInfo(),
3055 false);
3056}
3057
3058SourceRange UsingDecl::getSourceRange() const {
3059 SourceLocation Begin = isAccessDeclaration()
3060 ? getQualifierLoc().getBeginLoc() : UsingLocation;
3061 return SourceRange(Begin, getNameInfo().getEndLoc());
3062}
3063
3064void UsingPackDecl::anchor() {}
3065
3066UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,
3067 NamedDecl *InstantiatedFrom,
3068 ArrayRef<NamedDecl *> UsingDecls) {
3069 size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size());
3070 return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);
3071}
3072
3073UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3074 unsigned NumExpansions) {
3075 size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions);
3076 auto *Result = new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, None);
3077 Result->NumExpansions = NumExpansions;
3078 auto *Trail = Result->getTrailingObjects<NamedDecl *>();
3079 for (unsigned I = 0; I != NumExpansions; ++I)
3080 new (Trail + I) NamedDecl*(nullptr);
3081 return Result;
3082}
3083
3084void UnresolvedUsingValueDecl::anchor() {}
3085
3086UnresolvedUsingValueDecl *
3087UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
3088 SourceLocation UsingLoc,
3089 NestedNameSpecifierLoc QualifierLoc,
3090 const DeclarationNameInfo &NameInfo,
3091 SourceLocation EllipsisLoc) {
3092 return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
3093 QualifierLoc, NameInfo,
3094 EllipsisLoc);
3095}
3096
3097UnresolvedUsingValueDecl *
3098UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3099 return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),
3100 SourceLocation(),
3101 NestedNameSpecifierLoc(),
3102 DeclarationNameInfo(),
3103 SourceLocation());
3104}
3105
3106SourceRange UnresolvedUsingValueDecl::getSourceRange() const {
3107 SourceLocation Begin = isAccessDeclaration()
3108 ? getQualifierLoc().getBeginLoc() : UsingLocation;
3109 return SourceRange(Begin, getNameInfo().getEndLoc());
3110}
3111
3112void UnresolvedUsingTypenameDecl::anchor() {}
3113
3114UnresolvedUsingTypenameDecl *
3115UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
3116 SourceLocation UsingLoc,
3117 SourceLocation TypenameLoc,
3118 NestedNameSpecifierLoc QualifierLoc,
3119 SourceLocation TargetNameLoc,
3120 DeclarationName TargetName,
3121 SourceLocation EllipsisLoc) {
3122 return new (C, DC) UnresolvedUsingTypenameDecl(
3123 DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,
3124 TargetName.getAsIdentifierInfo(), EllipsisLoc);
3125}
3126
3127UnresolvedUsingTypenameDecl *
3128UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3129 return new (C, ID) UnresolvedUsingTypenameDecl(
3130 nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),
3131 SourceLocation(), nullptr, SourceLocation());
3132}
3133
3134void StaticAssertDecl::anchor() {}
3135
3136StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
3137 SourceLocation StaticAssertLoc,
3138 Expr *AssertExpr,
3139 StringLiteral *Message,
3140 SourceLocation RParenLoc,
3141 bool Failed) {
3142 return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
3143 RParenLoc, Failed);
3144}
3145
3146StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
3147 unsigned ID) {
3148 return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,
3149 nullptr, SourceLocation(), false);
3150}
3151
3152void BindingDecl::anchor() {}
3153
3154BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
3155 SourceLocation IdLoc, IdentifierInfo *Id) {
3156 return new (C, DC) BindingDecl(DC, IdLoc, Id);
3157}
3158
3159BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3160 return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
3161}
3162
3163ValueDecl *BindingDecl::getDecomposedDecl() const {
3164 ExternalASTSource *Source =
3165 Decomp.isOffset() ? getASTContext().getExternalSource() : nullptr;
3166 return cast_or_null<ValueDecl>(Decomp.get(Source));
3167}
3168
3169VarDecl *BindingDecl::getHoldingVar() const {
3170 Expr *B = getBinding();
3171 if (!B)
3172 return nullptr;
3173 auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit());
3174 if (!DRE)
3175 return nullptr;
3176
3177 auto *VD = cast<VarDecl>(DRE->getDecl());
3178 assert(VD->isImplicit() && "holding var for binding decl not implicit")((VD->isImplicit() && "holding var for binding decl not implicit"
) ? static_cast<void> (0) : __assert_fail ("VD->isImplicit() && \"holding var for binding decl not implicit\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3178, __PRETTY_FUNCTION__))
;
3179 return VD;
3180}
3181
3182void DecompositionDecl::anchor() {}
3183
3184DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,
3185 SourceLocation StartLoc,
3186 SourceLocation LSquareLoc,
3187 QualType T, TypeSourceInfo *TInfo,
3188 StorageClass SC,
3189 ArrayRef<BindingDecl *> Bindings) {
3190 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size());
3191 return new (C, DC, Extra)
3192 DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);
3193}
3194
3195DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,
3196 unsigned ID,
3197 unsigned NumBindings) {
3198 size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings);
3199 auto *Result = new (C, ID, Extra)
3200 DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),
3201 QualType(), nullptr, StorageClass(), None);
3202 // Set up and clean out the bindings array.
3203 Result->NumBindings = NumBindings;
3204 auto *Trail = Result->getTrailingObjects<BindingDecl *>();
3205 for (unsigned I = 0; I != NumBindings; ++I)
3206 new (Trail + I) BindingDecl*(nullptr);
3207 return Result;
3208}
3209
3210void DecompositionDecl::printName(llvm::raw_ostream &os) const {
3211 os << '[';
3212 bool Comma = false;
3213 for (const auto *B : bindings()) {
3214 if (Comma)
3215 os << ", ";
3216 B->printName(os);
3217 Comma = true;
3218 }
3219 os << ']';
3220}
3221
3222void MSPropertyDecl::anchor() {}
3223
3224MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,
3225 SourceLocation L, DeclarationName N,
3226 QualType T, TypeSourceInfo *TInfo,
3227 SourceLocation StartL,
3228 IdentifierInfo *Getter,
3229 IdentifierInfo *Setter) {
3230 return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);
3231}
3232
3233MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
3234 unsigned ID) {
3235 return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),
3236 DeclarationName(), QualType(), nullptr,
3237 SourceLocation(), nullptr, nullptr);
3238}
3239
3240void MSGuidDecl::anchor() {}
3241
3242MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)
3243 : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),
3244 PartVal(P), APVal() {}
3245
3246MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {
3247 DeclContext *DC = C.getTranslationUnitDecl();
3248 return new (C, DC) MSGuidDecl(DC, T, P);
3249}
3250
3251MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3252 return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());
3253}
3254
3255void MSGuidDecl::printName(llvm::raw_ostream &OS) const {
3256 OS << llvm::format("GUID{%08" PRIx32"x" "-%04" PRIx16"x" "-%04" PRIx16"x" "-",
3257 PartVal.Part1, PartVal.Part2, PartVal.Part3);
3258 unsigned I = 0;
3259 for (uint8_t Byte : PartVal.Part4And5) {
3260 OS << llvm::format("%02" PRIx8"x", Byte);
3261 if (++I == 2)
3262 OS << '-';
3263 }
3264 OS << '}';
3265}
3266
3267/// Determine if T is a valid 'struct _GUID' of the shape that we expect.
3268static bool isValidStructGUID(ASTContext &Ctx, QualType T) {
3269 // FIXME: We only need to check this once, not once each time we compute a
3270 // GUID APValue.
3271 using MatcherRef = llvm::function_ref<bool(QualType)>;
3272
3273 auto IsInt = [&Ctx](unsigned N) {
3274 return [&Ctx, N](QualType T) {
3275 return T->isUnsignedIntegerOrEnumerationType() &&
3276 Ctx.getIntWidth(T) == N;
3277 };
3278 };
3279
3280 auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {
3281 return [&Ctx, Elem, N](QualType T) {
3282 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);
3283 return CAT && CAT->getSize() == N && Elem(CAT->getElementType());
3284 };
3285 };
3286
3287 auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {
3288 return [Fields](QualType T) {
3289 const RecordDecl *RD = T->getAsRecordDecl();
3290 if (!RD || RD->isUnion())
3291 return false;
3292 RD = RD->getDefinition();
3293 if (!RD)
3294 return false;
3295 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3296 if (CXXRD->getNumBases())
3297 return false;
3298 auto MatcherIt = Fields.begin();
3299 for (const FieldDecl *FD : RD->fields()) {
3300 if (FD->isUnnamedBitfield()) continue;
3301 if (FD->isBitField() || MatcherIt == Fields.end() ||
3302 !(*MatcherIt)(FD->getType()))
3303 return false;
3304 ++MatcherIt;
3305 }
3306 return MatcherIt == Fields.end();
3307 };
3308 };
3309
3310 // We expect an {i32, i16, i16, [8 x i8]}.
3311 return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);
3312}
3313
3314APValue &MSGuidDecl::getAsAPValue() const {
3315 if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {
3316 using llvm::APInt;
3317 using llvm::APSInt;
3318 APVal = APValue(APValue::UninitStruct(), 0, 4);
3319 APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true));
3320 APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true));
3321 APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true));
3322 APValue &Arr = APVal.getStructField(3) =
3323 APValue(APValue::UninitArray(), 8, 8);
3324 for (unsigned I = 0; I != 8; ++I) {
3325 Arr.getArrayInitializedElt(I) =
3326 APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));
3327 }
3328 // Register this APValue to be destroyed if necessary. (Note that the
3329 // MSGuidDecl destructor is never run.)
3330 getASTContext().addDestruction(&APVal);
3331 }
3332
3333 return APVal;
3334}
3335
3336static const char *getAccessName(AccessSpecifier AS) {
3337 switch (AS) {
3338 case AS_none:
3339 llvm_unreachable("Invalid access specifier!")::llvm::llvm_unreachable_internal("Invalid access specifier!"
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3339)
;
3340 case AS_public:
3341 return "public";
3342 case AS_private:
3343 return "private";
3344 case AS_protected:
3345 return "protected";
3346 }
3347 llvm_unreachable("Invalid access specifier!")::llvm::llvm_unreachable_internal("Invalid access specifier!"
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/lib/AST/DeclCXX.cpp"
, 3347)
;
3348}
3349
3350const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
3351 AccessSpecifier AS) {
3352 return DB << getAccessName(AS);
3353}

/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h

1//===- DeclCXX.h - Classes for representing C++ declarations --*- 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/// Defines the C++ Decl subclasses, other than those for templates
11/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLCXX_H
16#define LLVM_CLANG_AST_DECLCXX_H
17
18#include "clang/AST/ASTUnresolvedSet.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/AST/LambdaCapture.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/Redeclarable.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/Lambda.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/OperatorKinds.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/Specifiers.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/TinyPtrVector.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/TrailingObjects.h"
48#include <cassert>
49#include <cstddef>
50#include <iterator>
51#include <memory>
52#include <vector>
53
54namespace clang {
55
56class ASTContext;
57class ClassTemplateDecl;
58class ConstructorUsingShadowDecl;
59class CXXBasePath;
60class CXXBasePaths;
61class CXXConstructorDecl;
62class CXXDestructorDecl;
63class CXXFinalOverriderMap;
64class CXXIndirectPrimaryBaseSet;
65class CXXMethodDecl;
66class DecompositionDecl;
67class DiagnosticBuilder;
68class FriendDecl;
69class FunctionTemplateDecl;
70class IdentifierInfo;
71class MemberSpecializationInfo;
72class TemplateDecl;
73class TemplateParameterList;
74class UsingDecl;
75
76/// Represents an access specifier followed by colon ':'.
77///
78/// An objects of this class represents sugar for the syntactic occurrence
79/// of an access specifier followed by a colon in the list of member
80/// specifiers of a C++ class definition.
81///
82/// Note that they do not represent other uses of access specifiers,
83/// such as those occurring in a list of base specifiers.
84/// Also note that this class has nothing to do with so-called
85/// "access declarations" (C++98 11.3 [class.access.dcl]).
86class AccessSpecDecl : public Decl {
87 /// The location of the ':'.
88 SourceLocation ColonLoc;
89
90 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
91 SourceLocation ASLoc, SourceLocation ColonLoc)
92 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
93 setAccess(AS);
94 }
95
96 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
97
98 virtual void anchor();
99
100public:
101 /// The location of the access specifier.
102 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
103
104 /// Sets the location of the access specifier.
105 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
106
107 /// The location of the colon following the access specifier.
108 SourceLocation getColonLoc() const { return ColonLoc; }
109
110 /// Sets the location of the colon.
111 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
112
113 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
114 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
115 }
116
117 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
118 DeclContext *DC, SourceLocation ASLoc,
119 SourceLocation ColonLoc) {
120 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
121 }
122
123 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
124
125 // Implement isa/cast/dyncast/etc.
126 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
127 static bool classofKind(Kind K) { return K == AccessSpec; }
128};
129
130/// Represents a base class of a C++ class.
131///
132/// Each CXXBaseSpecifier represents a single, direct base class (or
133/// struct) of a C++ class (or struct). It specifies the type of that
134/// base class, whether it is a virtual or non-virtual base, and what
135/// level of access (public, protected, private) is used for the
136/// derivation. For example:
137///
138/// \code
139/// class A { };
140/// class B { };
141/// class C : public virtual A, protected B { };
142/// \endcode
143///
144/// In this code, C will have two CXXBaseSpecifiers, one for "public
145/// virtual A" and the other for "protected B".
146class CXXBaseSpecifier {
147 /// The source code range that covers the full base
148 /// specifier, including the "virtual" (if present) and access
149 /// specifier (if present).
150 SourceRange Range;
151
152 /// The source location of the ellipsis, if this is a pack
153 /// expansion.
154 SourceLocation EllipsisLoc;
155
156 /// Whether this is a virtual base class or not.
157 unsigned Virtual : 1;
158
159 /// Whether this is the base of a class (true) or of a struct (false).
160 ///
161 /// This determines the mapping from the access specifier as written in the
162 /// source code to the access specifier used for semantic analysis.
163 unsigned BaseOfClass : 1;
164
165 /// Access specifier as written in the source code (may be AS_none).
166 ///
167 /// The actual type of data stored here is an AccessSpecifier, but we use
168 /// "unsigned" here to work around a VC++ bug.
169 unsigned Access : 2;
170
171 /// Whether the class contains a using declaration
172 /// to inherit the named class's constructors.
173 unsigned InheritConstructors : 1;
174
175 /// The type of the base class.
176 ///
177 /// This will be a class or struct (or a typedef of such). The source code
178 /// range does not include the \c virtual or the access specifier.
179 TypeSourceInfo *BaseTypeInfo;
180
181public:
182 CXXBaseSpecifier() = default;
183 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
184 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
185 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
186 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
187
188 /// Retrieves the source range that contains the entire base specifier.
189 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
190 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
191 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
192
193 /// Get the location at which the base class type was written.
194 SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) {
195 return BaseTypeInfo->getTypeLoc().getBeginLoc();
196 }
197
198 /// Determines whether the base class is a virtual base class (or not).
199 bool isVirtual() const { return Virtual; }
200
201 /// Determine whether this base class is a base of a class declared
202 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
203 bool isBaseOfClass() const { return BaseOfClass; }
204
205 /// Determine whether this base specifier is a pack expansion.
206 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
207
208 /// Determine whether this base class's constructors get inherited.
209 bool getInheritConstructors() const { return InheritConstructors; }
210
211 /// Set that this base class's constructors should be inherited.
212 void setInheritConstructors(bool Inherit = true) {
213 InheritConstructors = Inherit;
214 }
215
216 /// For a pack expansion, determine the location of the ellipsis.
217 SourceLocation getEllipsisLoc() const {
218 return EllipsisLoc;
219 }
220
221 /// Returns the access specifier for this base specifier.
222 ///
223 /// This is the actual base specifier as used for semantic analysis, so
224 /// the result can never be AS_none. To retrieve the access specifier as
225 /// written in the source code, use getAccessSpecifierAsWritten().
226 AccessSpecifier getAccessSpecifier() const {
227 if ((AccessSpecifier)Access == AS_none)
228 return BaseOfClass? AS_private : AS_public;
229 else
230 return (AccessSpecifier)Access;
231 }
232
233 /// Retrieves the access specifier as written in the source code
234 /// (which may mean that no access specifier was explicitly written).
235 ///
236 /// Use getAccessSpecifier() to retrieve the access specifier for use in
237 /// semantic analysis.
238 AccessSpecifier getAccessSpecifierAsWritten() const {
239 return (AccessSpecifier)Access;
240 }
241
242 /// Retrieves the type of the base class.
243 ///
244 /// This type will always be an unqualified class type.
245 QualType getType() const {
246 return BaseTypeInfo->getType().getUnqualifiedType();
247 }
248
249 /// Retrieves the type and source location of the base class.
250 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
251};
252
253/// Represents a C++ struct/union/class.
254class CXXRecordDecl : public RecordDecl {
255 friend class ASTDeclReader;
256 friend class ASTDeclWriter;
257 friend class ASTNodeImporter;
258 friend class ASTReader;
259 friend class ASTRecordWriter;
260 friend class ASTWriter;
261 friend class DeclContext;
262 friend class LambdaExpr;
263
264 friend void FunctionDecl::setPure(bool);
265 friend void TagDecl::startDefinition();
266
267 /// Values used in DefinitionData fields to represent special members.
268 enum SpecialMemberFlags {
269 SMF_DefaultConstructor = 0x1,
270 SMF_CopyConstructor = 0x2,
271 SMF_MoveConstructor = 0x4,
272 SMF_CopyAssignment = 0x8,
273 SMF_MoveAssignment = 0x10,
274 SMF_Destructor = 0x20,
275 SMF_All = 0x3f
276 };
277
278 struct DefinitionData {
279 #define FIELD(Name, Width, Merge) \
280 unsigned Name : Width;
281 #include "CXXRecordDeclDefinitionBits.def"
282
283 /// Whether this class describes a C++ lambda.
284 unsigned IsLambda : 1;
285
286 /// Whether we are currently parsing base specifiers.
287 unsigned IsParsingBaseSpecifiers : 1;
288
289 /// True when visible conversion functions are already computed
290 /// and are available.
291 unsigned ComputedVisibleConversions : 1;
292
293 unsigned HasODRHash : 1;
294
295 /// A hash of parts of the class to help in ODR checking.
296 unsigned ODRHash = 0;
297
298 /// The number of base class specifiers in Bases.
299 unsigned NumBases = 0;
300
301 /// The number of virtual base class specifiers in VBases.
302 unsigned NumVBases = 0;
303
304 /// Base classes of this class.
305 ///
306 /// FIXME: This is wasted space for a union.
307 LazyCXXBaseSpecifiersPtr Bases;
308
309 /// direct and indirect virtual base classes of this class.
310 LazyCXXBaseSpecifiersPtr VBases;
311
312 /// The conversion functions of this C++ class (but not its
313 /// inherited conversion functions).
314 ///
315 /// Each of the entries in this overload set is a CXXConversionDecl.
316 LazyASTUnresolvedSet Conversions;
317
318 /// The conversion functions of this C++ class and all those
319 /// inherited conversion functions that are visible in this class.
320 ///
321 /// Each of the entries in this overload set is a CXXConversionDecl or a
322 /// FunctionTemplateDecl.
323 LazyASTUnresolvedSet VisibleConversions;
324
325 /// The declaration which defines this record.
326 CXXRecordDecl *Definition;
327
328 /// The first friend declaration in this class, or null if there
329 /// aren't any.
330 ///
331 /// This is actually currently stored in reverse order.
332 LazyDeclPtr FirstFriend;
333
334 DefinitionData(CXXRecordDecl *D);
335
336 /// Retrieve the set of direct base classes.
337 CXXBaseSpecifier *getBases() const {
338 if (!Bases.isOffset())
339 return Bases.get(nullptr);
340 return getBasesSlowCase();
341 }
342
343 /// Retrieve the set of virtual base classes.
344 CXXBaseSpecifier *getVBases() const {
345 if (!VBases.isOffset())
346 return VBases.get(nullptr);
347 return getVBasesSlowCase();
348 }
349
350 ArrayRef<CXXBaseSpecifier> bases() const {
351 return llvm::makeArrayRef(getBases(), NumBases);
352 }
353
354 ArrayRef<CXXBaseSpecifier> vbases() const {
355 return llvm::makeArrayRef(getVBases(), NumVBases);
356 }
357
358 private:
359 CXXBaseSpecifier *getBasesSlowCase() const;
360 CXXBaseSpecifier *getVBasesSlowCase() const;
361 };
362
363 struct DefinitionData *DefinitionData;
364
365 /// Describes a C++ closure type (generated by a lambda expression).
366 struct LambdaDefinitionData : public DefinitionData {
367 using Capture = LambdaCapture;
368
369 /// Whether this lambda is known to be dependent, even if its
370 /// context isn't dependent.
371 ///
372 /// A lambda with a non-dependent context can be dependent if it occurs
373 /// within the default argument of a function template, because the
374 /// lambda will have been created with the enclosing context as its
375 /// declaration context, rather than function. This is an unfortunate
376 /// artifact of having to parse the default arguments before.
377 unsigned Dependent : 1;
378
379 /// Whether this lambda is a generic lambda.
380 unsigned IsGenericLambda : 1;
381
382 /// The Default Capture.
383 unsigned CaptureDefault : 2;
384
385 /// The number of captures in this lambda is limited 2^NumCaptures.
386 unsigned NumCaptures : 15;
387
388 /// The number of explicit captures in this lambda.
389 unsigned NumExplicitCaptures : 13;
390
391 /// Has known `internal` linkage.
392 unsigned HasKnownInternalLinkage : 1;
393
394 /// The number used to indicate this lambda expression for name
395 /// mangling in the Itanium C++ ABI.
396 unsigned ManglingNumber : 31;
397
398 /// The declaration that provides context for this lambda, if the
399 /// actual DeclContext does not suffice. This is used for lambdas that
400 /// occur within default arguments of function parameters within the class
401 /// or within a data member initializer.
402 LazyDeclPtr ContextDecl;
403
404 /// The list of captures, both explicit and implicit, for this
405 /// lambda.
406 Capture *Captures = nullptr;
407
408 /// The type of the call method.
409 TypeSourceInfo *MethodTyInfo;
410
411 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent,
412 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
413 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
414 CaptureDefault(CaptureDefault), NumCaptures(0),
415 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
416 MethodTyInfo(Info) {
417 IsLambda = true;
418
419 // C++1z [expr.prim.lambda]p4:
420 // This class type is not an aggregate type.
421 Aggregate = false;
422 PlainOldData = false;
423 }
424 };
425
426 struct DefinitionData *dataPtr() const {
427 // Complete the redecl chain (if necessary).
428 getMostRecentDecl();
429 return DefinitionData;
430 }
431
432 struct DefinitionData &data() const {
433 auto *DD = dataPtr();
434 assert(DD && "queried property of class with no definition")((DD && "queried property of class with no definition"
) ? static_cast<void> (0) : __assert_fail ("DD && \"queried property of class with no definition\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 434, __PRETTY_FUNCTION__))
;
435 return *DD;
436 }
437
438 struct LambdaDefinitionData &getLambdaData() const {
439 // No update required: a merged definition cannot change any lambda
440 // properties.
441 auto *DD = DefinitionData;
442 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")((DD && DD->IsLambda && "queried lambda property of non-lambda class"
) ? static_cast<void> (0) : __assert_fail ("DD && DD->IsLambda && \"queried lambda property of non-lambda class\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 442, __PRETTY_FUNCTION__))
;
443 return static_cast<LambdaDefinitionData&>(*DD);
444 }
445
446 /// The template or declaration that this declaration
447 /// describes or was instantiated from, respectively.
448 ///
449 /// For non-templates, this value will be null. For record
450 /// declarations that describe a class template, this will be a
451 /// pointer to a ClassTemplateDecl. For member
452 /// classes of class template specializations, this will be the
453 /// MemberSpecializationInfo referring to the member class that was
454 /// instantiated or specialized.
455 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
456 TemplateOrInstantiation;
457
458 /// Called from setBases and addedMember to notify the class that a
459 /// direct or virtual base class or a member of class type has been added.
460 void addedClassSubobject(CXXRecordDecl *Base);
461
462 /// Notify the class that member has been added.
463 ///
464 /// This routine helps maintain information about the class based on which
465 /// members have been added. It will be invoked by DeclContext::addDecl()
466 /// whenever a member is added to this record.
467 void addedMember(Decl *D);
468
469 void markedVirtualFunctionPure();
470
471 /// Get the head of our list of friend declarations, possibly
472 /// deserializing the friends from an external AST source.
473 FriendDecl *getFirstFriend() const;
474
475 /// Determine whether this class has an empty base class subobject of type X
476 /// or of one of the types that might be at offset 0 within X (per the C++
477 /// "standard layout" rules).
478 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
479 const CXXRecordDecl *X);
480
481protected:
482 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
483 SourceLocation StartLoc, SourceLocation IdLoc,
484 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
485
486public:
487 /// Iterator that traverses the base classes of a class.
488 using base_class_iterator = CXXBaseSpecifier *;
489
490 /// Iterator that traverses the base classes of a class.
491 using base_class_const_iterator = const CXXBaseSpecifier *;
492
493 CXXRecordDecl *getCanonicalDecl() override {
494 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
495 }
496
497 const CXXRecordDecl *getCanonicalDecl() const {
498 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
499 }
500
501 CXXRecordDecl *getPreviousDecl() {
502 return cast_or_null<CXXRecordDecl>(
503 static_cast<RecordDecl *>(this)->getPreviousDecl());
504 }
505
506 const CXXRecordDecl *getPreviousDecl() const {
507 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
508 }
509
510 CXXRecordDecl *getMostRecentDecl() {
511 return cast<CXXRecordDecl>(
512 static_cast<RecordDecl *>(this)->getMostRecentDecl());
513 }
514
515 const CXXRecordDecl *getMostRecentDecl() const {
516 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
517 }
518
519 CXXRecordDecl *getMostRecentNonInjectedDecl() {
520 CXXRecordDecl *Recent =
521 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
522 while (Recent->isInjectedClassName()) {
523 // FIXME: Does injected class name need to be in the redeclarations chain?
524 assert(Recent->getPreviousDecl())((Recent->getPreviousDecl()) ? static_cast<void> (0)
: __assert_fail ("Recent->getPreviousDecl()", "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 524, __PRETTY_FUNCTION__))
;
525 Recent = Recent->getPreviousDecl();
526 }
527 return Recent;
528 }
529
530 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
531 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
532 }
533
534 CXXRecordDecl *getDefinition() const {
535 // We only need an update if we don't already know which
536 // declaration is the definition.
537 auto *DD = DefinitionData ? DefinitionData : dataPtr();
538 return DD ? DD->Definition : nullptr;
539 }
540
541 bool hasDefinition() const { return DefinitionData || dataPtr(); }
542
543 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
544 SourceLocation StartLoc, SourceLocation IdLoc,
545 IdentifierInfo *Id,
546 CXXRecordDecl *PrevDecl = nullptr,
547 bool DelayTypeCreation = false);
548 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
549 TypeSourceInfo *Info, SourceLocation Loc,
550 bool DependentLambda, bool IsGeneric,
551 LambdaCaptureDefault CaptureDefault);
552 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
553
554 bool isDynamicClass() const {
555 return data().Polymorphic || data().NumVBases != 0;
556 }
557
558 /// @returns true if class is dynamic or might be dynamic because the
559 /// definition is incomplete of dependent.
560 bool mayBeDynamicClass() const {
561 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
562 }
563
564 /// @returns true if class is non dynamic or might be non dynamic because the
565 /// definition is incomplete of dependent.
566 bool mayBeNonDynamicClass() const {
567 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
568 }
569
570 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
571
572 bool isParsingBaseSpecifiers() const {
573 return data().IsParsingBaseSpecifiers;
574 }
575
576 unsigned getODRHash() const;
577
578 /// Sets the base classes of this struct or class.
579 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
580
581 /// Retrieves the number of base classes of this class.
582 unsigned getNumBases() const { return data().NumBases; }
583
584 using base_class_range = llvm::iterator_range<base_class_iterator>;
585 using base_class_const_range =
586 llvm::iterator_range<base_class_const_iterator>;
587
588 base_class_range bases() {
589 return base_class_range(bases_begin(), bases_end());
590 }
591 base_class_const_range bases() const {
592 return base_class_const_range(bases_begin(), bases_end());
593 }
594
595 base_class_iterator bases_begin() { return data().getBases(); }
596 base_class_const_iterator bases_begin() const { return data().getBases(); }
597 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
598 base_class_const_iterator bases_end() const {
599 return bases_begin() + data().NumBases;
600 }
601
602 /// Retrieves the number of virtual base classes of this class.
603 unsigned getNumVBases() const { return data().NumVBases; }
604
605 base_class_range vbases() {
606 return base_class_range(vbases_begin(), vbases_end());
607 }
608 base_class_const_range vbases() const {
609 return base_class_const_range(vbases_begin(), vbases_end());
610 }
611
612 base_class_iterator vbases_begin() { return data().getVBases(); }
613 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
614 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
615 base_class_const_iterator vbases_end() const {
616 return vbases_begin() + data().NumVBases;
617 }
618
619 /// Determine whether this class has any dependent base classes which
620 /// are not the current instantiation.
621 bool hasAnyDependentBases() const;
622
623 /// Iterator access to method members. The method iterator visits
624 /// all method members of the class, including non-instance methods,
625 /// special methods, etc.
626 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
627 using method_range =
628 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
629
630 method_range methods() const {
631 return method_range(method_begin(), method_end());
632 }
633
634 /// Method begin iterator. Iterates in the order the methods
635 /// were declared.
636 method_iterator method_begin() const {
637 return method_iterator(decls_begin());
638 }
639
640 /// Method past-the-end iterator.
641 method_iterator method_end() const {
642 return method_iterator(decls_end());
643 }
644
645 /// Iterator access to constructor members.
646 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
647 using ctor_range =
648 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
649
650 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
651
652 ctor_iterator ctor_begin() const {
653 return ctor_iterator(decls_begin());
654 }
655
656 ctor_iterator ctor_end() const {
657 return ctor_iterator(decls_end());
658 }
659
660 /// An iterator over friend declarations. All of these are defined
661 /// in DeclFriend.h.
662 class friend_iterator;
663 using friend_range = llvm::iterator_range<friend_iterator>;
664
665 friend_range friends() const;
666 friend_iterator friend_begin() const;
667 friend_iterator friend_end() const;
668 void pushFriendDecl(FriendDecl *FD);
669
670 /// Determines whether this record has any friends.
671 bool hasFriends() const {
672 return data().FirstFriend.isValid();
673 }
674
675 /// \c true if a defaulted copy constructor for this class would be
676 /// deleted.
677 bool defaultedCopyConstructorIsDeleted() const {
678 assert((!needsOverloadResolutionForCopyConstructor() ||(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 680, __PRETTY_FUNCTION__))
679 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 680, __PRETTY_FUNCTION__))
680 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 680, __PRETTY_FUNCTION__))
;
681 return data().DefaultedCopyConstructorIsDeleted;
682 }
683
684 /// \c true if a defaulted move constructor for this class would be
685 /// deleted.
686 bool defaultedMoveConstructorIsDeleted() const {
687 assert((!needsOverloadResolutionForMoveConstructor() ||(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 689, __PRETTY_FUNCTION__))
688 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 689, __PRETTY_FUNCTION__))
689 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 689, __PRETTY_FUNCTION__))
;
690 return data().DefaultedMoveConstructorIsDeleted;
691 }
692
693 /// \c true if a defaulted destructor for this class would be deleted.
694 bool defaultedDestructorIsDeleted() const {
695 assert((!needsOverloadResolutionForDestructor() ||(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 697, __PRETTY_FUNCTION__))
696 (data().DeclaredSpecialMembers & SMF_Destructor)) &&(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 697, __PRETTY_FUNCTION__))
697 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 697, __PRETTY_FUNCTION__))
;
698 return data().DefaultedDestructorIsDeleted;
699 }
700
701 /// \c true if we know for sure that this class has a single,
702 /// accessible, unambiguous copy constructor that is not deleted.
703 bool hasSimpleCopyConstructor() const {
704 return !hasUserDeclaredCopyConstructor() &&
705 !data().DefaultedCopyConstructorIsDeleted;
706 }
707
708 /// \c true if we know for sure that this class has a single,
709 /// accessible, unambiguous move constructor that is not deleted.
710 bool hasSimpleMoveConstructor() const {
711 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
712 !data().DefaultedMoveConstructorIsDeleted;
713 }
714
715 /// \c true if we know for sure that this class has a single,
716 /// accessible, unambiguous copy assignment operator that is not deleted.
717 bool hasSimpleCopyAssignment() const {
718 return !hasUserDeclaredCopyAssignment() &&
719 !data().DefaultedCopyAssignmentIsDeleted;
720 }
721
722 /// \c true if we know for sure that this class has a single,
723 /// accessible, unambiguous move assignment operator that is not deleted.
724 bool hasSimpleMoveAssignment() const {
725 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
726 !data().DefaultedMoveAssignmentIsDeleted;
727 }
728
729 /// \c true if we know for sure that this class has an accessible
730 /// destructor that is not deleted.
731 bool hasSimpleDestructor() const {
732 return !hasUserDeclaredDestructor() &&
733 !data().DefaultedDestructorIsDeleted;
734 }
735
736 /// Determine whether this class has any default constructors.
737 bool hasDefaultConstructor() const {
738 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
739 needsImplicitDefaultConstructor();
740 }
741
742 /// Determine if we need to declare a default constructor for
743 /// this class.
744 ///
745 /// This value is used for lazy creation of default constructors.
746 bool needsImplicitDefaultConstructor() const {
747 return !data().UserDeclaredConstructor &&
748 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
749 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
750 }
751
752 /// Determine whether this class has any user-declared constructors.
753 ///
754 /// When true, a default constructor will not be implicitly declared.
755 bool hasUserDeclaredConstructor() const {
756 return data().UserDeclaredConstructor;
757 }
758
759 /// Whether this class has a user-provided default constructor
760 /// per C++11.
761 bool hasUserProvidedDefaultConstructor() const {
762 return data().UserProvidedDefaultConstructor;
763 }
764
765 /// Determine whether this class has a user-declared copy constructor.
766 ///
767 /// When false, a copy constructor will be implicitly declared.
768 bool hasUserDeclaredCopyConstructor() const {
769 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
770 }
771
772 /// Determine whether this class needs an implicit copy
773 /// constructor to be lazily declared.
774 bool needsImplicitCopyConstructor() const {
775 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
776 }
777
778 /// Determine whether we need to eagerly declare a defaulted copy
779 /// constructor for this class.
780 bool needsOverloadResolutionForCopyConstructor() const {
781 // C++17 [class.copy.ctor]p6:
782 // If the class definition declares a move constructor or move assignment
783 // operator, the implicitly declared copy constructor is defined as
784 // deleted.
785 // In MSVC mode, sometimes a declared move assignment does not delete an
786 // implicit copy constructor, so defer this choice to Sema.
787 if (data().UserDeclaredSpecialMembers &
788 (SMF_MoveConstructor | SMF_MoveAssignment))
789 return true;
790 return data().NeedOverloadResolutionForCopyConstructor;
791 }
792
793 /// Determine whether an implicit copy constructor for this type
794 /// would have a parameter with a const-qualified reference type.
795 bool implicitCopyConstructorHasConstParam() const {
796 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
797 (isAbstract() ||
798 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
799 }
800
801 /// Determine whether this class has a copy constructor with
802 /// a parameter type which is a reference to a const-qualified type.
803 bool hasCopyConstructorWithConstParam() const {
804 return data().HasDeclaredCopyConstructorWithConstParam ||
805 (needsImplicitCopyConstructor() &&
806 implicitCopyConstructorHasConstParam());
807 }
808
809 /// Whether this class has a user-declared move constructor or
810 /// assignment operator.
811 ///
812 /// When false, a move constructor and assignment operator may be
813 /// implicitly declared.
814 bool hasUserDeclaredMoveOperation() const {
815 return data().UserDeclaredSpecialMembers &
816 (SMF_MoveConstructor | SMF_MoveAssignment);
817 }
818
819 /// Determine whether this class has had a move constructor
820 /// declared by the user.
821 bool hasUserDeclaredMoveConstructor() const {
822 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
823 }
824
825 /// Determine whether this class has a move constructor.
826 bool hasMoveConstructor() const {
827 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
828 needsImplicitMoveConstructor();
829 }
830
831 /// Set that we attempted to declare an implicit copy
832 /// constructor, but overload resolution failed so we deleted it.
833 void setImplicitCopyConstructorIsDeleted() {
834 assert((data().DefaultedCopyConstructorIsDeleted ||(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 836, __PRETTY_FUNCTION__))
835 needsOverloadResolutionForCopyConstructor()) &&(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 836, __PRETTY_FUNCTION__))
836 "Copy constructor should not be deleted")(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 836, __PRETTY_FUNCTION__))
;
837 data().DefaultedCopyConstructorIsDeleted = true;
838 }
839
840 /// Set that we attempted to declare an implicit move
841 /// constructor, but overload resolution failed so we deleted it.
842 void setImplicitMoveConstructorIsDeleted() {
843 assert((data().DefaultedMoveConstructorIsDeleted ||(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 845, __PRETTY_FUNCTION__))
844 needsOverloadResolutionForMoveConstructor()) &&(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 845, __PRETTY_FUNCTION__))
845 "move constructor should not be deleted")(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 845, __PRETTY_FUNCTION__))
;
846 data().DefaultedMoveConstructorIsDeleted = true;
847 }
848
849 /// Set that we attempted to declare an implicit destructor,
850 /// but overload resolution failed so we deleted it.
851 void setImplicitDestructorIsDeleted() {
852 assert((data().DefaultedDestructorIsDeleted ||(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 854, __PRETTY_FUNCTION__))
853 needsOverloadResolutionForDestructor()) &&(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 854, __PRETTY_FUNCTION__))
854 "destructor should not be deleted")(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 854, __PRETTY_FUNCTION__))
;
855 data().DefaultedDestructorIsDeleted = true;
856 }
857
858 /// Determine whether this class should get an implicit move
859 /// constructor or if any existing special member function inhibits this.
860 bool needsImplicitMoveConstructor() const {
861 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
862 !hasUserDeclaredCopyConstructor() &&
863 !hasUserDeclaredCopyAssignment() &&
864 !hasUserDeclaredMoveAssignment() &&
865 !hasUserDeclaredDestructor();
866 }
867
868 /// Determine whether we need to eagerly declare a defaulted move
869 /// constructor for this class.
870 bool needsOverloadResolutionForMoveConstructor() const {
871 return data().NeedOverloadResolutionForMoveConstructor;
872 }
873
874 /// Determine whether this class has a user-declared copy assignment
875 /// operator.
876 ///
877 /// When false, a copy assignment operator will be implicitly declared.
878 bool hasUserDeclaredCopyAssignment() const {
879 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
880 }
881
882 /// Set that we attempted to declare an implicit copy assignment
883 /// operator, but overload resolution failed so we deleted it.
884 void setImplicitCopyAssignmentIsDeleted() {
885 assert((data().DefaultedCopyAssignmentIsDeleted ||(((data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment
()) && "copy assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 887, __PRETTY_FUNCTION__))
886 needsOverloadResolutionForCopyAssignment()) &&(((data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment
()) && "copy assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 887, __PRETTY_FUNCTION__))
887 "copy assignment should not be deleted")(((data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment
()) && "copy assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyAssignmentIsDeleted || needsOverloadResolutionForCopyAssignment()) && \"copy assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 887, __PRETTY_FUNCTION__))
;
888 data().DefaultedCopyAssignmentIsDeleted = true;
889 }
890
891 /// Determine whether this class needs an implicit copy
892 /// assignment operator to be lazily declared.
893 bool needsImplicitCopyAssignment() const {
894 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
895 }
896
897 /// Determine whether we need to eagerly declare a defaulted copy
898 /// assignment operator for this class.
899 bool needsOverloadResolutionForCopyAssignment() const {
900 // C++20 [class.copy.assign]p2:
901 // If the class definition declares a move constructor or move assignment
902 // operator, the implicitly declared copy assignment operator is defined
903 // as deleted.
904 // In MSVC mode, sometimes a declared move constructor does not delete an
905 // implicit copy assignment, so defer this choice to Sema.
906 if (data().UserDeclaredSpecialMembers &
907 (SMF_MoveConstructor | SMF_MoveAssignment))
908 return true;
909 return data().NeedOverloadResolutionForCopyAssignment;
910 }
911
912 /// Determine whether an implicit copy assignment operator for this
913 /// type would have a parameter with a const-qualified reference type.
914 bool implicitCopyAssignmentHasConstParam() const {
915 return data().ImplicitCopyAssignmentHasConstParam;
916 }
917
918 /// Determine whether this class has a copy assignment operator with
919 /// a parameter type which is a reference to a const-qualified type or is not
920 /// a reference.
921 bool hasCopyAssignmentWithConstParam() const {
922 return data().HasDeclaredCopyAssignmentWithConstParam ||
923 (needsImplicitCopyAssignment() &&
924 implicitCopyAssignmentHasConstParam());
925 }
926
927 /// Determine whether this class has had a move assignment
928 /// declared by the user.
929 bool hasUserDeclaredMoveAssignment() const {
930 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
931 }
932
933 /// Determine whether this class has a move assignment operator.
934 bool hasMoveAssignment() const {
935 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
936 needsImplicitMoveAssignment();
937 }
938
939 /// Set that we attempted to declare an implicit move assignment
940 /// operator, but overload resolution failed so we deleted it.
941 void setImplicitMoveAssignmentIsDeleted() {
942 assert((data().DefaultedMoveAssignmentIsDeleted ||(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 944, __PRETTY_FUNCTION__))
943 needsOverloadResolutionForMoveAssignment()) &&(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 944, __PRETTY_FUNCTION__))
944 "move assignment should not be deleted")(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 944, __PRETTY_FUNCTION__))
;
945 data().DefaultedMoveAssignmentIsDeleted = true;
946 }
947
948 /// Determine whether this class should get an implicit move
949 /// assignment operator or if any existing special member function inhibits
950 /// this.
951 bool needsImplicitMoveAssignment() const {
952 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
953 !hasUserDeclaredCopyConstructor() &&
954 !hasUserDeclaredCopyAssignment() &&
955 !hasUserDeclaredMoveConstructor() &&
956 !hasUserDeclaredDestructor() &&
957 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
958 }
959
960 /// Determine whether we need to eagerly declare a move assignment
961 /// operator for this class.
962 bool needsOverloadResolutionForMoveAssignment() const {
963 return data().NeedOverloadResolutionForMoveAssignment;
964 }
965
966 /// Determine whether this class has a user-declared destructor.
967 ///
968 /// When false, a destructor will be implicitly declared.
969 bool hasUserDeclaredDestructor() const {
970 return data().UserDeclaredSpecialMembers & SMF_Destructor;
971 }
972
973 /// Determine whether this class needs an implicit destructor to
974 /// be lazily declared.
975 bool needsImplicitDestructor() const {
976 return !(data().DeclaredSpecialMembers & SMF_Destructor);
977 }
978
979 /// Determine whether we need to eagerly declare a destructor for this
980 /// class.
981 bool needsOverloadResolutionForDestructor() const {
982 return data().NeedOverloadResolutionForDestructor;
983 }
984
985 /// Determine whether this class describes a lambda function object.
986 bool isLambda() const {
987 // An update record can't turn a non-lambda into a lambda.
988 auto *DD = DefinitionData;
989 return DD && DD->IsLambda;
4
Assuming 'DD' is non-null
5
Returning value, which participates in a condition later
990 }
991
992 /// Determine whether this class describes a generic
993 /// lambda function object (i.e. function call operator is
994 /// a template).
995 bool isGenericLambda() const;
996
997 /// Determine whether this lambda should have an implicit default constructor
998 /// and copy and move assignment operators.
999 bool lambdaIsDefaultConstructibleAndAssignable() const;
1000
1001 /// Retrieve the lambda call operator of the closure type
1002 /// if this is a closure type.
1003 CXXMethodDecl *getLambdaCallOperator() const;
1004
1005 /// Retrieve the dependent lambda call operator of the closure type
1006 /// if this is a templated closure type.
1007 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1008
1009 /// Retrieve the lambda static invoker, the address of which
1010 /// is returned by the conversion operator, and the body of which
1011 /// is forwarded to the lambda call operator. The version that does not
1012 /// take a calling convention uses the 'default' calling convention for free
1013 /// functions if the Lambda's calling convention was not modified via
1014 /// attribute. Otherwise, it will return the calling convention specified for
1015 /// the lambda.
1016 CXXMethodDecl *getLambdaStaticInvoker() const;
1017 CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1018
1019 /// Retrieve the generic lambda's template parameter list.
1020 /// Returns null if the class does not represent a lambda or a generic
1021 /// lambda.
1022 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1023
1024 /// Retrieve the lambda template parameters that were specified explicitly.
1025 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1026
1027 LambdaCaptureDefault getLambdaCaptureDefault() const {
1028 assert(isLambda())((isLambda()) ? static_cast<void> (0) : __assert_fail (
"isLambda()", "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 1028, __PRETTY_FUNCTION__))
;
1029 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1030 }
1031
1032 /// Set the captures for this lambda closure type.
1033 void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1034
1035 /// For a closure type, retrieve the mapping from captured
1036 /// variables and \c this to the non-static data members that store the
1037 /// values or references of the captures.
1038 ///
1039 /// \param Captures Will be populated with the mapping from captured
1040 /// variables to the corresponding fields.
1041 ///
1042 /// \param ThisCapture Will be set to the field declaration for the
1043 /// \c this capture.
1044 ///
1045 /// \note No entries will be added for init-captures, as they do not capture
1046 /// variables.
1047 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1048 FieldDecl *&ThisCapture) const;
1049
1050 using capture_const_iterator = const LambdaCapture *;
1051 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1052
1053 capture_const_range captures() const {
1054 return capture_const_range(captures_begin(), captures_end());
1055 }
1056
1057 capture_const_iterator captures_begin() const {
1058 return isLambda() ? getLambdaData().Captures : nullptr;
1059 }
1060
1061 capture_const_iterator captures_end() const {
1062 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1063 : nullptr;
1064 }
1065
1066 unsigned capture_size() const { return getLambdaData().NumCaptures; }
1067
1068 using conversion_iterator = UnresolvedSetIterator;
1069
1070 conversion_iterator conversion_begin() const {
1071 return data().Conversions.get(getASTContext()).begin();
1072 }
1073
1074 conversion_iterator conversion_end() const {
1075 return data().Conversions.get(getASTContext()).end();
1076 }
1077
1078 /// Removes a conversion function from this class. The conversion
1079 /// function must currently be a member of this class. Furthermore,
1080 /// this class must currently be in the process of being defined.
1081 void removeConversion(const NamedDecl *Old);
1082
1083 /// Get all conversion functions visible in current class,
1084 /// including conversion function templates.
1085 llvm::iterator_range<conversion_iterator>
1086 getVisibleConversionFunctions() const;
1087
1088 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1089 /// which is a class with no user-declared constructors, no private
1090 /// or protected non-static data members, no base classes, and no virtual
1091 /// functions (C++ [dcl.init.aggr]p1).
1092 bool isAggregate() const { return data().Aggregate; }
1093
1094 /// Whether this class has any in-class initializers
1095 /// for non-static data members (including those in anonymous unions or
1096 /// structs).
1097 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1098
1099 /// Whether this class or any of its subobjects has any members of
1100 /// reference type which would make value-initialization ill-formed.
1101 ///
1102 /// Per C++03 [dcl.init]p5:
1103 /// - if T is a non-union class type without a user-declared constructor,
1104 /// then every non-static data member and base-class component of T is
1105 /// value-initialized [...] A program that calls for [...]
1106 /// value-initialization of an entity of reference type is ill-formed.
1107 bool hasUninitializedReferenceMember() const {
1108 return !isUnion() && !hasUserDeclaredConstructor() &&
1109 data().HasUninitializedReferenceMember;
1110 }
1111
1112 /// Whether this class is a POD-type (C++ [class]p4)
1113 ///
1114 /// For purposes of this function a class is POD if it is an aggregate
1115 /// that has no non-static non-POD data members, no reference data
1116 /// members, no user-defined copy assignment operator and no
1117 /// user-defined destructor.
1118 ///
1119 /// Note that this is the C++ TR1 definition of POD.
1120 bool isPOD() const { return data().PlainOldData; }
1121
1122 /// True if this class is C-like, without C++-specific features, e.g.
1123 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1124 bool isCLike() const;
1125
1126 /// Determine whether this is an empty class in the sense of
1127 /// (C++11 [meta.unary.prop]).
1128 ///
1129 /// The CXXRecordDecl is a class type, but not a union type,
1130 /// with no non-static data members other than bit-fields of length 0,
1131 /// no virtual member functions, no virtual base classes,
1132 /// and no base class B for which is_empty<B>::value is false.
1133 ///
1134 /// \note This does NOT include a check for union-ness.
1135 bool isEmpty() const { return data().Empty; }
1136
1137 bool hasPrivateFields() const {
1138 return data().HasPrivateFields;
1139 }
1140
1141 bool hasProtectedFields() const {
1142 return data().HasProtectedFields;
1143 }
1144
1145 /// Determine whether this class has direct non-static data members.
1146 bool hasDirectFields() const {
1147 auto &D = data();
1148 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1149 }
1150
1151 /// Whether this class is polymorphic (C++ [class.virtual]),
1152 /// which means that the class contains or inherits a virtual function.
1153 bool isPolymorphic() const { return data().Polymorphic; }
1154
1155 /// Determine whether this class has a pure virtual function.
1156 ///
1157 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1158 /// a pure virtual function or inherits a pure virtual function that is
1159 /// not overridden.
1160 bool isAbstract() const { return data().Abstract; }
1161
1162 /// Determine whether this class is standard-layout per
1163 /// C++ [class]p7.
1164 bool isStandardLayout() const { return data().IsStandardLayout; }
1165
1166 /// Determine whether this class was standard-layout per
1167 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1168 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1169
1170 /// Determine whether this class, or any of its class subobjects,
1171 /// contains a mutable field.
1172 bool hasMutableFields() const { return data().HasMutableFields; }
1173
1174 /// Determine whether this class has any variant members.
1175 bool hasVariantMembers() const { return data().HasVariantMembers; }
1176
1177 /// Determine whether this class has a trivial default constructor
1178 /// (C++11 [class.ctor]p5).
1179 bool hasTrivialDefaultConstructor() const {
1180 return hasDefaultConstructor() &&
1181 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1182 }
1183
1184 /// Determine whether this class has a non-trivial default constructor
1185 /// (C++11 [class.ctor]p5).
1186 bool hasNonTrivialDefaultConstructor() const {
1187 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1188 (needsImplicitDefaultConstructor() &&
1189 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1190 }
1191
1192 /// Determine whether this class has at least one constexpr constructor
1193 /// other than the copy or move constructors.
1194 bool hasConstexprNonCopyMoveConstructor() const {
1195 return data().HasConstexprNonCopyMoveConstructor ||
1196 (needsImplicitDefaultConstructor() &&
1197 defaultedDefaultConstructorIsConstexpr());
1198 }
1199
1200 /// Determine whether a defaulted default constructor for this class
1201 /// would be constexpr.
1202 bool defaultedDefaultConstructorIsConstexpr() const {
1203 return data().DefaultedDefaultConstructorIsConstexpr &&
1204 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1205 getLangOpts().CPlusPlus20);
1206 }
1207
1208 /// Determine whether this class has a constexpr default constructor.
1209 bool hasConstexprDefaultConstructor() const {
1210 return data().HasConstexprDefaultConstructor ||
1211 (needsImplicitDefaultConstructor() &&
1212 defaultedDefaultConstructorIsConstexpr());
1213 }
1214
1215 /// Determine whether this class has a trivial copy constructor
1216 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1217 bool hasTrivialCopyConstructor() const {
1218 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1219 }
1220
1221 bool hasTrivialCopyConstructorForCall() const {
1222 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1223 }
1224
1225 /// Determine whether this class has a non-trivial copy constructor
1226 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1227 bool hasNonTrivialCopyConstructor() const {
1228 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1229 !hasTrivialCopyConstructor();
1230 }
1231
1232 bool hasNonTrivialCopyConstructorForCall() const {
1233 return (data().DeclaredNonTrivialSpecialMembersForCall &
1234 SMF_CopyConstructor) ||
1235 !hasTrivialCopyConstructorForCall();
1236 }
1237
1238 /// Determine whether this class has a trivial move constructor
1239 /// (C++11 [class.copy]p12)
1240 bool hasTrivialMoveConstructor() const {
1241 return hasMoveConstructor() &&
1242 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1243 }
1244
1245 bool hasTrivialMoveConstructorForCall() const {
1246 return hasMoveConstructor() &&
1247 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1248 }
1249
1250 /// Determine whether this class has a non-trivial move constructor
1251 /// (C++11 [class.copy]p12)
1252 bool hasNonTrivialMoveConstructor() const {
1253 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1254 (needsImplicitMoveConstructor() &&
1255 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1256 }
1257
1258 bool hasNonTrivialMoveConstructorForCall() const {
1259 return (data().DeclaredNonTrivialSpecialMembersForCall &
1260 SMF_MoveConstructor) ||
1261 (needsImplicitMoveConstructor() &&
1262 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1263 }
1264
1265 /// Determine whether this class has a trivial copy assignment operator
1266 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1267 bool hasTrivialCopyAssignment() const {
1268 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1269 }
1270
1271 /// Determine whether this class has a non-trivial copy assignment
1272 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1273 bool hasNonTrivialCopyAssignment() const {
1274 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1275 !hasTrivialCopyAssignment();
1276 }
1277
1278 /// Determine whether this class has a trivial move assignment operator
1279 /// (C++11 [class.copy]p25)
1280 bool hasTrivialMoveAssignment() const {
1281 return hasMoveAssignment() &&
1282 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1283 }
1284
1285 /// Determine whether this class has a non-trivial move assignment
1286 /// operator (C++11 [class.copy]p25)
1287 bool hasNonTrivialMoveAssignment() const {
1288 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1289 (needsImplicitMoveAssignment() &&
1290 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1291 }
1292
1293 /// Determine whether a defaulted default constructor for this class
1294 /// would be constexpr.
1295 bool defaultedDestructorIsConstexpr() const {
1296 return data().DefaultedDestructorIsConstexpr &&
1297 getLangOpts().CPlusPlus20;
1298 }
1299
1300 /// Determine whether this class has a constexpr destructor.
1301 bool hasConstexprDestructor() const;
1302
1303 /// Determine whether this class has a trivial destructor
1304 /// (C++ [class.dtor]p3)
1305 bool hasTrivialDestructor() const {
1306 return data().HasTrivialSpecialMembers & SMF_Destructor;
1307 }
1308
1309 bool hasTrivialDestructorForCall() const {
1310 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1311 }
1312
1313 /// Determine whether this class has a non-trivial destructor
1314 /// (C++ [class.dtor]p3)
1315 bool hasNonTrivialDestructor() const {
1316 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1317 }
1318
1319 bool hasNonTrivialDestructorForCall() const {
1320 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1321 }
1322
1323 void setHasTrivialSpecialMemberForCall() {
1324 data().HasTrivialSpecialMembersForCall =
1325 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1326 }
1327
1328 /// Determine whether declaring a const variable with this type is ok
1329 /// per core issue 253.
1330 bool allowConstDefaultInit() const {
1331 return !data().HasUninitializedFields ||
1332 !(data().HasDefaultedDefaultConstructor ||
1333 needsImplicitDefaultConstructor());
1334 }
1335
1336 /// Determine whether this class has a destructor which has no
1337 /// semantic effect.
1338 ///
1339 /// Any such destructor will be trivial, public, defaulted and not deleted,
1340 /// and will call only irrelevant destructors.
1341 bool hasIrrelevantDestructor() const {
1342 return data().HasIrrelevantDestructor;
1343 }
1344
1345 /// Determine whether this class has a non-literal or/ volatile type
1346 /// non-static data member or base class.
1347 bool hasNonLiteralTypeFieldsOrBases() const {
1348 return data().HasNonLiteralTypeFieldsOrBases;
1349 }
1350
1351 /// Determine whether this class has a using-declaration that names
1352 /// a user-declared base class constructor.
1353 bool hasInheritedConstructor() const {
1354 return data().HasInheritedConstructor;
1355 }
1356
1357 /// Determine whether this class has a using-declaration that names
1358 /// a base class assignment operator.
1359 bool hasInheritedAssignment() const {
1360 return data().HasInheritedAssignment;
1361 }
1362
1363 /// Determine whether this class is considered trivially copyable per
1364 /// (C++11 [class]p6).
1365 bool isTriviallyCopyable() const;
1366
1367 /// Determine whether this class is considered trivial.
1368 ///
1369 /// C++11 [class]p6:
1370 /// "A trivial class is a class that has a trivial default constructor and
1371 /// is trivially copyable."
1372 bool isTrivial() const {
1373 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1374 }
1375
1376 /// Determine whether this class is a literal type.
1377 ///
1378 /// C++11 [basic.types]p10:
1379 /// A class type that has all the following properties:
1380 /// - it has a trivial destructor
1381 /// - every constructor call and full-expression in the
1382 /// brace-or-equal-intializers for non-static data members (if any) is
1383 /// a constant expression.
1384 /// - it is an aggregate type or has at least one constexpr constructor
1385 /// or constructor template that is not a copy or move constructor, and
1386 /// - all of its non-static data members and base classes are of literal
1387 /// types
1388 ///
1389 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1390 /// treating types with trivial default constructors as literal types.
1391 ///
1392 /// Only in C++17 and beyond, are lambdas literal types.
1393 bool isLiteral() const {
1394 const LangOptions &LangOpts = getLangOpts();
1395 return (LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1396 : hasTrivialDestructor()) &&
1397 (!isLambda() || LangOpts.CPlusPlus17) &&
1398 !hasNonLiteralTypeFieldsOrBases() &&
1399 (isAggregate() || isLambda() ||
1400 hasConstexprNonCopyMoveConstructor() ||
1401 hasTrivialDefaultConstructor());
1402 }
1403
1404 /// Determine whether this is a structural type.
1405 bool isStructural() const {
1406 return isLiteral() && data().StructuralIfLiteral;
1407 }
1408
1409 /// If this record is an instantiation of a member class,
1410 /// retrieves the member class from which it was instantiated.
1411 ///
1412 /// This routine will return non-null for (non-templated) member
1413 /// classes of class templates. For example, given:
1414 ///
1415 /// \code
1416 /// template<typename T>
1417 /// struct X {
1418 /// struct A { };
1419 /// };
1420 /// \endcode
1421 ///
1422 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1423 /// whose parent is the class template specialization X<int>. For
1424 /// this declaration, getInstantiatedFromMemberClass() will return
1425 /// the CXXRecordDecl X<T>::A. When a complete definition of
1426 /// X<int>::A is required, it will be instantiated from the
1427 /// declaration returned by getInstantiatedFromMemberClass().
1428 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1429
1430 /// If this class is an instantiation of a member class of a
1431 /// class template specialization, retrieves the member specialization
1432 /// information.
1433 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1434
1435 /// Specify that this record is an instantiation of the
1436 /// member class \p RD.
1437 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1438 TemplateSpecializationKind TSK);
1439
1440 /// Retrieves the class template that is described by this
1441 /// class declaration.
1442 ///
1443 /// Every class template is represented as a ClassTemplateDecl and a
1444 /// CXXRecordDecl. The former contains template properties (such as
1445 /// the template parameter lists) while the latter contains the
1446 /// actual description of the template's
1447 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1448 /// CXXRecordDecl that from a ClassTemplateDecl, while
1449 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1450 /// a CXXRecordDecl.
1451 ClassTemplateDecl *getDescribedClassTemplate() const;
1452
1453 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1454
1455 /// Determine whether this particular class is a specialization or
1456 /// instantiation of a class template or member class of a class template,
1457 /// and how it was instantiated or specialized.
1458 TemplateSpecializationKind getTemplateSpecializationKind() const;
1459
1460 /// Set the kind of specialization or template instantiation this is.
1461 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1462
1463 /// Retrieve the record declaration from which this record could be
1464 /// instantiated. Returns null if this class is not a template instantiation.
1465 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1466
1467 CXXRecordDecl *getTemplateInstantiationPattern() {
1468 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1469 ->getTemplateInstantiationPattern());
1470 }
1471
1472 /// Returns the destructor decl for this class.
1473 CXXDestructorDecl *getDestructor() const;
1474
1475 /// Returns true if the class destructor, or any implicitly invoked
1476 /// destructors are marked noreturn.
1477 bool isAnyDestructorNoReturn() const;
1478
1479 /// If the class is a local class [class.local], returns
1480 /// the enclosing function declaration.
1481 const FunctionDecl *isLocalClass() const {
1482 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1483 return RD->isLocalClass();
1484
1485 return dyn_cast<FunctionDecl>(getDeclContext());
1486 }
1487
1488 FunctionDecl *isLocalClass() {
1489 return const_cast<FunctionDecl*>(
1490 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1491 }
1492
1493 /// Determine whether this dependent class is a current instantiation,
1494 /// when viewed from within the given context.
1495 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1496
1497 /// Determine whether this class is derived from the class \p Base.
1498 ///
1499 /// This routine only determines whether this class is derived from \p Base,
1500 /// but does not account for factors that may make a Derived -> Base class
1501 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1502 /// base class subobjects.
1503 ///
1504 /// \param Base the base class we are searching for.
1505 ///
1506 /// \returns true if this class is derived from Base, false otherwise.
1507 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1508
1509 /// Determine whether this class is derived from the type \p Base.
1510 ///
1511 /// This routine only determines whether this class is derived from \p Base,
1512 /// but does not account for factors that may make a Derived -> Base class
1513 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1514 /// base class subobjects.
1515 ///
1516 /// \param Base the base class we are searching for.
1517 ///
1518 /// \param Paths will contain the paths taken from the current class to the
1519 /// given \p Base class.
1520 ///
1521 /// \returns true if this class is derived from \p Base, false otherwise.
1522 ///
1523 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1524 /// tangling input and output in \p Paths
1525 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1526
1527 /// Determine whether this class is virtually derived from
1528 /// the class \p Base.
1529 ///
1530 /// This routine only determines whether this class is virtually
1531 /// derived from \p Base, but does not account for factors that may
1532 /// make a Derived -> Base class ill-formed, such as
1533 /// private/protected inheritance or multiple, ambiguous base class
1534 /// subobjects.
1535 ///
1536 /// \param Base the base class we are searching for.
1537 ///
1538 /// \returns true if this class is virtually derived from Base,
1539 /// false otherwise.
1540 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1541
1542 /// Determine whether this class is provably not derived from
1543 /// the type \p Base.
1544 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1545
1546 /// Function type used by forallBases() as a callback.
1547 ///
1548 /// \param BaseDefinition the definition of the base class
1549 ///
1550 /// \returns true if this base matched the search criteria
1551 using ForallBasesCallback =
1552 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1553
1554 /// Determines if the given callback holds for all the direct
1555 /// or indirect base classes of this type.
1556 ///
1557 /// The class itself does not count as a base class. This routine
1558 /// returns false if the class has non-computable base classes.
1559 ///
1560 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1561 /// class of this type until a call returns false.
1562 bool forallBases(ForallBasesCallback BaseMatches) const;
1563
1564 /// Function type used by lookupInBases() to determine whether a
1565 /// specific base class subobject matches the lookup criteria.
1566 ///
1567 /// \param Specifier the base-class specifier that describes the inheritance
1568 /// from the base class we are trying to match.
1569 ///
1570 /// \param Path the current path, from the most-derived class down to the
1571 /// base named by the \p Specifier.
1572 ///
1573 /// \returns true if this base matched the search criteria, false otherwise.
1574 using BaseMatchesCallback =
1575 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1576 CXXBasePath &Path)>;
1577
1578 /// Look for entities within the base classes of this C++ class,
1579 /// transitively searching all base class subobjects.
1580 ///
1581 /// This routine uses the callback function \p BaseMatches to find base
1582 /// classes meeting some search criteria, walking all base class subobjects
1583 /// and populating the given \p Paths structure with the paths through the
1584 /// inheritance hierarchy that resulted in a match. On a successful search,
1585 /// the \p Paths structure can be queried to retrieve the matching paths and
1586 /// to determine if there were any ambiguities.
1587 ///
1588 /// \param BaseMatches callback function used to determine whether a given
1589 /// base matches the user-defined search criteria.
1590 ///
1591 /// \param Paths used to record the paths from this class to its base class
1592 /// subobjects that match the search criteria.
1593 ///
1594 /// \param LookupInDependent can be set to true to extend the search to
1595 /// dependent base classes.
1596 ///
1597 /// \returns true if there exists any path from this class to a base class
1598 /// subobject that matches the search criteria.
1599 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1600 bool LookupInDependent = false) const;
1601
1602 /// Base-class lookup callback that determines whether the given
1603 /// base class specifier refers to a specific class declaration.
1604 ///
1605 /// This callback can be used with \c lookupInBases() to determine whether
1606 /// a given derived class has is a base class subobject of a particular type.
1607 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1608 /// base class that we are searching for.
1609 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1610 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1611
1612 /// Base-class lookup callback that determines whether the
1613 /// given base class specifier refers to a specific class
1614 /// declaration and describes virtual derivation.
1615 ///
1616 /// This callback can be used with \c lookupInBases() to determine
1617 /// whether a given derived class has is a virtual base class
1618 /// subobject of a particular type. The base record pointer should
1619 /// refer to the canonical CXXRecordDecl of the base class that we
1620 /// are searching for.
1621 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1622 CXXBasePath &Path,
1623 const CXXRecordDecl *BaseRecord);
1624
1625 /// Retrieve the final overriders for each virtual member
1626 /// function in the class hierarchy where this class is the
1627 /// most-derived class in the class hierarchy.
1628 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1629
1630 /// Get the indirect primary bases for this class.
1631 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1632
1633 /// Determine whether this class has a member with the given name, possibly
1634 /// in a non-dependent base class.
1635 ///
1636 /// No check for ambiguity is performed, so this should never be used when
1637 /// implementing language semantics, but it may be appropriate for warnings,
1638 /// static analysis, or similar.
1639 bool hasMemberName(DeclarationName N) const;
1640
1641 /// Performs an imprecise lookup of a dependent name in this class.
1642 ///
1643 /// This function does not follow strict semantic rules and should be used
1644 /// only when lookup rules can be relaxed, e.g. indexing.
1645 std::vector<const NamedDecl *>
1646 lookupDependentName(DeclarationName Name,
1647 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1648
1649 /// Renders and displays an inheritance diagram
1650 /// for this C++ class and all of its base classes (transitively) using
1651 /// GraphViz.
1652 void viewInheritance(ASTContext& Context) const;
1653
1654 /// Calculates the access of a decl that is reached
1655 /// along a path.
1656 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1657 AccessSpecifier DeclAccess) {
1658 assert(DeclAccess != AS_none)((DeclAccess != AS_none) ? static_cast<void> (0) : __assert_fail
("DeclAccess != AS_none", "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 1658, __PRETTY_FUNCTION__))
;
1659 if (DeclAccess == AS_private) return AS_none;
1660 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1661 }
1662
1663 /// Indicates that the declaration of a defaulted or deleted special
1664 /// member function is now complete.
1665 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1666
1667 void setTrivialForCallFlags(CXXMethodDecl *MD);
1668
1669 /// Indicates that the definition of this class is now complete.
1670 void completeDefinition() override;
1671
1672 /// Indicates that the definition of this class is now complete,
1673 /// and provides a final overrider map to help determine
1674 ///
1675 /// \param FinalOverriders The final overrider map for this class, which can
1676 /// be provided as an optimization for abstract-class checking. If NULL,
1677 /// final overriders will be computed if they are needed to complete the
1678 /// definition.
1679 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1680
1681 /// Determine whether this class may end up being abstract, even though
1682 /// it is not yet known to be abstract.
1683 ///
1684 /// \returns true if this class is not known to be abstract but has any
1685 /// base classes that are abstract. In this case, \c completeDefinition()
1686 /// will need to compute final overriders to determine whether the class is
1687 /// actually abstract.
1688 bool mayBeAbstract() const;
1689
1690 /// Determine whether it's impossible for a class to be derived from this
1691 /// class. This is best-effort, and may conservatively return false.
1692 bool isEffectivelyFinal() const;
1693
1694 /// If this is the closure type of a lambda expression, retrieve the
1695 /// number to be used for name mangling in the Itanium C++ ABI.
1696 ///
1697 /// Zero indicates that this closure type has internal linkage, so the
1698 /// mangling number does not matter, while a non-zero value indicates which
1699 /// lambda expression this is in this particular context.
1700 unsigned getLambdaManglingNumber() const {
1701 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 1701, __PRETTY_FUNCTION__))
;
1702 return getLambdaData().ManglingNumber;
1703 }
1704
1705 /// The lambda is known to has internal linkage no matter whether it has name
1706 /// mangling number.
1707 bool hasKnownLambdaInternalLinkage() const {
1708 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 1708, __PRETTY_FUNCTION__))
;
1709 return getLambdaData().HasKnownInternalLinkage;
1710 }
1711
1712 /// Retrieve the declaration that provides additional context for a
1713 /// lambda, when the normal declaration context is not specific enough.
1714 ///
1715 /// Certain contexts (default arguments of in-class function parameters and
1716 /// the initializers of data members) have separate name mangling rules for
1717 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1718 /// the declaration in which the lambda occurs, e.g., the function parameter
1719 /// or the non-static data member. Otherwise, it returns NULL to imply that
1720 /// the declaration context suffices.
1721 Decl *getLambdaContextDecl() const;
1722
1723 /// Set the mangling number and context declaration for a lambda
1724 /// class.
1725 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1726 bool HasKnownInternalLinkage = false) {
1727 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 1727, __PRETTY_FUNCTION__))
;
1728 getLambdaData().ManglingNumber = ManglingNumber;
1729 getLambdaData().ContextDecl = ContextDecl;
1730 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1731 }
1732
1733 /// Returns the inheritance model used for this record.
1734 MSInheritanceModel getMSInheritanceModel() const;
1735
1736 /// Calculate what the inheritance model would be for this class.
1737 MSInheritanceModel calculateInheritanceModel() const;
1738
1739 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1740 /// member pointer if we can guarantee that zero is not a valid field offset,
1741 /// or if the member pointer has multiple fields. Polymorphic classes have a
1742 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1743 /// fields, we can use zero even if it is a valid field offset because
1744 /// null-ness testing will check the other fields.
1745 bool nullFieldOffsetIsZero() const;
1746
1747 /// Controls when vtordisps will be emitted if this record is used as a
1748 /// virtual base.
1749 MSVtorDispMode getMSVtorDispMode() const;
1750
1751 /// Determine whether this lambda expression was known to be dependent
1752 /// at the time it was created, even if its context does not appear to be
1753 /// dependent.
1754 ///
1755 /// This flag is a workaround for an issue with parsing, where default
1756 /// arguments are parsed before their enclosing function declarations have
1757 /// been created. This means that any lambda expressions within those
1758 /// default arguments will have as their DeclContext the context enclosing
1759 /// the function declaration, which may be non-dependent even when the
1760 /// function declaration itself is dependent. This flag indicates when we
1761 /// know that the lambda is dependent despite that.
1762 bool isDependentLambda() const {
1763 return isLambda() && getLambdaData().Dependent;
1764 }
1765
1766 TypeSourceInfo *getLambdaTypeInfo() const {
1767 return getLambdaData().MethodTyInfo;
1768 }
1769
1770 // Determine whether this type is an Interface Like type for
1771 // __interface inheritance purposes.
1772 bool isInterfaceLike() const;
1773
1774 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1775 static bool classofKind(Kind K) {
1776 return K >= firstCXXRecord && K <= lastCXXRecord;
1777 }
1778};
1779
1780/// Store information needed for an explicit specifier.
1781/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1782class ExplicitSpecifier {
1783 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1784 nullptr, ExplicitSpecKind::ResolvedFalse};
1785
1786public:
1787 ExplicitSpecifier() = default;
1788 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1789 : ExplicitSpec(Expression, Kind) {}
1790 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1791 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1792 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1793
1794 /// Determine if the declaration had an explicit specifier of any kind.
1795 bool isSpecified() const {
1796 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1797 ExplicitSpec.getPointer();
1798 }
1799
1800 /// Check for equivalence of explicit specifiers.
1801 /// \return true if the explicit specifier are equivalent, false otherwise.
1802 bool isEquivalent(const ExplicitSpecifier Other) const;
1803 /// Determine whether this specifier is known to correspond to an explicit
1804 /// declaration. Returns false if the specifier is absent or has an
1805 /// expression that is value-dependent or evaluates to false.
1806 bool isExplicit() const {
1807 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1808 }
1809 /// Determine if the explicit specifier is invalid.
1810 /// This state occurs after a substitution failures.
1811 bool isInvalid() const {
1812 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1813 !ExplicitSpec.getPointer();
1814 }
1815 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1816 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1817 // Retrieve the explicit specifier in the given declaration, if any.
1818 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1819 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1820 return getFromDecl(const_cast<FunctionDecl *>(Function));
1821 }
1822 static ExplicitSpecifier Invalid() {
1823 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1824 }
1825};
1826
1827/// Represents a C++ deduction guide declaration.
1828///
1829/// \code
1830/// template<typename T> struct A { A(); A(T); };
1831/// A() -> A<int>;
1832/// \endcode
1833///
1834/// In this example, there will be an explicit deduction guide from the
1835/// second line, and implicit deduction guide templates synthesized from
1836/// the constructors of \c A.
1837class CXXDeductionGuideDecl : public FunctionDecl {
1838 void anchor() override;
1839
1840private:
1841 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1842 ExplicitSpecifier ES,
1843 const DeclarationNameInfo &NameInfo, QualType T,
1844 TypeSourceInfo *TInfo, SourceLocation EndLocation)
1845 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1846 SC_None, false, ConstexprSpecKind::Unspecified),
1847 ExplicitSpec(ES) {
1848 if (EndLocation.isValid())
1849 setRangeEnd(EndLocation);
1850 setIsCopyDeductionCandidate(false);
1851 }
1852
1853 ExplicitSpecifier ExplicitSpec;
1854 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1855
1856public:
1857 friend class ASTDeclReader;
1858 friend class ASTDeclWriter;
1859
1860 static CXXDeductionGuideDecl *
1861 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1862 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1863 TypeSourceInfo *TInfo, SourceLocation EndLocation);
1864
1865 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1866
1867 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1868 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1869
1870 /// Return true if the declartion is already resolved to be explicit.
1871 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1872
1873 /// Get the template for which this guide performs deduction.
1874 TemplateDecl *getDeducedTemplate() const {
1875 return getDeclName().getCXXDeductionGuideTemplate();
1876 }
1877
1878 void setIsCopyDeductionCandidate(bool isCDC = true) {
1879 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1880 }
1881
1882 bool isCopyDeductionCandidate() const {
1883 return FunctionDeclBits.IsCopyDeductionCandidate;
1884 }
1885
1886 // Implement isa/cast/dyncast/etc.
1887 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1888 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1889};
1890
1891/// \brief Represents the body of a requires-expression.
1892///
1893/// This decl exists merely to serve as the DeclContext for the local
1894/// parameters of the requires expression as well as other declarations inside
1895/// it.
1896///
1897/// \code
1898/// template<typename T> requires requires (T t) { {t++} -> regular; }
1899/// \endcode
1900///
1901/// In this example, a RequiresExpr object will be generated for the expression,
1902/// and a RequiresExprBodyDecl will be created to hold the parameter t and the
1903/// template argument list imposed by the compound requirement.
1904class RequiresExprBodyDecl : public Decl, public DeclContext {
1905 RequiresExprBodyDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
1906 : Decl(RequiresExprBody, DC, StartLoc), DeclContext(RequiresExprBody) {}
1907
1908public:
1909 friend class ASTDeclReader;
1910 friend class ASTDeclWriter;
1911
1912 static RequiresExprBodyDecl *Create(ASTContext &C, DeclContext *DC,
1913 SourceLocation StartLoc);
1914
1915 static RequiresExprBodyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1916
1917 // Implement isa/cast/dyncast/etc.
1918 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1919 static bool classofKind(Kind K) { return K == RequiresExprBody; }
1920};
1921
1922/// Represents a static or instance method of a struct/union/class.
1923///
1924/// In the terminology of the C++ Standard, these are the (static and
1925/// non-static) member functions, whether virtual or not.
1926class CXXMethodDecl : public FunctionDecl {
1927 void anchor() override;
1928
1929protected:
1930 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1931 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1932 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1933 bool isInline, ConstexprSpecKind ConstexprKind,
1934 SourceLocation EndLocation,
1935 Expr *TrailingRequiresClause = nullptr)
1936 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
1937 ConstexprKind, TrailingRequiresClause) {
1938 if (EndLocation.isValid())
1939 setRangeEnd(EndLocation);
1940 }
1941
1942public:
1943 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
1944 SourceLocation StartLoc,
1945 const DeclarationNameInfo &NameInfo, QualType T,
1946 TypeSourceInfo *TInfo, StorageClass SC,
1947 bool isInline, ConstexprSpecKind ConstexprKind,
1948 SourceLocation EndLocation,
1949 Expr *TrailingRequiresClause = nullptr);
1950
1951 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1952
1953 bool isStatic() const;
1954 bool isInstance() const { return !isStatic(); }
1955
1956 /// Returns true if the given operator is implicitly static in a record
1957 /// context.
1958 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
1959 // [class.free]p1:
1960 // Any allocation function for a class T is a static member
1961 // (even if not explicitly declared static).
1962 // [class.free]p6 Any deallocation function for a class X is a static member
1963 // (even if not explicitly declared static).
1964 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
1965 OOK == OO_Array_Delete;
1966 }
1967
1968 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
1969 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
1970
1971 bool isVirtual() const {
1972 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1973
1974 // Member function is virtual if it is marked explicitly so, or if it is
1975 // declared in __interface -- then it is automatically pure virtual.
1976 if (CD->isVirtualAsWritten() || CD->isPure())
1977 return true;
1978
1979 return CD->size_overridden_methods() != 0;
1980 }
1981
1982 /// If it's possible to devirtualize a call to this method, return the called
1983 /// function. Otherwise, return null.
1984
1985 /// \param Base The object on which this virtual function is called.
1986 /// \param IsAppleKext True if we are compiling for Apple kext.
1987 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
1988
1989 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
1990 bool IsAppleKext) const {
1991 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
1992 Base, IsAppleKext);
1993 }
1994
1995 /// Determine whether this is a usual deallocation function (C++
1996 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
1997 /// delete[] operator with a particular signature. Populates \p PreventedBy
1998 /// with the declarations of the functions of the same kind if they were the
1999 /// reason for this function returning false. This is used by
2000 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2001 /// context.
2002 bool isUsualDeallocationFunction(
2003 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2004
2005 /// Determine whether this is a copy-assignment operator, regardless
2006 /// of whether it was declared implicitly or explicitly.
2007 bool isCopyAssignmentOperator() const;
2008
2009 /// Determine whether this is a move assignment operator.
2010 bool isMoveAssignmentOperator() const;
2011
2012 CXXMethodDecl *getCanonicalDecl() override {
2013 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2014 }
2015 const CXXMethodDecl *getCanonicalDecl() const {
2016 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2017 }
2018
2019 CXXMethodDecl *getMostRecentDecl() {
2020 return cast<CXXMethodDecl>(
2021 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2022 }
2023 const CXXMethodDecl *getMostRecentDecl() const {
2024 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2025 }
2026
2027 void addOverriddenMethod(const CXXMethodDecl *MD);
2028
2029 using method_iterator = const CXXMethodDecl *const *;
2030
2031 method_iterator begin_overridden_methods() const;
2032 method_iterator end_overridden_methods() const;
2033 unsigned size_overridden_methods() const;
2034
2035 using overridden_method_range = llvm::iterator_range<
2036 llvm::TinyPtrVector<const CXXMethodDecl *>::const_iterator>;
2037
2038 overridden_method_range overridden_methods() const;
2039
2040 /// Return the parent of this method declaration, which
2041 /// is the class in which this method is defined.
2042 const CXXRecordDecl *getParent() const {
2043 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2044 }
2045
2046 /// Return the parent of this method declaration, which
2047 /// is the class in which this method is defined.
2048 CXXRecordDecl *getParent() {
2049 return const_cast<CXXRecordDecl *>(
2050 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2051 }
2052
2053 /// Return the type of the \c this pointer.
2054 ///
2055 /// Should only be called for instance (i.e., non-static) methods. Note
2056 /// that for the call operator of a lambda closure type, this returns the
2057 /// desugared 'this' type (a pointer to the closure type), not the captured
2058 /// 'this' type.
2059 QualType getThisType() const;
2060
2061 /// Return the type of the object pointed by \c this.
2062 ///
2063 /// See getThisType() for usage restriction.
2064 QualType getThisObjectType() const;
2065
2066 static QualType getThisType(const FunctionProtoType *FPT,
2067 const CXXRecordDecl *Decl);
2068
2069 static QualType getThisObjectType(const FunctionProtoType *FPT,
2070 const CXXRecordDecl *Decl);
2071
2072 Qualifiers getMethodQualifiers() const {
2073 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2074 }
2075
2076 /// Retrieve the ref-qualifier associated with this method.
2077 ///
2078 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2079 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2080 /// @code
2081 /// struct X {
2082 /// void f() &;
2083 /// void g() &&;
2084 /// void h();
2085 /// };
2086 /// @endcode
2087 RefQualifierKind getRefQualifier() const {
2088 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2089 }
2090
2091 bool hasInlineBody() const;
2092
2093 /// Determine whether this is a lambda closure type's static member
2094 /// function that is used for the result of the lambda's conversion to
2095 /// function pointer (for a lambda with no captures).
2096 ///
2097 /// The function itself, if used, will have a placeholder body that will be
2098 /// supplied by IR generation to either forward to the function call operator
2099 /// or clone the function call operator.
2100 bool isLambdaStaticInvoker() const;
2101
2102 /// Find the method in \p RD that corresponds to this one.
2103 ///
2104 /// Find if \p RD or one of the classes it inherits from override this method.
2105 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2106 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2107 CXXMethodDecl *
2108 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2109 bool MayBeBase = false);
2110
2111 const CXXMethodDecl *
2112 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2113 bool MayBeBase = false) const {
2114 return const_cast<CXXMethodDecl *>(this)
2115 ->getCorrespondingMethodInClass(RD, MayBeBase);
2116 }
2117
2118 /// Find if \p RD declares a function that overrides this function, and if so,
2119 /// return it. Does not search base classes.
2120 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2121 bool MayBeBase = false);
2122 const CXXMethodDecl *
2123 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2124 bool MayBeBase = false) const {
2125 return const_cast<CXXMethodDecl *>(this)
2126 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2127 }
2128
2129 // Implement isa/cast/dyncast/etc.
2130 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2131 static bool classofKind(Kind K) {
2132 return K >= firstCXXMethod && K <= lastCXXMethod;
2133 }
2134};
2135
2136/// Represents a C++ base or member initializer.
2137///
2138/// This is part of a constructor initializer that
2139/// initializes one non-static member variable or one base class. For
2140/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2141/// initializers:
2142///
2143/// \code
2144/// class A { };
2145/// class B : public A {
2146/// float f;
2147/// public:
2148/// B(A& a) : A(a), f(3.14159) { }
2149/// };
2150/// \endcode
2151class CXXCtorInitializer final {
2152 /// Either the base class name/delegating constructor type (stored as
2153 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2154 /// (IndirectFieldDecl*) being initialized.
2155 llvm::PointerUnion<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2156 Initializee;
2157
2158 /// The source location for the field name or, for a base initializer
2159 /// pack expansion, the location of the ellipsis.
2160 ///
2161 /// In the case of a delegating
2162 /// constructor, it will still include the type's source location as the
2163 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2164 SourceLocation MemberOrEllipsisLocation;
2165
2166 /// The argument used to initialize the base or member, which may
2167 /// end up constructing an object (when multiple arguments are involved).
2168 Stmt *Init;
2169
2170 /// Location of the left paren of the ctor-initializer.
2171 SourceLocation LParenLoc;
2172
2173 /// Location of the right paren of the ctor-initializer.
2174 SourceLocation RParenLoc;
2175
2176 /// If the initializee is a type, whether that type makes this
2177 /// a delegating initialization.
2178 unsigned IsDelegating : 1;
2179
2180 /// If the initializer is a base initializer, this keeps track
2181 /// of whether the base is virtual or not.
2182 unsigned IsVirtual : 1;
2183
2184 /// Whether or not the initializer is explicitly written
2185 /// in the sources.
2186 unsigned IsWritten : 1;
2187
2188 /// If IsWritten is true, then this number keeps track of the textual order
2189 /// of this initializer in the original sources, counting from 0.
2190 unsigned SourceOrder : 13;
2191
2192public:
2193 /// Creates a new base-class initializer.
2194 explicit
2195 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2196 SourceLocation L, Expr *Init, SourceLocation R,
2197 SourceLocation EllipsisLoc);
2198
2199 /// Creates a new member initializer.
2200 explicit
2201 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2202 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2203 SourceLocation R);
2204
2205 /// Creates a new anonymous field initializer.
2206 explicit
2207 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2208 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2209 SourceLocation R);
2210
2211 /// Creates a new delegating initializer.
2212 explicit
2213 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2214 SourceLocation L, Expr *Init, SourceLocation R);
2215
2216 /// \return Unique reproducible object identifier.
2217 int64_t getID(const ASTContext &Context) const;
2218
2219 /// Determine whether this initializer is initializing a base class.
2220 bool isBaseInitializer() const {
2221 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2222 }
2223
2224 /// Determine whether this initializer is initializing a non-static
2225 /// data member.
2226 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2227
2228 bool isAnyMemberInitializer() const {
2229 return isMemberInitializer() || isIndirectMemberInitializer();
2230 }
2231
2232 bool isIndirectMemberInitializer() const {
2233 return Initializee.is<IndirectFieldDecl*>();
2234 }
2235
2236 /// Determine whether this initializer is an implicit initializer
2237 /// generated for a field with an initializer defined on the member
2238 /// declaration.
2239 ///
2240 /// In-class member initializers (also known as "non-static data member
2241 /// initializations", NSDMIs) were introduced in C++11.
2242 bool isInClassMemberInitializer() const {
2243 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2244 }
2245
2246 /// Determine whether this initializer is creating a delegating
2247 /// constructor.
2248 bool isDelegatingInitializer() const {
2249 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2250 }
2251
2252 /// Determine whether this initializer is a pack expansion.
2253 bool isPackExpansion() const {
2254 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2255 }
2256
2257 // For a pack expansion, returns the location of the ellipsis.
2258 SourceLocation getEllipsisLoc() const {
2259 assert(isPackExpansion() && "Initializer is not a pack expansion")((isPackExpansion() && "Initializer is not a pack expansion"
) ? static_cast<void> (0) : __assert_fail ("isPackExpansion() && \"Initializer is not a pack expansion\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2259, __PRETTY_FUNCTION__))
;
2260 return MemberOrEllipsisLocation;
2261 }
2262
2263 /// If this is a base class initializer, returns the type of the
2264 /// base class with location information. Otherwise, returns an NULL
2265 /// type location.
2266 TypeLoc getBaseClassLoc() const;
2267
2268 /// If this is a base class initializer, returns the type of the base class.
2269 /// Otherwise, returns null.
2270 const Type *getBaseClass() const;
2271
2272 /// Returns whether the base is virtual or not.
2273 bool isBaseVirtual() const {
2274 assert(isBaseInitializer() && "Must call this on base initializer!")((isBaseInitializer() && "Must call this on base initializer!"
) ? static_cast<void> (0) : __assert_fail ("isBaseInitializer() && \"Must call this on base initializer!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2274, __PRETTY_FUNCTION__))
;
2275
2276 return IsVirtual;
2277 }
2278
2279 /// Returns the declarator information for a base class or delegating
2280 /// initializer.
2281 TypeSourceInfo *getTypeSourceInfo() const {
2282 return Initializee.dyn_cast<TypeSourceInfo *>();
2283 }
2284
2285 /// If this is a member initializer, returns the declaration of the
2286 /// non-static data member being initialized. Otherwise, returns null.
2287 FieldDecl *getMember() const {
2288 if (isMemberInitializer())
2289 return Initializee.get<FieldDecl*>();
2290 return nullptr;
2291 }
2292
2293 FieldDecl *getAnyMember() const {
2294 if (isMemberInitializer())
2295 return Initializee.get<FieldDecl*>();
2296 if (isIndirectMemberInitializer())
2297 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2298 return nullptr;
2299 }
2300
2301 IndirectFieldDecl *getIndirectMember() const {
2302 if (isIndirectMemberInitializer())
2303 return Initializee.get<IndirectFieldDecl*>();
2304 return nullptr;
2305 }
2306
2307 SourceLocation getMemberLocation() const {
2308 return MemberOrEllipsisLocation;
2309 }
2310
2311 /// Determine the source location of the initializer.
2312 SourceLocation getSourceLocation() const;
2313
2314 /// Determine the source range covering the entire initializer.
2315 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__));
2316
2317 /// Determine whether this initializer is explicitly written
2318 /// in the source code.
2319 bool isWritten() const { return IsWritten; }
2320
2321 /// Return the source position of the initializer, counting from 0.
2322 /// If the initializer was implicit, -1 is returned.
2323 int getSourceOrder() const {
2324 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2325 }
2326
2327 /// Set the source order of this initializer.
2328 ///
2329 /// This can only be called once for each initializer; it cannot be called
2330 /// on an initializer having a positive number of (implicit) array indices.
2331 ///
2332 /// This assumes that the initializer was written in the source code, and
2333 /// ensures that isWritten() returns true.
2334 void setSourceOrder(int Pos) {
2335 assert(!IsWritten &&((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2336, __PRETTY_FUNCTION__))
2336 "setSourceOrder() used on implicit initializer")((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2336, __PRETTY_FUNCTION__))
;
2337 assert(SourceOrder == 0 &&((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2338, __PRETTY_FUNCTION__))
2338 "calling twice setSourceOrder() on the same initializer")((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2338, __PRETTY_FUNCTION__))
;
2339 assert(Pos >= 0 &&((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2340, __PRETTY_FUNCTION__))
2340 "setSourceOrder() used to make an initializer implicit")((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2340, __PRETTY_FUNCTION__))
;
2341 IsWritten = true;
2342 SourceOrder = static_cast<unsigned>(Pos);
2343 }
2344
2345 SourceLocation getLParenLoc() const { return LParenLoc; }
2346 SourceLocation getRParenLoc() const { return RParenLoc; }
2347
2348 /// Get the initializer.
2349 Expr *getInit() const { return static_cast<Expr *>(Init); }
2350};
2351
2352/// Description of a constructor that was inherited from a base class.
2353class InheritedConstructor {
2354 ConstructorUsingShadowDecl *Shadow = nullptr;
2355 CXXConstructorDecl *BaseCtor = nullptr;
2356
2357public:
2358 InheritedConstructor() = default;
2359 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2360 CXXConstructorDecl *BaseCtor)
2361 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2362
2363 explicit operator bool() const { return Shadow; }
2364
2365 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2366 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2367};
2368
2369/// Represents a C++ constructor within a class.
2370///
2371/// For example:
2372///
2373/// \code
2374/// class X {
2375/// public:
2376/// explicit X(int); // represented by a CXXConstructorDecl.
2377/// };
2378/// \endcode
2379class CXXConstructorDecl final
2380 : public CXXMethodDecl,
2381 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2382 ExplicitSpecifier> {
2383 // This class stores some data in DeclContext::CXXConstructorDeclBits
2384 // to save some space. Use the provided accessors to access it.
2385
2386 /// \name Support for base and member initializers.
2387 /// \{
2388 /// The arguments used to initialize the base or member.
2389 LazyCXXCtorInitializersPtr CtorInitializers;
2390
2391 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2392 const DeclarationNameInfo &NameInfo, QualType T,
2393 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2394 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2395 InheritedConstructor Inherited,
2396 Expr *TrailingRequiresClause);
2397
2398 void anchor() override;
2399
2400 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2401 return CXXConstructorDeclBits.IsInheritingConstructor;
2402 }
2403 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2404 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2405 }
2406
2407 ExplicitSpecifier getExplicitSpecifierInternal() const {
2408 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2409 return *getTrailingObjects<ExplicitSpecifier>();
2410 return ExplicitSpecifier(
2411 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2412 ? ExplicitSpecKind::ResolvedTrue
2413 : ExplicitSpecKind::ResolvedFalse);
2414 }
2415
2416 enum TraillingAllocKind {
2417 TAKInheritsConstructor = 1,
2418 TAKHasTailExplicit = 1 << 1,
2419 };
2420
2421 uint64_t getTraillingAllocKind() const {
2422 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2423 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2424 }
2425
2426public:
2427 friend class ASTDeclReader;
2428 friend class ASTDeclWriter;
2429 friend TrailingObjects;
2430
2431 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2432 uint64_t AllocKind);
2433 static CXXConstructorDecl *
2434 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2435 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2436 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2437 ConstexprSpecKind ConstexprKind,
2438 InheritedConstructor Inherited = InheritedConstructor(),
2439 Expr *TrailingRequiresClause = nullptr);
2440
2441 void setExplicitSpecifier(ExplicitSpecifier ES) {
2442 assert((!ES.getExpr() ||(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2445, __PRETTY_FUNCTION__))
2443 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2445, __PRETTY_FUNCTION__))
2444 "cannot set this explicit specifier. no trail-allocated space for "(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2445, __PRETTY_FUNCTION__))
2445 "explicit")(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2445, __PRETTY_FUNCTION__))
;
2446 if (ES.getExpr())
2447 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2448 else
2449 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2450 }
2451
2452 ExplicitSpecifier getExplicitSpecifier() {
2453 return getCanonicalDecl()->getExplicitSpecifierInternal();
2454 }
2455 const ExplicitSpecifier getExplicitSpecifier() const {
2456 return getCanonicalDecl()->getExplicitSpecifierInternal();
2457 }
2458
2459 /// Return true if the declartion is already resolved to be explicit.
2460 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2461
2462 /// Iterates through the member/base initializer list.
2463 using init_iterator = CXXCtorInitializer **;
2464
2465 /// Iterates through the member/base initializer list.
2466 using init_const_iterator = CXXCtorInitializer *const *;
2467
2468 using init_range = llvm::iterator_range<init_iterator>;
2469 using init_const_range = llvm::iterator_range<init_const_iterator>;
2470
2471 init_range inits() { return init_range(init_begin(), init_end()); }
2472 init_const_range inits() const {
2473 return init_const_range(init_begin(), init_end());
2474 }
2475
2476 /// Retrieve an iterator to the first initializer.
2477 init_iterator init_begin() {
2478 const auto *ConstThis = this;
2479 return const_cast<init_iterator>(ConstThis->init_begin());
2480 }
2481
2482 /// Retrieve an iterator to the first initializer.
2483 init_const_iterator init_begin() const;
2484
2485 /// Retrieve an iterator past the last initializer.
2486 init_iterator init_end() {
2487 return init_begin() + getNumCtorInitializers();
2488 }
2489
2490 /// Retrieve an iterator past the last initializer.
2491 init_const_iterator init_end() const {
2492 return init_begin() + getNumCtorInitializers();
2493 }
2494
2495 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2496 using init_const_reverse_iterator =
2497 std::reverse_iterator<init_const_iterator>;
2498
2499 init_reverse_iterator init_rbegin() {
2500 return init_reverse_iterator(init_end());
2501 }
2502 init_const_reverse_iterator init_rbegin() const {
2503 return init_const_reverse_iterator(init_end());
2504 }
2505
2506 init_reverse_iterator init_rend() {
2507 return init_reverse_iterator(init_begin());
2508 }
2509 init_const_reverse_iterator init_rend() const {
2510 return init_const_reverse_iterator(init_begin());
2511 }
2512
2513 /// Determine the number of arguments used to initialize the member
2514 /// or base.
2515 unsigned getNumCtorInitializers() const {
2516 return CXXConstructorDeclBits.NumCtorInitializers;
2517 }
2518
2519 void setNumCtorInitializers(unsigned numCtorInitializers) {
2520 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2521 // This assert added because NumCtorInitializers is stored
2522 // in CXXConstructorDeclBits as a bitfield and its width has
2523 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2524 assert(CXXConstructorDeclBits.NumCtorInitializers ==((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers
&& "NumCtorInitializers overflow!") ? static_cast<
void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2525, __PRETTY_FUNCTION__))
2525 numCtorInitializers && "NumCtorInitializers overflow!")((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers
&& "NumCtorInitializers overflow!") ? static_cast<
void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2525, __PRETTY_FUNCTION__))
;
2526 }
2527
2528 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2529 CtorInitializers = Initializers;
2530 }
2531
2532 /// Determine whether this constructor is a delegating constructor.
2533 bool isDelegatingConstructor() const {
2534 return (getNumCtorInitializers() == 1) &&
2535 init_begin()[0]->isDelegatingInitializer();
2536 }
2537
2538 /// When this constructor delegates to another, retrieve the target.
2539 CXXConstructorDecl *getTargetConstructor() const;
2540
2541 /// Whether this constructor is a default
2542 /// constructor (C++ [class.ctor]p5), which can be used to
2543 /// default-initialize a class of this type.
2544 bool isDefaultConstructor() const;
2545
2546 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2547 /// which can be used to copy the class.
2548 ///
2549 /// \p TypeQuals will be set to the qualifiers on the
2550 /// argument type. For example, \p TypeQuals would be set to \c
2551 /// Qualifiers::Const for the following copy constructor:
2552 ///
2553 /// \code
2554 /// class X {
2555 /// public:
2556 /// X(const X&);
2557 /// };
2558 /// \endcode
2559 bool isCopyConstructor(unsigned &TypeQuals) const;
2560
2561 /// Whether this constructor is a copy
2562 /// constructor (C++ [class.copy]p2, which can be used to copy the
2563 /// class.
2564 bool isCopyConstructor() const {
2565 unsigned TypeQuals = 0;
2566 return isCopyConstructor(TypeQuals);
2567 }
2568
2569 /// Determine whether this constructor is a move constructor
2570 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2571 ///
2572 /// \param TypeQuals If this constructor is a move constructor, will be set
2573 /// to the type qualifiers on the referent of the first parameter's type.
2574 bool isMoveConstructor(unsigned &TypeQuals) const;
2575
2576 /// Determine whether this constructor is a move constructor
2577 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2578 bool isMoveConstructor() const {
2579 unsigned TypeQuals = 0;
2580 return isMoveConstructor(TypeQuals);
2581 }
2582
2583 /// Determine whether this is a copy or move constructor.
2584 ///
2585 /// \param TypeQuals Will be set to the type qualifiers on the reference
2586 /// parameter, if in fact this is a copy or move constructor.
2587 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2588
2589 /// Determine whether this a copy or move constructor.
2590 bool isCopyOrMoveConstructor() const {
2591 unsigned Quals;
2592 return isCopyOrMoveConstructor(Quals);
2593 }
2594
2595 /// Whether this constructor is a
2596 /// converting constructor (C++ [class.conv.ctor]), which can be
2597 /// used for user-defined conversions.
2598 bool isConvertingConstructor(bool AllowExplicit) const;
2599
2600 /// Determine whether this is a member template specialization that
2601 /// would copy the object to itself. Such constructors are never used to copy
2602 /// an object.
2603 bool isSpecializationCopyingObject() const;
2604
2605 /// Determine whether this is an implicit constructor synthesized to
2606 /// model a call to a constructor inherited from a base class.
2607 bool isInheritingConstructor() const {
2608 return CXXConstructorDeclBits.IsInheritingConstructor;
2609 }
2610
2611 /// State that this is an implicit constructor synthesized to
2612 /// model a call to a constructor inherited from a base class.
2613 void setInheritingConstructor(bool isIC = true) {
2614 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2615 }
2616
2617 /// Get the constructor that this inheriting constructor is based on.
2618 InheritedConstructor getInheritedConstructor() const {
2619 return isInheritingConstructor() ?
2620 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2621 }
2622
2623 CXXConstructorDecl *getCanonicalDecl() override {
2624 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2625 }
2626 const CXXConstructorDecl *getCanonicalDecl() const {
2627 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2628 }
2629
2630 // Implement isa/cast/dyncast/etc.
2631 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2632 static bool classofKind(Kind K) { return K == CXXConstructor; }
2633};
2634
2635/// Represents a C++ destructor within a class.
2636///
2637/// For example:
2638///
2639/// \code
2640/// class X {
2641/// public:
2642/// ~X(); // represented by a CXXDestructorDecl.
2643/// };
2644/// \endcode
2645class CXXDestructorDecl : public CXXMethodDecl {
2646 friend class ASTDeclReader;
2647 friend class ASTDeclWriter;
2648
2649 // FIXME: Don't allocate storage for these except in the first declaration
2650 // of a virtual destructor.
2651 FunctionDecl *OperatorDelete = nullptr;
2652 Expr *OperatorDeleteThisArg = nullptr;
2653
2654 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2655 const DeclarationNameInfo &NameInfo, QualType T,
2656 TypeSourceInfo *TInfo, bool isInline,
2657 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2658 Expr *TrailingRequiresClause = nullptr)
2659 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2660 SC_None, isInline, ConstexprKind, SourceLocation(),
2661 TrailingRequiresClause) {
2662 setImplicit(isImplicitlyDeclared);
2663 }
2664
2665 void anchor() override;
2666
2667public:
2668 static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2669 SourceLocation StartLoc,
2670 const DeclarationNameInfo &NameInfo,
2671 QualType T, TypeSourceInfo *TInfo,
2672 bool isInline, bool isImplicitlyDeclared,
2673 ConstexprSpecKind ConstexprKind,
2674 Expr *TrailingRequiresClause = nullptr);
2675 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2676
2677 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2678
2679 const FunctionDecl *getOperatorDelete() const {
2680 return getCanonicalDecl()->OperatorDelete;
2681 }
2682
2683 Expr *getOperatorDeleteThisArg() const {
2684 return getCanonicalDecl()->OperatorDeleteThisArg;
2685 }
2686
2687 CXXDestructorDecl *getCanonicalDecl() override {
2688 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2689 }
2690 const CXXDestructorDecl *getCanonicalDecl() const {
2691 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2692 }
2693
2694 // Implement isa/cast/dyncast/etc.
2695 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2696 static bool classofKind(Kind K) { return K == CXXDestructor; }
2697};
2698
2699/// Represents a C++ conversion function within a class.
2700///
2701/// For example:
2702///
2703/// \code
2704/// class X {
2705/// public:
2706/// operator bool();
2707/// };
2708/// \endcode
2709class CXXConversionDecl : public CXXMethodDecl {
2710 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2711 const DeclarationNameInfo &NameInfo, QualType T,
2712 TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES,
2713 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2714 Expr *TrailingRequiresClause = nullptr)
2715 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2716 SC_None, isInline, ConstexprKind, EndLocation,
2717 TrailingRequiresClause),
2718 ExplicitSpec(ES) {}
2719 void anchor() override;
2720
2721 ExplicitSpecifier ExplicitSpec;
2722
2723public:
2724 friend class ASTDeclReader;
2725 friend class ASTDeclWriter;
2726
2727 static CXXConversionDecl *
2728 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2729 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2730 bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2731 SourceLocation EndLocation, Expr *TrailingRequiresClause = nullptr);
2732 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2733
2734 ExplicitSpecifier getExplicitSpecifier() {
2735 return getCanonicalDecl()->ExplicitSpec;
2736 }
2737
2738 const ExplicitSpecifier getExplicitSpecifier() const {
2739 return getCanonicalDecl()->ExplicitSpec;
2740 }
2741
2742 /// Return true if the declartion is already resolved to be explicit.
2743 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2744 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2745
2746 /// Returns the type that this conversion function is converting to.
2747 QualType getConversionType() const {
2748 return getType()->castAs<FunctionType>()->getReturnType();
2749 }
2750
2751 /// Determine whether this conversion function is a conversion from
2752 /// a lambda closure type to a block pointer.
2753 bool isLambdaToBlockPointerConversion() const;
2754
2755 CXXConversionDecl *getCanonicalDecl() override {
2756 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2757 }
2758 const CXXConversionDecl *getCanonicalDecl() const {
2759 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2760 }
2761
2762 // Implement isa/cast/dyncast/etc.
2763 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2764 static bool classofKind(Kind K) { return K == CXXConversion; }
2765};
2766
2767/// Represents a linkage specification.
2768///
2769/// For example:
2770/// \code
2771/// extern "C" void foo();
2772/// \endcode
2773class LinkageSpecDecl : public Decl, public DeclContext {
2774 virtual void anchor();
2775 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2776 // some space. Use the provided accessors to access it.
2777public:
2778 /// Represents the language in a linkage specification.
2779 ///
2780 /// The values are part of the serialization ABI for
2781 /// ASTs and cannot be changed without altering that ABI.
2782 enum LanguageIDs { lang_c = 1, lang_cxx = 2 };
2783
2784private:
2785 /// The source location for the extern keyword.
2786 SourceLocation ExternLoc;
2787
2788 /// The source location for the right brace (if valid).
2789 SourceLocation RBraceLoc;
2790
2791 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2792 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2793
2794public:
2795 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2796 SourceLocation ExternLoc,
2797 SourceLocation LangLoc, LanguageIDs Lang,
2798 bool HasBraces);
2799 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2800
2801 /// Return the language specified by this linkage specification.
2802 LanguageIDs getLanguage() const {
2803 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
2804 }
2805
2806 /// Set the language specified by this linkage specification.
2807 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
2808
2809 /// Determines whether this linkage specification had braces in
2810 /// its syntactic form.
2811 bool hasBraces() const {
2812 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces)((!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces) ? static_cast
<void> (0) : __assert_fail ("!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces"
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 2812, __PRETTY_FUNCTION__))
;
2813 return LinkageSpecDeclBits.HasBraces;
2814 }
2815
2816 SourceLocation getExternLoc() const { return ExternLoc; }
2817 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2818 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2819 void setRBraceLoc(SourceLocation L) {
2820 RBraceLoc = L;
2821 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
2822 }
2823
2824 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2825 if (hasBraces())
2826 return getRBraceLoc();
2827 // No braces: get the end location of the (only) declaration in context
2828 // (if present).
2829 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
2830 }
2831
2832 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2833 return SourceRange(ExternLoc, getEndLoc());
2834 }
2835
2836 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2837 static bool classofKind(Kind K) { return K == LinkageSpec; }
2838
2839 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2840 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2841 }
2842
2843 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2844 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2845 }
2846};
2847
2848/// Represents C++ using-directive.
2849///
2850/// For example:
2851/// \code
2852/// using namespace std;
2853/// \endcode
2854///
2855/// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2856/// artificial names for all using-directives in order to store
2857/// them in DeclContext effectively.
2858class UsingDirectiveDecl : public NamedDecl {
2859 /// The location of the \c using keyword.
2860 SourceLocation UsingLoc;
2861
2862 /// The location of the \c namespace keyword.
2863 SourceLocation NamespaceLoc;
2864
2865 /// The nested-name-specifier that precedes the namespace.
2866 NestedNameSpecifierLoc QualifierLoc;
2867
2868 /// The namespace nominated by this using-directive.
2869 NamedDecl *NominatedNamespace;
2870
2871 /// Enclosing context containing both using-directive and nominated
2872 /// namespace.
2873 DeclContext *CommonAncestor;
2874
2875 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2876 SourceLocation NamespcLoc,
2877 NestedNameSpecifierLoc QualifierLoc,
2878 SourceLocation IdentLoc,
2879 NamedDecl *Nominated,
2880 DeclContext *CommonAncestor)
2881 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2882 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2883 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2884
2885 /// Returns special DeclarationName used by using-directives.
2886 ///
2887 /// This is only used by DeclContext for storing UsingDirectiveDecls in
2888 /// its lookup structure.
2889 static DeclarationName getName() {
2890 return DeclarationName::getUsingDirectiveName();
2891 }
2892
2893 void anchor() override;
2894
2895public:
2896 friend class ASTDeclReader;
2897
2898 // Friend for getUsingDirectiveName.
2899 friend class DeclContext;
2900
2901 /// Retrieve the nested-name-specifier that qualifies the
2902 /// name of the namespace, with source-location information.
2903 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2904
2905 /// Retrieve the nested-name-specifier that qualifies the
2906 /// name of the namespace.
2907 NestedNameSpecifier *getQualifier() const {
2908 return QualifierLoc.getNestedNameSpecifier();
2909 }
2910
2911 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
2912 const NamedDecl *getNominatedNamespaceAsWritten() const {
2913 return NominatedNamespace;
2914 }
2915
2916 /// Returns the namespace nominated by this using-directive.
2917 NamespaceDecl *getNominatedNamespace();
2918
2919 const NamespaceDecl *getNominatedNamespace() const {
2920 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
2921 }
2922
2923 /// Returns the common ancestor context of this using-directive and
2924 /// its nominated namespace.
2925 DeclContext *getCommonAncestor() { return CommonAncestor; }
2926 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
2927
2928 /// Return the location of the \c using keyword.
2929 SourceLocation getUsingLoc() const { return UsingLoc; }
2930
2931 // FIXME: Could omit 'Key' in name.
2932 /// Returns the location of the \c namespace keyword.
2933 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
2934
2935 /// Returns the location of this using declaration's identifier.
2936 SourceLocation getIdentLocation() const { return getLocation(); }
2937
2938 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
2939 SourceLocation UsingLoc,
2940 SourceLocation NamespaceLoc,
2941 NestedNameSpecifierLoc QualifierLoc,
2942 SourceLocation IdentLoc,
2943 NamedDecl *Nominated,
2944 DeclContext *CommonAncestor);
2945 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2946
2947 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2948 return SourceRange(UsingLoc, getLocation());
2949 }
2950
2951 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2952 static bool classofKind(Kind K) { return K == UsingDirective; }
2953};
2954
2955/// Represents a C++ namespace alias.
2956///
2957/// For example:
2958///
2959/// \code
2960/// namespace Foo = Bar;
2961/// \endcode
2962class NamespaceAliasDecl : public NamedDecl,
2963 public Redeclarable<NamespaceAliasDecl> {
2964 friend class ASTDeclReader;
2965
2966 /// The location of the \c namespace keyword.
2967 SourceLocation NamespaceLoc;
2968
2969 /// The location of the namespace's identifier.
2970 ///
2971 /// This is accessed by TargetNameLoc.
2972 SourceLocation IdentLoc;
2973
2974 /// The nested-name-specifier that precedes the namespace.
2975 NestedNameSpecifierLoc QualifierLoc;
2976
2977 /// The Decl that this alias points to, either a NamespaceDecl or
2978 /// a NamespaceAliasDecl.
2979 NamedDecl *Namespace;
2980
2981 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
2982 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
2983 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
2984 SourceLocation IdentLoc, NamedDecl *Namespace)
2985 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
2986 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
2987 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
2988
2989 void anchor() override;
2990
2991 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
2992
2993 NamespaceAliasDecl *getNextRedeclarationImpl() override;
2994 NamespaceAliasDecl *getPreviousDeclImpl() override;
2995 NamespaceAliasDecl *getMostRecentDeclImpl() override;
2996
2997public:
2998 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
2999 SourceLocation NamespaceLoc,
3000 SourceLocation AliasLoc,
3001 IdentifierInfo *Alias,
3002 NestedNameSpecifierLoc QualifierLoc,
3003 SourceLocation IdentLoc,
3004 NamedDecl *Namespace);
3005
3006 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3007
3008 using redecl_range = redeclarable_base::redecl_range;
3009 using redecl_iterator = redeclarable_base::redecl_iterator;
3010
3011 using redeclarable_base::redecls_begin;
3012 using redeclarable_base::redecls_end;
3013 using redeclarable_base::redecls;
3014 using redeclarable_base::getPreviousDecl;
3015 using redeclarable_base::getMostRecentDecl;
3016
3017 NamespaceAliasDecl *getCanonicalDecl() override {
3018 return getFirstDecl();
3019 }
3020 const NamespaceAliasDecl *getCanonicalDecl() const {
3021 return getFirstDecl();
3022 }
3023
3024 /// Retrieve the nested-name-specifier that qualifies the
3025 /// name of the namespace, with source-location information.
3026 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3027
3028 /// Retrieve the nested-name-specifier that qualifies the
3029 /// name of the namespace.
3030 NestedNameSpecifier *getQualifier() const {
3031 return QualifierLoc.getNestedNameSpecifier();
3032 }
3033
3034 /// Retrieve the namespace declaration aliased by this directive.
3035 NamespaceDecl *getNamespace() {
3036 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3037 return AD->getNamespace();
3038
3039 return cast<NamespaceDecl>(Namespace);
3040 }
3041
3042 const NamespaceDecl *getNamespace() const {
3043 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3044 }
3045
3046 /// Returns the location of the alias name, i.e. 'foo' in
3047 /// "namespace foo = ns::bar;".
3048 SourceLocation getAliasLoc() const { return getLocation(); }
3049
3050 /// Returns the location of the \c namespace keyword.
3051 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3052
3053 /// Returns the location of the identifier in the named namespace.
3054 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3055
3056 /// Retrieve the namespace that this alias refers to, which
3057 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3058 NamedDecl *getAliasedNamespace() const { return Namespace; }
3059
3060 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3061 return SourceRange(NamespaceLoc, IdentLoc);
3062 }
3063
3064 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3065 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3066};
3067
3068/// Implicit declaration of a temporary that was materialized by
3069/// a MaterializeTemporaryExpr and lifetime-extended by a declaration
3070class LifetimeExtendedTemporaryDecl final
3071 : public Decl,
3072 public Mergeable<LifetimeExtendedTemporaryDecl> {
3073 friend class MaterializeTemporaryExpr;
3074 friend class ASTDeclReader;
3075
3076 Stmt *ExprWithTemporary = nullptr;
3077
3078 /// The declaration which lifetime-extended this reference, if any.
3079 /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3080 ValueDecl *ExtendingDecl = nullptr;
3081 unsigned ManglingNumber;
3082
3083 mutable APValue *Value = nullptr;
3084
3085 virtual void anchor();
3086
3087 LifetimeExtendedTemporaryDecl(Expr *Temp, ValueDecl *EDecl, unsigned Mangling)
3088 : Decl(Decl::LifetimeExtendedTemporary, EDecl->getDeclContext(),
3089 EDecl->getLocation()),
3090 ExprWithTemporary(Temp), ExtendingDecl(EDecl),
3091 ManglingNumber(Mangling) {}
3092
3093 LifetimeExtendedTemporaryDecl(EmptyShell)
3094 : Decl(Decl::LifetimeExtendedTemporary, EmptyShell{}) {}
3095
3096public:
3097 static LifetimeExtendedTemporaryDecl *Create(Expr *Temp, ValueDecl *EDec,
3098 unsigned Mangling) {
3099 return new (EDec->getASTContext(), EDec->getDeclContext())
3100 LifetimeExtendedTemporaryDecl(Temp, EDec, Mangling);
3101 }
3102 static LifetimeExtendedTemporaryDecl *CreateDeserialized(ASTContext &C,
3103 unsigned ID) {
3104 return new (C, ID) LifetimeExtendedTemporaryDecl(EmptyShell{});
3105 }
3106
3107 ValueDecl *getExtendingDecl() { return ExtendingDecl; }
3108 const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
3109
3110 /// Retrieve the storage duration for the materialized temporary.
3111 StorageDuration getStorageDuration() const;
3112
3113 /// Retrieve the expression to which the temporary materialization conversion
3114 /// was applied. This isn't necessarily the initializer of the temporary due
3115 /// to the C++98 delayed materialization rules, but
3116 /// skipRValueSubobjectAdjustments can be used to find said initializer within
3117 /// the subexpression.
3118 Expr *getTemporaryExpr() { return cast<Expr>(ExprWithTemporary); }
3119 const Expr *getTemporaryExpr() const { return cast<Expr>(ExprWithTemporary); }
3120
3121 unsigned getManglingNumber() const { return ManglingNumber; }
3122
3123 /// Get the storage for the constant value of a materialized temporary
3124 /// of static storage duration.
3125 APValue *getOrCreateValue(bool MayCreate) const;
3126
3127 APValue *getValue() const { return Value; }
3128
3129 // Iterators
3130 Stmt::child_range childrenExpr() {
3131 return Stmt::child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3132 }
3133
3134 Stmt::const_child_range childrenExpr() const {
3135 return Stmt::const_child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3136 }
3137
3138 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3139 static bool classofKind(Kind K) {
3140 return K == Decl::LifetimeExtendedTemporary;
3141 }
3142};
3143
3144/// Represents a shadow declaration introduced into a scope by a
3145/// (resolved) using declaration.
3146///
3147/// For example,
3148/// \code
3149/// namespace A {
3150/// void foo();
3151/// }
3152/// namespace B {
3153/// using A::foo; // <- a UsingDecl
3154/// // Also creates a UsingShadowDecl for A::foo() in B
3155/// }
3156/// \endcode
3157class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3158 friend class UsingDecl;
3159
3160 /// The referenced declaration.
3161 NamedDecl *Underlying = nullptr;
3162
3163 /// The using declaration which introduced this decl or the next using
3164 /// shadow declaration contained in the aforementioned using declaration.
3165 NamedDecl *UsingOrNextShadow = nullptr;
3166
3167 void anchor() override;
3168
3169 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3170
3171 UsingShadowDecl *getNextRedeclarationImpl() override {
3172 return getNextRedeclaration();
3173 }
3174
3175 UsingShadowDecl *getPreviousDeclImpl() override {
3176 return getPreviousDecl();
3177 }
3178
3179 UsingShadowDecl *getMostRecentDeclImpl() override {
3180 return getMostRecentDecl();
3181 }
3182
3183protected:
3184 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3185 UsingDecl *Using, NamedDecl *Target);
3186 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3187
3188public:
3189 friend class ASTDeclReader;
3190 friend class ASTDeclWriter;
3191
3192 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3193 SourceLocation Loc, UsingDecl *Using,
3194 NamedDecl *Target) {
3195 return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3196 }
3197
3198 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3199
3200 using redecl_range = redeclarable_base::redecl_range;
3201 using redecl_iterator = redeclarable_base::redecl_iterator;
3202
3203 using redeclarable_base::redecls_begin;
3204 using redeclarable_base::redecls_end;
3205 using redeclarable_base::redecls;
3206 using redeclarable_base::getPreviousDecl;
3207 using redeclarable_base::getMostRecentDecl;
3208 using redeclarable_base::isFirstDecl;
3209
3210 UsingShadowDecl *getCanonicalDecl() override {
3211 return getFirstDecl();
3212 }
3213 const UsingShadowDecl *getCanonicalDecl() const {
3214 return getFirstDecl();
3215 }
3216
3217 /// Gets the underlying declaration which has been brought into the
3218 /// local scope.
3219 NamedDecl *getTargetDecl() const { return Underlying; }
3220
3221 /// Sets the underlying declaration which has been brought into the
3222 /// local scope.
3223 void setTargetDecl(NamedDecl *ND) {
3224 assert(ND && "Target decl is null!")((ND && "Target decl is null!") ? static_cast<void
> (0) : __assert_fail ("ND && \"Target decl is null!\""
, "/build/llvm-toolchain-snapshot-12~++20210104111112+e43b3d1f5e05/clang/include/clang/AST/DeclCXX.h"
, 3224, __PRETTY_FUNCTION__))
;
3225 Underlying = ND;
3226 // A UsingShadowDecl is never a friend or local extern declaration, even
3227 // if it is a shadow declaration for one.
3228 IdentifierNamespace =
3229 ND->getIdentifierNamespace() &
3230 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3231 }
3232
3233 /// Gets the using declaration to which this declaration is tied.
3234 UsingDecl *getUsingDecl() const;
3235
3236 /// The next using shadow declaration contained in the shadow decl
3237 /// chain of the using declaration which introduced this decl.
3238 UsingShadowDecl *getNextUsingShadowDecl() const {
3239 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3240 }
3241
3242 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3243 static bool classofKind(Kind K) {
3244 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3245 }
3246};
3247
3248/// Represents a shadow constructor declaration introduced into a
3249/// class by a C++11 using-declaration that names a constructor.
3250///
3251/// For example:
3252/// \code
3253/// struct Base { Base(int); };
3254/// struct Derived {
3255/// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3256/// };
3257/// \endcode
3258class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3259 /// If this constructor using declaration inherted the constructor
3260 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3261 /// in the named direct base class from which the declaration was inherited.
3262 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3263
3264 /// If this constructor using declaration inherted the constructor
3265 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3266 /// that will be used to construct the unique direct or virtual base class
3267 /// that receives the constructor arguments.
3268 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3269
3270 /// \c true if the constructor ultimately named by this using shadow
3271 /// declaration is within a virtual base class subobject of the class that
3272 /// contains this declaration.
3273 unsigned IsVirtual : 1;
3274
3275 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3276 UsingDecl *Using, NamedDecl *Target,
3277 bool TargetInVirtualBase)
3278 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3279 Target->getUnderlyingDecl()),
3280 NominatedBaseClassShadowDecl(
3281 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3282 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3283 IsVirtual(TargetInVirtualBase) {
3284 // If we found a constructor that chains to a constructor for a virtual
3285 // base, we should directly call that virtual base constructor instead.
3286 // FIXME: This logic belongs in Sema.
3287 if (NominatedBaseClassShadowDecl &&
3288 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3289 ConstructedBaseClassShadowDecl =
3290 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3291 IsVirtual = true;
3292 }
3293 }
3294
3295 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3296 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3297
3298 void anchor() override;
3299
3300public:
3301 friend class ASTDeclReader;
3302 friend class ASTDeclWriter;
3303
3304 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3305 SourceLocation Loc,
3306 UsingDecl *Using, NamedDecl *Target,
3307 bool IsVirtual);
3308 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3309 unsigned ID);
3310
3311 /// Returns the parent of this using shadow declaration, which
3312 /// is the class in which this is declared.
3313 //@{
3314 const CXXRecordDecl *getParent() const {
3315 return cast<CXXRecordDecl>(getDeclContext());
3316 }
3317 CXXRecordDecl *getParent() {
3318 return cast<CXXRecordDecl>(getDeclContext());
3319 }
3320 //@}
3321
3322 /// Get the inheriting constructor declaration for the direct base
3323 /// class from which this using shadow declaration was inherited, if there is
3324 /// one. This can be different for each redeclaration of the same shadow decl.
3325 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3326 return NominatedBaseClassShadowDecl;
3327 }
3328
3329 /// Get the inheriting constructor declaration for the base class
3330 /// for which we don't have an explicit initializer, if there is one.
3331 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3332 return ConstructedBaseClassShadowDecl;
3333 }
3334
3335 /// Get the base class that was named in the using declaration. This
3336 /// can be different for each redeclaration of this same shadow decl.
3337 CXXRecordDecl *getNominatedBaseClass() const;
3338
3339 /// Get the base class whose constructor or constructor shadow
3340 /// declaration is passed the constructor arguments.
3341 CXXRecordDecl *getConstructedBaseClass() const {
3342 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3343 ? ConstructedBaseClassShadowDecl
3344 : getTargetDecl())
3345 ->getDeclContext());
3346 }
3347
3348 /// Returns \c true if the constructed base class is a virtual base
3349 /// class subobject of this declaration's class.
3350 bool constructsVirtualBase() const {
3351 return IsVirtual;
3352 }
3353
3354 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3355 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3356};
3357
3358/// Represents a C++ using-declaration.
3359///
3360/// For example:
3361/// \code
3362/// using someNameSpace::someIdentifier;
3363/// \endcode
3364class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3365 /// The source location of the 'using' keyword itself.
3366 SourceLocation UsingLocation;
3367
3368 /// The nested-name-specifier that precedes the name.
3369 NestedNameSpecifierLoc QualifierLoc;
3370
3371 /// Provides source/type location info for the declaration name
3372 /// embedded in the ValueDecl base class.
3373 DeclarationNameLoc DNLoc;
3374
3375 /// The first shadow declaration of the shadow decl chain associated
3376 /// with this using declaration.
3377 ///
3378 /// The bool member of the pair store whether this decl has the \c typename
3379 /// keyword.
3380 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3381
3382 UsingDecl(DeclContext *DC, SourceLocation UL,
3383 NestedNameSpecifierLoc QualifierLoc,
3384 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3385 : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3386 UsingLocation(UL), QualifierLoc(QualifierLoc),
3387 DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
3388 }
3389
3390 void anchor() override;
3391
3392public:
3393 friend class ASTDeclReader;
3394 friend class ASTDeclWriter;
3395
3396 /// Return the source location of the 'using' keyword.
3397 SourceLocation getUsingLoc() const { return UsingLocation; }
3398
3399 /// Set the source location of the 'using' keyword.
3400 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3401
3402 /// Retrieve the nested-name-specifier that qualifies the name,
3403 /// with source-location information.
3404 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3405
3406 /// Retrieve the nested-name-specifier that qualifies the name.
3407 NestedNameSpecifier *getQualifier() const {
3408 return QualifierLoc.getNestedNameSpecifier();
3409 }
3410
3411 DeclarationNameInfo getNameInfo() const {
3412 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3413 }
3414
3415 /// Return true if it is a C++03 access declaration (no 'using').
3416 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3417
3418 /// Return true if the using declaration has 'typename'.
3419 bool hasTypename() const { return FirstUsingShadow.getInt(); }
3420
3421 /// Sets whether the using declaration has 'typename'.
3422 void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
3423
3424 /// Iterates through the using shadow declarations associated with
3425 /// this using declaration.
3426 class shadow_iterator {
3427 /// The current using shadow declaration.
3428 UsingShadowDecl *Current = nullptr;
3429
3430 public:
3431 using value_type = UsingShadowDecl *;
3432 using reference = UsingShadowDecl *;
3433 using pointer = UsingShadowDecl *;
3434 using iterator_category = std::forward_iterator_tag;
3435 using difference_type = std::ptrdiff_t;
3436
3437 shadow_iterator() = default;
3438 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3439
3440 reference operator*() const { return Current; }
3441 pointer operator->() const { return Current; }
3442
3443 shadow_iterator& operator++() {
3444 Current = Current->getNextUsingShadowDecl();
3445 return *this;
3446 }
3447
3448 shadow_iterator operator++(int) {
3449 shadow_iterator tmp(*this);
3450 ++(*this);
3451 return tmp;
3452 }
3453
3454 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3455 return x.Current == y.Current;
3456 }
3457 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3458 return x.Current != y.Current;
3459 }
3460 };
3461
3462 using shadow_range = llvm::iterator_range<shadow_iterator>;
3463
3464 shadow_range shadows() const {
3465 return shadow_range(shadow_begin(), shadow_end());
3466 }
3467
3468 shadow_iterator shadow_begin() const {
3469 return shadow_iterator(FirstUsingShadow.getPointer());
3470 }
3471
3472 shadow_iterator shadow_end() const { return shadow_iterator(); }
3473
3474 /// Return the number of shadowed declarations associated with this
3475 /// using declaration.
3476 unsigned shadow_size() const {
3477 return std::distance(shadow_begin(), shadow_end());
3478 }
3479
3480 void addShadowDecl(UsingShadowDecl *S);
3481 void removeShadowDecl(UsingShadowDecl *S);
3482
3483 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3484 SourceLocation UsingL,
3485 NestedNameSpecifierLoc QualifierLoc,
3486 const DeclarationNameInfo &NameInfo,
3487 bool HasTypenameKeyword);
3488
3489 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3490
3491 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3492
3493 /// Retrieves the canonical declaration of this declaration.
3494 UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
3495 const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
3496
3497 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3498 static bool classofKind(Kind K) { return K == Using; }
3499};
3500
3501/// Represents a pack of using declarations that a single
3502/// using-declarator pack-expanded into.
3503///
3504/// \code
3505/// template<typename ...T> struct X : T... {
3506/// using T::operator()...;
3507/// using T::operator T...;
3508/// };
3509/// \endcode
3510///
3511/// In the second case above, the UsingPackDecl will have the name
3512/// 'operator T' (which contains an unexpanded pack), but the individual
3513/// UsingDecls and UsingShadowDecls will have more reasonable names.
3514class UsingPackDecl final
3515 : public NamedDecl, public Mergeable<UsingPackDecl>,
3516 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3517 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3518 /// which this waas instantiated.
3519 NamedDecl *InstantiatedFrom;
3520
3521 /// The number of using-declarations created by this pack expansion.
3522 unsigned NumExpansions;
3523
3524 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3525 ArrayRef<NamedDecl *> UsingDecls)
3526 : NamedDecl(UsingPack, DC,
3527 InstantiatedFrom ? InstantiatedFrom->getLocation()
3528 : SourceLocation(),
3529 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3530 : DeclarationName()),
3531 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3532 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3533 getTrailingObjects<NamedDecl *>());
3534 }
3535
3536 void anchor() override;
3537
3538public:
3539 friend class ASTDeclReader;
3540 friend class ASTDeclWriter;
3541 friend TrailingObjects;
3542
3543 /// Get the using declaration from which this was instantiated. This will
3544 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3545 /// that is a pack expansion.
3546 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3547
3548 /// Get the set of using declarations that this pack expanded into. Note that
3549 /// some of these may still be unresolved.
3550 ArrayRef<NamedDecl *> expansions() const {
3551 return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3552 }
3553
3554 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3555 NamedDecl *InstantiatedFrom,
3556 ArrayRef<NamedDecl *> UsingDecls);
3557
3558 static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3559 unsigned NumExpansions);
3560
3561 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3562 return InstantiatedFrom->getSourceRange();
3563 }
3564
3565 UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3566 const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3567
3568 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3569 static bool classofKind(Kind K) { return K == UsingPack; }
3570};
3571
3572/// Represents a dependent using declaration which was not marked with
3573/// \c typename.
3574///
3575/// Unlike non-dependent using declarations, these *only* bring through
3576/// non-types; otherwise they would break two-phase lookup.
3577///
3578/// \code
3579/// template \<class T> class A : public Base<T> {
3580/// using Base<T>::foo;
3581/// };
3582/// \endcode
3583class UnresolvedUsingValueDecl : public ValueDecl,
3584 public Mergeable<UnresolvedUsingValueDecl> {
3585 /// The source location of the 'using' keyword
3586 SourceLocation UsingLocation;
3587
3588 /// If this is a pack expansion, the location of the '...'.
3589 SourceLocation EllipsisLoc;
3590
3591 /// The nested-name-specifier that precedes the name.
3592 NestedNameSpecifierLoc QualifierLoc;
3593
3594 /// Provides source/type location info for the declaration name
3595 /// embedded in the ValueDecl base class.
3596 DeclarationNameLoc DNLoc;
3597
3598 UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3599 SourceLocation UsingLoc,
3600 NestedNameSpecifierLoc QualifierLoc,
3601 const DeclarationNameInfo &NameInfo,
3602 SourceLocation EllipsisLoc)
3603 : ValueDecl(UnresolvedUsingValue, DC,
3604 NameInfo.getLoc(), NameInfo.getName(), Ty),
3605 UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3606 QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3607
3608 void anchor() override;
3609
3610public:
3611 friend class ASTDeclReader;
3612 friend class ASTDeclWriter;
3613
3614 /// Returns the source location of the 'using' keyword.
3615 SourceLocation getUsingLoc() const { return UsingLocation; }
3616
3617 /// Set the source location of the 'using' keyword.
3618 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3619
3620 /// Return true if it is a C++03 access declaration (no 'using').
3621 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3622
3623 /// Retrieve the nested-name-specifier that qualifies the name,
3624 /// with source-location information.
3625 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3626
3627 /// Retrieve the nested-name-specifier that qualifies the name.
3628 NestedNameSpecifier *getQualifier() const {
3629 return QualifierLoc.getNestedNameSpecifier();
3630 }
3631
3632 DeclarationNameInfo getNameInfo() const {
3633 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3634 }
3635
3636 /// Determine whether this is a pack expansion.
3637 bool isPackExpansion() const {
3638 return EllipsisLoc.isValid();
3639 }
3640
3641 /// Get the location of the ellipsis if this is a pack expansion.
3642 SourceLocation getEllipsisLoc() const {
3643 return EllipsisLoc;
3644 }
3645
3646 static UnresolvedUsingValueDecl *
3647 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3648 NestedNameSpecifierLoc QualifierLoc,
3649 const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3650
3651 static UnresolvedUsingValueDecl *
3652 CreateDeserialized(ASTContext &C, unsigned ID);
3653
3654 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3655
3656 /// Retrieves the canonical declaration of this declaration.
3657 UnresolvedUsingValueDecl *getCanonicalDecl() override {
3658 return getFirstDecl();
3659 }
3660 const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3661 return getFirstDecl();
3662 }
3663
3664 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3665 static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3666};
3667
3668/// Represents a dependent using declaration which was marked with
3669/// \c typename.
3670///
3671/// \code
3672/// template \<class T> class A : public Base<T> {
3673/// using typename Base<T>::foo;
3674/// };
3675/// \endcode
3676///
3677/// The type associated with an unresolved using typename decl is
3678/// currently always a typename type.
3679class UnresolvedUsingTypenameDecl
3680 : public TypeDecl,
3681 public Mergeable<UnresolvedUsingTypenameDecl> {
3682 friend class ASTDeclReader;
3683
3684 /// The source location of the 'typename' keyword
3685 SourceLocation TypenameLocation;
3686
3687 /// If this is a pack expansion, the location of the '...'.
3688 SourceLocation EllipsisLoc;
3689
3690 /// The nested-name-specifier that precedes the name.
3691 NestedNameSpecifierLoc QualifierLoc;
3692
3693 UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3694 SourceLocation TypenameLoc,
3695 NestedNameSpecifierLoc QualifierLoc,
3696 SourceLocation TargetNameLoc,
3697 IdentifierInfo *TargetName,
3698 SourceLocation EllipsisLoc)
3699 : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3700 UsingLoc),
3701 TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3702 QualifierLoc(QualifierLoc) {}
3703
3704 void anchor() override;
3705
3706public:
3707 /// Returns the source location of the 'using' keyword.
3708 SourceLocation getUsingLoc() const { return getBeginLoc(); }
3709
3710 /// Returns the source location of the 'typename' keyword.
3711 SourceLocation getTypenameLoc() const { return TypenameLocation; }
3712
3713 /// Retrieve the nested-name-specifier that qualifies the name,
3714 /// with source-location information.
3715 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3716
3717 /// Retrieve the nested-name-specifier that qualifies the name.
3718 NestedNameSpecifier *getQualifier() const {
3719 return QualifierLoc.getNestedNameSpecifier();
3720 }
3721
3722 DeclarationNameInfo getNameInfo() const {
3723 return DeclarationNameInfo(getDeclName(), getLocation());
3724 }
3725
3726 /// Determine whether this is a pack expansion.
3727 bool isPackExpansion() const {
3728 return EllipsisLoc.isValid();
3729 }
3730
3731 /// Get the location of the ellipsis if this is a pack expansion.
3732 SourceLocation getEllipsisLoc() const {
3733 return EllipsisLoc;
3734 }
3735
3736 static UnresolvedUsingTypenameDecl *
3737 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3738 SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3739 SourceLocation TargetNameLoc, DeclarationName TargetName,
3740 SourceLocation EllipsisLoc);
3741
3742 static UnresolvedUsingTypenameDecl *
3743 CreateDeserialized(ASTContext &C, unsigned ID);
3744
3745 /// Retrieves the canonical declaration of this declaration.
3746 UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3747 return getFirstDecl();
3748 }
3749 const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3750 return getFirstDecl();
3751 }
3752
3753 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3754 static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3755};
3756
3757/// Represents a C++11 static_assert declaration.
3758class StaticAssertDecl : public Decl {
3759 llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
3760 StringLiteral *Message;
3761 SourceLocation RParenLoc;
3762
3763 StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
3764 Expr *AssertExpr, StringLiteral *Message,
3765 SourceLocation RParenLoc, bool Failed)
3766 : Decl(StaticAssert, DC, StaticAssertLoc),
3767 AssertExprAndFailed(AssertExpr, Failed), Message(Message),
3768 RParenLoc(RParenLoc) {}
3769
3770 virtual void anchor();
3771
3772public:
3773 friend class ASTDeclReader;
3774
3775 static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
3776 SourceLocation StaticAssertLoc,
3777 Expr *AssertExpr, StringLiteral *Message,
3778 SourceLocation RParenLoc, bool Failed);
3779 static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3780
3781 Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
3782 const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
3783
3784 StringLiteral *getMessage() { return Message; }
3785 const StringLiteral *getMessage() const { return Message; }
3786
3787 bool isFailed() const { return AssertExprAndFailed.getInt(); }
3788
3789 SourceLocation getRParenLoc() const { return RParenLoc; }
3790
3791 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3792 return SourceRange(getLocation(), getRParenLoc());
3793 }
3794
3795 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3796 static bool classofKind(Kind K) { return K == StaticAssert; }
3797};
3798
3799/// A binding in a decomposition declaration. For instance, given:
3800///
3801/// int n[3];
3802/// auto &[a, b, c] = n;
3803///
3804/// a, b, and c are BindingDecls, whose bindings are the expressions
3805/// x[0], x[1], and x[2] respectively, where x is the implicit
3806/// DecompositionDecl of type 'int (&)[3]'.
3807class BindingDecl : public ValueDecl {
3808 /// The declaration that this binding binds to part of.
3809 LazyDeclPtr Decomp;
3810 /// The binding represented by this declaration. References to this
3811 /// declaration are effectively equivalent to this expression (except
3812 /// that it is only evaluated once at the point of declaration of the
3813 /// binding).
3814 Expr *Binding = nullptr;
3815
3816 BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
3817 : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
3818
3819 void anchor() override;
3820
3821public:
3822 friend class ASTDeclReader;
3823
3824 static BindingDecl *Create(ASTContext &C, DeclContext *DC,
3825 SourceLocation IdLoc, IdentifierInfo *Id);
3826 static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3827
3828 /// Get the expression to which this declaration is bound. This may be null
3829 /// in two different cases: while parsing the initializer for the
3830 /// decomposition declaration, and when the initializer is type-dependent.
3831 Expr *getBinding() const { return Binding; }
3832
3833 /// Get the decomposition declaration that this binding represents a
3834 /// decomposition of.
3835 ValueDecl *getDecomposedDecl() const;
3836
3837 /// Get the variable (if any) that holds the value of evaluating the binding.
3838 /// Only present for user-defined bindings for tuple-like types.
3839 VarDecl *getHoldingVar() const;
3840
3841 /// Set the binding for this BindingDecl, along with its declared type (which
3842 /// should be a possibly-cv-qualified form of the type of the binding, or a
3843 /// reference to such a type).
3844 void setBinding(QualType DeclaredType, Expr *Binding) {
3845 setType(DeclaredType);
3846 this->Binding = Binding;
3847 }
3848
3849 /// Set the decomposed variable for this BindingDecl.
3850 void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; }
3851
3852 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3853 static bool classofKind(Kind K) { return K == Decl::Binding; }
3854};
3855
3856/// A decomposition declaration. For instance, given:
3857///
3858/// int n[3];
3859/// auto &[a, b, c] = n;
3860///
3861/// the second line declares a DecompositionDecl of type 'int (&)[3]', and
3862/// three BindingDecls (named a, b, and c). An instance of this class is always
3863/// unnamed, but behaves in almost all other respects like a VarDecl.
3864class DecompositionDecl final
3865 : public VarDecl,
3866 private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
3867 /// The number of BindingDecl*s following this object.
3868 unsigned NumBindings;
3869
3870 DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3871 SourceLocation LSquareLoc, QualType T,
3872 TypeSourceInfo *TInfo, StorageClass SC,
3873 ArrayRef<BindingDecl *> Bindings)
3874 : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
3875 SC),
3876 NumBindings(Bindings.size()) {
3877 std::uninitialized_copy(Bindings.begin(), Bindings.end(),
3878 getTrailingObjects<BindingDecl *>());
3879 for (auto *B : Bindings)
3880 B->setDecomposedDecl(this);
3881 }
3882
3883 void anchor() override;
3884
3885public:
3886 friend class ASTDeclReader;
3887 friend TrailingObjects;
3888
3889 static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
3890 SourceLocation StartLoc,
3891 SourceLocation LSquareLoc,
3892 QualType T, TypeSourceInfo *TInfo,
3893 StorageClass S,
3894 ArrayRef<BindingDecl *> Bindings);
3895 static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3896 unsigned NumBindings);
3897
3898 ArrayRef<BindingDecl *> bindings() const {
3899 return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
3900 }
3901
3902 void printName(raw_ostream &os) const override;
3903
3904 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3905 static bool classofKind(Kind K) { return K == Decomposition; }
3906};
3907
3908/// An instance of this class represents the declaration of a property
3909/// member. This is a Microsoft extension to C++, first introduced in
3910/// Visual Studio .NET 2003 as a parallel to similar features in C#
3911/// and Managed C++.
3912///
3913/// A property must always be a non-static class member.
3914///
3915/// A property member superficially resembles a non-static data
3916/// member, except preceded by a property attribute:
3917/// __declspec(property(get=GetX, put=PutX)) int x;
3918/// Either (but not both) of the 'get' and 'put' names may be omitted.
3919///
3920/// A reference to a property is always an lvalue. If the lvalue
3921/// undergoes lvalue-to-rvalue conversion, then a getter name is
3922/// required, and that member is called with no arguments.
3923/// If the lvalue is assigned into, then a setter name is required,
3924/// and that member is called with one argument, the value assigned.
3925/// Both operations are potentially overloaded. Compound assignments
3926/// are permitted, as are the increment and decrement operators.
3927///
3928/// The getter and putter methods are permitted to be overloaded,
3929/// although their return and parameter types are subject to certain
3930/// restrictions according to the type of the property.
3931///
3932/// A property declared using an incomplete array type may
3933/// additionally be subscripted, adding extra parameters to the getter
3934/// and putter methods.
3935class MSPropertyDecl : public DeclaratorDecl {
3936 IdentifierInfo *GetterId, *SetterId;
3937
3938 MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
3939 QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
3940 IdentifierInfo *Getter, IdentifierInfo *Setter)
3941 : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
3942 GetterId(Getter), SetterId(Setter) {}
3943
3944 void anchor() override;
3945public:
3946 friend class ASTDeclReader;
3947
3948 static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
3949 SourceLocation L, DeclarationName N, QualType T,
3950 TypeSourceInfo *TInfo, SourceLocation StartL,
3951 IdentifierInfo *Getter, IdentifierInfo *Setter);
3952 static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3953
3954 static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
3955
3956 bool hasGetter() const { return GetterId != nullptr; }
3957 IdentifierInfo* getGetterId() const { return GetterId; }
3958 bool hasSetter() const { return SetterId != nullptr; }
3959 IdentifierInfo* getSetterId() const { return SetterId; }
3960};
3961
3962/// Parts of a decomposed MSGuidDecl. Factored out to avoid unnecessary
3963/// dependencies on DeclCXX.h.
3964struct MSGuidDeclParts {
3965 /// {01234567-...
3966 uint32_t Part1;
3967 /// ...-89ab-...
3968 uint16_t Part2;
3969 /// ...-cdef-...
3970 uint16_t Part3;
3971 /// ...-0123-456789abcdef}
3972 uint8_t Part4And5[8];
3973
3974 uint64_t getPart4And5AsUint64() const {
3975 uint64_t Val;
3976 memcpy(&Val, &Part4And5, sizeof(Part4And5));
3977 return Val;
3978 }
3979};
3980
3981/// A global _GUID constant. These are implicitly created by UuidAttrs.
3982///
3983/// struct _declspec(uuid("01234567-89ab-cdef-0123-456789abcdef")) X{};
3984///
3985/// X is a CXXRecordDecl that contains a UuidAttr that references the (unique)
3986/// MSGuidDecl for the specified UUID.
3987class MSGuidDecl : public ValueDecl,
3988 public Mergeable<MSGuidDecl>,
3989 public llvm::FoldingSetNode {
3990public:
3991 using Parts = MSGuidDeclParts;
3992
3993private:
3994 /// The decomposed form of the UUID.
3995 Parts PartVal;
3996
3997 /// The resolved value of the UUID as an APValue. Computed on demand and
3998 /// cached.
3999 mutable APValue APVal;
4000
4001 void anchor() override;
4002
4003 MSGuidDecl(DeclContext *DC, QualType T, Parts P);
4004
4005 static MSGuidDecl *Create(const ASTContext &C, QualType T, Parts P);
4006 static MSGuidDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4007
4008 // Only ASTContext::getMSGuidDecl and deserialization create these.
4009 friend class ASTContext;
4010 friend class ASTReader;
4011 friend class ASTDeclReader;
4012
4013public:
4014 /// Print this UUID in a human-readable format.
4015 void printName(llvm::raw_ostream &OS) const override;
4016
4017 /// Get the decomposed parts of this declaration.
4018 Parts getParts() const { return PartVal; }
4019
4020 /// Get the value of this MSGuidDecl as an APValue. This may fail and return
4021 /// an absent APValue if the type of the declaration is not of the expected
4022 /// shape.
4023 APValue &getAsAPValue() const;
4024
4025 static void Profile(llvm::FoldingSetNodeID &ID, Parts P) {
4026 ID.AddInteger(P.Part1);
4027 ID.AddInteger(P.Part2);
4028 ID.AddInteger(P.Part3);
4029 ID.AddInteger(P.getPart4And5AsUint64());
4030 }
4031 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, PartVal); }
4032
4033 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4034 static bool classofKind(Kind K) { return K == Decl::MSGuid; }
4035};
4036
4037/// Insertion operator for diagnostics. This allows sending an AccessSpecifier
4038/// into a diagnostic with <<.
4039const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
4040 AccessSpecifier AS);
4041
4042} // namespace clang
4043
4044#endif // LLVM_CLANG_AST_DECLCXX_H