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