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