Bug Summary

File:src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/include/clang/AST/ExternalASTSource.h
Warning:line 378, column 40
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -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 -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include/clang/AST -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../include -I /usr/src/gnu/usr.bin/clang/libclangAST/obj -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/DeclCXX.cpp

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

/usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/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 BaseUsingDecl;
73class TemplateDecl;
74class TemplateParameterList;
75class UsingDecl;
76
77/// Represents an access specifier followed by colon ':'.
78///
79/// An objects of this class represents sugar for the syntactic occurrence
80/// of an access specifier followed by a colon in the list of member
81/// specifiers of a C++ class definition.
82///
83/// Note that they do not represent other uses of access specifiers,
84/// such as those occurring in a list of base specifiers.
85/// Also note that this class has nothing to do with so-called
86/// "access declarations" (C++98 11.3 [class.access.dcl]).
87class AccessSpecDecl : public Decl {
88 /// The location of the ':'.
89 SourceLocation ColonLoc;
90
91 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
92 SourceLocation ASLoc, SourceLocation ColonLoc)
93 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
94 setAccess(AS);
95 }
96
97 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
98
99 virtual void anchor();
100
101public:
102 /// The location of the access specifier.
103 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
104
105 /// Sets the location of the access specifier.
106 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
107
108 /// The location of the colon following the access specifier.
109 SourceLocation getColonLoc() const { return ColonLoc; }
110
111 /// Sets the location of the colon.
112 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
113
114 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
115 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
116 }
117
118 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
119 DeclContext *DC, SourceLocation ASLoc,
120 SourceLocation ColonLoc) {
121 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
122 }
123
124 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == AccessSpec; }
129};
130
131/// Represents a base class of a C++ class.
132///
133/// Each CXXBaseSpecifier represents a single, direct base class (or
134/// struct) of a C++ class (or struct). It specifies the type of that
135/// base class, whether it is a virtual or non-virtual base, and what
136/// level of access (public, protected, private) is used for the
137/// derivation. For example:
138///
139/// \code
140/// class A { };
141/// class B { };
142/// class C : public virtual A, protected B { };
143/// \endcode
144///
145/// In this code, C will have two CXXBaseSpecifiers, one for "public
146/// virtual A" and the other for "protected B".
147class CXXBaseSpecifier {
148 /// The source code range that covers the full base
149 /// specifier, including the "virtual" (if present) and access
150 /// specifier (if present).
151 SourceRange Range;
152
153 /// The source location of the ellipsis, if this is a pack
154 /// expansion.
155 SourceLocation EllipsisLoc;
156
157 /// Whether this is a virtual base class or not.
158 unsigned Virtual : 1;
159
160 /// Whether this is the base of a class (true) or of a struct (false).
161 ///
162 /// This determines the mapping from the access specifier as written in the
163 /// source code to the access specifier used for semantic analysis.
164 unsigned BaseOfClass : 1;
165
166 /// Access specifier as written in the source code (may be AS_none).
167 ///
168 /// The actual type of data stored here is an AccessSpecifier, but we use
169 /// "unsigned" here to work around a VC++ bug.
170 unsigned Access : 2;
171
172 /// Whether the class contains a using declaration
173 /// to inherit the named class's constructors.
174 unsigned InheritConstructors : 1;
175
176 /// The type of the base class.
177 ///
178 /// This will be a class or struct (or a typedef of such). The source code
179 /// range does not include the \c virtual or the access specifier.
180 TypeSourceInfo *BaseTypeInfo;
181
182public:
183 CXXBaseSpecifier() = default;
184 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
185 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
186 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
187 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
188
189 /// Retrieves the source range that contains the entire base specifier.
190 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
191 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
192 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
193
194 /// Get the location at which the base class type was written.
195 SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) {
196 return BaseTypeInfo->getTypeLoc().getBeginLoc();
197 }
198
199 /// Determines whether the base class is a virtual base class (or not).
200 bool isVirtual() const { return Virtual; }
201
202 /// Determine whether this base class is a base of a class declared
203 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
204 bool isBaseOfClass() const { return BaseOfClass; }
205
206 /// Determine whether this base specifier is a pack expansion.
207 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
208
209 /// Determine whether this base class's constructors get inherited.
210 bool getInheritConstructors() const { return InheritConstructors; }
211
212 /// Set that this base class's constructors should be inherited.
213 void setInheritConstructors(bool Inherit = true) {
214 InheritConstructors = Inherit;
215 }
216
217 /// For a pack expansion, determine the location of the ellipsis.
218 SourceLocation getEllipsisLoc() const {
219 return EllipsisLoc;
220 }
221
222 /// Returns the access specifier for this base specifier.
223 ///
224 /// This is the actual base specifier as used for semantic analysis, so
225 /// the result can never be AS_none. To retrieve the access specifier as
226 /// written in the source code, use getAccessSpecifierAsWritten().
227 AccessSpecifier getAccessSpecifier() const {
228 if ((AccessSpecifier)Access == AS_none)
229 return BaseOfClass? AS_private : AS_public;
230 else
231 return (AccessSpecifier)Access;
232 }
233
234 /// Retrieves the access specifier as written in the source code
235 /// (which may mean that no access specifier was explicitly written).
236 ///
237 /// Use getAccessSpecifier() to retrieve the access specifier for use in
238 /// semantic analysis.
239 AccessSpecifier getAccessSpecifierAsWritten() const {
240 return (AccessSpecifier)Access;
241 }
242
243 /// Retrieves the type of the base class.
244 ///
245 /// This type will always be an unqualified class type.
246 QualType getType() const {
247 return BaseTypeInfo->getType().getUnqualifiedType();
248 }
249
250 /// Retrieves the type and source location of the base class.
251 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
252};
253
254/// Represents a C++ struct/union/class.
255class CXXRecordDecl : public RecordDecl {
256 friend class ASTDeclReader;
257 friend class ASTDeclWriter;
258 friend class ASTNodeImporter;
259 friend class ASTReader;
260 friend class ASTRecordWriter;
261 friend class ASTWriter;
262 friend class DeclContext;
263 friend class LambdaExpr;
264
265 friend void FunctionDecl::setPure(bool);
266 friend void TagDecl::startDefinition();
267
268 /// Values used in DefinitionData fields to represent special members.
269 enum SpecialMemberFlags {
270 SMF_DefaultConstructor = 0x1,
271 SMF_CopyConstructor = 0x2,
272 SMF_MoveConstructor = 0x4,
273 SMF_CopyAssignment = 0x8,
274 SMF_MoveAssignment = 0x10,
275 SMF_Destructor = 0x20,
276 SMF_All = 0x3f
277 };
278
279 struct DefinitionData {
280 #define FIELD(Name, Width, Merge) \
281 unsigned Name : Width;
282 #include "CXXRecordDeclDefinitionBits.def"
283
284 /// Whether this class describes a C++ lambda.
285 unsigned IsLambda : 1;
286
287 /// Whether we are currently parsing base specifiers.
288 unsigned IsParsingBaseSpecifiers : 1;
289
290 /// True when visible conversion functions are already computed
291 /// and are available.
292 unsigned ComputedVisibleConversions : 1;
293
294 unsigned HasODRHash : 1;
295
296 /// A hash of parts of the class to help in ODR checking.
297 unsigned ODRHash = 0;
298
299 /// The number of base class specifiers in Bases.
300 unsigned NumBases = 0;
301
302 /// The number of virtual base class specifiers in VBases.
303 unsigned NumVBases = 0;
304
305 /// Base classes of this class.
306 ///
307 /// FIXME: This is wasted space for a union.
308 LazyCXXBaseSpecifiersPtr Bases;
309
310 /// direct and indirect virtual base classes of this class.
311 LazyCXXBaseSpecifiersPtr VBases;
312
313 /// The conversion functions of this C++ class (but not its
314 /// inherited conversion functions).
315 ///
316 /// Each of the entries in this overload set is a CXXConversionDecl.
317 LazyASTUnresolvedSet Conversions;
318
319 /// The conversion functions of this C++ class and all those
320 /// inherited conversion functions that are visible in this class.
321 ///
322 /// Each of the entries in this overload set is a CXXConversionDecl or a
323 /// FunctionTemplateDecl.
324 LazyASTUnresolvedSet VisibleConversions;
325
326 /// The declaration which defines this record.
327 CXXRecordDecl *Definition;
328
329 /// The first friend declaration in this class, or null if there
330 /// aren't any.
331 ///
332 /// This is actually currently stored in reverse order.
333 LazyDeclPtr FirstFriend;
334
335 DefinitionData(CXXRecordDecl *D);
336
337 /// Retrieve the set of direct base classes.
338 CXXBaseSpecifier *getBases() const {
339 if (!Bases.isOffset())
4
Assuming the condition is true
5
Taking true branch
340 return Bases.get(nullptr);
6
Passing null pointer value via 1st parameter 'Source'
7
Calling 'LazyOffsetPtr::get'
341 return getBasesSlowCase();
342 }
343
344 /// Retrieve the set of virtual base classes.
345 CXXBaseSpecifier *getVBases() const {
346 if (!VBases.isOffset())
347 return VBases.get(nullptr);
348 return getVBasesSlowCase();
349 }
350
351 ArrayRef<CXXBaseSpecifier> bases() const {
352 return llvm::makeArrayRef(getBases(), NumBases);
353 }
354
355 ArrayRef<CXXBaseSpecifier> vbases() const {
356 return llvm::makeArrayRef(getVBases(), NumVBases);
357 }
358
359 private:
360 CXXBaseSpecifier *getBasesSlowCase() const;
361 CXXBaseSpecifier *getVBasesSlowCase() const;
362 };
363
364 struct DefinitionData *DefinitionData;
365
366 /// Describes a C++ closure type (generated by a lambda expression).
367 struct LambdaDefinitionData : public DefinitionData {
368 using Capture = LambdaCapture;
369
370 /// Whether this lambda is known to be dependent, even if its
371 /// context isn't dependent.
372 ///
373 /// A lambda with a non-dependent context can be dependent if it occurs
374 /// within the default argument of a function template, because the
375 /// lambda will have been created with the enclosing context as its
376 /// declaration context, rather than function. This is an unfortunate
377 /// artifact of having to parse the default arguments before.
378 unsigned Dependent : 1;
379
380 /// Whether this lambda is a generic lambda.
381 unsigned IsGenericLambda : 1;
382
383 /// The Default Capture.
384 unsigned CaptureDefault : 2;
385
386 /// The number of captures in this lambda is limited 2^NumCaptures.
387 unsigned NumCaptures : 15;
388
389 /// The number of explicit captures in this lambda.
390 unsigned NumExplicitCaptures : 13;
391
392 /// Has known `internal` linkage.
393 unsigned HasKnownInternalLinkage : 1;
394
395 /// The number used to indicate this lambda expression for name
396 /// mangling in the Itanium C++ ABI.
397 unsigned ManglingNumber : 31;
398
399 /// The declaration that provides context for this lambda, if the
400 /// actual DeclContext does not suffice. This is used for lambdas that
401 /// occur within default arguments of function parameters within the class
402 /// or within a data member initializer.
403 LazyDeclPtr ContextDecl;
404
405 /// The list of captures, both explicit and implicit, for this
406 /// lambda.
407 Capture *Captures = nullptr;
408
409 /// The type of the call method.
410 TypeSourceInfo *MethodTyInfo;
411
412 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent,
413 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
414 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
415 CaptureDefault(CaptureDefault), NumCaptures(0),
416 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
417 MethodTyInfo(Info) {
418 IsLambda = true;
419
420 // C++1z [expr.prim.lambda]p4:
421 // This class type is not an aggregate type.
422 Aggregate = false;
423 PlainOldData = false;
424 }
425 };
426
427 struct DefinitionData *dataPtr() const {
428 // Complete the redecl chain (if necessary).
429 getMostRecentDecl();
430 return DefinitionData;
431 }
432
433 struct DefinitionData &data() const {
434 auto *DD = dataPtr();
435 assert(DD && "queried property of class with no definition")((void)0);
436 return *DD;
437 }
438
439 struct LambdaDefinitionData &getLambdaData() const {
440 // No update required: a merged definition cannot change any lambda
441 // properties.
442 auto *DD = DefinitionData;
443 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")((void)0);
444 return static_cast<LambdaDefinitionData&>(*DD);
445 }
446
447 /// The template or declaration that this declaration
448 /// describes or was instantiated from, respectively.
449 ///
450 /// For non-templates, this value will be null. For record
451 /// declarations that describe a class template, this will be a
452 /// pointer to a ClassTemplateDecl. For member
453 /// classes of class template specializations, this will be the
454 /// MemberSpecializationInfo referring to the member class that was
455 /// instantiated or specialized.
456 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
457 TemplateOrInstantiation;
458
459 /// Called from setBases and addedMember to notify the class that a
460 /// direct or virtual base class or a member of class type has been added.
461 void addedClassSubobject(CXXRecordDecl *Base);
462
463 /// Notify the class that member has been added.
464 ///
465 /// This routine helps maintain information about the class based on which
466 /// members have been added. It will be invoked by DeclContext::addDecl()
467 /// whenever a member is added to this record.
468 void addedMember(Decl *D);
469
470 void markedVirtualFunctionPure();
471
472 /// Get the head of our list of friend declarations, possibly
473 /// deserializing the friends from an external AST source.
474 FriendDecl *getFirstFriend() const;
475
476 /// Determine whether this class has an empty base class subobject of type X
477 /// or of one of the types that might be at offset 0 within X (per the C++
478 /// "standard layout" rules).
479 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
480 const CXXRecordDecl *X);
481
482protected:
483 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
484 SourceLocation StartLoc, SourceLocation IdLoc,
485 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
486
487public:
488 /// Iterator that traverses the base classes of a class.
489 using base_class_iterator = CXXBaseSpecifier *;
490
491 /// Iterator that traverses the base classes of a class.
492 using base_class_const_iterator = const CXXBaseSpecifier *;
493
494 CXXRecordDecl *getCanonicalDecl() override {
495 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
496 }
497
498 const CXXRecordDecl *getCanonicalDecl() const {
499 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
500 }
501
502 CXXRecordDecl *getPreviousDecl() {
503 return cast_or_null<CXXRecordDecl>(
504 static_cast<RecordDecl *>(this)->getPreviousDecl());
505 }
506
507 const CXXRecordDecl *getPreviousDecl() const {
508 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
509 }
510
511 CXXRecordDecl *getMostRecentDecl() {
512 return cast<CXXRecordDecl>(
513 static_cast<RecordDecl *>(this)->getMostRecentDecl());
514 }
515
516 const CXXRecordDecl *getMostRecentDecl() const {
517 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
518 }
519
520 CXXRecordDecl *getMostRecentNonInjectedDecl() {
521 CXXRecordDecl *Recent =
522 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
523 while (Recent->isInjectedClassName()) {
524 // FIXME: Does injected class name need to be in the redeclarations chain?
525 assert(Recent->getPreviousDecl())((void)0);
526 Recent = Recent->getPreviousDecl();
527 }
528 return Recent;
529 }
530
531 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
532 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
533 }
534
535 CXXRecordDecl *getDefinition() const {
536 // We only need an update if we don't already know which
537 // declaration is the definition.
538 auto *DD = DefinitionData ? DefinitionData : dataPtr();
539 return DD ? DD->Definition : nullptr;
540 }
541
542 bool hasDefinition() const { return DefinitionData || dataPtr(); }
543
544 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
545 SourceLocation StartLoc, SourceLocation IdLoc,
546 IdentifierInfo *Id,
547 CXXRecordDecl *PrevDecl = nullptr,
548 bool DelayTypeCreation = false);
549 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
550 TypeSourceInfo *Info, SourceLocation Loc,
551 bool DependentLambda, bool IsGeneric,
552 LambdaCaptureDefault CaptureDefault);
553 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
554
555 bool isDynamicClass() const {
556 return data().Polymorphic || data().NumVBases != 0;
557 }
558
559 /// @returns true if class is dynamic or might be dynamic because the
560 /// definition is incomplete of dependent.
561 bool mayBeDynamicClass() const {
562 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
563 }
564
565 /// @returns true if class is non dynamic or might be non dynamic because the
566 /// definition is incomplete of dependent.
567 bool mayBeNonDynamicClass() const {
568 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
569 }
570
571 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
572
573 bool isParsingBaseSpecifiers() const {
574 return data().IsParsingBaseSpecifiers;
575 }
576
577 unsigned getODRHash() const;
578
579 /// Sets the base classes of this struct or class.
580 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
581
582 /// Retrieves the number of base classes of this class.
583 unsigned getNumBases() const { return data().NumBases; }
584
585 using base_class_range = llvm::iterator_range<base_class_iterator>;
586 using base_class_const_range =
587 llvm::iterator_range<base_class_const_iterator>;
588
589 base_class_range bases() {
590 return base_class_range(bases_begin(), bases_end());
591 }
592 base_class_const_range bases() const {
593 return base_class_const_range(bases_begin(), bases_end());
594 }
595
596 base_class_iterator bases_begin() { return data().getBases(); }
597 base_class_const_iterator bases_begin() const { return data().getBases(); }
3
Calling 'DefinitionData::getBases'
598 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
599 base_class_const_iterator bases_end() const {
600 return bases_begin() + data().NumBases;
2
Calling 'CXXRecordDecl::bases_begin'
601 }
602
603 /// Retrieves the number of virtual base classes of this class.
604 unsigned getNumVBases() const { return data().NumVBases; }
605
606 base_class_range vbases() {
607 return base_class_range(vbases_begin(), vbases_end());
608 }
609 base_class_const_range vbases() const {
610 return base_class_const_range(vbases_begin(), vbases_end());
611 }
612
613 base_class_iterator vbases_begin() { return data().getVBases(); }
614 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
615 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
616 base_class_const_iterator vbases_end() const {
617 return vbases_begin() + data().NumVBases;
618 }
619
620 /// Determine whether this class has any dependent base classes which
621 /// are not the current instantiation.
622 bool hasAnyDependentBases() const;
623
624 /// Iterator access to method members. The method iterator visits
625 /// all method members of the class, including non-instance methods,
626 /// special methods, etc.
627 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
628 using method_range =
629 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
630
631 method_range methods() const {
632 return method_range(method_begin(), method_end());
633 }
634
635 /// Method begin iterator. Iterates in the order the methods
636 /// were declared.
637 method_iterator method_begin() const {
638 return method_iterator(decls_begin());
639 }
640
641 /// Method past-the-end iterator.
642 method_iterator method_end() const {
643 return method_iterator(decls_end());
644 }
645
646 /// Iterator access to constructor members.
647 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
648 using ctor_range =
649 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
650
651 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
652
653 ctor_iterator ctor_begin() const {
654 return ctor_iterator(decls_begin());
655 }
656
657 ctor_iterator ctor_end() const {
658 return ctor_iterator(decls_end());
659 }
660
661 /// An iterator over friend declarations. All of these are defined
662 /// in DeclFriend.h.
663 class friend_iterator;
664 using friend_range = llvm::iterator_range<friend_iterator>;
665
666 friend_range friends() const;
667 friend_iterator friend_begin() const;
668 friend_iterator friend_end() const;
669 void pushFriendDecl(FriendDecl *FD);
670
671 /// Determines whether this record has any friends.
672 bool hasFriends() const {
673 return data().FirstFriend.isValid();
674 }
675
676 /// \c true if a defaulted copy constructor for this class would be
677 /// deleted.
678 bool defaultedCopyConstructorIsDeleted() const {
679 assert((!needsOverloadResolutionForCopyConstructor() ||((void)0)
680 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&((void)0)
681 "this property has not yet been computed by Sema")((void)0);
682 return data().DefaultedCopyConstructorIsDeleted;
683 }
684
685 /// \c true if a defaulted move constructor for this class would be
686 /// deleted.
687 bool defaultedMoveConstructorIsDeleted() const {
688 assert((!needsOverloadResolutionForMoveConstructor() ||((void)0)
689 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&((void)0)
690 "this property has not yet been computed by Sema")((void)0);
691 return data().DefaultedMoveConstructorIsDeleted;
692 }
693
694 /// \c true if a defaulted destructor for this class would be deleted.
695 bool defaultedDestructorIsDeleted() const {
696 assert((!needsOverloadResolutionForDestructor() ||((void)0)
697 (data().DeclaredSpecialMembers & SMF_Destructor)) &&((void)0)
698 "this property has not yet been computed by Sema")((void)0);
699 return data().DefaultedDestructorIsDeleted;
700 }
701
702 /// \c true if we know for sure that this class has a single,
703 /// accessible, unambiguous copy constructor that is not deleted.
704 bool hasSimpleCopyConstructor() const {
705 return !hasUserDeclaredCopyConstructor() &&
706 !data().DefaultedCopyConstructorIsDeleted;
707 }
708
709 /// \c true if we know for sure that this class has a single,
710 /// accessible, unambiguous move constructor that is not deleted.
711 bool hasSimpleMoveConstructor() const {
712 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
713 !data().DefaultedMoveConstructorIsDeleted;
714 }
715
716 /// \c true if we know for sure that this class has a single,
717 /// accessible, unambiguous copy assignment operator that is not deleted.
718 bool hasSimpleCopyAssignment() const {
719 return !hasUserDeclaredCopyAssignment() &&
720 !data().DefaultedCopyAssignmentIsDeleted;
721 }
722
723 /// \c true if we know for sure that this class has a single,
724 /// accessible, unambiguous move assignment operator that is not deleted.
725 bool hasSimpleMoveAssignment() const {
726 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
727 !data().DefaultedMoveAssignmentIsDeleted;
728 }
729
730 /// \c true if we know for sure that this class has an accessible
731 /// destructor that is not deleted.
732 bool hasSimpleDestructor() const {
733 return !hasUserDeclaredDestructor() &&
734 !data().DefaultedDestructorIsDeleted;
735 }
736
737 /// Determine whether this class has any default constructors.
738 bool hasDefaultConstructor() const {
739 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
740 needsImplicitDefaultConstructor();
741 }
742
743 /// Determine if we need to declare a default constructor for
744 /// this class.
745 ///
746 /// This value is used for lazy creation of default constructors.
747 bool needsImplicitDefaultConstructor() const {
748 return (!data().UserDeclaredConstructor &&
749 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
750 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable())) ||
751 // FIXME: Proposed fix to core wording issue: if a class inherits
752 // a default constructor and doesn't explicitly declare one, one
753 // is declared implicitly.
754 (data().HasInheritedDefaultConstructor &&
755 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor));
756 }
757
758 /// Determine whether this class has any user-declared constructors.
759 ///
760 /// When true, a default constructor will not be implicitly declared.
761 bool hasUserDeclaredConstructor() const {
762 return data().UserDeclaredConstructor;
763 }
764
765 /// Whether this class has a user-provided default constructor
766 /// per C++11.
767 bool hasUserProvidedDefaultConstructor() const {
768 return data().UserProvidedDefaultConstructor;
769 }
770
771 /// Determine whether this class has a user-declared copy constructor.
772 ///
773 /// When false, a copy constructor will be implicitly declared.
774 bool hasUserDeclaredCopyConstructor() const {
775 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
776 }
777
778 /// Determine whether this class needs an implicit copy
779 /// constructor to be lazily declared.
780 bool needsImplicitCopyConstructor() const {
781 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
782 }
783
784 /// Determine whether we need to eagerly declare a defaulted copy
785 /// constructor for this class.
786 bool needsOverloadResolutionForCopyConstructor() const {
787 // C++17 [class.copy.ctor]p6:
788 // If the class definition declares a move constructor or move assignment
789 // operator, the implicitly declared copy constructor is defined as
790 // deleted.
791 // In MSVC mode, sometimes a declared move assignment does not delete an
792 // implicit copy constructor, so defer this choice to Sema.
793 if (data().UserDeclaredSpecialMembers &
794 (SMF_MoveConstructor | SMF_MoveAssignment))
795 return true;
796 return data().NeedOverloadResolutionForCopyConstructor;
797 }
798
799 /// Determine whether an implicit copy constructor for this type
800 /// would have a parameter with a const-qualified reference type.
801 bool implicitCopyConstructorHasConstParam() const {
802 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
803 (isAbstract() ||
804 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
805 }
806
807 /// Determine whether this class has a copy constructor with
808 /// a parameter type which is a reference to a const-qualified type.
809 bool hasCopyConstructorWithConstParam() const {
810 return data().HasDeclaredCopyConstructorWithConstParam ||
811 (needsImplicitCopyConstructor() &&
812 implicitCopyConstructorHasConstParam());
813 }
814
815 /// Whether this class has a user-declared move constructor or
816 /// assignment operator.
817 ///
818 /// When false, a move constructor and assignment operator may be
819 /// implicitly declared.
820 bool hasUserDeclaredMoveOperation() const {
821 return data().UserDeclaredSpecialMembers &
822 (SMF_MoveConstructor | SMF_MoveAssignment);
823 }
824
825 /// Determine whether this class has had a move constructor
826 /// declared by the user.
827 bool hasUserDeclaredMoveConstructor() const {
828 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
829 }
830
831 /// Determine whether this class has a move constructor.
832 bool hasMoveConstructor() const {
833 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
834 needsImplicitMoveConstructor();
835 }
836
837 /// Set that we attempted to declare an implicit copy
838 /// constructor, but overload resolution failed so we deleted it.
839 void setImplicitCopyConstructorIsDeleted() {
840 assert((data().DefaultedCopyConstructorIsDeleted ||((void)0)
841 needsOverloadResolutionForCopyConstructor()) &&((void)0)
842 "Copy constructor should not be deleted")((void)0);
843 data().DefaultedCopyConstructorIsDeleted = true;
844 }
845
846 /// Set that we attempted to declare an implicit move
847 /// constructor, but overload resolution failed so we deleted it.
848 void setImplicitMoveConstructorIsDeleted() {
849 assert((data().DefaultedMoveConstructorIsDeleted ||((void)0)
850 needsOverloadResolutionForMoveConstructor()) &&((void)0)
851 "move constructor should not be deleted")((void)0);
852 data().DefaultedMoveConstructorIsDeleted = true;
853 }
854
855 /// Set that we attempted to declare an implicit destructor,
856 /// but overload resolution failed so we deleted it.
857 void setImplicitDestructorIsDeleted() {
858 assert((data().DefaultedDestructorIsDeleted ||((void)0)
859 needsOverloadResolutionForDestructor()) &&((void)0)
860 "destructor should not be deleted")((void)0);
861 data().DefaultedDestructorIsDeleted = true;
862 }
863
864 /// Determine whether this class should get an implicit move
865 /// constructor or if any existing special member function inhibits this.
866 bool needsImplicitMoveConstructor() const {
867 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
868 !hasUserDeclaredCopyConstructor() &&
869 !hasUserDeclaredCopyAssignment() &&
870 !hasUserDeclaredMoveAssignment() &&
871 !hasUserDeclaredDestructor();
872 }
873
874 /// Determine whether we need to eagerly declare a defaulted move
875 /// constructor for this class.
876 bool needsOverloadResolutionForMoveConstructor() const {
877 return data().NeedOverloadResolutionForMoveConstructor;
878 }
879
880 /// Determine whether this class has a user-declared copy assignment
881 /// operator.
882 ///
883 /// When false, a copy assignment operator will be implicitly declared.
884 bool hasUserDeclaredCopyAssignment() const {
885 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
886 }
887
888 /// Set that we attempted to declare an implicit copy assignment
889 /// operator, but overload resolution failed so we deleted it.
890 void setImplicitCopyAssignmentIsDeleted() {
891 assert((data().DefaultedCopyAssignmentIsDeleted ||((void)0)
892 needsOverloadResolutionForCopyAssignment()) &&((void)0)
893 "copy assignment should not be deleted")((void)0);
894 data().DefaultedCopyAssignmentIsDeleted = true;
895 }
896
897 /// Determine whether this class needs an implicit copy
898 /// assignment operator to be lazily declared.
899 bool needsImplicitCopyAssignment() const {
900 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
901 }
902
903 /// Determine whether we need to eagerly declare a defaulted copy
904 /// assignment operator for this class.
905 bool needsOverloadResolutionForCopyAssignment() const {
906 // C++20 [class.copy.assign]p2:
907 // If the class definition declares a move constructor or move assignment
908 // operator, the implicitly declared copy assignment operator is defined
909 // as deleted.
910 // In MSVC mode, sometimes a declared move constructor does not delete an
911 // implicit copy assignment, so defer this choice to Sema.
912 if (data().UserDeclaredSpecialMembers &
913 (SMF_MoveConstructor | SMF_MoveAssignment))
914 return true;
915 return data().NeedOverloadResolutionForCopyAssignment;
916 }
917
918 /// Determine whether an implicit copy assignment operator for this
919 /// type would have a parameter with a const-qualified reference type.
920 bool implicitCopyAssignmentHasConstParam() const {
921 return data().ImplicitCopyAssignmentHasConstParam;
922 }
923
924 /// Determine whether this class has a copy assignment operator with
925 /// a parameter type which is a reference to a const-qualified type or is not
926 /// a reference.
927 bool hasCopyAssignmentWithConstParam() const {
928 return data().HasDeclaredCopyAssignmentWithConstParam ||
929 (needsImplicitCopyAssignment() &&
930 implicitCopyAssignmentHasConstParam());
931 }
932
933 /// Determine whether this class has had a move assignment
934 /// declared by the user.
935 bool hasUserDeclaredMoveAssignment() const {
936 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
937 }
938
939 /// Determine whether this class has a move assignment operator.
940 bool hasMoveAssignment() const {
941 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
942 needsImplicitMoveAssignment();
943 }
944
945 /// Set that we attempted to declare an implicit move assignment
946 /// operator, but overload resolution failed so we deleted it.
947 void setImplicitMoveAssignmentIsDeleted() {
948 assert((data().DefaultedMoveAssignmentIsDeleted ||((void)0)
949 needsOverloadResolutionForMoveAssignment()) &&((void)0)
950 "move assignment should not be deleted")((void)0);
951 data().DefaultedMoveAssignmentIsDeleted = true;
952 }
953
954 /// Determine whether this class should get an implicit move
955 /// assignment operator or if any existing special member function inhibits
956 /// this.
957 bool needsImplicitMoveAssignment() const {
958 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
959 !hasUserDeclaredCopyConstructor() &&
960 !hasUserDeclaredCopyAssignment() &&
961 !hasUserDeclaredMoveConstructor() &&
962 !hasUserDeclaredDestructor() &&
963 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
964 }
965
966 /// Determine whether we need to eagerly declare a move assignment
967 /// operator for this class.
968 bool needsOverloadResolutionForMoveAssignment() const {
969 return data().NeedOverloadResolutionForMoveAssignment;
970 }
971
972 /// Determine whether this class has a user-declared destructor.
973 ///
974 /// When false, a destructor will be implicitly declared.
975 bool hasUserDeclaredDestructor() const {
976 return data().UserDeclaredSpecialMembers & SMF_Destructor;
977 }
978
979 /// Determine whether this class needs an implicit destructor to
980 /// be lazily declared.
981 bool needsImplicitDestructor() const {
982 return !(data().DeclaredSpecialMembers & SMF_Destructor);
983 }
984
985 /// Determine whether we need to eagerly declare a destructor for this
986 /// class.
987 bool needsOverloadResolutionForDestructor() const {
988 return data().NeedOverloadResolutionForDestructor;
989 }
990
991 /// Determine whether this class describes a lambda function object.
992 bool isLambda() const {
993 // An update record can't turn a non-lambda into a lambda.
994 auto *DD = DefinitionData;
995 return DD && DD->IsLambda;
996 }
997
998 /// Determine whether this class describes a generic
999 /// lambda function object (i.e. function call operator is
1000 /// a template).
1001 bool isGenericLambda() const;
1002
1003 /// Determine whether this lambda should have an implicit default constructor
1004 /// and copy and move assignment operators.
1005 bool lambdaIsDefaultConstructibleAndAssignable() const;
1006
1007 /// Retrieve the lambda call operator of the closure type
1008 /// if this is a closure type.
1009 CXXMethodDecl *getLambdaCallOperator() const;
1010
1011 /// Retrieve the dependent lambda call operator of the closure type
1012 /// if this is a templated closure type.
1013 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1014
1015 /// Retrieve the lambda static invoker, the address of which
1016 /// is returned by the conversion operator, and the body of which
1017 /// is forwarded to the lambda call operator. The version that does not
1018 /// take a calling convention uses the 'default' calling convention for free
1019 /// functions if the Lambda's calling convention was not modified via
1020 /// attribute. Otherwise, it will return the calling convention specified for
1021 /// the lambda.
1022 CXXMethodDecl *getLambdaStaticInvoker() const;
1023 CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1024
1025 /// Retrieve the generic lambda's template parameter list.
1026 /// Returns null if the class does not represent a lambda or a generic
1027 /// lambda.
1028 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1029
1030 /// Retrieve the lambda template parameters that were specified explicitly.
1031 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1032
1033 LambdaCaptureDefault getLambdaCaptureDefault() const {
1034 assert(isLambda())((void)0);
1035 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1036 }
1037
1038 /// Set the captures for this lambda closure type.
1039 void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1040
1041 /// For a closure type, retrieve the mapping from captured
1042 /// variables and \c this to the non-static data members that store the
1043 /// values or references of the captures.
1044 ///
1045 /// \param Captures Will be populated with the mapping from captured
1046 /// variables to the corresponding fields.
1047 ///
1048 /// \param ThisCapture Will be set to the field declaration for the
1049 /// \c this capture.
1050 ///
1051 /// \note No entries will be added for init-captures, as they do not capture
1052 /// variables.
1053 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1054 FieldDecl *&ThisCapture) const;
1055
1056 using capture_const_iterator = const LambdaCapture *;
1057 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1058
1059 capture_const_range captures() const {
1060 return capture_const_range(captures_begin(), captures_end());
1061 }
1062
1063 capture_const_iterator captures_begin() const {
1064 return isLambda() ? getLambdaData().Captures : nullptr;
1065 }
1066
1067 capture_const_iterator captures_end() const {
1068 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1069 : nullptr;
1070 }
1071
1072 unsigned capture_size() const { return getLambdaData().NumCaptures; }
1073
1074 using conversion_iterator = UnresolvedSetIterator;
1075
1076 conversion_iterator conversion_begin() const {
1077 return data().Conversions.get(getASTContext()).begin();
1078 }
1079
1080 conversion_iterator conversion_end() const {
1081 return data().Conversions.get(getASTContext()).end();
1082 }
1083
1084 /// Removes a conversion function from this class. The conversion
1085 /// function must currently be a member of this class. Furthermore,
1086 /// this class must currently be in the process of being defined.
1087 void removeConversion(const NamedDecl *Old);
1088
1089 /// Get all conversion functions visible in current class,
1090 /// including conversion function templates.
1091 llvm::iterator_range<conversion_iterator>
1092 getVisibleConversionFunctions() const;
1093
1094 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1095 /// which is a class with no user-declared constructors, no private
1096 /// or protected non-static data members, no base classes, and no virtual
1097 /// functions (C++ [dcl.init.aggr]p1).
1098 bool isAggregate() const { return data().Aggregate; }
1099
1100 /// Whether this class has any in-class initializers
1101 /// for non-static data members (including those in anonymous unions or
1102 /// structs).
1103 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1104
1105 /// Whether this class or any of its subobjects has any members of
1106 /// reference type which would make value-initialization ill-formed.
1107 ///
1108 /// Per C++03 [dcl.init]p5:
1109 /// - if T is a non-union class type without a user-declared constructor,
1110 /// then every non-static data member and base-class component of T is
1111 /// value-initialized [...] A program that calls for [...]
1112 /// value-initialization of an entity of reference type is ill-formed.
1113 bool hasUninitializedReferenceMember() const {
1114 return !isUnion() && !hasUserDeclaredConstructor() &&
1115 data().HasUninitializedReferenceMember;
1116 }
1117
1118 /// Whether this class is a POD-type (C++ [class]p4)
1119 ///
1120 /// For purposes of this function a class is POD if it is an aggregate
1121 /// that has no non-static non-POD data members, no reference data
1122 /// members, no user-defined copy assignment operator and no
1123 /// user-defined destructor.
1124 ///
1125 /// Note that this is the C++ TR1 definition of POD.
1126 bool isPOD() const { return data().PlainOldData; }
1127
1128 /// True if this class is C-like, without C++-specific features, e.g.
1129 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1130 bool isCLike() const;
1131
1132 /// Determine whether this is an empty class in the sense of
1133 /// (C++11 [meta.unary.prop]).
1134 ///
1135 /// The CXXRecordDecl is a class type, but not a union type,
1136 /// with no non-static data members other than bit-fields of length 0,
1137 /// no virtual member functions, no virtual base classes,
1138 /// and no base class B for which is_empty<B>::value is false.
1139 ///
1140 /// \note This does NOT include a check for union-ness.
1141 bool isEmpty() const { return data().Empty; }
1142
1143 bool hasPrivateFields() const {
1144 return data().HasPrivateFields;
1145 }
1146
1147 bool hasProtectedFields() const {
1148 return data().HasProtectedFields;
1149 }
1150
1151 /// Determine whether this class has direct non-static data members.
1152 bool hasDirectFields() const {
1153 auto &D = data();
1154 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1155 }
1156
1157 /// Whether this class is polymorphic (C++ [class.virtual]),
1158 /// which means that the class contains or inherits a virtual function.
1159 bool isPolymorphic() const { return data().Polymorphic; }
1160
1161 /// Determine whether this class has a pure virtual function.
1162 ///
1163 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1164 /// a pure virtual function or inherits a pure virtual function that is
1165 /// not overridden.
1166 bool isAbstract() const { return data().Abstract; }
1167
1168 /// Determine whether this class is standard-layout per
1169 /// C++ [class]p7.
1170 bool isStandardLayout() const { return data().IsStandardLayout; }
1171
1172 /// Determine whether this class was standard-layout per
1173 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1174 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1175
1176 /// Determine whether this class, or any of its class subobjects,
1177 /// contains a mutable field.
1178 bool hasMutableFields() const { return data().HasMutableFields; }
1179
1180 /// Determine whether this class has any variant members.
1181 bool hasVariantMembers() const { return data().HasVariantMembers; }
1182
1183 /// Determine whether this class has a trivial default constructor
1184 /// (C++11 [class.ctor]p5).
1185 bool hasTrivialDefaultConstructor() const {
1186 return hasDefaultConstructor() &&
1187 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1188 }
1189
1190 /// Determine whether this class has a non-trivial default constructor
1191 /// (C++11 [class.ctor]p5).
1192 bool hasNonTrivialDefaultConstructor() const {
1193 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1194 (needsImplicitDefaultConstructor() &&
1195 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1196 }
1197
1198 /// Determine whether this class has at least one constexpr constructor
1199 /// other than the copy or move constructors.
1200 bool hasConstexprNonCopyMoveConstructor() const {
1201 return data().HasConstexprNonCopyMoveConstructor ||
1202 (needsImplicitDefaultConstructor() &&
1203 defaultedDefaultConstructorIsConstexpr());
1204 }
1205
1206 /// Determine whether a defaulted default constructor for this class
1207 /// would be constexpr.
1208 bool defaultedDefaultConstructorIsConstexpr() const {
1209 return data().DefaultedDefaultConstructorIsConstexpr &&
1210 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1211 getLangOpts().CPlusPlus20);
1212 }
1213
1214 /// Determine whether this class has a constexpr default constructor.
1215 bool hasConstexprDefaultConstructor() const {
1216 return data().HasConstexprDefaultConstructor ||
1217 (needsImplicitDefaultConstructor() &&
1218 defaultedDefaultConstructorIsConstexpr());
1219 }
1220
1221 /// Determine whether this class has a trivial copy constructor
1222 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1223 bool hasTrivialCopyConstructor() const {
1224 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1225 }
1226
1227 bool hasTrivialCopyConstructorForCall() const {
1228 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1229 }
1230
1231 /// Determine whether this class has a non-trivial copy constructor
1232 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1233 bool hasNonTrivialCopyConstructor() const {
1234 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1235 !hasTrivialCopyConstructor();
1236 }
1237
1238 bool hasNonTrivialCopyConstructorForCall() const {
1239 return (data().DeclaredNonTrivialSpecialMembersForCall &
1240 SMF_CopyConstructor) ||
1241 !hasTrivialCopyConstructorForCall();
1242 }
1243
1244 /// Determine whether this class has a trivial move constructor
1245 /// (C++11 [class.copy]p12)
1246 bool hasTrivialMoveConstructor() const {
1247 return hasMoveConstructor() &&
1248 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1249 }
1250
1251 bool hasTrivialMoveConstructorForCall() const {
1252 return hasMoveConstructor() &&
1253 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1254 }
1255
1256 /// Determine whether this class has a non-trivial move constructor
1257 /// (C++11 [class.copy]p12)
1258 bool hasNonTrivialMoveConstructor() const {
1259 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1260 (needsImplicitMoveConstructor() &&
1261 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1262 }
1263
1264 bool hasNonTrivialMoveConstructorForCall() const {
1265 return (data().DeclaredNonTrivialSpecialMembersForCall &
1266 SMF_MoveConstructor) ||
1267 (needsImplicitMoveConstructor() &&
1268 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1269 }
1270
1271 /// Determine whether this class has a trivial copy assignment operator
1272 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1273 bool hasTrivialCopyAssignment() const {
1274 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1275 }
1276
1277 /// Determine whether this class has a non-trivial copy assignment
1278 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1279 bool hasNonTrivialCopyAssignment() const {
1280 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1281 !hasTrivialCopyAssignment();
1282 }
1283
1284 /// Determine whether this class has a trivial move assignment operator
1285 /// (C++11 [class.copy]p25)
1286 bool hasTrivialMoveAssignment() const {
1287 return hasMoveAssignment() &&
1288 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1289 }
1290
1291 /// Determine whether this class has a non-trivial move assignment
1292 /// operator (C++11 [class.copy]p25)
1293 bool hasNonTrivialMoveAssignment() const {
1294 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1295 (needsImplicitMoveAssignment() &&
1296 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1297 }
1298
1299 /// Determine whether a defaulted default constructor for this class
1300 /// would be constexpr.
1301 bool defaultedDestructorIsConstexpr() const {
1302 return data().DefaultedDestructorIsConstexpr &&
1303 getLangOpts().CPlusPlus20;
1304 }
1305
1306 /// Determine whether this class has a constexpr destructor.
1307 bool hasConstexprDestructor() const;
1308
1309 /// Determine whether this class has a trivial destructor
1310 /// (C++ [class.dtor]p3)
1311 bool hasTrivialDestructor() const {
1312 return data().HasTrivialSpecialMembers & SMF_Destructor;
1313 }
1314
1315 bool hasTrivialDestructorForCall() const {
1316 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1317 }
1318
1319 /// Determine whether this class has a non-trivial destructor
1320 /// (C++ [class.dtor]p3)
1321 bool hasNonTrivialDestructor() const {
1322 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1323 }
1324
1325 bool hasNonTrivialDestructorForCall() const {
1326 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1327 }
1328
1329 void setHasTrivialSpecialMemberForCall() {
1330 data().HasTrivialSpecialMembersForCall =
1331 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1332 }
1333
1334 /// Determine whether declaring a const variable with this type is ok
1335 /// per core issue 253.
1336 bool allowConstDefaultInit() const {
1337 return !data().HasUninitializedFields ||
1338 !(data().HasDefaultedDefaultConstructor ||
1339 needsImplicitDefaultConstructor());
1340 }
1341
1342 /// Determine whether this class has a destructor which has no
1343 /// semantic effect.
1344 ///
1345 /// Any such destructor will be trivial, public, defaulted and not deleted,
1346 /// and will call only irrelevant destructors.
1347 bool hasIrrelevantDestructor() const {
1348 return data().HasIrrelevantDestructor;
1349 }
1350
1351 /// Determine whether this class has a non-literal or/ volatile type
1352 /// non-static data member or base class.
1353 bool hasNonLiteralTypeFieldsOrBases() const {
1354 return data().HasNonLiteralTypeFieldsOrBases;
1355 }
1356
1357 /// Determine whether this class has a using-declaration that names
1358 /// a user-declared base class constructor.
1359 bool hasInheritedConstructor() const {
1360 return data().HasInheritedConstructor;
1361 }
1362
1363 /// Determine whether this class has a using-declaration that names
1364 /// a base class assignment operator.
1365 bool hasInheritedAssignment() const {
1366 return data().HasInheritedAssignment;
1367 }
1368
1369 /// Determine whether this class is considered trivially copyable per
1370 /// (C++11 [class]p6).
1371 bool isTriviallyCopyable() const;
1372
1373 /// Determine whether this class is considered trivial.
1374 ///
1375 /// C++11 [class]p6:
1376 /// "A trivial class is a class that has a trivial default constructor and
1377 /// is trivially copyable."
1378 bool isTrivial() const {
1379 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1380 }
1381
1382 /// Determine whether this class is a literal type.
1383 ///
1384 /// C++11 [basic.types]p10:
1385 /// A class type that has all the following properties:
1386 /// - it has a trivial destructor
1387 /// - every constructor call and full-expression in the
1388 /// brace-or-equal-intializers for non-static data members (if any) is
1389 /// a constant expression.
1390 /// - it is an aggregate type or has at least one constexpr constructor
1391 /// or constructor template that is not a copy or move constructor, and
1392 /// - all of its non-static data members and base classes are of literal
1393 /// types
1394 ///
1395 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1396 /// treating types with trivial default constructors as literal types.
1397 ///
1398 /// Only in C++17 and beyond, are lambdas literal types.
1399 bool isLiteral() const {
1400 const LangOptions &LangOpts = getLangOpts();
1401 return (LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1402 : hasTrivialDestructor()) &&
1403 (!isLambda() || LangOpts.CPlusPlus17) &&
1404 !hasNonLiteralTypeFieldsOrBases() &&
1405 (isAggregate() || isLambda() ||
1406 hasConstexprNonCopyMoveConstructor() ||
1407 hasTrivialDefaultConstructor());
1408 }
1409
1410 /// Determine whether this is a structural type.
1411 bool isStructural() const {
1412 return isLiteral() && data().StructuralIfLiteral;
1413 }
1414
1415 /// If this record is an instantiation of a member class,
1416 /// retrieves the member class from which it was instantiated.
1417 ///
1418 /// This routine will return non-null for (non-templated) member
1419 /// classes of class templates. For example, given:
1420 ///
1421 /// \code
1422 /// template<typename T>
1423 /// struct X {
1424 /// struct A { };
1425 /// };
1426 /// \endcode
1427 ///
1428 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1429 /// whose parent is the class template specialization X<int>. For
1430 /// this declaration, getInstantiatedFromMemberClass() will return
1431 /// the CXXRecordDecl X<T>::A. When a complete definition of
1432 /// X<int>::A is required, it will be instantiated from the
1433 /// declaration returned by getInstantiatedFromMemberClass().
1434 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1435
1436 /// If this class is an instantiation of a member class of a
1437 /// class template specialization, retrieves the member specialization
1438 /// information.
1439 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1440
1441 /// Specify that this record is an instantiation of the
1442 /// member class \p RD.
1443 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1444 TemplateSpecializationKind TSK);
1445
1446 /// Retrieves the class template that is described by this
1447 /// class declaration.
1448 ///
1449 /// Every class template is represented as a ClassTemplateDecl and a
1450 /// CXXRecordDecl. The former contains template properties (such as
1451 /// the template parameter lists) while the latter contains the
1452 /// actual description of the template's
1453 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1454 /// CXXRecordDecl that from a ClassTemplateDecl, while
1455 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1456 /// a CXXRecordDecl.
1457 ClassTemplateDecl *getDescribedClassTemplate() const;
1458
1459 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1460
1461 /// Determine whether this particular class is a specialization or
1462 /// instantiation of a class template or member class of a class template,
1463 /// and how it was instantiated or specialized.
1464 TemplateSpecializationKind getTemplateSpecializationKind() const;
1465
1466 /// Set the kind of specialization or template instantiation this is.
1467 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1468
1469 /// Retrieve the record declaration from which this record could be
1470 /// instantiated. Returns null if this class is not a template instantiation.
1471 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1472
1473 CXXRecordDecl *getTemplateInstantiationPattern() {
1474 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1475 ->getTemplateInstantiationPattern());
1476 }
1477
1478 /// Returns the destructor decl for this class.
1479 CXXDestructorDecl *getDestructor() const;
1480
1481 /// Returns true if the class destructor, or any implicitly invoked
1482 /// destructors are marked noreturn.
1483 bool isAnyDestructorNoReturn() const { return data().IsAnyDestructorNoReturn; }
1484
1485 /// If the class is a local class [class.local], returns
1486 /// the enclosing function declaration.
1487 const FunctionDecl *isLocalClass() const {
1488 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1489 return RD->isLocalClass();
1490
1491 return dyn_cast<FunctionDecl>(getDeclContext());
1492 }
1493
1494 FunctionDecl *isLocalClass() {
1495 return const_cast<FunctionDecl*>(
1496 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1497 }
1498
1499 /// Determine whether this dependent class is a current instantiation,
1500 /// when viewed from within the given context.
1501 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1502
1503 /// Determine whether this class is derived from the class \p Base.
1504 ///
1505 /// This routine only determines whether this class is derived from \p Base,
1506 /// but does not account for factors that may make a Derived -> Base class
1507 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1508 /// base class subobjects.
1509 ///
1510 /// \param Base the base class we are searching for.
1511 ///
1512 /// \returns true if this class is derived from Base, false otherwise.
1513 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1514
1515 /// Determine whether this class is derived from the type \p Base.
1516 ///
1517 /// This routine only determines whether this class is derived from \p Base,
1518 /// but does not account for factors that may make a Derived -> Base class
1519 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1520 /// base class subobjects.
1521 ///
1522 /// \param Base the base class we are searching for.
1523 ///
1524 /// \param Paths will contain the paths taken from the current class to the
1525 /// given \p Base class.
1526 ///
1527 /// \returns true if this class is derived from \p Base, false otherwise.
1528 ///
1529 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1530 /// tangling input and output in \p Paths
1531 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1532
1533 /// Determine whether this class is virtually derived from
1534 /// the class \p Base.
1535 ///
1536 /// This routine only determines whether this class is virtually
1537 /// derived from \p Base, but does not account for factors that may
1538 /// make a Derived -> Base class ill-formed, such as
1539 /// private/protected inheritance or multiple, ambiguous base class
1540 /// subobjects.
1541 ///
1542 /// \param Base the base class we are searching for.
1543 ///
1544 /// \returns true if this class is virtually derived from Base,
1545 /// false otherwise.
1546 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1547
1548 /// Determine whether this class is provably not derived from
1549 /// the type \p Base.
1550 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1551
1552 /// Function type used by forallBases() as a callback.
1553 ///
1554 /// \param BaseDefinition the definition of the base class
1555 ///
1556 /// \returns true if this base matched the search criteria
1557 using ForallBasesCallback =
1558 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1559
1560 /// Determines if the given callback holds for all the direct
1561 /// or indirect base classes of this type.
1562 ///
1563 /// The class itself does not count as a base class. This routine
1564 /// returns false if the class has non-computable base classes.
1565 ///
1566 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1567 /// class of this type until a call returns false.
1568 bool forallBases(ForallBasesCallback BaseMatches) const;
1569
1570 /// Function type used by lookupInBases() to determine whether a
1571 /// specific base class subobject matches the lookup criteria.
1572 ///
1573 /// \param Specifier the base-class specifier that describes the inheritance
1574 /// from the base class we are trying to match.
1575 ///
1576 /// \param Path the current path, from the most-derived class down to the
1577 /// base named by the \p Specifier.
1578 ///
1579 /// \returns true if this base matched the search criteria, false otherwise.
1580 using BaseMatchesCallback =
1581 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1582 CXXBasePath &Path)>;
1583
1584 /// Look for entities within the base classes of this C++ class,
1585 /// transitively searching all base class subobjects.
1586 ///
1587 /// This routine uses the callback function \p BaseMatches to find base
1588 /// classes meeting some search criteria, walking all base class subobjects
1589 /// and populating the given \p Paths structure with the paths through the
1590 /// inheritance hierarchy that resulted in a match. On a successful search,
1591 /// the \p Paths structure can be queried to retrieve the matching paths and
1592 /// to determine if there were any ambiguities.
1593 ///
1594 /// \param BaseMatches callback function used to determine whether a given
1595 /// base matches the user-defined search criteria.
1596 ///
1597 /// \param Paths used to record the paths from this class to its base class
1598 /// subobjects that match the search criteria.
1599 ///
1600 /// \param LookupInDependent can be set to true to extend the search to
1601 /// dependent base classes.
1602 ///
1603 /// \returns true if there exists any path from this class to a base class
1604 /// subobject that matches the search criteria.
1605 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1606 bool LookupInDependent = false) const;
1607
1608 /// Base-class lookup callback that determines whether the given
1609 /// base class specifier refers to a specific class declaration.
1610 ///
1611 /// This callback can be used with \c lookupInBases() to determine whether
1612 /// a given derived class has is a base class subobject of a particular type.
1613 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1614 /// base class that we are searching for.
1615 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1616 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1617
1618 /// Base-class lookup callback that determines whether the
1619 /// given base class specifier refers to a specific class
1620 /// declaration and describes virtual derivation.
1621 ///
1622 /// This callback can be used with \c lookupInBases() to determine
1623 /// whether a given derived class has is a virtual base class
1624 /// subobject of a particular type. The base record pointer should
1625 /// refer to the canonical CXXRecordDecl of the base class that we
1626 /// are searching for.
1627 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1628 CXXBasePath &Path,
1629 const CXXRecordDecl *BaseRecord);
1630
1631 /// Retrieve the final overriders for each virtual member
1632 /// function in the class hierarchy where this class is the
1633 /// most-derived class in the class hierarchy.
1634 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1635
1636 /// Get the indirect primary bases for this class.
1637 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1638
1639 /// Determine whether this class has a member with the given name, possibly
1640 /// in a non-dependent base class.
1641 ///
1642 /// No check for ambiguity is performed, so this should never be used when
1643 /// implementing language semantics, but it may be appropriate for warnings,
1644 /// static analysis, or similar.
1645 bool hasMemberName(DeclarationName N) const;
1646
1647 /// Performs an imprecise lookup of a dependent name in this class.
1648 ///
1649 /// This function does not follow strict semantic rules and should be used
1650 /// only when lookup rules can be relaxed, e.g. indexing.
1651 std::vector<const NamedDecl *>
1652 lookupDependentName(DeclarationName Name,
1653 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1654
1655 /// Renders and displays an inheritance diagram
1656 /// for this C++ class and all of its base classes (transitively) using
1657 /// GraphViz.
1658 void viewInheritance(ASTContext& Context) const;
1659
1660 /// Calculates the access of a decl that is reached
1661 /// along a path.
1662 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1663 AccessSpecifier DeclAccess) {
1664 assert(DeclAccess != AS_none)((void)0);
1665 if (DeclAccess == AS_private) return AS_none;
1666 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1667 }
1668
1669 /// Indicates that the declaration of a defaulted or deleted special
1670 /// member function is now complete.
1671 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1672
1673 void setTrivialForCallFlags(CXXMethodDecl *MD);
1674
1675 /// Indicates that the definition of this class is now complete.
1676 void completeDefinition() override;
1677
1678 /// Indicates that the definition of this class is now complete,
1679 /// and provides a final overrider map to help determine
1680 ///
1681 /// \param FinalOverriders The final overrider map for this class, which can
1682 /// be provided as an optimization for abstract-class checking. If NULL,
1683 /// final overriders will be computed if they are needed to complete the
1684 /// definition.
1685 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1686
1687 /// Determine whether this class may end up being abstract, even though
1688 /// it is not yet known to be abstract.
1689 ///
1690 /// \returns true if this class is not known to be abstract but has any
1691 /// base classes that are abstract. In this case, \c completeDefinition()
1692 /// will need to compute final overriders to determine whether the class is
1693 /// actually abstract.
1694 bool mayBeAbstract() const;
1695
1696 /// Determine whether it's impossible for a class to be derived from this
1697 /// class. This is best-effort, and may conservatively return false.
1698 bool isEffectivelyFinal() const;
1699
1700 /// If this is the closure type of a lambda expression, retrieve the
1701 /// number to be used for name mangling in the Itanium C++ ABI.
1702 ///
1703 /// Zero indicates that this closure type has internal linkage, so the
1704 /// mangling number does not matter, while a non-zero value indicates which
1705 /// lambda expression this is in this particular context.
1706 unsigned getLambdaManglingNumber() const {
1707 assert(isLambda() && "Not a lambda closure type!")((void)0);
1708 return getLambdaData().ManglingNumber;
1709 }
1710
1711 /// The lambda is known to has internal linkage no matter whether it has name
1712 /// mangling number.
1713 bool hasKnownLambdaInternalLinkage() const {
1714 assert(isLambda() && "Not a lambda closure type!")((void)0);
1715 return getLambdaData().HasKnownInternalLinkage;
1716 }
1717
1718 /// Retrieve the declaration that provides additional context for a
1719 /// lambda, when the normal declaration context is not specific enough.
1720 ///
1721 /// Certain contexts (default arguments of in-class function parameters and
1722 /// the initializers of data members) have separate name mangling rules for
1723 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1724 /// the declaration in which the lambda occurs, e.g., the function parameter
1725 /// or the non-static data member. Otherwise, it returns NULL to imply that
1726 /// the declaration context suffices.
1727 Decl *getLambdaContextDecl() const;
1728
1729 /// Set the mangling number and context declaration for a lambda
1730 /// class.
1731 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1732 bool HasKnownInternalLinkage = false) {
1733 assert(isLambda() && "Not a lambda closure type!")((void)0);
1734 getLambdaData().ManglingNumber = ManglingNumber;
1735 getLambdaData().ContextDecl = ContextDecl;
1736 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1737 }
1738
1739 /// Set the device side mangling number.
1740 void setDeviceLambdaManglingNumber(unsigned Num) const;
1741
1742 /// Retrieve the device side mangling number.
1743 unsigned getDeviceLambdaManglingNumber() const;
1744
1745 /// Returns the inheritance model used for this record.
1746 MSInheritanceModel getMSInheritanceModel() const;
1747
1748 /// Calculate what the inheritance model would be for this class.
1749 MSInheritanceModel calculateInheritanceModel() const;
1750
1751 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1752 /// member pointer if we can guarantee that zero is not a valid field offset,
1753 /// or if the member pointer has multiple fields. Polymorphic classes have a
1754 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1755 /// fields, we can use zero even if it is a valid field offset because
1756 /// null-ness testing will check the other fields.
1757 bool nullFieldOffsetIsZero() const;
1758
1759 /// Controls when vtordisps will be emitted if this record is used as a
1760 /// virtual base.
1761 MSVtorDispMode getMSVtorDispMode() const;
1762
1763 /// Determine whether this lambda expression was known to be dependent
1764 /// at the time it was created, even if its context does not appear to be
1765 /// dependent.
1766 ///
1767 /// This flag is a workaround for an issue with parsing, where default
1768 /// arguments are parsed before their enclosing function declarations have
1769 /// been created. This means that any lambda expressions within those
1770 /// default arguments will have as their DeclContext the context enclosing
1771 /// the function declaration, which may be non-dependent even when the
1772 /// function declaration itself is dependent. This flag indicates when we
1773 /// know that the lambda is dependent despite that.
1774 bool isDependentLambda() const {
1775 return isLambda() && getLambdaData().Dependent;
1776 }
1777
1778 TypeSourceInfo *getLambdaTypeInfo() const {
1779 return getLambdaData().MethodTyInfo;
1780 }
1781
1782 // Determine whether this type is an Interface Like type for
1783 // __interface inheritance purposes.
1784 bool isInterfaceLike() const;
1785
1786 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1787 static bool classofKind(Kind K) {
1788 return K >= firstCXXRecord && K <= lastCXXRecord;
1789 }
1790 void markAbstract() { data().Abstract = true; }
1791};
1792
1793/// Store information needed for an explicit specifier.
1794/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1795class ExplicitSpecifier {
1796 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1797 nullptr, ExplicitSpecKind::ResolvedFalse};
1798
1799public:
1800 ExplicitSpecifier() = default;
1801 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1802 : ExplicitSpec(Expression, Kind) {}
1803 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1804 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1805 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1806
1807 /// Determine if the declaration had an explicit specifier of any kind.
1808 bool isSpecified() const {
1809 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1810 ExplicitSpec.getPointer();
1811 }
1812
1813 /// Check for equivalence of explicit specifiers.
1814 /// \return true if the explicit specifier are equivalent, false otherwise.
1815 bool isEquivalent(const ExplicitSpecifier Other) const;
1816 /// Determine whether this specifier is known to correspond to an explicit
1817 /// declaration. Returns false if the specifier is absent or has an
1818 /// expression that is value-dependent or evaluates to false.
1819 bool isExplicit() const {
1820 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1821 }
1822 /// Determine if the explicit specifier is invalid.
1823 /// This state occurs after a substitution failures.
1824 bool isInvalid() const {
1825 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1826 !ExplicitSpec.getPointer();
1827 }
1828 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1829 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1830 // Retrieve the explicit specifier in the given declaration, if any.
1831 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1832 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1833 return getFromDecl(const_cast<FunctionDecl *>(Function));
1834 }
1835 static ExplicitSpecifier Invalid() {
1836 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1837 }
1838};
1839
1840/// Represents a C++ deduction guide declaration.
1841///
1842/// \code
1843/// template<typename T> struct A { A(); A(T); };
1844/// A() -> A<int>;
1845/// \endcode
1846///
1847/// In this example, there will be an explicit deduction guide from the
1848/// second line, and implicit deduction guide templates synthesized from
1849/// the constructors of \c A.
1850class CXXDeductionGuideDecl : public FunctionDecl {
1851 void anchor() override;
1852
1853private:
1854 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1855 ExplicitSpecifier ES,
1856 const DeclarationNameInfo &NameInfo, QualType T,
1857 TypeSourceInfo *TInfo, SourceLocation EndLocation,
1858 CXXConstructorDecl *Ctor)
1859 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1860 SC_None, false, ConstexprSpecKind::Unspecified),
1861 Ctor(Ctor), ExplicitSpec(ES) {
1862 if (EndLocation.isValid())
1863 setRangeEnd(EndLocation);
1864 setIsCopyDeductionCandidate(false);
1865 }
1866
1867 CXXConstructorDecl *Ctor;
1868 ExplicitSpecifier ExplicitSpec;
1869 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1870
1871public:
1872 friend class ASTDeclReader;
1873 friend class ASTDeclWriter;
1874
1875 static CXXDeductionGuideDecl *
1876 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1877 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1878 TypeSourceInfo *TInfo, SourceLocation EndLocation,
1879 CXXConstructorDecl *Ctor = nullptr);
1880
1881 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1882
1883 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1884 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1885
1886 /// Return true if the declartion is already resolved to be explicit.
1887 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1888
1889 /// Get the template for which this guide performs deduction.
1890 TemplateDecl *getDeducedTemplate() const {
1891 return getDeclName().getCXXDeductionGuideTemplate();
1892 }
1893
1894 /// Get the constructor from which this deduction guide was generated, if
1895 /// this is an implicit deduction guide.
1896 CXXConstructorDecl *getCorrespondingConstructor() const {
1897 return Ctor;
1898 }
1899
1900 void setIsCopyDeductionCandidate(bool isCDC = true) {
1901 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1902 }
1903
1904 bool isCopyDeductionCandidate() const {
1905 return FunctionDeclBits.IsCopyDeductionCandidate;
1906 }
1907
1908 // Implement isa/cast/dyncast/etc.
1909 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1910 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1911};
1912
1913/// \brief Represents the body of a requires-expression.
1914///
1915/// This decl exists merely to serve as the DeclContext for the local
1916/// parameters of the requires expression as well as other declarations inside
1917/// it.
1918///
1919/// \code
1920/// template<typename T> requires requires (T t) { {t++} -> regular; }
1921/// \endcode
1922///
1923/// In this example, a RequiresExpr object will be generated for the expression,
1924/// and a RequiresExprBodyDecl will be created to hold the parameter t and the
1925/// template argument list imposed by the compound requirement.
1926class RequiresExprBodyDecl : public Decl, public DeclContext {
1927 RequiresExprBodyDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
1928 : Decl(RequiresExprBody, DC, StartLoc), DeclContext(RequiresExprBody) {}
1929
1930public:
1931 friend class ASTDeclReader;
1932 friend class ASTDeclWriter;
1933
1934 static RequiresExprBodyDecl *Create(ASTContext &C, DeclContext *DC,
1935 SourceLocation StartLoc);
1936
1937 static RequiresExprBodyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1938
1939 // Implement isa/cast/dyncast/etc.
1940 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1941 static bool classofKind(Kind K) { return K == RequiresExprBody; }
1942};
1943
1944/// Represents a static or instance method of a struct/union/class.
1945///
1946/// In the terminology of the C++ Standard, these are the (static and
1947/// non-static) member functions, whether virtual or not.
1948class CXXMethodDecl : public FunctionDecl {
1949 void anchor() override;
1950
1951protected:
1952 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1953 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1954 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1955 bool isInline, ConstexprSpecKind ConstexprKind,
1956 SourceLocation EndLocation,
1957 Expr *TrailingRequiresClause = nullptr)
1958 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
1959 ConstexprKind, TrailingRequiresClause) {
1960 if (EndLocation.isValid())
1961 setRangeEnd(EndLocation);
1962 }
1963
1964public:
1965 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
1966 SourceLocation StartLoc,
1967 const DeclarationNameInfo &NameInfo, QualType T,
1968 TypeSourceInfo *TInfo, StorageClass SC,
1969 bool isInline, ConstexprSpecKind ConstexprKind,
1970 SourceLocation EndLocation,
1971 Expr *TrailingRequiresClause = nullptr);
1972
1973 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1974
1975 bool isStatic() const;
1976 bool isInstance() const { return !isStatic(); }
1977
1978 /// Returns true if the given operator is implicitly static in a record
1979 /// context.
1980 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
1981 // [class.free]p1:
1982 // Any allocation function for a class T is a static member
1983 // (even if not explicitly declared static).
1984 // [class.free]p6 Any deallocation function for a class X is a static member
1985 // (even if not explicitly declared static).
1986 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
1987 OOK == OO_Array_Delete;
1988 }
1989
1990 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
1991 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
1992
1993 bool isVirtual() const {
1994 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1995
1996 // Member function is virtual if it is marked explicitly so, or if it is
1997 // declared in __interface -- then it is automatically pure virtual.
1998 if (CD->isVirtualAsWritten() || CD->isPure())
1999 return true;
2000
2001 return CD->size_overridden_methods() != 0;
2002 }
2003
2004 /// If it's possible to devirtualize a call to this method, return the called
2005 /// function. Otherwise, return null.
2006
2007 /// \param Base The object on which this virtual function is called.
2008 /// \param IsAppleKext True if we are compiling for Apple kext.
2009 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2010
2011 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2012 bool IsAppleKext) const {
2013 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2014 Base, IsAppleKext);
2015 }
2016
2017 /// Determine whether this is a usual deallocation function (C++
2018 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2019 /// delete[] operator with a particular signature. Populates \p PreventedBy
2020 /// with the declarations of the functions of the same kind if they were the
2021 /// reason for this function returning false. This is used by
2022 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2023 /// context.
2024 bool isUsualDeallocationFunction(
2025 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2026
2027 /// Determine whether this is a copy-assignment operator, regardless
2028 /// of whether it was declared implicitly or explicitly.
2029 bool isCopyAssignmentOperator() const;
2030
2031 /// Determine whether this is a move assignment operator.
2032 bool isMoveAssignmentOperator() const;
2033
2034 CXXMethodDecl *getCanonicalDecl() override {
2035 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2036 }
2037 const CXXMethodDecl *getCanonicalDecl() const {
2038 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2039 }
2040
2041 CXXMethodDecl *getMostRecentDecl() {
2042 return cast<CXXMethodDecl>(
2043 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2044 }
2045 const CXXMethodDecl *getMostRecentDecl() const {
2046 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2047 }
2048
2049 void addOverriddenMethod(const CXXMethodDecl *MD);
2050
2051 using method_iterator = const CXXMethodDecl *const *;
2052
2053 method_iterator begin_overridden_methods() const;
2054 method_iterator end_overridden_methods() const;
2055 unsigned size_overridden_methods() const;
2056
2057 using overridden_method_range = llvm::iterator_range<
2058 llvm::TinyPtrVector<const CXXMethodDecl *>::const_iterator>;
2059
2060 overridden_method_range overridden_methods() const;
2061
2062 /// Return the parent of this method declaration, which
2063 /// is the class in which this method is defined.
2064 const CXXRecordDecl *getParent() const {
2065 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2066 }
2067
2068 /// Return the parent of this method declaration, which
2069 /// is the class in which this method is defined.
2070 CXXRecordDecl *getParent() {
2071 return const_cast<CXXRecordDecl *>(
2072 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2073 }
2074
2075 /// Return the type of the \c this pointer.
2076 ///
2077 /// Should only be called for instance (i.e., non-static) methods. Note
2078 /// that for the call operator of a lambda closure type, this returns the
2079 /// desugared 'this' type (a pointer to the closure type), not the captured
2080 /// 'this' type.
2081 QualType getThisType() const;
2082
2083 /// Return the type of the object pointed by \c this.
2084 ///
2085 /// See getThisType() for usage restriction.
2086 QualType getThisObjectType() const;
2087
2088 static QualType getThisType(const FunctionProtoType *FPT,
2089 const CXXRecordDecl *Decl);
2090
2091 static QualType getThisObjectType(const FunctionProtoType *FPT,
2092 const CXXRecordDecl *Decl);
2093
2094 Qualifiers getMethodQualifiers() const {
2095 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2096 }
2097
2098 /// Retrieve the ref-qualifier associated with this method.
2099 ///
2100 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2101 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2102 /// @code
2103 /// struct X {
2104 /// void f() &;
2105 /// void g() &&;
2106 /// void h();
2107 /// };
2108 /// @endcode
2109 RefQualifierKind getRefQualifier() const {
2110 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2111 }
2112
2113 bool hasInlineBody() const;
2114
2115 /// Determine whether this is a lambda closure type's static member
2116 /// function that is used for the result of the lambda's conversion to
2117 /// function pointer (for a lambda with no captures).
2118 ///
2119 /// The function itself, if used, will have a placeholder body that will be
2120 /// supplied by IR generation to either forward to the function call operator
2121 /// or clone the function call operator.
2122 bool isLambdaStaticInvoker() const;
2123
2124 /// Find the method in \p RD that corresponds to this one.
2125 ///
2126 /// Find if \p RD or one of the classes it inherits from override this method.
2127 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2128 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2129 CXXMethodDecl *
2130 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2131 bool MayBeBase = false);
2132
2133 const CXXMethodDecl *
2134 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2135 bool MayBeBase = false) const {
2136 return const_cast<CXXMethodDecl *>(this)
2137 ->getCorrespondingMethodInClass(RD, MayBeBase);
2138 }
2139
2140 /// Find if \p RD declares a function that overrides this function, and if so,
2141 /// return it. Does not search base classes.
2142 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2143 bool MayBeBase = false);
2144 const CXXMethodDecl *
2145 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2146 bool MayBeBase = false) const {
2147 return const_cast<CXXMethodDecl *>(this)
2148 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2149 }
2150
2151 // Implement isa/cast/dyncast/etc.
2152 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2153 static bool classofKind(Kind K) {
2154 return K >= firstCXXMethod && K <= lastCXXMethod;
2155 }
2156};
2157
2158/// Represents a C++ base or member initializer.
2159///
2160/// This is part of a constructor initializer that
2161/// initializes one non-static member variable or one base class. For
2162/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2163/// initializers:
2164///
2165/// \code
2166/// class A { };
2167/// class B : public A {
2168/// float f;
2169/// public:
2170/// B(A& a) : A(a), f(3.14159) { }
2171/// };
2172/// \endcode
2173class CXXCtorInitializer final {
2174 /// Either the base class name/delegating constructor type (stored as
2175 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2176 /// (IndirectFieldDecl*) being initialized.
2177 llvm::PointerUnion<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2178 Initializee;
2179
2180 /// The argument used to initialize the base or member, which may
2181 /// end up constructing an object (when multiple arguments are involved).
2182 Stmt *Init;
2183
2184 /// The source location for the field name or, for a base initializer
2185 /// pack expansion, the location of the ellipsis.
2186 ///
2187 /// In the case of a delegating
2188 /// constructor, it will still include the type's source location as the
2189 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2190 SourceLocation MemberOrEllipsisLocation;
2191
2192 /// Location of the left paren of the ctor-initializer.
2193 SourceLocation LParenLoc;
2194
2195 /// Location of the right paren of the ctor-initializer.
2196 SourceLocation RParenLoc;
2197
2198 /// If the initializee is a type, whether that type makes this
2199 /// a delegating initialization.
2200 unsigned IsDelegating : 1;
2201
2202 /// If the initializer is a base initializer, this keeps track
2203 /// of whether the base is virtual or not.
2204 unsigned IsVirtual : 1;
2205
2206 /// Whether or not the initializer is explicitly written
2207 /// in the sources.
2208 unsigned IsWritten : 1;
2209
2210 /// If IsWritten is true, then this number keeps track of the textual order
2211 /// of this initializer in the original sources, counting from 0.
2212 unsigned SourceOrder : 13;
2213
2214public:
2215 /// Creates a new base-class initializer.
2216 explicit
2217 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2218 SourceLocation L, Expr *Init, SourceLocation R,
2219 SourceLocation EllipsisLoc);
2220
2221 /// Creates a new member initializer.
2222 explicit
2223 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2224 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2225 SourceLocation R);
2226
2227 /// Creates a new anonymous field initializer.
2228 explicit
2229 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2230 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2231 SourceLocation R);
2232
2233 /// Creates a new delegating initializer.
2234 explicit
2235 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2236 SourceLocation L, Expr *Init, SourceLocation R);
2237
2238 /// \return Unique reproducible object identifier.
2239 int64_t getID(const ASTContext &Context) const;
2240
2241 /// Determine whether this initializer is initializing a base class.
2242 bool isBaseInitializer() const {
2243 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2244 }
2245
2246 /// Determine whether this initializer is initializing a non-static
2247 /// data member.
2248 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2249
2250 bool isAnyMemberInitializer() const {
2251 return isMemberInitializer() || isIndirectMemberInitializer();
2252 }
2253
2254 bool isIndirectMemberInitializer() const {
2255 return Initializee.is<IndirectFieldDecl*>();
2256 }
2257
2258 /// Determine whether this initializer is an implicit initializer
2259 /// generated for a field with an initializer defined on the member
2260 /// declaration.
2261 ///
2262 /// In-class member initializers (also known as "non-static data member
2263 /// initializations", NSDMIs) were introduced in C++11.
2264 bool isInClassMemberInitializer() const {
2265 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2266 }
2267
2268 /// Determine whether this initializer is creating a delegating
2269 /// constructor.
2270 bool isDelegatingInitializer() const {
2271 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2272 }
2273
2274 /// Determine whether this initializer is a pack expansion.
2275 bool isPackExpansion() const {
2276 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2277 }
2278
2279 // For a pack expansion, returns the location of the ellipsis.
2280 SourceLocation getEllipsisLoc() const {
2281 if (!isPackExpansion())
2282 return {};
2283 return MemberOrEllipsisLocation;
2284 }
2285
2286 /// If this is a base class initializer, returns the type of the
2287 /// base class with location information. Otherwise, returns an NULL
2288 /// type location.
2289 TypeLoc getBaseClassLoc() const;
2290
2291 /// If this is a base class initializer, returns the type of the base class.
2292 /// Otherwise, returns null.
2293 const Type *getBaseClass() const;
2294
2295 /// Returns whether the base is virtual or not.
2296 bool isBaseVirtual() const {
2297 assert(isBaseInitializer() && "Must call this on base initializer!")((void)0);
2298
2299 return IsVirtual;
2300 }
2301
2302 /// Returns the declarator information for a base class or delegating
2303 /// initializer.
2304 TypeSourceInfo *getTypeSourceInfo() const {
2305 return Initializee.dyn_cast<TypeSourceInfo *>();
2306 }
2307
2308 /// If this is a member initializer, returns the declaration of the
2309 /// non-static data member being initialized. Otherwise, returns null.
2310 FieldDecl *getMember() const {
2311 if (isMemberInitializer())
2312 return Initializee.get<FieldDecl*>();
2313 return nullptr;
2314 }
2315
2316 FieldDecl *getAnyMember() const {
2317 if (isMemberInitializer())
2318 return Initializee.get<FieldDecl*>();
2319 if (isIndirectMemberInitializer())
2320 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2321 return nullptr;
2322 }
2323
2324 IndirectFieldDecl *getIndirectMember() const {
2325 if (isIndirectMemberInitializer())
2326 return Initializee.get<IndirectFieldDecl*>();
2327 return nullptr;
2328 }
2329
2330 SourceLocation getMemberLocation() const {
2331 return MemberOrEllipsisLocation;
2332 }
2333
2334 /// Determine the source location of the initializer.
2335 SourceLocation getSourceLocation() const;
2336
2337 /// Determine the source range covering the entire initializer.
2338 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__));
2339
2340 /// Determine whether this initializer is explicitly written
2341 /// in the source code.
2342 bool isWritten() const { return IsWritten; }
2343
2344 /// Return the source position of the initializer, counting from 0.
2345 /// If the initializer was implicit, -1 is returned.
2346 int getSourceOrder() const {
2347 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2348 }
2349
2350 /// Set the source order of this initializer.
2351 ///
2352 /// This can only be called once for each initializer; it cannot be called
2353 /// on an initializer having a positive number of (implicit) array indices.
2354 ///
2355 /// This assumes that the initializer was written in the source code, and
2356 /// ensures that isWritten() returns true.
2357 void setSourceOrder(int Pos) {
2358 assert(!IsWritten &&((void)0)
2359 "setSourceOrder() used on implicit initializer")((void)0);
2360 assert(SourceOrder == 0 &&((void)0)
2361 "calling twice setSourceOrder() on the same initializer")((void)0);
2362 assert(Pos >= 0 &&((void)0)
2363 "setSourceOrder() used to make an initializer implicit")((void)0);
2364 IsWritten = true;
2365 SourceOrder = static_cast<unsigned>(Pos);
2366 }
2367
2368 SourceLocation getLParenLoc() const { return LParenLoc; }
2369 SourceLocation getRParenLoc() const { return RParenLoc; }
2370
2371 /// Get the initializer.
2372 Expr *getInit() const { return static_cast<Expr *>(Init); }
2373};
2374
2375/// Description of a constructor that was inherited from a base class.
2376class InheritedConstructor {
2377 ConstructorUsingShadowDecl *Shadow = nullptr;
2378 CXXConstructorDecl *BaseCtor = nullptr;
2379
2380public:
2381 InheritedConstructor() = default;
2382 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2383 CXXConstructorDecl *BaseCtor)
2384 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2385
2386 explicit operator bool() const { return Shadow; }
2387
2388 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2389 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2390};
2391
2392/// Represents a C++ constructor within a class.
2393///
2394/// For example:
2395///
2396/// \code
2397/// class X {
2398/// public:
2399/// explicit X(int); // represented by a CXXConstructorDecl.
2400/// };
2401/// \endcode
2402class CXXConstructorDecl final
2403 : public CXXMethodDecl,
2404 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2405 ExplicitSpecifier> {
2406 // This class stores some data in DeclContext::CXXConstructorDeclBits
2407 // to save some space. Use the provided accessors to access it.
2408
2409 /// \name Support for base and member initializers.
2410 /// \{
2411 /// The arguments used to initialize the base or member.
2412 LazyCXXCtorInitializersPtr CtorInitializers;
2413
2414 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2415 const DeclarationNameInfo &NameInfo, QualType T,
2416 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2417 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2418 InheritedConstructor Inherited,
2419 Expr *TrailingRequiresClause);
2420
2421 void anchor() override;
2422
2423 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2424 return CXXConstructorDeclBits.IsInheritingConstructor;
2425 }
2426 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2427 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2428 }
2429
2430 ExplicitSpecifier getExplicitSpecifierInternal() const {
2431 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2432 return *getTrailingObjects<ExplicitSpecifier>();
2433 return ExplicitSpecifier(
2434 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2435 ? ExplicitSpecKind::ResolvedTrue
2436 : ExplicitSpecKind::ResolvedFalse);
2437 }
2438
2439 enum TrailingAllocKind {
2440 TAKInheritsConstructor = 1,
2441 TAKHasTailExplicit = 1 << 1,
2442 };
2443
2444 uint64_t getTrailingAllocKind() const {
2445 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2446 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2447 }
2448
2449public:
2450 friend class ASTDeclReader;
2451 friend class ASTDeclWriter;
2452 friend TrailingObjects;
2453
2454 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2455 uint64_t AllocKind);
2456 static CXXConstructorDecl *
2457 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2458 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2459 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2460 ConstexprSpecKind ConstexprKind,
2461 InheritedConstructor Inherited = InheritedConstructor(),
2462 Expr *TrailingRequiresClause = nullptr);
2463
2464 void setExplicitSpecifier(ExplicitSpecifier ES) {
2465 assert((!ES.getExpr() ||((void)0)
2466 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&((void)0)
2467 "cannot set this explicit specifier. no trail-allocated space for "((void)0)
2468 "explicit")((void)0);
2469 if (ES.getExpr())
2470 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2471 else
2472 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2473 }
2474
2475 ExplicitSpecifier getExplicitSpecifier() {
2476 return getCanonicalDecl()->getExplicitSpecifierInternal();
2477 }
2478 const ExplicitSpecifier getExplicitSpecifier() const {
2479 return getCanonicalDecl()->getExplicitSpecifierInternal();
2480 }
2481
2482 /// Return true if the declartion is already resolved to be explicit.
2483 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2484
2485 /// Iterates through the member/base initializer list.
2486 using init_iterator = CXXCtorInitializer **;
2487
2488 /// Iterates through the member/base initializer list.
2489 using init_const_iterator = CXXCtorInitializer *const *;
2490
2491 using init_range = llvm::iterator_range<init_iterator>;
2492 using init_const_range = llvm::iterator_range<init_const_iterator>;
2493
2494 init_range inits() { return init_range(init_begin(), init_end()); }
2495 init_const_range inits() const {
2496 return init_const_range(init_begin(), init_end());
2497 }
2498
2499 /// Retrieve an iterator to the first initializer.
2500 init_iterator init_begin() {
2501 const auto *ConstThis = this;
2502 return const_cast<init_iterator>(ConstThis->init_begin());
2503 }
2504
2505 /// Retrieve an iterator to the first initializer.
2506 init_const_iterator init_begin() const;
2507
2508 /// Retrieve an iterator past the last initializer.
2509 init_iterator init_end() {
2510 return init_begin() + getNumCtorInitializers();
2511 }
2512
2513 /// Retrieve an iterator past the last initializer.
2514 init_const_iterator init_end() const {
2515 return init_begin() + getNumCtorInitializers();
2516 }
2517
2518 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2519 using init_const_reverse_iterator =
2520 std::reverse_iterator<init_const_iterator>;
2521
2522 init_reverse_iterator init_rbegin() {
2523 return init_reverse_iterator(init_end());
2524 }
2525 init_const_reverse_iterator init_rbegin() const {
2526 return init_const_reverse_iterator(init_end());
2527 }
2528
2529 init_reverse_iterator init_rend() {
2530 return init_reverse_iterator(init_begin());
2531 }
2532 init_const_reverse_iterator init_rend() const {
2533 return init_const_reverse_iterator(init_begin());
2534 }
2535
2536 /// Determine the number of arguments used to initialize the member
2537 /// or base.
2538 unsigned getNumCtorInitializers() const {
2539 return CXXConstructorDeclBits.NumCtorInitializers;
2540 }
2541
2542 void setNumCtorInitializers(unsigned numCtorInitializers) {
2543 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2544 // This assert added because NumCtorInitializers is stored
2545 // in CXXConstructorDeclBits as a bitfield and its width has
2546 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2547 assert(CXXConstructorDeclBits.NumCtorInitializers ==((void)0)
2548 numCtorInitializers && "NumCtorInitializers overflow!")((void)0);
2549 }
2550
2551 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2552 CtorInitializers = Initializers;
2553 }
2554
2555 /// Determine whether this constructor is a delegating constructor.
2556 bool isDelegatingConstructor() const {
2557 return (getNumCtorInitializers() == 1) &&
2558 init_begin()[0]->isDelegatingInitializer();
2559 }
2560
2561 /// When this constructor delegates to another, retrieve the target.
2562 CXXConstructorDecl *getTargetConstructor() const;
2563
2564 /// Whether this constructor is a default
2565 /// constructor (C++ [class.ctor]p5), which can be used to
2566 /// default-initialize a class of this type.
2567 bool isDefaultConstructor() const;
2568
2569 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2570 /// which can be used to copy the class.
2571 ///
2572 /// \p TypeQuals will be set to the qualifiers on the
2573 /// argument type. For example, \p TypeQuals would be set to \c
2574 /// Qualifiers::Const for the following copy constructor:
2575 ///
2576 /// \code
2577 /// class X {
2578 /// public:
2579 /// X(const X&);
2580 /// };
2581 /// \endcode
2582 bool isCopyConstructor(unsigned &TypeQuals) const;
2583
2584 /// Whether this constructor is a copy
2585 /// constructor (C++ [class.copy]p2, which can be used to copy the
2586 /// class.
2587 bool isCopyConstructor() const {
2588 unsigned TypeQuals = 0;
2589 return isCopyConstructor(TypeQuals);
2590 }
2591
2592 /// Determine whether this constructor is a move constructor
2593 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2594 ///
2595 /// \param TypeQuals If this constructor is a move constructor, will be set
2596 /// to the type qualifiers on the referent of the first parameter's type.
2597 bool isMoveConstructor(unsigned &TypeQuals) const;
2598
2599 /// Determine whether this constructor is a move constructor
2600 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2601 bool isMoveConstructor() const {
2602 unsigned TypeQuals = 0;
2603 return isMoveConstructor(TypeQuals);
2604 }
2605
2606 /// Determine whether this is a copy or move constructor.
2607 ///
2608 /// \param TypeQuals Will be set to the type qualifiers on the reference
2609 /// parameter, if in fact this is a copy or move constructor.
2610 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2611
2612 /// Determine whether this a copy or move constructor.
2613 bool isCopyOrMoveConstructor() const {
2614 unsigned Quals;
2615 return isCopyOrMoveConstructor(Quals);
2616 }
2617
2618 /// Whether this constructor is a
2619 /// converting constructor (C++ [class.conv.ctor]), which can be
2620 /// used for user-defined conversions.
2621 bool isConvertingConstructor(bool AllowExplicit) const;
2622
2623 /// Determine whether this is a member template specialization that
2624 /// would copy the object to itself. Such constructors are never used to copy
2625 /// an object.
2626 bool isSpecializationCopyingObject() const;
2627
2628 /// Determine whether this is an implicit constructor synthesized to
2629 /// model a call to a constructor inherited from a base class.
2630 bool isInheritingConstructor() const {
2631 return CXXConstructorDeclBits.IsInheritingConstructor;
2632 }
2633
2634 /// State that this is an implicit constructor synthesized to
2635 /// model a call to a constructor inherited from a base class.
2636 void setInheritingConstructor(bool isIC = true) {
2637 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2638 }
2639
2640 /// Get the constructor that this inheriting constructor is based on.
2641 InheritedConstructor getInheritedConstructor() const {
2642 return isInheritingConstructor() ?
2643 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2644 }
2645
2646 CXXConstructorDecl *getCanonicalDecl() override {
2647 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2648 }
2649 const CXXConstructorDecl *getCanonicalDecl() const {
2650 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2651 }
2652
2653 // Implement isa/cast/dyncast/etc.
2654 static bool classof