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