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