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