Bug Summary

File:clang/include/clang/AST/ExternalASTSource.h
Warning:line 378, column 40
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/AST/DeclCXX.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/AST/DeclCXX.cpp

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
52using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Decl Allocation/Deallocation Method Implementations
56//===----------------------------------------------------------------------===//
57
58void AccessSpecDecl::anchor() {}
59
60AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
61 return new (C, ID) AccessSpecDecl(EmptyShell());
62}
63
64void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {
65 ExternalASTSource *Source = C.getExternalSource();
66 assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set")(static_cast<void> (0));
67 assert(Source && "getFromExternalSource with no external source")(static_cast<void> (0));
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
75CXXRecordDecl::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
116CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
117 return Bases.get(Definition->getASTContext().getExternalSource());
118}
119
120CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
121 return VBases.get(Definition->getASTContext().getExternalSource());
122}
123
124CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,
125 DeclContext *DC, SourceLocation StartLoc,
126 SourceLocation IdLoc, IdentifierInfo *Id,
127 CXXRecordDecl *PrevDecl)
128 : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),
129 DefinitionData(PrevDecl ? PrevDecl->DefinitionData
130 : nullptr) {}
131
132CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
133 DeclContext *DC, SourceLocation StartLoc,
134 SourceLocation IdLoc, IdentifierInfo *Id,
135 CXXRecordDecl *PrevDecl,
136 bool DelayTypeCreation) {
137 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id,
138 PrevDecl);
139 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
140
141 // FIXME: DelayTypeCreation seems like such a hack
142 if (!DelayTypeCreation)
143 C.getTypeDeclType(R, PrevDecl);
144 return R;
145}
146
147CXXRecordDecl *
148CXXRecordDecl::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
164CXXRecordDecl *
165CXXRecordDecl::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.
176static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {
177 llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;
178 SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};
179 while (!WorkList.empty()) {
180 const CXXRecordDecl *RD = WorkList.pop_back_val();
181 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
192void
193CXXRecordDecl::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
492unsigned CXXRecordDecl::getODRHash() const {
493 assert(hasDefinition() && "ODRHash only for records with definitions")(static_cast<void> (0));
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
508void 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
560bool CXXRecordDecl::hasConstexprDestructor() const {
561 auto *Dtor = getDestructor();
562 return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();
563}
564
565bool CXXRecordDecl::hasAnyDependentBases() const {
566 if (!isDependentContext())
567 return false;
568
569 return !forallBases([](const CXXRecordDecl *) { return true; });
570}
571
572bool 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
589void 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
595bool 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
675bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {
676 assert(isLambda() && "not a lambda")(static_cast<void> (0));
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
693void 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")__builtin_unreachable();
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
1395void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
1396 assert(!D->isImplicit() && !D->isUserProvided())(static_cast<void> (0));
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
1431void 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
1452void 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
1469bool 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
1479bool CXXRecordDecl::isGenericLambda() const {
1480 if (!isLambda()) return false;
1481 return getLambdaData().IsGenericLambda;
1482}
1483
1484#ifndef NDEBUG1
1485static 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
1493static 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!")(static_cast<void> (0));
1500 assert(allLookupResultsAreTheSame(Calls) &&(static_cast<void> (0))
1501 "More than one lambda call operator!")(static_cast<void> (0));
1502 return Calls.front();
1503}
1504
1505FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {
1506 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
1507 return dyn_cast_or_null<FunctionTemplateDecl>(CallOp);
1508}
1509
1510CXXMethodDecl *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
1522CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {
1523 CXXMethodDecl *CallOp = getLambdaCallOperator();
1524 CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv();
1525 return getLambdaStaticInvoker(CC);
1526}
1527
1528static DeclContext::lookup_result
1529getLambdaStaticInvokers(const CXXRecordDecl &RD) {
1530 assert(RD.isLambda() && "Must be a lambda")(static_cast<void> (0));
1531 DeclarationName Name =
1532 &RD.getASTContext().Idents.get(getLambdaStaticInvokerName());
1533 return RD.lookup(Name);
1534}
1535
1536static 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
1542CXXMethodDecl *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
1557void 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())(static_cast<void> (0));
1573}
1574
1575TemplateParameterList *
1576CXXRecordDecl::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
1584ArrayRef<NamedDecl *>
1585CXXRecordDecl::getLambdaExplicitTemplateParameters() const {
1586 TemplateParameterList *List = getGenericLambdaTemplateParameterList();
1587 if (!List)
1588 return {};
1589
1590 assert(std::is_partitioned(List->begin(), List->end(),(static_cast<void> (0))
1591 [](const NamedDecl *D) { return !D->isImplicit(); })(static_cast<void> (0))
1592 && "Explicit template params should be ordered before implicit ones")(static_cast<void> (0));
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
1599Decl *CXXRecordDecl::getLambdaContextDecl() const {
1600 assert(isLambda() && "Not a lambda closure type!")(static_cast<void> (0));
1601 ExternalASTSource *Source = getParentASTContext().getExternalSource();
1602 return getLambdaData().ContextDecl.get(Source);
1603}
1604
1605void CXXRecordDecl::setDeviceLambdaManglingNumber(unsigned Num) const {
1606 assert(isLambda() && "Not a lambda closure type!")(static_cast<void> (0));
1607 if (Num)
1608 getASTContext().DeviceLambdaManglingNumbers[this] = Num;
1609}
1610
1611unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const {
1612 assert(isLambda() && "Not a lambda closure type!")(static_cast<void> (0));
1613 auto I = getASTContext().DeviceLambdaManglingNumbers.find(this);
1614 if (I != getASTContext().DeviceLambdaManglingNumbers.end())
1615 return I->second;
1616 return 0;
1617}
1618
1619static 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
1638static 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.
1701static 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.
1744llvm::iterator_range<CXXRecordDecl::conversion_iterator>
1745CXXRecordDecl::getVisibleConversionFunctions() const {
1746 ASTContext &Ctx = getASTContext();
1747
1748 ASTUnresolvedSet *Set;
1749 if (bases_begin() == bases_end()) {
1
Calling 'CXXRecordDecl::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
1763void 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() &&(static_cast<void> (0))
1780 "conversion was found multiple times in unresolved set")(static_cast<void> (0));
1781 return;
1782 }
1783 }
1784
1785 llvm_unreachable("conversion not found in set!")__builtin_unreachable();
1786}
1787
1788CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1789 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1790 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1791
1792 return nullptr;
1793}
1794
1795MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
1796 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
1797}
1798
1799void
1800CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1801 TemplateSpecializationKind TSK) {
1802 assert(TemplateOrInstantiation.isNull() &&(static_cast<void> (0))
1803 "Previous template or instantiation?")(static_cast<void> (0));
1804 assert(!isa<ClassTemplatePartialSpecializationDecl>(this))(static_cast<void> (0));
1805 TemplateOrInstantiation
1806 = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1807}
1808
1809ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {
1810 return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>();
1811}
1812
1813void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {
1814 TemplateOrInstantiation = Template;
1815}
1816
1817TemplateSpecializationKind 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
1827void
1828CXXRecordDecl::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")__builtin_unreachable();
1840}
1841
1842const 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()) &&(static_cast<void> (0))
1883 "couldn't find pattern for class template instantiation")(static_cast<void> (0));
1884 return nullptr;
1885}
1886
1887CXXDestructorDecl *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
1900static 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
1909bool CXXRecordDecl::isInterfaceLike() const {
1910 assert(hasDefinition() && "checking for interface-like without a definition")(static_cast<void> (0));
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
1960void CXXRecordDecl::completeDefinition() {
1961 completeDefinition(nullptr);
1962}
1963
1964void 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 &&(static_cast<void> (0))
1984 "All virtual functions have overriding virtual functions")(static_cast<void> (0));
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
2005bool 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
2020bool 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
2032void CXXDeductionGuideDecl::anchor() {}
2033
2034bool 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
2049ExplicitSpecifier 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
2062CXXDeductionGuideDecl *
2063CXXDeductionGuideDecl::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
2072CXXDeductionGuideDecl *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
2079RequiresExprBodyDecl *RequiresExprBodyDecl::Create(
2080 ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {
2081 return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);
2082}
2083
2084RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C,
2085 unsigned ID) {
2086 return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());
2087}
2088
2089void CXXMethodDecl::anchor() {}
2090
2091bool 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
2101static 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
2112CXXMethodDecl *
2113CXXMethodDecl::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
2143CXXMethodDecl *
2144CXXMethodDecl::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
2181CXXMethodDecl *
2182CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2183 const DeclarationNameInfo &NameInfo, QualType T,
2184 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
2185 bool isInline, ConstexprSpecKind ConstexprKind,
2186 SourceLocation EndLocation,
2187 Expr *TrailingRequiresClause) {
2188 return new (C, RD) CXXMethodDecl(
2189 CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
2190 isInline, ConstexprKind, EndLocation, TrailingRequiresClause);
2191}
2192
2193CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2194 return new (C, ID) CXXMethodDecl(
2195 CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(),
2196 QualType(), nullptr, SC_None, false, false,
2197 ConstexprSpecKind::Unspecified, SourceLocation(), nullptr);
2198}
2199
2200CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,
2201 bool IsAppleKext) {
2202 assert(isVirtual() && "this method is expected to be virtual")(static_cast<void> (0));
2203
2204 // When building with -fapple-kext, all calls must go through the vtable since
2205 // the kernel linker can do runtime patching of vtables.
2206 if (IsAppleKext)
2207 return nullptr;
2208
2209 // If the member function is marked 'final', we know that it can't be
2210 // overridden and can therefore devirtualize it unless it's pure virtual.
2211 if (hasAttr<FinalAttr>())
2212 return isPure() ? nullptr : this;
2213
2214 // If Base is unknown, we cannot devirtualize.
2215 if (!Base)
2216 return nullptr;
2217
2218 // If the base expression (after skipping derived-to-base conversions) is a
2219 // class prvalue, then we can devirtualize.
2220 Base = Base->getBestDynamicClassTypeExpr();
2221 if (Base->isPRValue() && Base->getType()->isRecordType())
2222 return this;
2223
2224 // If we don't even know what we would call, we can't devirtualize.
2225 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2226 if (!BestDynamicDecl)
2227 return nullptr;
2228
2229 // There may be a method corresponding to MD in a derived class.
2230 CXXMethodDecl *DevirtualizedMethod =
2231 getCorrespondingMethodInClass(BestDynamicDecl);
2232
2233 // If there final overrider in the dynamic type is ambiguous, we can't
2234 // devirtualize this call.
2235 if (!DevirtualizedMethod)
2236 return nullptr;
2237
2238 // If that method is pure virtual, we can't devirtualize. If this code is
2239 // reached, the result would be UB, not a direct call to the derived class
2240 // function, and we can't assume the derived class function is defined.
2241 if (DevirtualizedMethod->isPure())
2242 return nullptr;
2243
2244 // If that method is marked final, we can devirtualize it.
2245 if (DevirtualizedMethod->hasAttr<FinalAttr>())
2246 return DevirtualizedMethod;
2247
2248 // Similarly, if the class itself or its destructor is marked 'final',
2249 // the class can't be derived from and we can therefore devirtualize the
2250 // member function call.
2251 if (BestDynamicDecl->isEffectivelyFinal())
2252 return DevirtualizedMethod;
2253
2254 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
2255 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2256 if (VD->getType()->isRecordType())
2257 // This is a record decl. We know the type and can devirtualize it.
2258 return DevirtualizedMethod;
2259
2260 return nullptr;
2261 }
2262
2263 // We can devirtualize calls on an object accessed by a class member access
2264 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2265 // a derived class object constructed in the same location.
2266 if (const auto *ME = dyn_cast<MemberExpr>(Base)) {
2267 const ValueDecl *VD = ME->getMemberDecl();
2268 return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;
2269 }
2270
2271 // Likewise for calls on an object accessed by a (non-reference) pointer to
2272 // member access.
2273 if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
2274 if (BO->isPtrMemOp()) {
2275 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2276 if (MPT->getPointeeType()->isRecordType())
2277 return DevirtualizedMethod;
2278 }
2279 }
2280
2281 // We can't devirtualize the call.
2282 return nullptr;
2283}
2284
2285bool CXXMethodDecl::isUsualDeallocationFunction(
2286 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {
2287 assert(PreventedBy.empty() && "PreventedBy is expected to be empty")(static_cast<void> (0));
2288 if (getOverloadedOperator() != OO_Delete &&
2289 getOverloadedOperator() != OO_Array_Delete)
2290 return false;
2291
2292 // C++ [basic.stc.dynamic.deallocation]p2:
2293 // A template instance is never a usual deallocation function,
2294 // regardless of its signature.
2295 if (getPrimaryTemplate())
2296 return false;
2297
2298 // C++ [basic.stc.dynamic.deallocation]p2:
2299 // If a class T has a member deallocation function named operator delete
2300 // with exactly one parameter, then that function is a usual (non-placement)
2301 // deallocation function. [...]
2302 if (getNumParams() == 1)
2303 return true;
2304 unsigned UsualParams = 1;
2305
2306 // C++ P0722:
2307 // A destroying operator delete is a usual deallocation function if
2308 // removing the std::destroying_delete_t parameter and changing the
2309 // first parameter type from T* to void* results in the signature of
2310 // a usual deallocation function.
2311 if (isDestroyingOperatorDelete())
2312 ++UsualParams;
2313
2314 // C++ <=14 [basic.stc.dynamic.deallocation]p2:
2315 // [...] If class T does not declare such an operator delete but does
2316 // declare a member deallocation function named operator delete with
2317 // exactly two parameters, the second of which has type std::size_t (18.1),
2318 // then this function is a usual deallocation function.
2319 //
2320 // C++17 says a usual deallocation function is one with the signature
2321 // (void* [, size_t] [, std::align_val_t] [, ...])
2322 // and all such functions are usual deallocation functions. It's not clear
2323 // that allowing varargs functions was intentional.
2324 ASTContext &Context = getASTContext();
2325 if (UsualParams < getNumParams() &&
2326 Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(),
2327 Context.getSizeType()))
2328 ++UsualParams;
2329
2330 if (UsualParams < getNumParams() &&
2331 getParamDecl(UsualParams)->getType()->isAlignValT())
2332 ++UsualParams;
2333
2334 if (UsualParams != getNumParams())
2335 return false;
2336
2337 // In C++17 onwards, all potential usual deallocation functions are actual
2338 // usual deallocation functions. Honor this behavior when post-C++14
2339 // deallocation functions are offered as extensions too.
2340 // FIXME(EricWF): Destrying Delete should be a language option. How do we
2341 // handle when destroying delete is used prior to C++17?
2342 if (Context.getLangOpts().CPlusPlus17 ||
2343 Context.getLangOpts().AlignedAllocation ||
2344 isDestroyingOperatorDelete())
2345 return true;
2346
2347 // This function is a usual deallocation function if there are no
2348 // single-parameter deallocation functions of the same kind.
2349 DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());
2350 bool Result = true;
2351 for (const auto *D : R) {
2352 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2353 if (FD->getNumParams() == 1) {
2354 PreventedBy.push_back(FD);
2355 Result = false;
2356 }
2357 }
2358 }
2359 return Result;
2360}
2361
2362bool CXXMethodDecl::isCopyAssignmentOperator() const {
2363 // C++0x [class.copy]p17:
2364 // A user-declared copy assignment operator X::operator= is a non-static
2365 // non-template member function of class X with exactly one parameter of
2366 // type X, X&, const X&, volatile X& or const volatile X&.
2367 if (/*operator=*/getOverloadedOperator() != OO_Equal ||
2368 /*non-static*/ isStatic() ||
2369 /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2370 getNumParams() != 1)
2371 return false;
2372
2373 QualType ParamType = getParamDecl(0)->getType();
2374 if (const auto *Ref = ParamType->getAs<LValueReferenceType>())
2375 ParamType = Ref->getPointeeType();
2376
2377 ASTContext &Context = getASTContext();
2378 QualType ClassType
2379 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2380 return Context.hasSameUnqualifiedType(ClassType, ParamType);
2381}
2382
2383bool CXXMethodDecl::isMoveAssignmentOperator() const {
2384 // C++0x [class.copy]p19:
2385 // A user-declared move assignment operator X::operator= is a non-static
2386 // non-template member function of class X with exactly one parameter of type
2387 // X&&, const X&&, volatile X&&, or const volatile X&&.
2388 if (getOverloadedOperator() != OO_Equal || isStatic() ||
2389 getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2390 getNumParams() != 1)
2391 return false;
2392
2393 QualType ParamType = getParamDecl(0)->getType();
2394 if (!isa<RValueReferenceType>(ParamType))
2395 return false;
2396 ParamType = ParamType->getPointeeType();
2397
2398 ASTContext &Context = getASTContext();
2399 QualType ClassType
2400 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2401 return Context.hasSameUnqualifiedType(ClassType, ParamType);
2402}
2403
2404void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
2405 assert(MD->isCanonicalDecl() && "Method is not canonical!")(static_cast<void> (0));
2406 assert(!MD->getParent()->isDependentContext() &&(static_cast<void> (0))
2407 "Can't add an overridden method to a class template!")(static_cast<void> (0));
2408 assert(MD->isVirtual() && "Method is not virtual!")(static_cast<void> (0));
2409
2410 getASTContext().addOverriddenMethod(this, MD);
2411}
2412
2413CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
2414 if (isa<CXXConstructorDecl>(this)) return nullptr;
2415 return getASTContext().overridden_methods_begin(this);
2416}
2417
2418CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
2419 if (isa<CXXConstructorDecl>(this)) return nullptr;
2420 return getASTContext().overridden_methods_end(this);
2421}
2422
2423unsigned CXXMethodDecl::size_overridden_methods() const {
2424 if (isa<CXXConstructorDecl>(this)) return 0;
2425 return getASTContext().overridden_methods_size(this);
2426}
2427
2428CXXMethodDecl::overridden_method_range
2429CXXMethodDecl::overridden_methods() const {
2430 if (isa<CXXConstructorDecl>(this))
2431 return overridden_method_range(nullptr, nullptr);
2432 return getASTContext().overridden_methods(this);
2433}
2434
2435static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,
2436 const CXXRecordDecl *Decl) {
2437 QualType ClassTy = C.getTypeDeclType(Decl);
2438 return C.getQualifiedType(ClassTy, FPT->getMethodQuals());
2439}
2440
2441QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,
2442 const CXXRecordDecl *Decl) {
2443 ASTContext &C = Decl->getASTContext();
2444 QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);
2445 return C.getPointerType(ObjectTy);
2446}
2447
2448QualType CXXMethodDecl::getThisObjectType(const FunctionProtoType *FPT,
2449 const CXXRecordDecl *Decl) {
2450 ASTContext &C = Decl->getASTContext();
2451 return ::getThisObjectType(C, FPT, Decl);
2452}
2453
2454QualType CXXMethodDecl::getThisType() const {
2455 // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
2456 // If the member function is declared const, the type of this is const X*,
2457 // if the member function is declared volatile, the type of this is
2458 // volatile X*, and if the member function is declared const volatile,
2459 // the type of this is const volatile X*.
2460 assert(isInstance() && "No 'this' for static methods!")(static_cast<void> (0));
2461 return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),
2462 getParent());
2463}
2464
2465QualType CXXMethodDecl::getThisObjectType() const {
2466 // Ditto getThisType.
2467 assert(isInstance() && "No 'this' for static methods!")(static_cast<void> (0));
2468 return CXXMethodDecl::getThisObjectType(
2469 getType()->castAs<FunctionProtoType>(), getParent());
2470}
2471
2472bool CXXMethodDecl::hasInlineBody() const {
2473 // If this function is a template instantiation, look at the template from
2474 // which it was instantiated.
2475 const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
2476 if (!CheckFn)
2477 CheckFn = this;
2478
2479 const FunctionDecl *fn;
2480 return CheckFn->isDefined(fn) && !fn->isOutOfLine() &&
2481 (fn->doesThisDeclarationHaveABody() || fn->willHaveBody());
2482}
2483
2484bool CXXMethodDecl::isLambdaStaticInvoker() const {
2485 const CXXRecordDecl *P = getParent();
2486 return P->isLambda() && getDeclName().isIdentifier() &&
2487 getName() == getLambdaStaticInvokerName();
2488}
2489
2490CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2491 TypeSourceInfo *TInfo, bool IsVirtual,
2492 SourceLocation L, Expr *Init,
2493 SourceLocation R,
2494 SourceLocation EllipsisLoc)
2495 : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc),
2496 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
2497 IsWritten(false), SourceOrder(0) {}
2498
2499CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2500 SourceLocation MemberLoc,
2501 SourceLocation L, Expr *Init,
2502 SourceLocation R)
2503 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
2504 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2505 IsWritten(false), SourceOrder(0) {}
2506
2507CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2508 IndirectFieldDecl *Member,
2509 SourceLocation MemberLoc,
2510 SourceLocation L, Expr *Init,
2511 SourceLocation R)
2512 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),
2513 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2514 IsWritten(false), SourceOrder(0) {}
2515
2516CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2517 TypeSourceInfo *TInfo,
2518 SourceLocation L, Expr *Init,
2519 SourceLocation R)
2520 : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),
2521 IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}
2522
2523int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {
2524 return Context.getAllocator()
2525 .identifyKnownAlignedObject<CXXCtorInitializer>(this);
2526}
2527
2528TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
2529 if (isBaseInitializer())
2530 return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
2531 else
2532 return {};
2533}
2534
2535const Type *CXXCtorInitializer::getBaseClass() const {
2536 if (isBaseInitializer())
2537 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
2538 else
2539 return nullptr;
2540}
2541
2542SourceLocation CXXCtorInitializer::getSourceLocation() const {
2543 if (isInClassMemberInitializer())
2544 return getAnyMember()->getLocation();
2545
2546 if (isAnyMemberInitializer())
2547 return getMemberLocation();
2548
2549 if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>())
2550 return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
2551
2552 return {};
2553}
2554
2555SourceRange CXXCtorInitializer::getSourceRange() const {
2556 if (isInClassMemberInitializer()) {
2557 FieldDecl *D = getAnyMember();
2558 if (Expr *I = D->getInClassInitializer())
2559 return I->getSourceRange();
2560 return {};
2561 }
2562
2563 return SourceRange(getSourceLocation(), getRParenLoc());
2564}
2565
2566CXXConstructorDecl::CXXConstructorDecl(
2567 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2568 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2569 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2570 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2571 InheritedConstructor Inherited, Expr *TrailingRequiresClause)
2572 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
2573 SC_None, UsesFPIntrin, isInline, ConstexprKind,
2574 SourceLocation(), TrailingRequiresClause) {
2575 setNumCtorInitializers(0);
2576 setInheritingConstructor(static_cast<bool>(Inherited));
2577 setImplicit(isImplicitlyDeclared);
2578 CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;
2579 if (Inherited)
2580 *getTrailingObjects<InheritedConstructor>() = Inherited;
2581 setExplicitSpecifier(ES);
2582}
2583
2584void CXXConstructorDecl::anchor() {}
2585
2586CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,
2587 unsigned ID,
2588 uint64_t AllocKind) {
2589 bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);
2590 bool isInheritingConstructor =
2591 static_cast<bool>(AllocKind & TAKInheritsConstructor);
2592 unsigned Extra =
2593 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2594 isInheritingConstructor, hasTrailingExplicit);
2595 auto *Result = new (C, ID, Extra) CXXConstructorDecl(
2596 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2597 ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified,
2598 InheritedConstructor(), nullptr);
2599 Result->setInheritingConstructor(isInheritingConstructor);
2600 Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =
2601 hasTrailingExplicit;
2602 Result->setExplicitSpecifier(ExplicitSpecifier());
2603 return Result;
2604}
2605
2606CXXConstructorDecl *CXXConstructorDecl::Create(
2607 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2608 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2609 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2610 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2611 InheritedConstructor Inherited, Expr *TrailingRequiresClause) {
2612 assert(NameInfo.getName().getNameKind()(static_cast<void> (0))
2613 == DeclarationName::CXXConstructorName &&(static_cast<void> (0))
2614 "Name must refer to a constructor")(static_cast<void> (0));
2615 unsigned Extra =
2616 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2617 Inherited ? 1 : 0, ES.getExpr() ? 1 : 0);
2618 return new (C, RD, Extra) CXXConstructorDecl(
2619 C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline,
2620 isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause);
2621}
2622
2623CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {
2624 return CtorInitializers.get(getASTContext().getExternalSource());
2625}
2626
2627CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
2628 assert(isDelegatingConstructor() && "Not a delegating constructor!")(static_cast<void> (0));
2629 Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
2630 if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
2631 return Construct->getConstructor();
2632
2633 return nullptr;
2634}
2635
2636bool CXXConstructorDecl::isDefaultConstructor() const {
2637 // C++ [class.default.ctor]p1:
2638 // A default constructor for a class X is a constructor of class X for
2639 // which each parameter that is not a function parameter pack has a default
2640 // argument (including the case of a constructor with no parameters)
2641 return getMinRequiredArguments() == 0;
2642}
2643
2644bool
2645CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
2646 return isCopyOrMoveConstructor(TypeQuals) &&
2647 getParamDecl(0)->getType()->isLValueReferenceType();
2648}
2649
2650bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
2651 return isCopyOrMoveConstructor(TypeQuals) &&
2652 getParamDecl(0)->getType()->isRValueReferenceType();
2653}
2654
2655/// Determine whether this is a copy or move constructor.
2656bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
2657 // C++ [class.copy]p2:
2658 // A non-template constructor for class X is a copy constructor
2659 // if its first parameter is of type X&, const X&, volatile X& or
2660 // const volatile X&, and either there are no other parameters
2661 // or else all other parameters have default arguments (8.3.6).
2662 // C++0x [class.copy]p3:
2663 // A non-template constructor for class X is a move constructor if its
2664 // first parameter is of type X&&, const X&&, volatile X&&, or
2665 // const volatile X&&, and either there are no other parameters or else
2666 // all other parameters have default arguments.
2667 if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||
2668 getDescribedFunctionTemplate() != nullptr)
2669 return false;
2670
2671 const ParmVarDecl *Param = getParamDecl(0);
2672
2673 // Do we have a reference type?
2674 const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();
2675 if (!ParamRefType)
2676 return false;
2677
2678 // Is it a reference to our class type?
2679 ASTContext &Context = getASTContext();
2680
2681 CanQualType PointeeType
2682 = Context.getCanonicalType(ParamRefType->getPointeeType());
2683 CanQualType ClassTy
2684 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2685 if (PointeeType.getUnqualifiedType() != ClassTy)
2686 return false;
2687
2688 // FIXME: other qualifiers?
2689
2690 // We have a copy or move constructor.
2691 TypeQuals = PointeeType.getCVRQualifiers();
2692 return true;
2693}
2694
2695bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
2696 // C++ [class.conv.ctor]p1:
2697 // A constructor declared without the function-specifier explicit
2698 // that can be called with a single parameter specifies a
2699 // conversion from the type of its first parameter to the type of
2700 // its class. Such a constructor is called a converting
2701 // constructor.
2702 if (isExplicit() && !AllowExplicit)
2703 return false;
2704
2705 // FIXME: This has nothing to do with the definition of converting
2706 // constructor, but is convenient for how we use this function in overload
2707 // resolution.
2708 return getNumParams() == 0
2709 ? getType()->castAs<FunctionProtoType>()->isVariadic()
2710 : getMinRequiredArguments() <= 1;
2711}
2712
2713bool CXXConstructorDecl::isSpecializationCopyingObject() const {
2714 if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)
2715 return false;
2716
2717 const ParmVarDecl *Param = getParamDecl(0);
2718
2719 ASTContext &Context = getASTContext();
2720 CanQualType ParamType = Context.getCanonicalType(Param->getType());
2721
2722 // Is it the same as our class type?
2723 CanQualType ClassTy
2724 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2725 if (ParamType.getUnqualifiedType() != ClassTy)
2726 return false;
2727
2728 return true;
2729}
2730
2731void CXXDestructorDecl::anchor() {}
2732
2733CXXDestructorDecl *
2734CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2735 return new (C, ID) CXXDestructorDecl(
2736 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2737 false, false, false, ConstexprSpecKind::Unspecified, nullptr);
2738}
2739
2740CXXDestructorDecl *CXXDestructorDecl::Create(
2741 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2742 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2743 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,
2744 ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) {
2745 assert(NameInfo.getName().getNameKind()(static_cast<void> (0))
2746 == DeclarationName::CXXDestructorName &&(static_cast<void> (0))
2747 "Name must refer to a destructor")(static_cast<void> (0));
2748 return new (C, RD) CXXDestructorDecl(
2749 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline,
2750 isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause);
2751}
2752
2753void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {
2754 auto *First = cast<CXXDestructorDecl>(getFirstDecl());
2755 if (OD && !First->OperatorDelete) {
2756 First->OperatorDelete = OD;
2757 First->OperatorDeleteThisArg = ThisArg;
2758 if (auto *L = getASTMutationListener())
2759 L->ResolvedOperatorDelete(First, OD, ThisArg);
2760 }
2761}
2762
2763void CXXConversionDecl::anchor() {}
2764
2765CXXConversionDecl *
2766CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2767 return new (C, ID) CXXConversionDecl(
2768 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2769 false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
2770 SourceLocation(), nullptr);
2771}
2772
2773CXXConversionDecl *CXXConversionDecl::Create(
2774 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2775 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2776 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,
2777 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2778 Expr *TrailingRequiresClause) {
2779 assert(NameInfo.getName().getNameKind()(static_cast<void> (0))
2780 == DeclarationName::CXXConversionFunctionName &&(static_cast<void> (0))
2781 "Name must refer to a conversion function")(static_cast<void> (0));
2782 return new (C, RD) CXXConversionDecl(
2783 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES,
2784 ConstexprKind, EndLocation, TrailingRequiresClause);
2785}
2786
2787bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
2788 return isImplicit() && getParent()->isLambda() &&
2789 getConversionType()->isBlockPointerType();
2790}
2791
2792LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2793 SourceLocation LangLoc, LanguageIDs lang,
2794 bool HasBraces)
2795 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
2796 ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {
2797 setLanguage(lang);
2798 LinkageSpecDeclBits.HasBraces = HasBraces;
2799}
2800
2801void LinkageSpecDecl::anchor() {}
2802
2803LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
2804 DeclContext *DC,
2805 SourceLocation ExternLoc,
2806 SourceLocation LangLoc,
2807 LanguageIDs Lang,
2808 bool HasBraces) {
2809 return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
2810}
2811
2812LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,
2813 unsigned ID) {
2814 return new (C, ID) LinkageSpecDecl(nullptr, SourceLocation(),
2815 SourceLocation(), lang_c, false);
2816}
2817
2818void UsingDirectiveDecl::anchor() {}
2819
2820UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
2821 SourceLocation L,
2822 SourceLocation NamespaceLoc,
2823 NestedNameSpecifierLoc QualifierLoc,
2824 SourceLocation IdentLoc,
2825 NamedDecl *Used,
2826 DeclContext *CommonAncestor) {
2827 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used))
2828 Used = NS->getOriginalNamespace();
2829 return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
2830 IdentLoc, Used, CommonAncestor);
2831}
2832
2833UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,
2834 unsigned ID) {
2835 return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),
2836 SourceLocation(),
2837 NestedNameSpecifierLoc(),
2838 SourceLocation(), nullptr, nullptr);
2839}
2840
2841NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
2842 if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
2843 return NA->getNamespace();
2844 return cast_or_null<NamespaceDecl>(NominatedNamespace);
2845}
2846
2847NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
2848 SourceLocation StartLoc, SourceLocation IdLoc,
2849 IdentifierInfo *Id, NamespaceDecl *PrevDecl)
2850 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
2851 redeclarable_base(C), LocStart(StartLoc),
2852 AnonOrFirstNamespaceAndInline(nullptr, Inline) {
2853 setPreviousDecl(PrevDecl);
2854
2855 if (PrevDecl)
2856 AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
2857}
2858
2859NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
2860 bool Inline, SourceLocation StartLoc,
2861 SourceLocation IdLoc, IdentifierInfo *Id,
2862 NamespaceDecl *PrevDecl) {
2863 return new (C, DC) NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id,
2864 PrevDecl);
2865}
2866
2867NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2868 return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),
2869 SourceLocation(), nullptr, nullptr);
2870}
2871
2872NamespaceDecl *NamespaceDecl::getOriginalNamespace() {
2873 if (isFirstDecl())
2874 return this;
2875
2876 return AnonOrFirstNamespaceAndInline.getPointer();
2877}
2878
2879const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const {
2880 if (isFirstDecl())
2881 return this;
2882
2883 return AnonOrFirstNamespaceAndInline.getPointer();
2884}
2885
2886bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); }
2887
2888NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {
2889 return getNextRedeclaration();
2890}
2891
2892NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {
2893 return getPreviousDecl();
2894}
2895
2896NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {
2897 return getMostRecentDecl();
2898}
2899
2900void NamespaceAliasDecl::anchor() {}
2901
2902NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {
2903 return getNextRedeclaration();
2904}
2905
2906NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {
2907 return getPreviousDecl();
2908}
2909
2910NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {
2911 return getMostRecentDecl();
2912}
2913
2914NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
2915 SourceLocation UsingLoc,
2916 SourceLocation AliasLoc,
2917 IdentifierInfo *Alias,
2918 NestedNameSpecifierLoc QualifierLoc,
2919 SourceLocation IdentLoc,
2920 NamedDecl *Namespace) {
2921 // FIXME: Preserve the aliased namespace as written.
2922 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
2923 Namespace = NS->getOriginalNamespace();
2924 return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,
2925 QualifierLoc, IdentLoc, Namespace);
2926}
2927
2928NamespaceAliasDecl *
2929NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2930 return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),
2931 SourceLocation(), nullptr,
2932 NestedNameSpecifierLoc(),
2933 SourceLocation(), nullptr);
2934}
2935
2936void LifetimeExtendedTemporaryDecl::anchor() {}
2937
2938/// Retrieve the storage duration for the materialized temporary.
2939StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {
2940 const ValueDecl *ExtendingDecl = getExtendingDecl();
2941 if (!ExtendingDecl)
2942 return SD_FullExpression;
2943 // FIXME: This is not necessarily correct for a temporary materialized
2944 // within a default initializer.
2945 if (isa<FieldDecl>(ExtendingDecl))
2946 return SD_Automatic;
2947 // FIXME: This only works because storage class specifiers are not allowed
2948 // on decomposition declarations.
2949 if (isa<BindingDecl>(ExtendingDecl))
2950 return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic
2951 : SD_Static;
2952 return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
2953}
2954
2955APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {
2956 assert(getStorageDuration() == SD_Static &&(static_cast<void> (0))
2957 "don't need to cache the computed value for this temporary")(static_cast<void> (0));
2958 if (MayCreate && !Value) {
2959 Value = (new (getASTContext()) APValue);
2960 getASTContext().addDestruction(Value);
2961 }
2962 assert(Value && "may not be null")(static_cast<void> (0));
2963 return Value;
2964}
2965
2966void UsingShadowDecl::anchor() {}
2967
2968UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,
2969 SourceLocation Loc, DeclarationName Name,
2970 BaseUsingDecl *Introducer, NamedDecl *Target)
2971 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),
2972 UsingOrNextShadow(Introducer) {
2973 if (Target)
2974 setTargetDecl(Target);
2975 setImplicit();
2976}
2977
2978UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)
2979 : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),
2980 redeclarable_base(C) {}
2981
2982UsingShadowDecl *
2983UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2984 return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());
2985}
2986
2987BaseUsingDecl *UsingShadowDecl::getIntroducer() const {
2988 const UsingShadowDecl *Shadow = this;
2989 while (const auto *NextShadow =
2990 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
2991 Shadow = NextShadow;
2992 return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow);
2993}
2994
2995void ConstructorUsingShadowDecl::anchor() {}
2996
2997ConstructorUsingShadowDecl *
2998ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,
2999 SourceLocation Loc, UsingDecl *Using,
3000 NamedDecl *Target, bool IsVirtual) {
3001 return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,
3002 IsVirtual);
3003}
3004
3005ConstructorUsingShadowDecl *
3006ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3007 return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());
3008}
3009
3010CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {
3011 return getIntroducer()->getQualifier()->getAsRecordDecl();
3012}
3013
3014void BaseUsingDecl::anchor() {}
3015
3016void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) {
3017 assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&(static_cast<void> (0))
3018 "declaration already in set")(static_cast<void> (0));
3019 assert(S->getIntroducer() == this)(static_cast<void> (0));
3020
3021 if (FirstUsingShadow.getPointer())
3022 S->UsingOrNextShadow = FirstUsingShadow.getPointer();
3023 FirstUsingShadow.setPointer(S);
3024}
3025
3026void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) {
3027 assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&(static_cast<void> (0))
3028 "declaration not in set")(static_cast<void> (0));
3029 assert(S->getIntroducer() == this)(static_cast<void> (0));
3030
3031 // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
3032
3033 if (FirstUsingShadow.getPointer() == S) {
3034 FirstUsingShadow.setPointer(
3035 dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
3036 S->UsingOrNextShadow = this;
3037 return;
3038 }
3039
3040 UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
3041 while (Prev->UsingOrNextShadow != S)
3042 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
3043 Prev->UsingOrNextShadow = S->UsingOrNextShadow;
3044 S->UsingOrNextShadow = this;
3045}
3046
3047void UsingDecl::anchor() {}
3048
3049UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
3050 NestedNameSpecifierLoc QualifierLoc,
3051 const DeclarationNameInfo &NameInfo,
3052 bool HasTypename) {
3053 return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);
3054}
3055
3056UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3057 return new (C, ID) UsingDecl(nullptr, SourceLocation(),
3058 NestedNameSpecifierLoc(), DeclarationNameInfo(),
3059 false);
3060}
3061
3062SourceRange UsingDecl::getSourceRange() const {
3063 SourceLocation Begin = isAccessDeclaration()
3064 ? getQualifierLoc().getBeginLoc() : UsingLocation;
3065 return SourceRange(Begin, getNameInfo().getEndLoc());
3066}
3067
3068void UsingEnumDecl::anchor() {}
3069
3070UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC,
3071 SourceLocation UL, SourceLocation EL,
3072 SourceLocation NL, EnumDecl *Enum) {
3073 return new (C, DC) UsingEnumDecl(DC, Enum->getDeclName(), UL, EL, NL, Enum);
3074}
3075
3076UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3077 return new (C, ID) UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(),
3078 SourceLocation(), SourceLocation(), nullptr);
3079}
3080
3081SourceRange UsingEnumDecl::getSourceRange() const {
3082 return SourceRange(EnumLocation, getLocation());
3083}
3084
3085void UsingPackDecl::anchor() {}
3086
3087UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,
3088 NamedDecl *InstantiatedFrom,
3089 ArrayRef<NamedDecl *> UsingDecls) {
3090 size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size());
3091 return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);
3092}
3093
3094UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3095 unsigned NumExpansions) {
3096 size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions);
3097 auto *Result = new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, None);
3098 Result->NumExpansions = NumExpansions;
3099 auto *Trail = Result->getTrailingObjects<NamedDecl *>();
3100 for (unsigned I = 0; I != NumExpansions; ++I)
3101 new (Trail + I) NamedDecl*(nullptr);
3102 return Result;
3103}
3104
3105void UnresolvedUsingValueDecl::anchor() {}
3106
3107UnresolvedUsingValueDecl *
3108UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
3109 SourceLocation UsingLoc,
3110 NestedNameSpecifierLoc QualifierLoc,
3111 const DeclarationNameInfo &NameInfo,
3112 SourceLocation EllipsisLoc) {
3113 return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
3114 QualifierLoc, NameInfo,
3115 EllipsisLoc);
3116}
3117
3118UnresolvedUsingValueDecl *
3119UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3120 return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),
3121 SourceLocation(),
3122 NestedNameSpecifierLoc(),
3123 DeclarationNameInfo(),
3124 SourceLocation());
3125}
3126
3127SourceRange UnresolvedUsingValueDecl::getSourceRange() const {
3128 SourceLocation Begin = isAccessDeclaration()
3129 ? getQualifierLoc().getBeginLoc() : UsingLocation;
3130 return SourceRange(Begin, getNameInfo().getEndLoc());
3131}
3132
3133void UnresolvedUsingTypenameDecl::anchor() {}
3134
3135UnresolvedUsingTypenameDecl *
3136UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
3137 SourceLocation UsingLoc,
3138 SourceLocation TypenameLoc,
3139 NestedNameSpecifierLoc QualifierLoc,
3140 SourceLocation TargetNameLoc,
3141 DeclarationName TargetName,
3142 SourceLocation EllipsisLoc) {
3143 return new (C, DC) UnresolvedUsingTypenameDecl(
3144 DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,
3145 TargetName.getAsIdentifierInfo(), EllipsisLoc);
3146}
3147
3148UnresolvedUsingTypenameDecl *
3149UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3150 return new (C, ID) UnresolvedUsingTypenameDecl(
3151 nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),
3152 SourceLocation(), nullptr, SourceLocation());
3153}
3154
3155UnresolvedUsingIfExistsDecl *
3156UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC,
3157 SourceLocation Loc, DeclarationName Name) {
3158 return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name);
3159}
3160
3161UnresolvedUsingIfExistsDecl *
3162UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx, unsigned ID) {
3163 return new (Ctx, ID)
3164 UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName());
3165}
3166
3167UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC,
3168 SourceLocation Loc,
3169 DeclarationName Name)
3170 : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {}
3171
3172void UnresolvedUsingIfExistsDecl::anchor() {}
3173
3174void StaticAssertDecl::anchor() {}
3175
3176StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
3177 SourceLocation StaticAssertLoc,
3178 Expr *AssertExpr,
3179 StringLiteral *Message,
3180 SourceLocation RParenLoc,
3181 bool Failed) {
3182 return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
3183 RParenLoc, Failed);
3184}
3185
3186StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
3187 unsigned ID) {
3188 return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,
3189 nullptr, SourceLocation(), false);
3190}
3191
3192void BindingDecl::anchor() {}
3193
3194BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
3195 SourceLocation IdLoc, IdentifierInfo *Id) {
3196 return new (C, DC) BindingDecl(DC, IdLoc, Id);
3197}
3198
3199BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3200 return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
3201}
3202
3203VarDecl *BindingDecl::getHoldingVar() const {
3204 Expr *B = getBinding();
3205 if (!B)
3206 return nullptr;
3207 auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit());
3208 if (!DRE)
3209 return nullptr;
3210
3211 auto *VD = cast<VarDecl>(DRE->getDecl());
3212 assert(VD->isImplicit() && "holding var for binding decl not implicit")(static_cast<void> (0));
3213 return VD;
3214}
3215
3216void DecompositionDecl::anchor() {}
3217
3218DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,
3219 SourceLocation StartLoc,
3220 SourceLocation LSquareLoc,
3221 QualType T, TypeSourceInfo *TInfo,
3222 StorageClass SC,
3223 ArrayRef<BindingDecl *> Bindings) {
3224 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size());
3225 return new (C, DC, Extra)
3226 DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);
3227}
3228
3229DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,
3230 unsigned ID,
3231 unsigned NumBindings) {
3232 size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings);
3233 auto *Result = new (C, ID, Extra)
3234 DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),
3235 QualType(), nullptr, StorageClass(), None);
3236 // Set up and clean out the bindings array.
3237 Result->NumBindings = NumBindings;
3238 auto *Trail = Result->getTrailingObjects<BindingDecl *>();
3239 for (unsigned I = 0; I != NumBindings; ++I)
3240 new (Trail + I) BindingDecl*(nullptr);
3241 return Result;
3242}
3243
3244void DecompositionDecl::printName(llvm::raw_ostream &os) const {
3245 os << '[';
3246 bool Comma = false;
3247 for (const auto *B : bindings()) {
3248 if (Comma)
3249 os << ", ";
3250 B->printName(os);
3251 Comma = true;
3252 }
3253 os << ']';
3254}
3255
3256void MSPropertyDecl::anchor() {}
3257
3258MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,
3259 SourceLocation L, DeclarationName N,
3260 QualType T, TypeSourceInfo *TInfo,
3261 SourceLocation StartL,
3262 IdentifierInfo *Getter,
3263 IdentifierInfo *Setter) {
3264 return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);
3265}
3266
3267MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
3268 unsigned ID) {
3269 return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),
3270 DeclarationName(), QualType(), nullptr,
3271 SourceLocation(), nullptr, nullptr);
3272}
3273
3274void MSGuidDecl::anchor() {}
3275
3276MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)
3277 : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),
3278 PartVal(P), APVal() {}
3279
3280MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {
3281 DeclContext *DC = C.getTranslationUnitDecl();
3282 return new (C, DC) MSGuidDecl(DC, T, P);
3283}
3284
3285MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3286 return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());
3287}
3288
3289void MSGuidDecl::printName(llvm::raw_ostream &OS) const {
3290 OS << llvm::format("GUID{%08" PRIx32"x" "-%04" PRIx16"x" "-%04" PRIx16"x" "-",
3291 PartVal.Part1, PartVal.Part2, PartVal.Part3);
3292 unsigned I = 0;
3293 for (uint8_t Byte : PartVal.Part4And5) {
3294 OS << llvm::format("%02" PRIx8"x", Byte);
3295 if (++I == 2)
3296 OS << '-';
3297 }
3298 OS << '}';
3299}
3300
3301/// Determine if T is a valid 'struct _GUID' of the shape that we expect.
3302static bool isValidStructGUID(ASTContext &Ctx, QualType T) {
3303 // FIXME: We only need to check this once, not once each time we compute a
3304 // GUID APValue.
3305 using MatcherRef = llvm::function_ref<bool(QualType)>;
3306
3307 auto IsInt = [&Ctx](unsigned N) {
3308 return [&Ctx, N](QualType T) {
3309 return T->isUnsignedIntegerOrEnumerationType() &&
3310 Ctx.getIntWidth(T) == N;
3311 };
3312 };
3313
3314 auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {
3315 return [&Ctx, Elem, N](QualType T) {
3316 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);
3317 return CAT && CAT->getSize() == N && Elem(CAT->getElementType());
3318 };
3319 };
3320
3321 auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {
3322 return [Fields](QualType T) {
3323 const RecordDecl *RD = T->getAsRecordDecl();
3324 if (!RD || RD->isUnion())
3325 return false;
3326 RD = RD->getDefinition();
3327 if (!RD)
3328 return false;
3329 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3330 if (CXXRD->getNumBases())
3331 return false;
3332 auto MatcherIt = Fields.begin();
3333 for (const FieldDecl *FD : RD->fields()) {
3334 if (FD->isUnnamedBitfield()) continue;
3335 if (FD->isBitField() || MatcherIt == Fields.end() ||
3336 !(*MatcherIt)(FD->getType()))
3337 return false;
3338 ++MatcherIt;
3339 }
3340 return MatcherIt == Fields.end();
3341 };
3342 };
3343
3344 // We expect an {i32, i16, i16, [8 x i8]}.
3345 return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);
3346}
3347
3348APValue &MSGuidDecl::getAsAPValue() const {
3349 if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {
3350 using llvm::APInt;
3351 using llvm::APSInt;
3352 APVal = APValue(APValue::UninitStruct(), 0, 4);
3353 APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true));
3354 APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true));
3355 APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true));
3356 APValue &Arr = APVal.getStructField(3) =
3357 APValue(APValue::UninitArray(), 8, 8);
3358 for (unsigned I = 0; I != 8; ++I) {
3359 Arr.getArrayInitializedElt(I) =
3360 APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));
3361 }
3362 // Register this APValue to be destroyed if necessary. (Note that the
3363 // MSGuidDecl destructor is never run.)
3364 getASTContext().addDestruction(&APVal);
3365 }
3366
3367 return APVal;
3368}
3369
3370static const char *getAccessName(AccessSpecifier AS) {
3371 switch (AS) {
3372 case AS_none:
3373 llvm_unreachable("Invalid access specifier!")__builtin_unreachable();
3374 case AS_public:
3375 return "public";
3376 case AS_private:
3377 return "private";
3378 case AS_protected:
3379 return "protected";
3380 }
3381 llvm_unreachable("Invalid access specifier!")__builtin_unreachable();
3382}
3383
3384const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,
3385 AccessSpecifier AS) {
3386 return DB << getAccessName(AS);
3387}

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/AST/DeclCXX.h

1//===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
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/// \file
10/// Defines the C++ Decl subclasses, other than those for templates
11/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLCXX_H
16#define LLVM_CLANG_AST_DECLCXX_H
17
18#include "clang/AST/ASTUnresolvedSet.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/AST/LambdaCapture.h"
25#include "clang/AST/NestedNameSpecifier.h"
26#include "clang/AST/Redeclarable.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/Lambda.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/OperatorKinds.h"
35#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/Specifiers.h"
37#include "llvm/ADT/ArrayRef.h"
38#include "llvm/ADT/DenseMap.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/TinyPtrVector.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/PointerLikeTypeTraits.h"
47#include "llvm/Support/TrailingObjects.h"
48#include <cassert>
49#include <cstddef>
50#include <iterator>
51#include <memory>
52#include <vector>
53
54namespace clang {
55
56class ASTContext;
57class ClassTemplateDecl;
58class ConstructorUsingShadowDecl;
59class CXXBasePath;
60class CXXBasePaths;
61class CXXConstructorDecl;
62class CXXDestructorDecl;
63class CXXFinalOverriderMap;
64class CXXIndirectPrimaryBaseSet;
65class CXXMethodDecl;
66class DecompositionDecl;
67class DiagnosticBuilder;
68class FriendDecl;
69class FunctionTemplateDecl;
70class IdentifierInfo;
71class MemberSpecializationInfo;
72class BaseUsingDecl;
73class TemplateDecl;
74class TemplateParameterList;
75class UsingDecl;
76
77/// Represents an access specifier followed by colon ':'.
78///
79/// An objects of this class represents sugar for the syntactic occurrence
80/// of an access specifier followed by a colon in the list of member
81/// specifiers of a C++ class definition.
82///
83/// Note that they do not represent other uses of access specifiers,
84/// such as those occurring in a list of base specifiers.
85/// Also note that this class has nothing to do with so-called
86/// "access declarations" (C++98 11.3 [class.access.dcl]).
87class AccessSpecDecl : public Decl {
88 /// The location of the ':'.
89 SourceLocation ColonLoc;
90
91 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
92 SourceLocation ASLoc, SourceLocation ColonLoc)
93 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
94 setAccess(AS);
95 }
96
97 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
98
99 virtual void anchor();
100
101public:
102 /// The location of the access specifier.
103 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
104
105 /// Sets the location of the access specifier.
106 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
107
108 /// The location of the colon following the access specifier.
109 SourceLocation getColonLoc() const { return ColonLoc; }
110
111 /// Sets the location of the colon.
112 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
113
114 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
115 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
116 }
117
118 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
119 DeclContext *DC, SourceLocation ASLoc,
120 SourceLocation ColonLoc) {
121 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
122 }
123
124 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == AccessSpec; }
129};
130
131/// Represents a base class of a C++ class.
132///
133/// Each CXXBaseSpecifier represents a single, direct base class (or
134/// struct) of a C++ class (or struct). It specifies the type of that
135/// base class, whether it is a virtual or non-virtual base, and what
136/// level of access (public, protected, private) is used for the
137/// derivation. For example:
138///
139/// \code
140/// class A { };
141/// class B { };
142/// class C : public virtual A, protected B { };
143/// \endcode
144///
145/// In this code, C will have two CXXBaseSpecifiers, one for "public
146/// virtual A" and the other for "protected B".
147class CXXBaseSpecifier {
148 /// The source code range that covers the full base
149 /// specifier, including the "virtual" (if present) and access
150 /// specifier (if present).
151 SourceRange Range;
152
153 /// The source location of the ellipsis, if this is a pack
154 /// expansion.
155 SourceLocation EllipsisLoc;
156
157 /// Whether this is a virtual base class or not.
158 unsigned Virtual : 1;
159
160 /// Whether this is the base of a class (true) or of a struct (false).
161 ///
162 /// This determines the mapping from the access specifier as written in the
163 /// source code to the access specifier used for semantic analysis.
164 unsigned BaseOfClass : 1;
165
166 /// Access specifier as written in the source code (may be AS_none).
167 ///
168 /// The actual type of data stored here is an AccessSpecifier, but we use
169 /// "unsigned" here to work around a VC++ bug.
170 unsigned Access : 2;
171
172 /// Whether the class contains a using declaration
173 /// to inherit the named class's constructors.
174 unsigned InheritConstructors : 1;
175
176 /// The type of the base class.
177 ///
178 /// This will be a class or struct (or a typedef of such). The source code
179 /// range does not include the \c virtual or the access specifier.
180 TypeSourceInfo *BaseTypeInfo;
181
182public:
183 CXXBaseSpecifier() = default;
184 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
185 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
186 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
187 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
188
189 /// Retrieves the source range that contains the entire base specifier.
190 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
191 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
192 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
193
194 /// Get the location at which the base class type was written.
195 SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) {
196 return BaseTypeInfo->getTypeLoc().getBeginLoc();
197 }
198
199 /// Determines whether the base class is a virtual base class (or not).
200 bool isVirtual() const { return Virtual; }
201
202 /// Determine whether this base class is a base of a class declared
203 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
204 bool isBaseOfClass() const { return BaseOfClass; }
205
206 /// Determine whether this base specifier is a pack expansion.
207 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
208
209 /// Determine whether this base class's constructors get inherited.
210 bool getInheritConstructors() const { return InheritConstructors; }
211
212 /// Set that this base class's constructors should be inherited.
213 void setInheritConstructors(bool Inherit = true) {
214 InheritConstructors = Inherit;
215 }
216
217 /// For a pack expansion, determine the location of the ellipsis.
218 SourceLocation getEllipsisLoc() const {
219 return EllipsisLoc;
220 }
221
222 /// Returns the access specifier for this base specifier.
223 ///
224 /// This is the actual base specifier as used for semantic analysis, so
225 /// the result can never be AS_none. To retrieve the access specifier as
226 /// written in the source code, use getAccessSpecifierAsWritten().
227 AccessSpecifier getAccessSpecifier() const {
228 if ((AccessSpecifier)Access == AS_none)
229 return BaseOfClass? AS_private : AS_public;
230 else
231 return (AccessSpecifier)Access;
232 }
233
234 /// Retrieves the access specifier as written in the source code
235 /// (which may mean that no access specifier was explicitly written).
236 ///
237 /// Use getAccessSpecifier() to retrieve the access specifier for use in
238 /// semantic analysis.
239 AccessSpecifier getAccessSpecifierAsWritten() const {
240 return (AccessSpecifier)Access;
241 }
242
243 /// Retrieves the type of the base class.
244 ///
245 /// This type will always be an unqualified class type.
246 QualType getType() const {
247 return BaseTypeInfo->getType().getUnqualifiedType();
248 }
249
250 /// Retrieves the type and source location of the base class.
251 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
252};
253
254/// Represents a C++ struct/union/class.
255class CXXRecordDecl : public RecordDecl {
256 friend class ASTDeclReader;
257 friend class ASTDeclWriter;
258 friend class ASTNodeImporter;
259 friend class ASTReader;
260 friend class ASTRecordWriter;
261 friend class ASTWriter;
262 friend class DeclContext;
263 friend class LambdaExpr;
264
265 friend void FunctionDecl::setPure(bool);
266 friend void TagDecl::startDefinition();
267
268 /// Values used in DefinitionData fields to represent special members.
269 enum SpecialMemberFlags {
270 SMF_DefaultConstructor = 0x1,
271 SMF_CopyConstructor = 0x2,
272 SMF_MoveConstructor = 0x4,
273 SMF_CopyAssignment = 0x8,
274 SMF_MoveAssignment = 0x10,
275 SMF_Destructor = 0x20,
276 SMF_All = 0x3f
277 };
278
279 struct DefinitionData {
280 #define FIELD(Name, Width, Merge) \
281 unsigned Name : Width;
282 #include "CXXRecordDeclDefinitionBits.def"
283
284 /// Whether this class describes a C++ lambda.
285 unsigned IsLambda : 1;
286
287 /// Whether we are currently parsing base specifiers.
288 unsigned IsParsingBaseSpecifiers : 1;
289
290 /// True when visible conversion functions are already computed
291 /// and are available.
292 unsigned ComputedVisibleConversions : 1;
293
294 unsigned HasODRHash : 1;
295
296 /// A hash of parts of the class to help in ODR checking.
297 unsigned ODRHash = 0;
298
299 /// The number of base class specifiers in Bases.
300 unsigned NumBases = 0;
301
302 /// The number of virtual base class specifiers in VBases.
303 unsigned NumVBases = 0;
304
305 /// Base classes of this class.
306 ///
307 /// FIXME: This is wasted space for a union.
308 LazyCXXBaseSpecifiersPtr Bases;
309
310 /// direct and indirect virtual base classes of this class.
311 LazyCXXBaseSpecifiersPtr VBases;
312
313 /// The conversion functions of this C++ class (but not its
314 /// inherited conversion functions).
315 ///
316 /// Each of the entries in this overload set is a CXXConversionDecl.
317 LazyASTUnresolvedSet Conversions;
318
319 /// The conversion functions of this C++ class and all those
320 /// inherited conversion functions that are visible in this class.
321 ///
322 /// Each of the entries in this overload set is a CXXConversionDecl or a
323 /// FunctionTemplateDecl.
324 LazyASTUnresolvedSet VisibleConversions;
325
326 /// The declaration which defines this record.
327 CXXRecordDecl *Definition;
328
329 /// The first friend declaration in this class, or null if there
330 /// aren't any.
331 ///
332 /// This is actually currently stored in reverse order.
333 LazyDeclPtr FirstFriend;
334
335 DefinitionData(CXXRecordDecl *D);
336
337 /// Retrieve the set of direct base classes.
338 CXXBaseSpecifier *getBases() const {
339 if (!Bases.isOffset())
4
Assuming the condition is true
5
Taking true branch
340 return Bases.get(nullptr);
6
Passing null pointer value via 1st parameter 'Source'
7
Calling 'LazyOffsetPtr::get'
341 return getBasesSlowCase();
342 }
343
344 /// Retrieve the set of virtual base classes.
345 CXXBaseSpecifier *getVBases() const {
346 if (!VBases.isOffset())
347 return VBases.get(nullptr);
348 return getVBasesSlowCase();
349 }
350
351 ArrayRef<CXXBaseSpecifier> bases() const {
352 return llvm::makeArrayRef(getBases(), NumBases);
353 }
354
355 ArrayRef<CXXBaseSpecifier> vbases() const {
356 return llvm::makeArrayRef(getVBases(), NumVBases);
357 }
358
359 private:
360 CXXBaseSpecifier *getBasesSlowCase() const;
361 CXXBaseSpecifier *getVBasesSlowCase() const;
362 };
363
364 struct DefinitionData *DefinitionData;
365
366 /// Describes a C++ closure type (generated by a lambda expression).
367 struct LambdaDefinitionData : public DefinitionData {
368 using Capture = LambdaCapture;
369
370 /// Whether this lambda is known to be dependent, even if its
371 /// context isn't dependent.
372 ///
373 /// A lambda with a non-dependent context can be dependent if it occurs
374 /// within the default argument of a function template, because the
375 /// lambda will have been created with the enclosing context as its
376 /// declaration context, rather than function. This is an unfortunate
377 /// artifact of having to parse the default arguments before.
378 unsigned Dependent : 1;
379
380 /// Whether this lambda is a generic lambda.
381 unsigned IsGenericLambda : 1;
382
383 /// The Default Capture.
384 unsigned CaptureDefault : 2;
385
386 /// The number of captures in this lambda is limited 2^NumCaptures.
387 unsigned NumCaptures : 15;
388
389 /// The number of explicit captures in this lambda.
390 unsigned NumExplicitCaptures : 13;
391
392 /// Has known `internal` linkage.
393 unsigned HasKnownInternalLinkage : 1;
394
395 /// The number used to indicate this lambda expression for name
396 /// mangling in the Itanium C++ ABI.
397 unsigned ManglingNumber : 31;
398
399 /// The declaration that provides context for this lambda, if the
400 /// actual DeclContext does not suffice. This is used for lambdas that
401 /// occur within default arguments of function parameters within the class
402 /// or within a data member initializer.
403 LazyDeclPtr ContextDecl;
404
405 /// The list of captures, both explicit and implicit, for this
406 /// lambda.
407 Capture *Captures = nullptr;
408
409 /// The type of the call method.
410 TypeSourceInfo *MethodTyInfo;
411
412 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent,
413 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
414 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
415 CaptureDefault(CaptureDefault), NumCaptures(0),
416 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
417 MethodTyInfo(Info) {
418 IsLambda = true;
419
420 // C++1z [expr.prim.lambda]p4:
421 // This class type is not an aggregate type.
422 Aggregate = false;
423 PlainOldData = false;
424 }
425 };
426
427 struct DefinitionData *dataPtr() const {
428 // Complete the redecl chain (if necessary).
429 getMostRecentDecl();
430 return DefinitionData;
431 }
432
433 struct DefinitionData &data() const {
434 auto *DD = dataPtr();
435 assert(DD && "queried property of class with no definition")(static_cast<void> (0));
436 return *DD;
437 }
438
439 struct LambdaDefinitionData &getLambdaData() const {
440 // No update required: a merged definition cannot change any lambda
441 // properties.
442 auto *DD = DefinitionData;
443 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")(static_cast<void> (0));
444 return static_cast<LambdaDefinitionData&>(*DD);
445 }
446
447 /// The template or declaration that this declaration
448 /// describes or was instantiated from, respectively.
449 ///
450 /// For non-templates, this value will be null. For record
451 /// declarations that describe a class template, this will be a
452 /// pointer to a ClassTemplateDecl. For member
453 /// classes of class template specializations, this will be the
454 /// MemberSpecializationInfo referring to the member class that was
455 /// instantiated or specialized.
456 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
457 TemplateOrInstantiation;
458
459 /// Called from setBases and addedMember to notify the class that a
460 /// direct or virtual base class or a member of class type has been added.
461 void addedClassSubobject(CXXRecordDecl *Base);
462
463 /// Notify the class that member has been added.
464 ///
465 /// This routine helps maintain information about the class based on which
466 /// members have been added. It will be invoked by DeclContext::addDecl()
467 /// whenever a member is added to this record.
468 void addedMember(Decl *D);
469
470 void markedVirtualFunctionPure();
471
472 /// Get the head of our list of friend declarations, possibly
473 /// deserializing the friends from an external AST source.
474 FriendDecl *getFirstFriend() const;
475
476 /// Determine whether this class has an empty base class subobject of type X
477 /// or of one of the types that might be at offset 0 within X (per the C++
478 /// "standard layout" rules).
479 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
480 const CXXRecordDecl *X);
481
482protected:
483 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
484 SourceLocation StartLoc, SourceLocation IdLoc,
485 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
486
487public:
488 /// Iterator that traverses the base classes of a class.
489 using base_class_iterator = CXXBaseSpecifier *;
490
491 /// Iterator that traverses the base classes of a class.
492 using base_class_const_iterator = const CXXBaseSpecifier *;
493
494 CXXRecordDecl *getCanonicalDecl() override {
495 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
496 }
497
498 const CXXRecordDecl *getCanonicalDecl() const {
499 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
500 }
501
502 CXXRecordDecl *getPreviousDecl() {
503 return cast_or_null<CXXRecordDecl>(
504 static_cast<RecordDecl *>(this)->getPreviousDecl());
505 }
506
507 const CXXRecordDecl *getPreviousDecl() const {
508 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
509 }
510
511 CXXRecordDecl *getMostRecentDecl() {
512 return cast<CXXRecordDecl>(
513 static_cast<RecordDecl *>(this)->getMostRecentDecl());
514 }
515
516 const CXXRecordDecl *getMostRecentDecl() const {
517 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
518 }
519
520 CXXRecordDecl *getMostRecentNonInjectedDecl() {
521 CXXRecordDecl *Recent =
522 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
523 while (Recent->isInjectedClassName()) {
524 // FIXME: Does injected class name need to be in the redeclarations chain?
525 assert(Recent->getPreviousDecl())(static_cast<void> (0));
526 Recent = Recent->getPreviousDecl();
527 }
528 return Recent;
529 }
530
531 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
532 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
533 }
534
535 CXXRecordDecl *getDefinition() const {
536 // We only need an update if we don't already know which
537 // declaration is the definition.
538 auto *DD = DefinitionData ? DefinitionData : dataPtr();
539 return DD ? DD->Definition : nullptr;
540 }
541
542 bool hasDefinition() const { return DefinitionData || dataPtr(); }
543
544 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
545 SourceLocation StartLoc, SourceLocation IdLoc,
546 IdentifierInfo *Id,
547 CXXRecordDecl *PrevDecl = nullptr,
548 bool DelayTypeCreation = false);
549 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
550 TypeSourceInfo *Info, SourceLocation Loc,
551 bool DependentLambda, bool IsGeneric,
552 LambdaCaptureDefault CaptureDefault);
553 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
554
555 bool isDynamicClass() const {
556 return data().Polymorphic || data().NumVBases != 0;
557 }
558
559 /// @returns true if class is dynamic or might be dynamic because the
560 /// definition is incomplete of dependent.
561 bool mayBeDynamicClass() const {
562 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
563 }
564
565 /// @returns true if class is non dynamic or might be non dynamic because the
566 /// definition is incomplete of dependent.
567 bool mayBeNonDynamicClass() const {
568 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
569 }
570
571 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
572
573 bool isParsingBaseSpecifiers() const {
574 return data().IsParsingBaseSpecifiers;
575 }
576
577 unsigned getODRHash() const;
578
579 /// Sets the base classes of this struct or class.
580 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
581
582 /// Retrieves the number of base classes of this class.
583 unsigned getNumBases() const { return data().NumBases; }
584
585 using base_class_range = llvm::iterator_range<base_class_iterator>;
586 using base_class_const_range =
587 llvm::iterator_range<base_class_const_iterator>;
588
589 base_class_range bases() {
590 return base_class_range(bases_begin(), bases_end());
591 }
592 base_class_const_range bases() const {
593 return base_class_const_range(bases_begin(), bases_end());
594 }
595
596 base_class_iterator bases_begin() { return data().getBases(); }
597 base_class_const_iterator bases_begin() const { return data().getBases(); }
3
Calling 'DefinitionData::getBases'
598 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
599 base_class_const_iterator bases_end() const {
600 return bases_begin() + data().NumBases;
2
Calling 'CXXRecordDecl::bases_begin'
601 }
602
603 /// Retrieves the number of virtual base classes of this class.
604 unsigned getNumVBases() const { return data().NumVBases; }
605
606 base_class_range vbases() {
607 return base_class_range(vbases_begin(), vbases_end());
608 }
609 base_class_const_range vbases() const {
610 return base_class_const_range(vbases_begin(), vbases_end());
611 }
612
613 base_class_iterator vbases_begin() { return data().getVBases(); }
614 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
615 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
616 base_class_const_iterator vbases_end() const {
617 return vbases_begin() + data().NumVBases;
618 }
619
620 /// Determine whether this class has any dependent base classes which
621 /// are not the current instantiation.
622 bool hasAnyDependentBases() const;
623
624 /// Iterator access to method members. The method iterator visits
625 /// all method members of the class, including non-instance methods,
626 /// special methods, etc.
627 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
628 using method_range =
629 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
630
631 method_range methods() const {
632 return method_range(method_begin(), method_end());
633 }
634
635 /// Method begin iterator. Iterates in the order the methods
636 /// were declared.
637 method_iterator method_begin() const {
638 return method_iterator(decls_begin());
639 }
640
641 /// Method past-the-end iterator.
642 method_iterator method_end() const {
643 return method_iterator(decls_end());
644 }
645
646 /// Iterator access to constructor members.
647 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
648 using ctor_range =
649 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
650
651 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
652
653 ctor_iterator ctor_begin() const {
654 return ctor_iterator(decls_begin());
655 }
656
657 ctor_iterator ctor_end() const {
658 return ctor_iterator(decls_end());
659 }
660
661 /// An iterator over friend declarations. All of these are defined
662 /// in DeclFriend.h.
663 class friend_iterator;
664 using friend_range = llvm::iterator_range<friend_iterator>;
665
666 friend_range friends() const;
667 friend_iterator friend_begin() const;
668 friend_iterator friend_end() const;
669 void pushFriendDecl(FriendDecl *FD);
670
671 /// Determines whether this record has any friends.
672 bool hasFriends() const {
673 return data().FirstFriend.isValid();
674 }
675
676 /// \c true if a defaulted copy constructor for this class would be
677 /// deleted.
678 bool defaultedCopyConstructorIsDeleted() const {
679 assert((!needsOverloadResolutionForCopyConstructor() ||(static_cast<void> (0))
680 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(static_cast<void> (0))
681 "this property has not yet been computed by Sema")(static_cast<void> (0));
682 return data().DefaultedCopyConstructorIsDeleted;
683 }
684
685 /// \c true if a defaulted move constructor for this class would be
686 /// deleted.
687 bool defaultedMoveConstructorIsDeleted() const {
688 assert((!needsOverloadResolutionForMoveConstructor() ||(static_cast<void> (0))
689 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(static_cast<void> (0))
690 "this property has not yet been computed by Sema")(static_cast<void> (0));
691 return data().DefaultedMoveConstructorIsDeleted;
692 }
693
694 /// \c true if a defaulted destructor for this class would be deleted.
695 bool defaultedDestructorIsDeleted() const {
696 assert((!needsOverloadResolutionForDestructor() ||(static_cast<void> (0))
697 (data().DeclaredSpecialMembers & SMF_Destructor)) &&(static_cast<void> (0))
698 "this property has not yet been computed by Sema")(static_cast<void> (0));
699 return data().DefaultedDestructorIsDeleted;
700 }
701
702 /// \c true if we know for sure that this class has a single,
703 /// accessible, unambiguous copy constructor that is not deleted.
704 bool hasSimpleCopyConstructor() const {
705 return !hasUserDeclaredCopyConstructor() &&
706 !data().DefaultedCopyConstructorIsDeleted;
707 }
708
709 /// \c true if we know for sure that this class has a single,
710 /// accessible, unambiguous move constructor that is not deleted.
711 bool hasSimpleMoveConstructor() const {
712 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
713 !data().DefaultedMoveConstructorIsDeleted;
714 }
715
716 /// \c true if we know for sure that this class has a single,
717 /// accessible, unambiguous copy assignment operator that is not deleted.
718 bool hasSimpleCopyAssignment() const {
719 return !hasUserDeclaredCopyAssignment() &&
720 !data().DefaultedCopyAssignmentIsDeleted;
721 }
722
723 /// \c true if we know for sure that this class has a single,
724 /// accessible, unambiguous move assignment operator that is not deleted.
725 bool hasSimpleMoveAssignment() const {
726 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
727 !data().DefaultedMoveAssignmentIsDeleted;
728 }
729
730 /// \c true if we know for sure that this class has an accessible
731 /// destructor that is not deleted.
732 bool hasSimpleDestructor() const {
733 return !hasUserDeclaredDestructor() &&
734 !data().DefaultedDestructorIsDeleted;
735 }
736
737 /// Determine whether this class has any default constructors.
738 bool hasDefaultConstructor() const {
739 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
740 needsImplicitDefaultConstructor();
741 }
742
743 /// Determine if we need to declare a default constructor for
744 /// this class.
745 ///
746 /// This value is used for lazy creation of default constructors.
747 bool needsImplicitDefaultConstructor() const {
748 return (!data().UserDeclaredConstructor &&
749 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
750 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable())) ||
751 // FIXME: Proposed fix to core wording issue: if a class inherits
752 // a default constructor and doesn't explicitly declare one, one
753 // is declared implicitly.
754 (data().HasInheritedDefaultConstructor &&
755 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor));
756 }
757
758 /// Determine whether this class has any user-declared constructors.
759 ///
760 /// When true, a default constructor will not be implicitly declared.
761 bool hasUserDeclaredConstructor() const {
762 return data().UserDeclaredConstructor;
763 }
764
765 /// Whether this class has a user-provided default constructor
766 /// per C++11.
767 bool hasUserProvidedDefaultConstructor() const {
768 return data().UserProvidedDefaultConstructor;
769 }
770
771 /// Determine whether this class has a user-declared copy constructor.
772 ///
773 /// When false, a copy constructor will be implicitly declared.
774 bool hasUserDeclaredCopyConstructor() const {
775 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
776 }
777
778 /// Determine whether this class needs an implicit copy
779 /// constructor to be lazily declared.
780 bool needsImplicitCopyConstructor() const {
781 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
782 }
783
784 /// Determine whether we need to eagerly declare a defaulted copy
785 /// constructor for this class.
786 bool needsOverloadResolutionForCopyConstructor() const {
787 // C++17 [class.copy.ctor]p6:
788 // If the class definition declares a move constructor or move assignment
789 // operator, the implicitly declared copy constructor is defined as
790 // deleted.
791 // In MSVC mode, sometimes a declared move assignment does not delete an
792 // implicit copy constructor, so defer this choice to Sema.
793 if (data().UserDeclaredSpecialMembers &
794 (SMF_MoveConstructor | SMF_MoveAssignment))
795 return true;
796 return data().NeedOverloadResolutionForCopyConstructor;
797 }
798
799 /// Determine whether an implicit copy constructor for this type
800 /// would have a parameter with a const-qualified reference type.
801 bool implicitCopyConstructorHasConstParam() const {
802 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
803 (isAbstract() ||
804 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
805 }
806
807 /// Determine whether this class has a copy constructor with
808 /// a parameter type which is a reference to a const-qualified type.
809 bool hasCopyConstructorWithConstParam() const {
810 return data().HasDeclaredCopyConstructorWithConstParam ||
811 (needsImplicitCopyConstructor() &&
812 implicitCopyConstructorHasConstParam());
813 }
814
815 /// Whether this class has a user-declared move constructor or
816 /// assignment operator.
817 ///
818 /// When false, a move constructor and assignment operator may be
819 /// implicitly declared.
820 bool hasUserDeclaredMoveOperation() const {
821 return data().UserDeclaredSpecialMembers &
822 (SMF_MoveConstructor | SMF_MoveAssignment);
823 }
824
825 /// Determine whether this class has had a move constructor
826 /// declared by the user.
827 bool hasUserDeclaredMoveConstructor() const {
828 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
829 }
830
831 /// Determine whether this class has a move constructor.
832 bool hasMoveConstructor() const {
833 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
834 needsImplicitMoveConstructor();
835 }
836
837 /// Set that we attempted to declare an implicit copy
838 /// constructor, but overload resolution failed so we deleted it.
839 void setImplicitCopyConstructorIsDeleted() {
840 assert((data().DefaultedCopyConstructorIsDeleted ||(static_cast<void> (0))
841 needsOverloadResolutionForCopyConstructor()) &&(static_cast<void> (0))
842 "Copy constructor should not be deleted")(static_cast<void> (0));
843 data().DefaultedCopyConstructorIsDeleted = true;
844 }
845
846 /// Set that we attempted to declare an implicit move
847 /// constructor, but overload resolution failed so we deleted it.
848 void setImplicitMoveConstructorIsDeleted() {
849 assert((data().DefaultedMoveConstructorIsDeleted ||(static_cast<void> (0))
850 needsOverloadResolutionForMoveConstructor()) &&(static_cast<void> (0))
851 "move constructor should not be deleted")(static_cast<void> (0));
852 data().DefaultedMoveConstructorIsDeleted = true;
853 }
854
855 /// Set that we attempted to declare an implicit destructor,
856 /// but overload resolution failed so we deleted it.
857 void setImplicitDestructorIsDeleted() {
858 assert((data().DefaultedDestructorIsDeleted ||(static_cast<void> (0))
859 needsOverloadResolutionForDestructor()) &&(static_cast<void> (0))
860 "destructor should not be deleted")(static_cast<void> (0));
861 data().DefaultedDestructorIsDeleted = true;
862 }
863
864 /// Determine whether this class should get an implicit move
865 /// constructor or if any existing special member function inhibits this.
866 bool needsImplicitMoveConstructor() const {
867 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
868 !hasUserDeclaredCopyConstructor() &&
869 !hasUserDeclaredCopyAssignment() &&
870 !hasUserDeclaredMoveAssignment() &&
871 !hasUserDeclaredDestructor();
872 }
873
874 /// Determine whether we need to eagerly declare a defaulted move
875 /// constructor for this class.
876 bool needsOverloadResolutionForMoveConstructor() const {
877 return data().NeedOverloadResolutionForMoveConstructor;
878 }
879
880 /// Determine whether this class has a user-declared copy assignment
881 /// operator.
882 ///
883 /// When false, a copy assignment operator will be implicitly declared.
884 bool hasUserDeclaredCopyAssignment() const {
885 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
886 }
887
888 /// Set that we attempted to declare an implicit copy assignment
889 /// operator, but overload resolution failed so we deleted it.
890 void setImplicitCopyAssignmentIsDeleted() {
891 assert((data().DefaultedCopyAssignmentIsDeleted ||(static_cast<void> (0))
892 needsOverloadResolutionForCopyAssignment()) &&(static_cast<void> (0))
893 "copy assignment should not be deleted")(static_cast<void> (0));
894 data().DefaultedCopyAssignmentIsDeleted = true;
895 }
896
897 /// Determine whether this class needs an implicit copy
898 /// assignment operator to be lazily declared.
899 bool needsImplicitCopyAssignment() const {
900 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
901 }
902
903 /// Determine whether we need to eagerly declare a defaulted copy
904 /// assignment operator for this class.
905 bool needsOverloadResolutionForCopyAssignment() const {
906 // C++20 [class.copy.assign]p2:
907 // If the class definition declares a move constructor or move assignment
908 // operator, the implicitly declared copy assignment operator is defined
909 // as deleted.
910 // In MSVC mode, sometimes a declared move constructor does not delete an
911 // implicit copy assignment, so defer this choice to Sema.
912 if (data().UserDeclaredSpecialMembers &
913 (SMF_MoveConstructor | SMF_MoveAssignment))
914 return true;
915 return data().NeedOverloadResolutionForCopyAssignment;
916 }
917
918 /// Determine whether an implicit copy assignment operator for this
919 /// type would have a parameter with a const-qualified reference type.
920 bool implicitCopyAssignmentHasConstParam() const {
921 return data().ImplicitCopyAssignmentHasConstParam;
922 }
923
924 /// Determine whether this class has a copy assignment operator with
925 /// a parameter type which is a reference to a const-qualified type or is not
926 /// a reference.
927 bool hasCopyAssignmentWithConstParam() const {
928 return data().HasDeclaredCopyAssignmentWithConstParam ||
929 (needsImplicitCopyAssignment() &&
930 implicitCopyAssignmentHasConstParam());
931 }
932
933 /// Determine whether this class has had a move assignment
934 /// declared by the user.
935 bool hasUserDeclaredMoveAssignment() const {
936 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
937 }
938
939 /// Determine whether this class has a move assignment operator.
940 bool hasMoveAssignment() const {
941 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
942 needsImplicitMoveAssignment();
943 }
944
945 /// Set that we attempted to declare an implicit move assignment
946 /// operator, but overload resolution failed so we deleted it.
947 void setImplicitMoveAssignmentIsDeleted() {
948 assert((data().DefaultedMoveAssignmentIsDeleted ||(static_cast<void> (0))
949 needsOverloadResolutionForMoveAssignment()) &&(static_cast<void> (0))
950 "move assignment should not be deleted")(static_cast<void> (0));
951 data().DefaultedMoveAssignmentIsDeleted = true;
952 }
953
954 /// Determine whether this class should get an implicit move
955 /// assignment operator or if any existing special member function inhibits
956 /// this.
957 bool needsImplicitMoveAssignment() const {
958 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
959 !hasUserDeclaredCopyConstructor() &&
960 !hasUserDeclaredCopyAssignment() &&
961 !hasUserDeclaredMoveConstructor() &&
962 !hasUserDeclaredDestructor() &&
963 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
964 }
965
966 /// Determine whether we need to eagerly declare a move assignment
967 /// operator for this class.
968 bool needsOverloadResolutionForMoveAssignment() const {
969 return data().NeedOverloadResolutionForMoveAssignment;
970 }
971
972 /// Determine whether this class has a user-declared destructor.
973 ///
974 /// When false, a destructor will be implicitly declared.
975 bool hasUserDeclaredDestructor() const {
976 return data().UserDeclaredSpecialMembers & SMF_Destructor;
977 }
978
979 /// Determine whether this class needs an implicit destructor to
980 /// be lazily declared.
981 bool needsImplicitDestructor() const {
982 return !(data().DeclaredSpecialMembers & SMF_Destructor);
983 }
984
985 /// Determine whether we need to eagerly declare a destructor for this
986 /// class.
987 bool needsOverloadResolutionForDestructor() const {
988 return data().NeedOverloadResolutionForDestructor;
989 }
990
991 /// Determine whether this class describes a lambda function object.
992 bool isLambda() const {
993 // An update record can't turn a non-lambda into a lambda.
994 auto *DD = DefinitionData;
995 return DD && DD->IsLambda;
996 }
997
998 /// Determine whether this class describes a generic
999 /// lambda function object (i.e. function call operator is
1000 /// a template).
1001 bool isGenericLambda() const;
1002
1003 /// Determine whether this lambda should have an implicit default constructor
1004 /// and copy and move assignment operators.
1005 bool lambdaIsDefaultConstructibleAndAssignable() const;
1006
1007 /// Retrieve the lambda call operator of the closure type
1008 /// if this is a closure type.
1009 CXXMethodDecl *getLambdaCallOperator() const;
1010
1011 /// Retrieve the dependent lambda call operator of the closure type
1012 /// if this is a templated closure type.
1013 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1014
1015 /// Retrieve the lambda static invoker, the address of which
1016 /// is returned by the conversion operator, and the body of which
1017 /// is forwarded to the lambda call operator. The version that does not
1018 /// take a calling convention uses the 'default' calling convention for free
1019 /// functions if the Lambda's calling convention was not modified via
1020 /// attribute. Otherwise, it will return the calling convention specified for
1021 /// the lambda.
1022 CXXMethodDecl *getLambdaStaticInvoker() const;
1023 CXXMethodDecl *getLambdaStaticInvoker(CallingConv CC) const;
1024
1025 /// Retrieve the generic lambda's template parameter list.
1026 /// Returns null if the class does not represent a lambda or a generic
1027 /// lambda.
1028 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1029
1030 /// Retrieve the lambda template parameters that were specified explicitly.
1031 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1032
1033 LambdaCaptureDefault getLambdaCaptureDefault() const {
1034 assert(isLambda())(static_cast<void> (0));
1035 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1036 }
1037
1038 /// Set the captures for this lambda closure type.
1039 void setCaptures(ASTContext &Context, ArrayRef<LambdaCapture> Captures);
1040
1041 /// For a closure type, retrieve the mapping from captured
1042 /// variables and \c this to the non-static data members that store the
1043 /// values or references of the captures.
1044 ///
1045 /// \param Captures Will be populated with the mapping from captured
1046 /// variables to the corresponding fields.
1047 ///
1048 /// \param ThisCapture Will be set to the field declaration for the
1049 /// \c this capture.
1050 ///
1051 /// \note No entries will be added for init-captures, as they do not capture
1052 /// variables.
1053 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1054 FieldDecl *&ThisCapture) const;
1055
1056 using capture_const_iterator = const LambdaCapture *;
1057 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1058
1059 capture_const_range captures() const {
1060 return capture_const_range(captures_begin(), captures_end());
1061 }
1062
1063 capture_const_iterator captures_begin() const {
1064 return isLambda() ? getLambdaData().Captures : nullptr;
1065 }
1066
1067 capture_const_iterator captures_end() const {
1068 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1069 : nullptr;
1070 }
1071
1072 unsigned capture_size() const { return getLambdaData().NumCaptures; }
1073
1074 using conversion_iterator = UnresolvedSetIterator;
1075
1076 conversion_iterator conversion_begin() const {
1077 return data().Conversions.get(getASTContext()).begin();
1078 }
1079
1080 conversion_iterator conversion_end() const {
1081 return data().Conversions.get(getASTContext()).end();
1082 }
1083
1084 /// Removes a conversion function from this class. The conversion
1085 /// function must currently be a member of this class. Furthermore,
1086 /// this class must currently be in the process of being defined.
1087 void removeConversion(const NamedDecl *Old);
1088
1089 /// Get all conversion functions visible in current class,
1090 /// including conversion function templates.
1091 llvm::iterator_range<conversion_iterator>
1092 getVisibleConversionFunctions() const;
1093
1094 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1095 /// which is a class with no user-declared constructors, no private
1096 /// or protected non-static data members, no base classes, and no virtual
1097 /// functions (C++ [dcl.init.aggr]p1).
1098 bool isAggregate() const { return data().Aggregate; }
1099
1100 /// Whether this class has any in-class initializers
1101 /// for non-static data members (including those in anonymous unions or
1102 /// structs).
1103 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1104
1105 /// Whether this class or any of its subobjects has any members of
1106 /// reference type which would make value-initialization ill-formed.
1107 ///
1108 /// Per C++03 [dcl.init]p5:
1109 /// - if T is a non-union class type without a user-declared constructor,
1110 /// then every non-static data member and base-class component of T is
1111 /// value-initialized [...] A program that calls for [...]
1112 /// value-initialization of an entity of reference type is ill-formed.
1113 bool hasUninitializedReferenceMember() const {
1114 return !isUnion() && !hasUserDeclaredConstructor() &&
1115 data().HasUninitializedReferenceMember;
1116 }
1117
1118 /// Whether this class is a POD-type (C++ [class]p4)
1119 ///
1120 /// For purposes of this function a class is POD if it is an aggregate
1121 /// that has no non-static non-POD data members, no reference data
1122 /// members, no user-defined copy assignment operator and no
1123 /// user-defined destructor.
1124 ///
1125 /// Note that this is the C++ TR1 definition of POD.
1126 bool isPOD() const { return data().PlainOldData; }
1127
1128 /// True if this class is C-like, without C++-specific features, e.g.
1129 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1130 bool isCLike() const;
1131
1132 /// Determine whether this is an empty class in the sense of
1133 /// (C++11 [meta.unary.prop]).
1134 ///
1135 /// The CXXRecordDecl is a class type, but not a union type,
1136 /// with no non-static data members other than bit-fields of length 0,
1137 /// no virtual member functions, no virtual base classes,
1138 /// and no base class B for which is_empty<B>::value is false.
1139 ///
1140 /// \note This does NOT include a check for union-ness.
1141 bool isEmpty() const { return data().Empty; }
1142
1143 bool hasPrivateFields() const {
1144 return data().HasPrivateFields;
1145 }
1146
1147 bool hasProtectedFields() const {
1148 return data().HasProtectedFields;
1149 }
1150
1151 /// Determine whether this class has direct non-static data members.
1152 bool hasDirectFields() const {
1153 auto &D = data();
1154 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1155 }
1156
1157 /// Whether this class is polymorphic (C++ [class.virtual]),
1158 /// which means that the class contains or inherits a virtual function.
1159 bool isPolymorphic() const { return data().Polymorphic; }
1160
1161 /// Determine whether this class has a pure virtual function.
1162 ///
1163 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1164 /// a pure virtual function or inherits a pure virtual function that is
1165 /// not overridden.
1166 bool isAbstract() const { return data().Abstract; }
1167
1168 /// Determine whether this class is standard-layout per
1169 /// C++ [class]p7.
1170 bool isStandardLayout() const { return data().IsStandardLayout; }
1171
1172 /// Determine whether this class was standard-layout per
1173 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1174 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1175
1176 /// Determine whether this class, or any of its class subobjects,
1177 /// contains a mutable field.
1178 bool hasMutableFields() const { return data().HasMutableFields; }
1179
1180 /// Determine whether this class has any variant members.
1181 bool hasVariantMembers() const { return data().HasVariantMembers; }
1182
1183 /// Determine whether this class has a trivial default constructor
1184 /// (C++11 [class.ctor]p5).
1185 bool hasTrivialDefaultConstructor() const {
1186 return hasDefaultConstructor() &&
1187 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1188 }
1189
1190 /// Determine whether this class has a non-trivial default constructor
1191 /// (C++11 [class.ctor]p5).
1192 bool hasNonTrivialDefaultConstructor() const {
1193 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1194 (needsImplicitDefaultConstructor() &&
1195 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1196 }
1197
1198 /// Determine whether this class has at least one constexpr constructor
1199 /// other than the copy or move constructors.
1200 bool hasConstexprNonCopyMoveConstructor() const {
1201 return data().HasConstexprNonCopyMoveConstructor ||
1202 (needsImplicitDefaultConstructor() &&
1203 defaultedDefaultConstructorIsConstexpr());
1204 }
1205
1206 /// Determine whether a defaulted default constructor for this class
1207 /// would be constexpr.
1208 bool defaultedDefaultConstructorIsConstexpr() const {
1209 return data().DefaultedDefaultConstructorIsConstexpr &&
1210 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1211 getLangOpts().CPlusPlus20);
1212 }
1213
1214 /// Determine whether this class has a constexpr default constructor.
1215 bool hasConstexprDefaultConstructor() const {
1216 return data().HasConstexprDefaultConstructor ||
1217 (needsImplicitDefaultConstructor() &&
1218 defaultedDefaultConstructorIsConstexpr());
1219 }
1220
1221 /// Determine whether this class has a trivial copy constructor
1222 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1223 bool hasTrivialCopyConstructor() const {
1224 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1225 }
1226
1227 bool hasTrivialCopyConstructorForCall() const {
1228 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1229 }
1230
1231 /// Determine whether this class has a non-trivial copy constructor
1232 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1233 bool hasNonTrivialCopyConstructor() const {
1234 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1235 !hasTrivialCopyConstructor();
1236 }
1237
1238 bool hasNonTrivialCopyConstructorForCall() const {
1239 return (data().DeclaredNonTrivialSpecialMembersForCall &
1240 SMF_CopyConstructor) ||
1241 !hasTrivialCopyConstructorForCall();
1242 }
1243
1244 /// Determine whether this class has a trivial move constructor
1245 /// (C++11 [class.copy]p12)
1246 bool hasTrivialMoveConstructor() const {
1247 return hasMoveConstructor() &&
1248 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1249 }
1250
1251 bool hasTrivialMoveConstructorForCall() const {
1252 return hasMoveConstructor() &&
1253 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1254 }
1255
1256 /// Determine whether this class has a non-trivial move constructor
1257 /// (C++11 [class.copy]p12)
1258 bool hasNonTrivialMoveConstructor() const {
1259 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1260 (needsImplicitMoveConstructor() &&
1261 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1262 }
1263
1264 bool hasNonTrivialMoveConstructorForCall() const {
1265 return (data().DeclaredNonTrivialSpecialMembersForCall &
1266 SMF_MoveConstructor) ||
1267 (needsImplicitMoveConstructor() &&
1268 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1269 }
1270
1271 /// Determine whether this class has a trivial copy assignment operator
1272 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1273 bool hasTrivialCopyAssignment() const {
1274 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1275 }
1276
1277 /// Determine whether this class has a non-trivial copy assignment
1278 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1279 bool hasNonTrivialCopyAssignment() const {
1280 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1281 !hasTrivialCopyAssignment();
1282 }
1283
1284 /// Determine whether this class has a trivial move assignment operator
1285 /// (C++11 [class.copy]p25)
1286 bool hasTrivialMoveAssignment() const {
1287 return hasMoveAssignment() &&
1288 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1289 }
1290
1291 /// Determine whether this class has a non-trivial move assignment
1292 /// operator (C++11 [class.copy]p25)
1293 bool hasNonTrivialMoveAssignment() const {
1294 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1295 (needsImplicitMoveAssignment() &&
1296 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1297 }
1298
1299 /// Determine whether a defaulted default constructor for this class
1300 /// would be constexpr.
1301 bool defaultedDestructorIsConstexpr() const {
1302 return data().DefaultedDestructorIsConstexpr &&
1303 getLangOpts().CPlusPlus20;
1304 }
1305
1306 /// Determine whether this class has a constexpr destructor.
1307 bool hasConstexprDestructor() const;
1308
1309 /// Determine whether this class has a trivial destructor
1310 /// (C++ [class.dtor]p3)
1311 bool hasTrivialDestructor() const {
1312 return data().HasTrivialSpecialMembers & SMF_Destructor;
1313 }
1314
1315 bool hasTrivialDestructorForCall() const {
1316 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1317 }
1318
1319 /// Determine whether this class has a non-trivial destructor
1320 /// (C++ [class.dtor]p3)
1321 bool hasNonTrivialDestructor() const {
1322 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1323 }
1324
1325 bool hasNonTrivialDestructorForCall() const {
1326 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1327 }
1328
1329 void setHasTrivialSpecialMemberForCall() {
1330 data().HasTrivialSpecialMembersForCall =
1331 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1332 }
1333
1334 /// Determine whether declaring a const variable with this type is ok
1335 /// per core issue 253.
1336 bool allowConstDefaultInit() const {
1337 return !data().HasUninitializedFields ||
1338 !(data().HasDefaultedDefaultConstructor ||
1339 needsImplicitDefaultConstructor());
1340 }
1341
1342 /// Determine whether this class has a destructor which has no
1343 /// semantic effect.
1344 ///
1345 /// Any such destructor will be trivial, public, defaulted and not deleted,
1346 /// and will call only irrelevant destructors.
1347 bool hasIrrelevantDestructor() const {
1348 return data().HasIrrelevantDestructor;
1349 }
1350
1351 /// Determine whether this class has a non-literal or/ volatile type
1352 /// non-static data member or base class.
1353 bool hasNonLiteralTypeFieldsOrBases() const {
1354 return data().HasNonLiteralTypeFieldsOrBases;
1355 }
1356
1357 /// Determine whether this class has a using-declaration that names
1358 /// a user-declared base class constructor.
1359 bool hasInheritedConstructor() const {
1360 return data().HasInheritedConstructor;
1361 }
1362
1363 /// Determine whether this class has a using-declaration that names
1364 /// a base class assignment operator.
1365 bool hasInheritedAssignment() const {
1366 return data().HasInheritedAssignment;
1367 }
1368
1369 /// Determine whether this class is considered trivially copyable per
1370 /// (C++11 [class]p6).
1371 bool isTriviallyCopyable() const;
1372
1373 /// Determine whether this class is considered trivial.
1374 ///
1375 /// C++11 [class]p6:
1376 /// "A trivial class is a class that has a trivial default constructor and
1377 /// is trivially copyable."
1378 bool isTrivial() const {
1379 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1380 }
1381
1382 /// Determine whether this class is a literal type.
1383 ///
1384 /// C++11 [basic.types]p10:
1385 /// A class type that has all the following properties:
1386 /// - it has a trivial destructor
1387 /// - every constructor call and full-expression in the
1388 /// brace-or-equal-intializers for non-static data members (if any) is
1389 /// a constant expression.
1390 /// - it is an aggregate type or has at least one constexpr constructor
1391 /// or constructor template that is not a copy or move constructor, and
1392 /// - all of its non-static data members and base classes are of literal
1393 /// types
1394 ///
1395 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1396 /// treating types with trivial default constructors as literal types.
1397 ///
1398 /// Only in C++17 and beyond, are lambdas literal types.
1399 bool isLiteral() const {
1400 const LangOptions &LangOpts = getLangOpts();
1401 return (LangOpts.CPlusPlus20 ? hasConstexprDestructor()
1402 : hasTrivialDestructor()) &&
1403 (!isLambda() || LangOpts.CPlusPlus17) &&
1404 !hasNonLiteralTypeFieldsOrBases() &&
1405 (isAggregate() || isLambda() ||
1406 hasConstexprNonCopyMoveConstructor() ||
1407 hasTrivialDefaultConstructor());
1408 }
1409
1410 /// Determine whether this is a structural type.
1411 bool isStructural() const {
1412 return isLiteral() && data().StructuralIfLiteral;
1413 }
1414
1415 /// If this record is an instantiation of a member class,
1416 /// retrieves the member class from which it was instantiated.
1417 ///
1418 /// This routine will return non-null for (non-templated) member
1419 /// classes of class templates. For example, given:
1420 ///
1421 /// \code
1422 /// template<typename T>
1423 /// struct X {
1424 /// struct A { };
1425 /// };
1426 /// \endcode
1427 ///
1428 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1429 /// whose parent is the class template specialization X<int>. For
1430 /// this declaration, getInstantiatedFromMemberClass() will return
1431 /// the CXXRecordDecl X<T>::A. When a complete definition of
1432 /// X<int>::A is required, it will be instantiated from the
1433 /// declaration returned by getInstantiatedFromMemberClass().
1434 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1435
1436 /// If this class is an instantiation of a member class of a
1437 /// class template specialization, retrieves the member specialization
1438 /// information.
1439 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1440
1441 /// Specify that this record is an instantiation of the
1442 /// member class \p RD.
1443 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1444 TemplateSpecializationKind TSK);
1445
1446 /// Retrieves the class template that is described by this
1447 /// class declaration.
1448 ///
1449 /// Every class template is represented as a ClassTemplateDecl and a
1450 /// CXXRecordDecl. The former contains template properties (such as
1451 /// the template parameter lists) while the latter contains the
1452 /// actual description of the template's
1453 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1454 /// CXXRecordDecl that from a ClassTemplateDecl, while
1455 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1456 /// a CXXRecordDecl.
1457 ClassTemplateDecl *getDescribedClassTemplate() const;
1458
1459 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1460
1461 /// Determine whether this particular class is a specialization or
1462 /// instantiation of a class template or member class of a class template,
1463 /// and how it was instantiated or specialized.
1464 TemplateSpecializationKind getTemplateSpecializationKind() const;
1465
1466 /// Set the kind of specialization or template instantiation this is.
1467 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1468
1469 /// Retrieve the record declaration from which this record could be
1470 /// instantiated. Returns null if this class is not a template instantiation.
1471 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1472
1473 CXXRecordDecl *getTemplateInstantiationPattern() {
1474 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1475 ->getTemplateInstantiationPattern());
1476 }
1477
1478 /// Returns the destructor decl for this class.
1479 CXXDestructorDecl *getDestructor() const;
1480
1481 /// Returns true if the class destructor, or any implicitly invoked
1482 /// destructors are marked noreturn.
1483 bool isAnyDestructorNoReturn() const { return data().IsAnyDestructorNoReturn; }
1484
1485 /// If the class is a local class [class.local], returns
1486 /// the enclosing function declaration.
1487 const FunctionDecl *isLocalClass() const {
1488 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1489 return RD->isLocalClass();
1490
1491 return dyn_cast<FunctionDecl>(getDeclContext());
1492 }
1493
1494 FunctionDecl *isLocalClass() {
1495 return const_cast<FunctionDecl*>(
1496 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1497 }
1498
1499 /// Determine whether this dependent class is a current instantiation,
1500 /// when viewed from within the given context.
1501 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1502
1503 /// Determine whether this class is derived from the class \p Base.
1504 ///
1505 /// This routine only determines whether this class is derived from \p Base,
1506 /// but does not account for factors that may make a Derived -> Base class
1507 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1508 /// base class subobjects.
1509 ///
1510 /// \param Base the base class we are searching for.
1511 ///
1512 /// \returns true if this class is derived from Base, false otherwise.
1513 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1514
1515 /// Determine whether this class is derived from the type \p Base.
1516 ///
1517 /// This routine only determines whether this class is derived from \p Base,
1518 /// but does not account for factors that may make a Derived -> Base class
1519 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1520 /// base class subobjects.
1521 ///
1522 /// \param Base the base class we are searching for.
1523 ///
1524 /// \param Paths will contain the paths taken from the current class to the
1525 /// given \p Base class.
1526 ///
1527 /// \returns true if this class is derived from \p Base, false otherwise.
1528 ///
1529 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1530 /// tangling input and output in \p Paths
1531 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1532
1533 /// Determine whether this class is virtually derived from
1534 /// the class \p Base.
1535 ///
1536 /// This routine only determines whether this class is virtually
1537 /// derived from \p Base, but does not account for factors that may
1538 /// make a Derived -> Base class ill-formed, such as
1539 /// private/protected inheritance or multiple, ambiguous base class
1540 /// subobjects.
1541 ///
1542 /// \param Base the base class we are searching for.
1543 ///
1544 /// \returns true if this class is virtually derived from Base,
1545 /// false otherwise.
1546 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1547
1548 /// Determine whether this class is provably not derived from
1549 /// the type \p Base.
1550 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1551
1552 /// Function type used by forallBases() as a callback.
1553 ///
1554 /// \param BaseDefinition the definition of the base class
1555 ///
1556 /// \returns true if this base matched the search criteria
1557 using ForallBasesCallback =
1558 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1559
1560 /// Determines if the given callback holds for all the direct
1561 /// or indirect base classes of this type.
1562 ///
1563 /// The class itself does not count as a base class. This routine
1564 /// returns false if the class has non-computable base classes.
1565 ///
1566 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1567 /// class of this type until a call returns false.
1568 bool forallBases(ForallBasesCallback BaseMatches) const;
1569
1570 /// Function type used by lookupInBases() to determine whether a
1571 /// specific base class subobject matches the lookup criteria.
1572 ///
1573 /// \param Specifier the base-class specifier that describes the inheritance
1574 /// from the base class we are trying to match.
1575 ///
1576 /// \param Path the current path, from the most-derived class down to the
1577 /// base named by the \p Specifier.
1578 ///
1579 /// \returns true if this base matched the search criteria, false otherwise.
1580 using BaseMatchesCallback =
1581 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1582 CXXBasePath &Path)>;
1583
1584 /// Look for entities within the base classes of this C++ class,
1585 /// transitively searching all base class subobjects.
1586 ///
1587 /// This routine uses the callback function \p BaseMatches to find base
1588 /// classes meeting some search criteria, walking all base class subobjects
1589 /// and populating the given \p Paths structure with the paths through the
1590 /// inheritance hierarchy that resulted in a match. On a successful search,
1591 /// the \p Paths structure can be queried to retrieve the matching paths and
1592 /// to determine if there were any ambiguities.
1593 ///
1594 /// \param BaseMatches callback function used to determine whether a given
1595 /// base matches the user-defined search criteria.
1596 ///
1597 /// \param Paths used to record the paths from this class to its base class
1598 /// subobjects that match the search criteria.
1599 ///
1600 /// \param LookupInDependent can be set to true to extend the search to
1601 /// dependent base classes.
1602 ///
1603 /// \returns true if there exists any path from this class to a base class
1604 /// subobject that matches the search criteria.
1605 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1606 bool LookupInDependent = false) const;
1607
1608 /// Base-class lookup callback that determines whether the given
1609 /// base class specifier refers to a specific class declaration.
1610 ///
1611 /// This callback can be used with \c lookupInBases() to determine whether
1612 /// a given derived class has is a base class subobject of a particular type.
1613 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1614 /// base class that we are searching for.
1615 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1616 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1617
1618 /// Base-class lookup callback that determines whether the
1619 /// given base class specifier refers to a specific class
1620 /// declaration and describes virtual derivation.
1621 ///
1622 /// This callback can be used with \c lookupInBases() to determine
1623 /// whether a given derived class has is a virtual base class
1624 /// subobject of a particular type. The base record pointer should
1625 /// refer to the canonical CXXRecordDecl of the base class that we
1626 /// are searching for.
1627 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1628 CXXBasePath &Path,
1629 const CXXRecordDecl *BaseRecord);
1630
1631 /// Retrieve the final overriders for each virtual member
1632 /// function in the class hierarchy where this class is the
1633 /// most-derived class in the class hierarchy.
1634 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1635
1636 /// Get the indirect primary bases for this class.
1637 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1638
1639 /// Determine whether this class has a member with the given name, possibly
1640 /// in a non-dependent base class.
1641 ///
1642 /// No check for ambiguity is performed, so this should never be used when
1643 /// implementing language semantics, but it may be appropriate for warnings,
1644 /// static analysis, or similar.
1645 bool hasMemberName(DeclarationName N) const;
1646
1647 /// Performs an imprecise lookup of a dependent name in this class.
1648 ///
1649 /// This function does not follow strict semantic rules and should be used
1650 /// only when lookup rules can be relaxed, e.g. indexing.
1651 std::vector<const NamedDecl *>
1652 lookupDependentName(DeclarationName Name,
1653 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1654
1655 /// Renders and displays an inheritance diagram
1656 /// for this C++ class and all of its base classes (transitively) using
1657 /// GraphViz.
1658 void viewInheritance(ASTContext& Context) const;
1659
1660 /// Calculates the access of a decl that is reached
1661 /// along a path.
1662 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1663 AccessSpecifier DeclAccess) {
1664 assert(DeclAccess != AS_none)(static_cast<void> (0));
1665 if (DeclAccess == AS_private) return AS_none;
1666 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1667 }
1668
1669 /// Indicates that the declaration of a defaulted or deleted special
1670 /// member function is now complete.
1671 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1672
1673 void setTrivialForCallFlags(CXXMethodDecl *MD);
1674
1675 /// Indicates that the definition of this class is now complete.
1676 void completeDefinition() override;
1677
1678 /// Indicates that the definition of this class is now complete,
1679 /// and provides a final overrider map to help determine
1680 ///
1681 /// \param FinalOverriders The final overrider map for this class, which can
1682 /// be provided as an optimization for abstract-class checking. If NULL,
1683 /// final overriders will be computed if they are needed to complete the
1684 /// definition.
1685 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1686
1687 /// Determine whether this class may end up being abstract, even though
1688 /// it is not yet known to be abstract.
1689 ///
1690 /// \returns true if this class is not known to be abstract but has any
1691 /// base classes that are abstract. In this case, \c completeDefinition()
1692 /// will need to compute final overriders to determine whether the class is
1693 /// actually abstract.
1694 bool mayBeAbstract() const;
1695
1696 /// Determine whether it's impossible for a class to be derived from this
1697 /// class. This is best-effort, and may conservatively return false.
1698 bool isEffectivelyFinal() const;
1699
1700 /// If this is the closure type of a lambda expression, retrieve the
1701 /// number to be used for name mangling in the Itanium C++ ABI.
1702 ///
1703 /// Zero indicates that this closure type has internal linkage, so the
1704 /// mangling number does not matter, while a non-zero value indicates which
1705 /// lambda expression this is in this particular context.
1706 unsigned getLambdaManglingNumber() const {
1707 assert(isLambda() && "Not a lambda closure type!")(static_cast<void> (0));
1708 return getLambdaData().ManglingNumber;
1709 }
1710
1711 /// The lambda is known to has internal linkage no matter whether it has name
1712 /// mangling number.
1713 bool hasKnownLambdaInternalLinkage() const {
1714 assert(isLambda() && "Not a lambda closure type!")(static_cast<void> (0));
1715 return getLambdaData().HasKnownInternalLinkage;
1716 }
1717
1718 /// Retrieve the declaration that provides additional context for a
1719 /// lambda, when the normal declaration context is not specific enough.
1720 ///
1721 /// Certain contexts (default arguments of in-class function parameters and
1722 /// the initializers of data members) have separate name mangling rules for
1723 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1724 /// the declaration in which the lambda occurs, e.g., the function parameter
1725 /// or the non-static data member. Otherwise, it returns NULL to imply that
1726 /// the declaration context suffices.
1727 Decl *getLambdaContextDecl() const;
1728
1729 /// Set the mangling number and context declaration for a lambda
1730 /// class.
1731 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1732 bool HasKnownInternalLinkage = false) {
1733 assert(isLambda() && "Not a lambda closure type!")(static_cast<void> (0));
1734 getLambdaData().ManglingNumber = ManglingNumber;
1735 getLambdaData().ContextDecl = ContextDecl;
1736 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1737 }
1738
1739 /// Set the device side mangling number.
1740 void setDeviceLambdaManglingNumber(unsigned Num) const;
1741
1742 /// Retrieve the device side mangling number.
1743 unsigned getDeviceLambdaManglingNumber() const;
1744
1745 /// Returns the inheritance model used for this record.
1746 MSInheritanceModel getMSInheritanceModel() const;
1747
1748 /// Calculate what the inheritance model would be for this class.
1749 MSInheritanceModel calculateInheritanceModel() const;
1750
1751 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1752 /// member pointer if we can guarantee that zero is not a valid field offset,
1753 /// or if the member pointer has multiple fields. Polymorphic classes have a
1754 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1755 /// fields, we can use zero even if it is a valid field offset because
1756 /// null-ness testing will check the other fields.
1757 bool nullFieldOffsetIsZero() const;
1758
1759 /// Controls when vtordisps will be emitted if this record is used as a
1760 /// virtual base.
1761 MSVtorDispMode getMSVtorDispMode() const;
1762
1763 /// Determine whether this lambda expression was known to be dependent
1764 /// at the time it was created, even if its context does not appear to be
1765 /// dependent.
1766 ///
1767 /// This flag is a workaround for an issue with parsing, where default
1768 /// arguments are parsed before their enclosing function declarations have
1769 /// been created. This means that any lambda expressions within those
1770 /// default arguments will have as their DeclContext the context enclosing
1771 /// the function declaration, which may be non-dependent even when the
1772 /// function declaration itself is dependent. This flag indicates when we
1773 /// know that the lambda is dependent despite that.
1774 bool isDependentLambda() const {
1775 return isLambda() && getLambdaData().Dependent;
1776 }
1777
1778 TypeSourceInfo *getLambdaTypeInfo() const {
1779 return getLambdaData().MethodTyInfo;
1780 }
1781
1782 // Determine whether this type is an Interface Like type for
1783 // __interface inheritance purposes.
1784 bool isInterfaceLike() const;
1785
1786 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1787 static bool classofKind(Kind K) {
1788 return K >= firstCXXRecord && K <= lastCXXRecord;
1789 }
1790 void markAbstract() { data().Abstract = true; }
1791};
1792
1793/// Store information needed for an explicit specifier.
1794/// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1795class ExplicitSpecifier {
1796 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1797 nullptr, ExplicitSpecKind::ResolvedFalse};
1798
1799public:
1800 ExplicitSpecifier() = default;
1801 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1802 : ExplicitSpec(Expression, Kind) {}
1803 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1804 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1805 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1806
1807 /// Determine if the declaration had an explicit specifier of any kind.
1808 bool isSpecified() const {
1809 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1810 ExplicitSpec.getPointer();
1811 }
1812
1813 /// Check for equivalence of explicit specifiers.
1814 /// \return true if the explicit specifier are equivalent, false otherwise.
1815 bool isEquivalent(const ExplicitSpecifier Other) const;
1816 /// Determine whether this specifier is known to correspond to an explicit
1817 /// declaration. Returns false if the specifier is absent or has an
1818 /// expression that is value-dependent or evaluates to false.
1819 bool isExplicit() const {
1820 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1821 }
1822 /// Determine if the explicit specifier is invalid.
1823 /// This state occurs after a substitution failures.
1824 bool isInvalid() const {
1825 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1826 !ExplicitSpec.getPointer();
1827 }
1828 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1829 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1830 // Retrieve the explicit specifier in the given declaration, if any.
1831 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1832 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1833 return getFromDecl(const_cast<FunctionDecl *>(Function));
1834 }
1835 static ExplicitSpecifier Invalid() {
1836 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1837 }
1838};
1839
1840/// Represents a C++ deduction guide declaration.
1841///
1842/// \code
1843/// template<typename T> struct A { A(); A(T); };
1844/// A() -> A<int>;
1845/// \endcode
1846///
1847/// In this example, there will be an explicit deduction guide from the
1848/// second line, and implicit deduction guide templates synthesized from
1849/// the constructors of \c A.
1850class CXXDeductionGuideDecl : public FunctionDecl {
1851 void anchor() override;
1852
1853private:
1854 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1855 ExplicitSpecifier ES,
1856 const DeclarationNameInfo &NameInfo, QualType T,
1857 TypeSourceInfo *TInfo, SourceLocation EndLocation,
1858 CXXConstructorDecl *Ctor)
1859 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1860 SC_None, false, false, ConstexprSpecKind::Unspecified),
1861 Ctor(Ctor), ExplicitSpec(ES) {
1862 if (EndLocation.isValid())
1863 setRangeEnd(EndLocation);
1864 setIsCopyDeductionCandidate(false);
1865 }
1866
1867 CXXConstructorDecl *Ctor;
1868 ExplicitSpecifier ExplicitSpec;
1869 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1870
1871public:
1872 friend class ASTDeclReader;
1873 friend class ASTDeclWriter;
1874
1875 static CXXDeductionGuideDecl *
1876 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1877 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1878 TypeSourceInfo *TInfo, SourceLocation EndLocation,
1879 CXXConstructorDecl *Ctor = nullptr);
1880
1881 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1882
1883 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1884 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1885
1886 /// Return true if the declartion is already resolved to be explicit.
1887 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1888
1889 /// Get the template for which this guide performs deduction.
1890 TemplateDecl *getDeducedTemplate() const {
1891 return getDeclName().getCXXDeductionGuideTemplate();
1892 }
1893
1894 /// Get the constructor from which this deduction guide was generated, if
1895 /// this is an implicit deduction guide.
1896 CXXConstructorDecl *getCorrespondingConstructor() const {
1897 return Ctor;
1898 }
1899
1900 void setIsCopyDeductionCandidate(bool isCDC = true) {
1901 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1902 }
1903
1904 bool isCopyDeductionCandidate() const {
1905 return FunctionDeclBits.IsCopyDeductionCandidate;
1906 }
1907
1908 // Implement isa/cast/dyncast/etc.
1909 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1910 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1911};
1912
1913/// \brief Represents the body of a requires-expression.
1914///
1915/// This decl exists merely to serve as the DeclContext for the local
1916/// parameters of the requires expression as well as other declarations inside
1917/// it.
1918///
1919/// \code
1920/// template<typename T> requires requires (T t) { {t++} -> regular; }
1921/// \endcode
1922///
1923/// In this example, a RequiresExpr object will be generated for the expression,
1924/// and a RequiresExprBodyDecl will be created to hold the parameter t and the
1925/// template argument list imposed by the compound requirement.
1926class RequiresExprBodyDecl : public Decl, public DeclContext {
1927 RequiresExprBodyDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
1928 : Decl(RequiresExprBody, DC, StartLoc), DeclContext(RequiresExprBody) {}
1929
1930public:
1931 friend class ASTDeclReader;
1932 friend class ASTDeclWriter;
1933
1934 static RequiresExprBodyDecl *Create(ASTContext &C, DeclContext *DC,
1935 SourceLocation StartLoc);
1936
1937 static RequiresExprBodyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1938
1939 // Implement isa/cast/dyncast/etc.
1940 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1941 static bool classofKind(Kind K) { return K == RequiresExprBody; }
1942};
1943
1944/// Represents a static or instance method of a struct/union/class.
1945///
1946/// In the terminology of the C++ Standard, these are the (static and
1947/// non-static) member functions, whether virtual or not.
1948class CXXMethodDecl : public FunctionDecl {
1949 void anchor() override;
1950
1951protected:
1952 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1953 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1954 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1955 bool UsesFPIntrin, bool isInline,
1956 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
1957 Expr *TrailingRequiresClause = nullptr)
1958 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
1959 isInline, ConstexprKind, TrailingRequiresClause) {
1960 if (EndLocation.isValid())
1961 setRangeEnd(EndLocation);
1962 }
1963
1964public:
1965 static CXXMethodDecl *
1966 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
1967 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
1968 StorageClass SC, bool UsesFPIntrin, bool isInline,
1969 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
1970 Expr *TrailingRequiresClause = nullptr);
1971
1972 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1973
1974 bool isStatic() const;
1975 bool isInstance() const { return !isStatic(); }
1976
1977 /// Returns true if the given operator is implicitly static in a record
1978 /// context.
1979 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
1980 // [class.free]p1:
1981 // Any allocation function for a class T is a static member
1982 // (even if not explicitly declared static).
1983 // [class.free]p6 Any deallocation function for a class X is a static member
1984 // (even if not explicitly declared static).
1985 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
1986 OOK == OO_Array_Delete;
1987 }
1988
1989 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
1990 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
1991
1992 bool isVirtual() const {
1993 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1994
1995 // Member function is virtual if it is marked explicitly so, or if it is
1996 // declared in __interface -- then it is automatically pure virtual.
1997 if (CD->isVirtualAsWritten() || CD->isPure())
1998 return true;
1999
2000 return CD->size_overridden_methods() != 0;
2001 }
2002
2003 /// If it's possible to devirtualize a call to this method, return the called
2004 /// function. Otherwise, return null.
2005
2006 /// \param Base The object on which this virtual function is called.
2007 /// \param IsAppleKext True if we are compiling for Apple kext.
2008 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2009
2010 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2011 bool IsAppleKext) const {
2012 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2013 Base, IsAppleKext);
2014 }
2015
2016 /// Determine whether this is a usual deallocation function (C++
2017 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2018 /// delete[] operator with a particular signature. Populates \p PreventedBy
2019 /// with the declarations of the functions of the same kind if they were the
2020 /// reason for this function returning false. This is used by
2021 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2022 /// context.
2023 bool isUsualDeallocationFunction(
2024 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2025
2026 /// Determine whether this is a copy-assignment operator, regardless
2027 /// of whether it was declared implicitly or explicitly.
2028 bool isCopyAssignmentOperator() const;
2029
2030 /// Determine whether this is a move assignment operator.
2031 bool isMoveAssignmentOperator() const;
2032
2033 CXXMethodDecl *getCanonicalDecl() override {
2034 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2035 }
2036 const CXXMethodDecl *getCanonicalDecl() const {
2037 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2038 }
2039
2040 CXXMethodDecl *getMostRecentDecl() {
2041 return cast<CXXMethodDecl>(
2042 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2043 }
2044 const CXXMethodDecl *getMostRecentDecl() const {
2045 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2046 }
2047
2048 void addOverriddenMethod(const CXXMethodDecl *MD);
2049
2050 using method_iterator = const CXXMethodDecl *const *;
2051
2052 method_iterator begin_overridden_methods() const;
2053 method_iterator end_overridden_methods() const;
2054 unsigned size_overridden_methods() const;
2055
2056 using overridden_method_range = llvm::iterator_range<
2057 llvm::TinyPtrVector<const CXXMethodDecl *>::const_iterator>;
2058
2059 overridden_method_range overridden_methods() const;
2060
2061 /// Return the parent of this method declaration, which
2062 /// is the class in which this method is defined.
2063 const CXXRecordDecl *getParent() const {
2064 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2065 }
2066
2067 /// Return the parent of this method declaration, which
2068 /// is the class in which this method is defined.
2069 CXXRecordDecl *getParent() {
2070 return const_cast<CXXRecordDecl *>(
2071 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2072 }
2073
2074 /// Return the type of the \c this pointer.
2075 ///
2076 /// Should only be called for instance (i.e., non-static) methods. Note
2077 /// that for the call operator of a lambda closure type, this returns the
2078 /// desugared 'this' type (a pointer to the closure type), not the captured
2079 /// 'this' type.
2080 QualType getThisType() const;
2081
2082 /// Return the type of the object pointed by \c this.
2083 ///
2084 /// See getThisType() for usage restriction.
2085 QualType getThisObjectType() const;
2086
2087 static QualType getThisType(const FunctionProtoType *FPT,
2088 const CXXRecordDecl *Decl);
2089
2090 static QualType getThisObjectType(const FunctionProtoType *FPT,
2091 const CXXRecordDecl *Decl);
2092
2093 Qualifiers getMethodQualifiers() const {
2094 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2095 }
2096
2097 /// Retrieve the ref-qualifier associated with this method.
2098 ///
2099 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2100 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2101 /// @code
2102 /// struct X {
2103 /// void f() &;
2104 /// void g() &&;
2105 /// void h();
2106 /// };
2107 /// @endcode
2108 RefQualifierKind getRefQualifier() const {
2109 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2110 }
2111
2112 bool hasInlineBody() const;
2113
2114 /// Determine whether this is a lambda closure type's static member
2115 /// function that is used for the result of the lambda's conversion to
2116 /// function pointer (for a lambda with no captures).
2117 ///
2118 /// The function itself, if used, will have a placeholder body that will be
2119 /// supplied by IR generation to either forward to the function call operator
2120 /// or clone the function call operator.
2121 bool isLambdaStaticInvoker() const;
2122
2123 /// Find the method in \p RD that corresponds to this one.
2124 ///
2125 /// Find if \p RD or one of the classes it inherits from override this method.
2126 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2127 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2128 CXXMethodDecl *
2129 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2130 bool MayBeBase = false);
2131
2132 const CXXMethodDecl *
2133 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2134 bool MayBeBase = false) const {
2135 return const_cast<CXXMethodDecl *>(this)
2136 ->getCorrespondingMethodInClass(RD, MayBeBase);
2137 }
2138
2139 /// Find if \p RD declares a function that overrides this function, and if so,
2140 /// return it. Does not search base classes.
2141 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2142 bool MayBeBase = false);
2143 const CXXMethodDecl *
2144 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2145 bool MayBeBase = false) const {
2146 return const_cast<CXXMethodDecl *>(this)
2147 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2148 }
2149
2150 // Implement isa/cast/dyncast/etc.
2151 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2152 static bool classofKind(Kind K) {
2153 return K >= firstCXXMethod && K <= lastCXXMethod;
2154 }
2155};
2156
2157/// Represents a C++ base or member initializer.
2158///
2159/// This is part of a constructor initializer that
2160/// initializes one non-static member variable or one base class. For
2161/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2162/// initializers:
2163///
2164/// \code
2165/// class A { };
2166/// class B : public A {
2167/// float f;
2168/// public:
2169/// B(A& a) : A(a), f(3.14159) { }
2170/// };
2171/// \endcode
2172class CXXCtorInitializer final {
2173 /// Either the base class name/delegating constructor type (stored as
2174 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2175 /// (IndirectFieldDecl*) being initialized.
2176 llvm::PointerUnion<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2177 Initializee;
2178
2179 /// The argument used to initialize the base or member, which may
2180 /// end up constructing an object (when multiple arguments are involved).
2181 Stmt *Init;
2182
2183 /// The source location for the field name or, for a base initializer
2184 /// pack expansion, the location of the ellipsis.
2185 ///
2186 /// In the case of a delegating
2187 /// constructor, it will still include the type's source location as the
2188 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2189 SourceLocation MemberOrEllipsisLocation;
2190
2191 /// Location of the left paren of the ctor-initializer.
2192 SourceLocation LParenLoc;
2193
2194 /// Location of the right paren of the ctor-initializer.
2195 SourceLocation RParenLoc;
2196
2197 /// If the initializee is a type, whether that type makes this
2198 /// a delegating initialization.
2199 unsigned IsDelegating : 1;
2200
2201 /// If the initializer is a base initializer, this keeps track
2202 /// of whether the base is virtual or not.
2203 unsigned IsVirtual : 1;
2204
2205 /// Whether or not the initializer is explicitly written
2206 /// in the sources.
2207 unsigned IsWritten : 1;
2208
2209 /// If IsWritten is true, then this number keeps track of the textual order
2210 /// of this initializer in the original sources, counting from 0.
2211 unsigned SourceOrder : 13;
2212
2213public:
2214 /// Creates a new base-class initializer.
2215 explicit
2216 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2217 SourceLocation L, Expr *Init, SourceLocation R,
2218 SourceLocation EllipsisLoc);
2219
2220 /// Creates a new member initializer.
2221 explicit
2222 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2223 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2224 SourceLocation R);
2225
2226 /// Creates a new anonymous field initializer.
2227 explicit
2228 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2229 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2230 SourceLocation R);
2231
2232 /// Creates a new delegating initializer.
2233 explicit
2234 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2235 SourceLocation L, Expr *Init, SourceLocation R);
2236
2237 /// \return Unique reproducible object identifier.
2238 int64_t getID(const ASTContext &Context) const;
2239
2240 /// Determine whether this initializer is initializing a base class.
2241 bool isBaseInitializer() const {
2242 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2243 }
2244
2245 /// Determine whether this initializer is initializing a non-static
2246 /// data member.
2247 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2248
2249 bool isAnyMemberInitializer() const {
2250 return isMemberInitializer() || isIndirectMemberInitializer();
2251 }
2252
2253 bool isIndirectMemberInitializer() const {
2254 return Initializee.is<IndirectFieldDecl*>();
2255 }
2256
2257 /// Determine whether this initializer is an implicit initializer
2258 /// generated for a field with an initializer defined on the member
2259 /// declaration.
2260 ///
2261 /// In-class member initializers (also known as "non-static data member
2262 /// initializations", NSDMIs) were introduced in C++11.
2263 bool isInClassMemberInitializer() const {
2264 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2265 }
2266
2267 /// Determine whether this initializer is creating a delegating
2268 /// constructor.
2269 bool isDelegatingInitializer() const {
2270 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2271 }
2272
2273 /// Determine whether this initializer is a pack expansion.
2274 bool isPackExpansion() const {
2275 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2276 }
2277
2278 // For a pack expansion, returns the location of the ellipsis.
2279 SourceLocation getEllipsisLoc() const {
2280 if (!isPackExpansion())
2281 return {};
2282 return MemberOrEllipsisLocation;
2283 }
2284
2285 /// If this is a base class initializer, returns the type of the
2286 /// base class with location information. Otherwise, returns an NULL
2287 /// type location.
2288 TypeLoc getBaseClassLoc() const;
2289
2290 /// If this is a base class initializer, returns the type of the base class.
2291 /// Otherwise, returns null.
2292 const Type *getBaseClass() const;
2293
2294 /// Returns whether the base is virtual or not.
2295 bool isBaseVirtual() const {
2296 assert(isBaseInitializer() && "Must call this on base initializer!")(static_cast<void> (0));
2297
2298 return IsVirtual;
2299 }
2300
2301 /// Returns the declarator information for a base class or delegating
2302 /// initializer.
2303 TypeSourceInfo *getTypeSourceInfo() const {
2304 return Initializee.dyn_cast<TypeSourceInfo *>();
2305 }
2306
2307 /// If this is a member initializer, returns the declaration of the
2308 /// non-static data member being initialized. Otherwise, returns null.
2309 FieldDecl *getMember() const {
2310 if (isMemberInitializer())
2311 return Initializee.get<FieldDecl*>();
2312 return nullptr;
2313 }
2314
2315 FieldDecl *getAnyMember() const {
2316 if (isMemberInitializer())
2317 return Initializee.get<FieldDecl*>();
2318 if (isIndirectMemberInitializer())
2319 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2320 return nullptr;
2321 }
2322
2323 IndirectFieldDecl *getIndirectMember() const {
2324 if (isIndirectMemberInitializer())
2325 return Initializee.get<IndirectFieldDecl*>();
2326 return nullptr;
2327 }
2328
2329 SourceLocation getMemberLocation() const {
2330 return MemberOrEllipsisLocation;
2331 }
2332
2333 /// Determine the source location of the initializer.
2334 SourceLocation getSourceLocation() const;
2335
2336 /// Determine the source range covering the entire initializer.
2337 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__));
2338
2339 /// Determine whether this initializer is explicitly written
2340 /// in the source code.
2341 bool isWritten() const { return IsWritten; }
2342
2343 /// Return the source position of the initializer, counting from 0.
2344 /// If the initializer was implicit, -1 is returned.
2345 int getSourceOrder() const {
2346 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2347 }
2348
2349 /// Set the source order of this initializer.
2350 ///
2351 /// This can only be called once for each initializer; it cannot be called
2352 /// on an initializer having a positive number of (implicit) array indices.
2353 ///
2354 /// This assumes that the initializer was written in the source code, and
2355 /// ensures that isWritten() returns true.
2356 void setSourceOrder(int Pos) {
2357 assert(!IsWritten &&(static_cast<void> (0))
2358 "setSourceOrder() used on implicit initializer")(static_cast<void> (0));
2359 assert(SourceOrder == 0 &&(static_cast<void> (0))
2360 "calling twice setSourceOrder() on the same initializer")(static_cast<void> (0));
2361 assert(Pos >= 0 &&(static_cast<void> (0))
2362 "setSourceOrder() used to make an initializer implicit")(static_cast<void> (0));
2363 IsWritten = true;
2364 SourceOrder = static_cast<unsigned>(Pos);
2365 }
2366
2367 SourceLocation getLParenLoc() const { return LParenLoc; }
2368 SourceLocation getRParenLoc() const { return RParenLoc; }
2369
2370 /// Get the initializer.
2371 Expr *getInit() const { return static_cast<Expr *>(Init); }
2372};
2373
2374/// Description of a constructor that was inherited from a base class.
2375class InheritedConstructor {
2376 ConstructorUsingShadowDecl *Shadow = nullptr;
2377 CXXConstructorDecl *BaseCtor = nullptr;
2378
2379public:
2380 InheritedConstructor() = default;
2381 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2382 CXXConstructorDecl *BaseCtor)
2383 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2384
2385 explicit operator bool() const { return Shadow; }
2386
2387 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2388 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2389};
2390
2391/// Represents a C++ constructor within a class.
2392///
2393/// For example:
2394///
2395/// \code
2396/// class X {
2397/// public:
2398/// explicit X(int); // represented by a CXXConstructorDecl.
2399/// };
2400/// \endcode
2401class CXXConstructorDecl final
2402 : public CXXMethodDecl,
2403 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2404 ExplicitSpecifier> {
2405 // This class stores some data in DeclContext::CXXConstructorDeclBits
2406 // to save some space. Use the provided accessors to access it.
2407
2408 /// \name Support for base and member initializers.
2409 /// \{
2410 /// The arguments used to initialize the base or member.
2411 LazyCXXCtorInitializersPtr CtorInitializers;
2412
2413 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2414 const DeclarationNameInfo &NameInfo, QualType T,
2415 TypeSourceInfo *TInfo, ExplicitSpecifier ES,
2416 bool UsesFPIntrin, bool isInline,
2417 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2418 InheritedConstructor Inherited,
2419 Expr *TrailingRequiresClause);
2420
2421 void anchor() override;
2422
2423 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2424 return CXXConstructorDeclBits.IsInheritingConstructor;
2425 }
2426 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2427 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2428 }
2429
2430 ExplicitSpecifier getExplicitSpecifierInternal() const {
2431 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2432 return *getTrailingObjects<ExplicitSpecifier>();
2433 return ExplicitSpecifier(
2434 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2435 ? ExplicitSpecKind::ResolvedTrue
2436 : ExplicitSpecKind::ResolvedFalse);
2437 }
2438
2439 enum TrailingAllocKind {
2440 TAKInheritsConstructor = 1,
2441 TAKHasTailExplicit = 1 << 1,
2442 };
2443
2444 uint64_t getTrailingAllocKind() const {
2445 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2446 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2447 }
2448
2449public:
2450 friend class ASTDeclReader;
2451 friend class ASTDeclWriter;
2452 friend TrailingObjects;
2453
2454 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2455 uint64_t AllocKind);
2456 static CXXConstructorDecl *
2457 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2458 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2459 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,
2460 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2461 InheritedConstructor Inherited = InheritedConstructor(),
2462 Expr *TrailingRequiresClause = nullptr);
2463
2464 void setExplicitSpecifier(ExplicitSpecifier ES) {
2465 assert((!ES.getExpr() ||(static_cast<void> (0))
2466 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&(static_cast<void> (0))
2467 "cannot set this explicit specifier. no trail-allocated space for "(static_cast<void> (0))
2468 "explicit")(static_cast<void> (0));
2469 if (ES.getExpr())
2470 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2471 else
2472 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2473 }
2474
2475 ExplicitSpecifier getExplicitSpecifier() {
2476 return getCanonicalDecl()->getExplicitSpecifierInternal();
2477 }
2478 const ExplicitSpecifier getExplicitSpecifier() const {
2479 return getCanonicalDecl()->getExplicitSpecifierInternal();
2480 }
2481
2482 /// Return true if the declartion is already resolved to be explicit.
2483 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2484
2485 /// Iterates through the member/base initializer list.
2486 using init_iterator = CXXCtorInitializer **;
2487
2488 /// Iterates through the member/base initializer list.
2489 using init_const_iterator = CXXCtorInitializer *const *;
2490
2491 using init_range = llvm::iterator_range<init_iterator>;
2492 using init_const_range = llvm::iterator_range<init_const_iterator>;
2493
2494 init_range inits() { return init_range(init_begin(), init_end()); }
2495 init_const_range inits() const {
2496 return init_const_range(init_begin(), init_end());
2497 }
2498
2499 /// Retrieve an iterator to the first initializer.
2500 init_iterator init_begin() {
2501 const auto *ConstThis = this;
2502 return const_cast<init_iterator>(ConstThis->init_begin());
2503 }
2504
2505 /// Retrieve an iterator to the first initializer.
2506 init_const_iterator init_begin() const;
2507
2508 /// Retrieve an iterator past the last initializer.
2509 init_iterator init_end() {
2510 return init_begin() + getNumCtorInitializers();
2511 }
2512
2513 /// Retrieve an iterator past the last initializer.
2514 init_const_iterator init_end() const {
2515 return init_begin() + getNumCtorInitializers();
2516 }
2517
2518 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2519 using init_const_reverse_iterator =
2520 std::reverse_iterator<init_const_iterator>;
2521
2522 init_reverse_iterator init_rbegin() {
2523 return init_reverse_iterator(init_end());
2524 }
2525 init_const_reverse_iterator init_rbegin() const {
2526 return init_const_reverse_iterator(init_end());
2527 }
2528
2529 init_reverse_iterator init_rend() {
2530 return init_reverse_iterator(init_begin());
2531 }
2532 init_const_reverse_iterator init_rend() const {
2533 return init_const_reverse_iterator(init_begin());
2534 }
2535
2536 /// Determine the number of arguments used to initialize the member
2537 /// or base.
2538 unsigned getNumCtorInitializers() const {
2539 return CXXConstructorDeclBits.NumCtorInitializers;
2540 }
2541
2542 void setNumCtorInitializers(unsigned numCtorInitializers) {
2543 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2544 // This assert added because NumCtorInitializers is stored
2545 // in CXXConstructorDeclBits as a bitfield and its width has
2546 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2547 assert(CXXConstructorDeclBits.NumCtorInitializers ==(static_cast<void> (0))
2548 numCtorInitializers && "NumCtorInitializers overflow!")(static_cast<void> (0));
2549 }
2550
2551 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2552 CtorInitializers = Initializers;
2553 }
2554
2555 /// Determine whether this constructor is a delegating constructor.
2556 bool isDelegatingConstructor() const {
2557 return (getNumCtorInitializers() == 1) &&
2558 init_begin()[0]->isDelegatingInitializer();
2559 }
2560
2561 /// When this constructor delegates to another, retrieve the target.
2562 CXXConstructorDecl *getTargetConstructor() const;
2563
2564 /// Whether this constructor is a default
2565 /// constructor (C++ [class.ctor]p5), which can be used to
2566 /// default-initialize a class of this type.
2567 bool isDefaultConstructor() const;
2568
2569 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2570 /// which can be used to copy the class.
2571 ///
2572 /// \p TypeQuals will be set to the qualifiers on the
2573 /// argument type. For example, \p TypeQuals would be set to \c
2574 /// Qualifiers::Const for the following copy constructor:
2575 ///
2576 /// \code
2577 /// class X {
2578 /// public:
2579 /// X(const X&);
2580 /// };
2581 /// \endcode
2582 bool isCopyConstructor(unsigned &TypeQuals) const;
2583
2584 /// Whether this constructor is a copy
2585 /// constructor (C++ [class.copy]p2, which can be used to copy the
2586 /// class.
2587 bool isCopyConstructor() const {
2588 unsigned TypeQuals = 0;
2589 return isCopyConstructor(TypeQuals);
2590 }
2591
2592 /// Determine whether this constructor is a move constructor
2593 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2594 ///
2595 /// \param TypeQuals If this constructor is a move constructor, will be set
2596 /// to the type qualifiers on the referent of the first parameter's type.
2597 bool isMoveConstructor(unsigned &TypeQuals) const;
2598
2599 /// Determine whether this constructor is a move constructor
2600 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2601 bool isMoveConstructor() const {
2602 unsigned TypeQuals = 0;
2603 return isMoveConstructor(TypeQuals);
2604 }
2605
2606 /// Determine whether this is a copy or move constructor.
2607 ///
2608 /// \param TypeQuals Will be set to the type qualifiers on the reference
2609 /// parameter, if in fact this is a copy or move constructor.
2610 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2611
2612 /// Determine whether this a copy or move constructor.
2613 bool isCopyOrMoveConstructor() const {
2614 unsigned Quals;
2615 return isCopyOrMoveConstructor(Quals);
2616 }
2617
2618 /// Whether this constructor is a
2619 /// converting constructor (C++ [class.conv.ctor]), which can be
2620 /// used for user-defined conversions.
2621 bool isConvertingConstructor(bool AllowExplicit) const;
2622
2623 /// Determine whether this is a member template specialization that
2624 /// would copy the object to itself. Such constructors are never used to copy
2625 /// an object.
2626 bool isSpecializationCopyingObject() const;
2627
2628 /// Determine whether this is an implicit constructor synthesized to
2629 /// model a call to a constructor inherited from a base class.
2630 bool isInheritingConstructor() const {
2631 return CXXConstructorDeclBits.IsInheritingConstructor;
2632 }
2633
2634 /// State that this is an implicit constructor synthesized to
2635 /// model a call to a constructor inherited from a base class.
2636 void setInheritingConstructor(bool isIC = true) {
2637 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2638 }
2639
2640 /// Get the constructor that this inheriting constructor is based on.
2641 InheritedConstructor getInheritedConstructor() const {
2642 return isInheritingConstructor() ?
2643 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2644 }
2645
2646 CXXConstructorDecl *getCanonicalDecl() override {
2647 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2648 }
2649 const CXXConstructorDecl *getCanonicalDecl() const {
2650 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2651 }
2652
2653 // Implement isa/cast/dyncast/etc.
2654 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2655 static bool classofKind(Kind K) { return K == CXXConstructor; }
2656};
2657
2658/// Represents a C++ destructor within a class.
2659///
2660/// For example:
2661///
2662/// \code
2663/// class X {
2664/// public:
2665/// ~X(); // represented by a CXXDestructorDecl.
2666/// };
2667/// \endcode
2668class CXXDestructorDecl : public CXXMethodDecl {
2669 friend class ASTDeclReader;
2670 friend class ASTDeclWriter;
2671
2672 // FIXME: Don't allocate storage for these except in the first declaration
2673 // of a virtual destructor.
2674 FunctionDecl *OperatorDelete = nullptr;
2675 Expr *OperatorDeleteThisArg = nullptr;
2676
2677 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2678 const DeclarationNameInfo &NameInfo, QualType T,
2679 TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline,
2680 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2681 Expr *TrailingRequiresClause = nullptr)
2682 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2683 SC_None, UsesFPIntrin, isInline, ConstexprKind,
2684 SourceLocation(), TrailingRequiresClause) {
2685 setImplicit(isImplicitlyDeclared);
2686 }
2687
2688 void anchor() override;
2689
2690public:
2691 static CXXDestructorDecl *
2692 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2693 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2694 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,
2695 ConstexprSpecKind ConstexprKind,
2696 Expr *TrailingRequiresClause = nullptr);
2697 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2698
2699 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2700
2701 const FunctionDecl *getOperatorDelete() const {
2702 return getCanonicalDecl()->OperatorDelete;
2703 }
2704
2705 Expr *getOperatorDeleteThisArg() const {
2706 return getCanonicalDecl()->OperatorDeleteThisArg;
2707 }
2708
2709 CXXDestructorDecl *getCanonicalDecl() override {
2710 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2711 }
2712 const CXXDestructorDecl *getCanonicalDecl() const {
2713 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2714 }
2715
2716 // Implement isa/cast/dyncast/etc.
2717 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2718 static bool classofKind(Kind K) { return K == CXXDestructor; }
2719};
2720
2721/// Represents a C++ conversion function within a class.
2722///
2723/// For example:
2724///
2725/// \code
2726/// class X {
2727/// public:
2728/// operator bool();
2729/// };
2730/// \endcode
2731class CXXConversionDecl : public CXXMethodDecl {
2732 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2733 const DeclarationNameInfo &NameInfo, QualType T,
2734 TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline,
2735 ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2736 SourceLocation EndLocation,
2737 Expr *TrailingRequiresClause = nullptr)
2738 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2739 SC_None, UsesFPIntrin, isInline, ConstexprKind,
2740 EndLocation, TrailingRequiresClause),
2741 ExplicitSpec(ES) {}
2742 void anchor() override;
2743
2744 ExplicitSpecifier ExplicitSpec;
2745
2746public:
2747 friend class ASTDeclReader;
2748 friend class ASTDeclWriter;
2749
2750 static CXXConversionDecl *
2751 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2752 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2753 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,
2754 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,
2755 Expr *TrailingRequiresClause = nullptr);
2756 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2757
2758 ExplicitSpecifier getExplicitSpecifier() {
2759 return getCanonicalDecl()->ExplicitSpec;
2760 }
2761
2762 const ExplicitSpecifier getExplicitSpecifier() const {
2763 return getCanonicalDecl()->ExplicitSpec;
2764 }
2765
2766 /// Return true if the declartion is already resolved to be explicit.
2767 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2768 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2769
2770 /// Returns the type that this conversion function is converting to.
2771 QualType getConversionType() const {
2772 return getType()->castAs<FunctionType>()->getReturnType();
2773 }
2774
2775 /// Determine whether this conversion function is a conversion from
2776 /// a lambda closure type to a block pointer.
2777 bool isLambdaToBlockPointerConversion() const;
2778
2779 CXXConversionDecl *getCanonicalDecl() override {
2780 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2781 }
2782 const CXXConversionDecl *getCanonicalDecl() const {
2783 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2784 }
2785
2786 // Implement isa/cast/dyncast/etc.
2787 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2788 static bool classofKind(Kind K) { return K == CXXConversion; }
2789};
2790
2791/// Represents a linkage specification.
2792///
2793/// For example:
2794/// \code
2795/// extern "C" void foo();
2796/// \endcode
2797class LinkageSpecDecl : public Decl, public DeclContext {
2798 virtual void anchor();
2799 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2800 // some space. Use the provided accessors to access it.
2801public:
2802 /// Represents the language in a linkage specification.
2803 ///
2804 /// The values are part of the serialization ABI for
2805 /// ASTs and cannot be changed without altering that ABI.
2806 enum LanguageIDs { lang_c = 1, lang_cxx = 2 };
2807
2808private:
2809 /// The source location for the extern keyword.
2810 SourceLocation ExternLoc;
2811
2812 /// The source location for the right brace (if valid).
2813 SourceLocation RBraceLoc;
2814
2815 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2816 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2817
2818public:
2819 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2820 SourceLocation ExternLoc,
2821 SourceLocation LangLoc, LanguageIDs Lang,
2822 bool HasBraces);
2823 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2824
2825 /// Return the language specified by this linkage specification.
2826 LanguageIDs getLanguage() const {
2827 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
2828 }
2829
2830 /// Set the language specified by this linkage specification.
2831 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
2832
2833 /// Determines whether this linkage specification had braces in
2834 /// its syntactic form.
2835 bool hasBraces() const {
2836 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces)(static_cast<void> (0));
2837 return LinkageSpecDeclBits.HasBraces;
2838 }
2839
2840 SourceLocation getExternLoc() const { return ExternLoc; }
2841 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2842 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2843 void setRBraceLoc(SourceLocation L) {
2844 RBraceLoc = L;
2845 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
2846 }
2847
2848 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2849 if (hasBraces())
2850 return getRBraceLoc();
2851 // No braces: get the end location of the (only) declaration in context
2852 // (if present).
2853 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
2854 }
2855
2856 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2857 return SourceRange(ExternLoc, getEndLoc());
2858 }
2859
2860 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2861 static bool classofKind(Kind K) { return K == LinkageSpec; }
2862
2863 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2864 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2865 }
2866
2867 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2868 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2869 }
2870};
2871
2872/// Represents C++ using-directive.
2873///
2874/// For example:
2875/// \code
2876/// using namespace std;
2877/// \endcode
2878///
2879/// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2880/// artificial names for all using-directives in order to store
2881/// them in DeclContext effectively.
2882class UsingDirectiveDecl : public NamedDecl {
2883 /// The location of the \c using keyword.
2884 SourceLocation UsingLoc;
2885
2886 /// The location of the \c namespace keyword.
2887 SourceLocation NamespaceLoc;
2888
2889 /// The nested-name-specifier that precedes the namespace.
2890 NestedNameSpecifierLoc QualifierLoc;
2891
2892 /// The namespace nominated by this using-directive.
2893 NamedDecl *NominatedNamespace;
2894
2895 /// Enclosing context containing both using-directive and nominated
2896 /// namespace.
2897 DeclContext *CommonAncestor;
2898
2899 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2900 SourceLocation NamespcLoc,
2901 NestedNameSpecifierLoc QualifierLoc,
2902 SourceLocation IdentLoc,
2903 NamedDecl *Nominated,
2904 DeclContext *CommonAncestor)
2905 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2906 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2907 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2908
2909 /// Returns special DeclarationName used by using-directives.
2910 ///
2911 /// This is only used by DeclContext for storing UsingDirectiveDecls in
2912 /// its lookup structure.
2913 static DeclarationName getName() {
2914 return DeclarationName::getUsingDirectiveName();
2915 }
2916
2917 void anchor() override;
2918
2919public:
2920 friend class ASTDeclReader;
2921
2922 // Friend for getUsingDirectiveName.
2923 friend class DeclContext;
2924
2925 /// Retrieve the nested-name-specifier that qualifies the
2926 /// name of the namespace, with source-location information.
2927 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2928
2929 /// Retrieve the nested-name-specifier that qualifies the
2930 /// name of the namespace.
2931 NestedNameSpecifier *getQualifier() const {
2932 return QualifierLoc.getNestedNameSpecifier();
2933 }
2934
2935 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
2936 const NamedDecl *getNominatedNamespaceAsWritten() const {
2937 return NominatedNamespace;
2938 }
2939
2940 /// Returns the namespace nominated by this using-directive.
2941 NamespaceDecl *getNominatedNamespace();
2942
2943 const NamespaceDecl *getNominatedNamespace() const {
2944 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
2945 }
2946
2947 /// Returns the common ancestor context of this using-directive and
2948 /// its nominated namespace.
2949 DeclContext *getCommonAncestor() { return CommonAncestor; }
2950 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
2951
2952 /// Return the location of the \c using keyword.
2953 SourceLocation getUsingLoc() const { return UsingLoc; }
2954
2955 // FIXME: Could omit 'Key' in name.
2956 /// Returns the location of the \c namespace keyword.
2957 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
2958
2959 /// Returns the location of this using declaration's identifier.
2960 SourceLocation getIdentLocation() const { return getLocation(); }
2961
2962 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
2963 SourceLocation UsingLoc,
2964 SourceLocation NamespaceLoc,
2965 NestedNameSpecifierLoc QualifierLoc,
2966 SourceLocation IdentLoc,
2967 NamedDecl *Nominated,
2968 DeclContext *CommonAncestor);
2969 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2970
2971 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
2972 return SourceRange(UsingLoc, getLocation());
2973 }
2974
2975 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2976 static bool classofKind(Kind K) { return K == UsingDirective; }
2977};
2978
2979/// Represents a C++ namespace alias.
2980///
2981/// For example:
2982///
2983/// \code
2984/// namespace Foo = Bar;
2985/// \endcode
2986class NamespaceAliasDecl : public NamedDecl,
2987 public Redeclarable<NamespaceAliasDecl> {
2988 friend class ASTDeclReader;
2989
2990 /// The location of the \c namespace keyword.
2991 SourceLocation NamespaceLoc;
2992
2993 /// The location of the namespace's identifier.
2994 ///
2995 /// This is accessed by TargetNameLoc.
2996 SourceLocation IdentLoc;
2997
2998 /// The nested-name-specifier that precedes the namespace.
2999 NestedNameSpecifierLoc QualifierLoc;
3000
3001 /// The Decl that this alias points to, either a NamespaceDecl or
3002 /// a NamespaceAliasDecl.
3003 NamedDecl *Namespace;
3004
3005 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3006 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3007 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3008 SourceLocation IdentLoc, NamedDecl *Namespace)
3009 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3010 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3011 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3012
3013 void anchor() override;
3014
3015 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3016
3017 NamespaceAliasDecl *getNextRedeclarationImpl() override;
3018 NamespaceAliasDecl *getPreviousDeclImpl() override;
3019 NamespaceAliasDecl *getMostRecentDeclImpl() override;
3020
3021public:
3022 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3023 SourceLocation NamespaceLoc,
3024 SourceLocation AliasLoc,
3025 IdentifierInfo *Alias,
3026 NestedNameSpecifierLoc QualifierLoc,
3027 SourceLocation IdentLoc,
3028 NamedDecl *Namespace);
3029
3030 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3031
3032 using redecl_range = redeclarable_base::redecl_range;
3033 using redecl_iterator = redeclarable_base::redecl_iterator;
3034
3035 using redeclarable_base::redecls_begin;
3036 using redeclarable_base::redecls_end;
3037 using redeclarable_base::redecls;
3038 using redeclarable_base::getPreviousDecl;
3039 using redeclarable_base::getMostRecentDecl;
3040
3041 NamespaceAliasDecl *getCanonicalDecl() override {
3042 return getFirstDecl();
3043 }
3044 const NamespaceAliasDecl *getCanonicalDecl() const {
3045 return getFirstDecl();
3046 }
3047
3048 /// Retrieve the nested-name-specifier that qualifies the
3049 /// name of the namespace, with source-location information.
3050 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3051
3052 /// Retrieve the nested-name-specifier that qualifies the
3053 /// name of the namespace.
3054 NestedNameSpecifier *getQualifier() const {
3055 return QualifierLoc.getNestedNameSpecifier();
3056 }
3057
3058 /// Retrieve the namespace declaration aliased by this directive.
3059 NamespaceDecl *getNamespace() {
3060 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3061 return AD->getNamespace();
3062
3063 return cast<NamespaceDecl>(Namespace);
3064 }
3065
3066 const NamespaceDecl *getNamespace() const {
3067 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3068 }
3069
3070 /// Returns the location of the alias name, i.e. 'foo' in
3071 /// "namespace foo = ns::bar;".
3072 SourceLocation getAliasLoc() const { return getLocation(); }
3073
3074 /// Returns the location of the \c namespace keyword.
3075 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3076
3077 /// Returns the location of the identifier in the named namespace.
3078 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3079
3080 /// Retrieve the namespace that this alias refers to, which
3081 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3082 NamedDecl *getAliasedNamespace() const { return Namespace; }
3083
3084 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3085 return SourceRange(NamespaceLoc, IdentLoc);
3086 }
3087
3088 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3089 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3090};
3091
3092/// Implicit declaration of a temporary that was materialized by
3093/// a MaterializeTemporaryExpr and lifetime-extended by a declaration
3094class LifetimeExtendedTemporaryDecl final
3095 : public Decl,
3096 public Mergeable<LifetimeExtendedTemporaryDecl> {
3097 friend class MaterializeTemporaryExpr;
3098 friend class ASTDeclReader;
3099
3100 Stmt *ExprWithTemporary = nullptr;
3101
3102 /// The declaration which lifetime-extended this reference, if any.
3103 /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
3104 ValueDecl *ExtendingDecl = nullptr;
3105 unsigned ManglingNumber;
3106
3107 mutable APValue *Value = nullptr;
3108
3109 virtual void anchor();
3110
3111 LifetimeExtendedTemporaryDecl(Expr *Temp, ValueDecl *EDecl, unsigned Mangling)
3112 : Decl(Decl::LifetimeExtendedTemporary, EDecl->getDeclContext(),
3113 EDecl->getLocation()),
3114 ExprWithTemporary(Temp), ExtendingDecl(EDecl),
3115 ManglingNumber(Mangling) {}
3116
3117 LifetimeExtendedTemporaryDecl(EmptyShell)
3118 : Decl(Decl::LifetimeExtendedTemporary, EmptyShell{}) {}
3119
3120public:
3121 static LifetimeExtendedTemporaryDecl *Create(Expr *Temp, ValueDecl *EDec,
3122 unsigned Mangling) {
3123 return new (EDec->getASTContext(), EDec->getDeclContext())
3124 LifetimeExtendedTemporaryDecl(Temp, EDec, Mangling);
3125 }
3126 static LifetimeExtendedTemporaryDecl *CreateDeserialized(ASTContext &C,
3127 unsigned ID) {
3128 return new (C, ID) LifetimeExtendedTemporaryDecl(EmptyShell{});
3129 }
3130
3131 ValueDecl *getExtendingDecl() { return ExtendingDecl; }
3132 const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
3133
3134 /// Retrieve the storage duration for the materialized temporary.
3135 StorageDuration getStorageDuration() const;
3136
3137 /// Retrieve the expression to which the temporary materialization conversion
3138 /// was applied. This isn't necessarily the initializer of the temporary due
3139 /// to the C++98 delayed materialization rules, but
3140 /// skipRValueSubobjectAdjustments can be used to find said initializer within
3141 /// the subexpression.
3142 Expr *getTemporaryExpr() { return cast<Expr>(ExprWithTemporary); }
3143 const Expr *getTemporaryExpr() const { return cast<Expr>(ExprWithTemporary); }
3144
3145 unsigned getManglingNumber() const { return ManglingNumber; }
3146
3147 /// Get the storage for the constant value of a materialized temporary
3148 /// of static storage duration.
3149 APValue *getOrCreateValue(bool MayCreate) const;
3150
3151 APValue *getValue() const { return Value; }
3152
3153 // Iterators
3154 Stmt::child_range childrenExpr() {
3155 return Stmt::child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3156 }
3157
3158 Stmt::const_child_range childrenExpr() const {
3159 return Stmt::const_child_range(&ExprWithTemporary, &ExprWithTemporary + 1);
3160 }
3161
3162 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3163 static bool classofKind(Kind K) {
3164 return K == Decl::LifetimeExtendedTemporary;
3165 }
3166};
3167
3168/// Represents a shadow declaration implicitly introduced into a scope by a
3169/// (resolved) using-declaration or using-enum-declaration to achieve
3170/// the desired lookup semantics.
3171///
3172/// For example:
3173/// \code
3174/// namespace A {
3175/// void foo();
3176/// void foo(int);
3177/// struct foo {};
3178/// enum bar { bar1, bar2 };
3179/// }
3180/// namespace B {
3181/// // add a UsingDecl and three UsingShadowDecls (named foo) to B.
3182/// using A::foo;
3183/// // adds UsingEnumDecl and two UsingShadowDecls (named bar1 and bar2) to B.
3184/// using enum A::bar;
3185/// }
3186/// \endcode
3187class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3188 friend class BaseUsingDecl;
3189
3190 /// The referenced declaration.
3191 NamedDecl *Underlying = nullptr;
3192
3193 /// The using declaration which introduced this decl or the next using
3194 /// shadow declaration contained in the aforementioned using declaration.
3195 NamedDecl *UsingOrNextShadow = nullptr;
3196
3197 void anchor() override;
3198
3199 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3200
3201 UsingShadowDecl *getNextRedeclarationImpl() override {
3202 return getNextRedeclaration();
3203 }
3204
3205 UsingShadowDecl *getPreviousDeclImpl() override {
3206 return getPreviousDecl();
3207 }
3208
3209 UsingShadowDecl *getMostRecentDeclImpl() override {
3210 return getMostRecentDecl();
3211 }
3212
3213protected:
3214 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3215 DeclarationName Name, BaseUsingDecl *Introducer,
3216 NamedDecl *Target);
3217 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3218
3219public:
3220 friend class ASTDeclReader;
3221 friend class ASTDeclWriter;
3222
3223 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3224 SourceLocation Loc, DeclarationName Name,
3225 BaseUsingDecl *Introducer, NamedDecl *Target) {
3226 return new (C, DC)
3227 UsingShadowDecl(UsingShadow, C, DC, Loc, Name, Introducer, Target);
3228 }
3229
3230 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3231
3232 using redecl_range = redeclarable_base::redecl_range;
3233 using redecl_iterator = redeclarable_base::redecl_iterator;
3234
3235 using redeclarable_base::redecls_begin;
3236 using redeclarable_base::redecls_end;
3237 using redeclarable_base::redecls;
3238 using redeclarable_base::getPreviousDecl;
3239 using redeclarable_base::getMostRecentDecl;
3240 using redeclarable_base::isFirstDecl;
3241
3242 UsingShadowDecl *getCanonicalDecl() override {
3243 return getFirstDecl();
3244 }
3245 const UsingShadowDecl *getCanonicalDecl() const {
3246 return getFirstDecl();
3247 }
3248
3249 /// Gets the underlying declaration which has been brought into the
3250 /// local scope.
3251 NamedDecl *getTargetDecl() const { return Underlying; }
3252
3253 /// Sets the underlying declaration which has been brought into the
3254 /// local scope.
3255 void setTargetDecl(NamedDecl *ND) {
3256 assert(ND && "Target decl is null!")(static_cast<void> (0));
3257 Underlying = ND;
3258 // A UsingShadowDecl is never a friend or local extern declaration, even
3259 // if it is a shadow declaration for one.
3260 IdentifierNamespace =
3261 ND->getIdentifierNamespace() &
3262 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3263 }
3264
3265 /// Gets the (written or instantiated) using declaration that introduced this
3266 /// declaration.
3267 BaseUsingDecl *getIntroducer() const;
3268
3269 /// The next using shadow declaration contained in the shadow decl
3270 /// chain of the using declaration which introduced this decl.
3271 UsingShadowDecl *getNextUsingShadowDecl() const {
3272 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3273 }
3274
3275 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3276 static bool classofKind(Kind K) {
3277 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3278 }
3279};
3280
3281/// Represents a C++ declaration that introduces decls from somewhere else. It
3282/// provides a set of the shadow decls so introduced.
3283
3284class BaseUsingDecl : public NamedDecl {
3285 /// The first shadow declaration of the shadow decl chain associated
3286 /// with this using declaration.
3287 ///
3288 /// The bool member of the pair is a bool flag a derived type may use
3289 /// (UsingDecl makes use of it).
3290 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3291
3292protected:
3293 BaseUsingDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
3294 : NamedDecl(DK, DC, L, N), FirstUsingShadow(nullptr, 0) {}
3295
3296private:
3297 void anchor() override;
3298
3299protected:
3300 /// A bool flag for use by a derived type
3301 bool getShadowFlag() const { return FirstUsingShadow.getInt(); }
3302
3303 /// A bool flag a derived type may set
3304 void setShadowFlag(bool V) { FirstUsingShadow.setInt(V); }
3305
3306public:
3307 friend class ASTDeclReader;
3308 friend class ASTDeclWriter;
3309
3310 /// Iterates through the using shadow declarations associated with
3311 /// this using declaration.
3312 class shadow_iterator {
3313 /// The current using shadow declaration.
3314 UsingShadowDecl *Current = nullptr;
3315
3316 public:
3317 using value_type = UsingShadowDecl *;
3318 using reference = UsingShadowDecl *;
3319 using pointer = UsingShadowDecl *;
3320 using iterator_category = std::forward_iterator_tag;
3321 using difference_type = std::ptrdiff_t;
3322
3323 shadow_iterator() = default;
3324 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3325
3326 reference operator*() const { return Current; }
3327 pointer operator->() const { return Current; }
3328
3329 shadow_iterator &operator++() {
3330 Current = Current->getNextUsingShadowDecl();
3331 return *this;
3332 }
3333
3334 shadow_iterator operator++(int) {
3335 shadow_iterator tmp(*this);
3336 ++(*this);
3337 return tmp;
3338 }
3339
3340 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3341 return x.Current == y.Current;
3342 }
3343 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3344 return x.Current != y.Current;
3345 }
3346 };
3347
3348 using shadow_range = llvm::iterator_range<shadow_iterator>;
3349
3350 shadow_range shadows() const {
3351 return shadow_range(shadow_begin(), shadow_end());
3352 }
3353
3354 shadow_iterator shadow_begin() const {
3355 return shadow_iterator(FirstUsingShadow.getPointer());
3356 }
3357
3358 shadow_iterator shadow_end() const { return shadow_iterator(); }
3359
3360 /// Return the number of shadowed declarations associated with this
3361 /// using declaration.
3362 unsigned shadow_size() const {
3363 return std::distance(shadow_begin(), shadow_end());
3364 }
3365
3366 void addShadowDecl(UsingShadowDecl *S);
3367 void removeShadowDecl(UsingShadowDecl *S);
3368
3369 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3370 static bool classofKind(Kind K) { return K == Using || K == UsingEnum; }
3371};
3372
3373/// Represents a C++ using-declaration.
3374///
3375/// For example:
3376/// \code
3377/// using someNameSpace::someIdentifier;
3378/// \endcode
3379class UsingDecl : public BaseUsingDecl, public Mergeable<UsingDecl> {
3380 /// The source location of the 'using' keyword itself.
3381 SourceLocation UsingLocation;
3382
3383 /// The nested-name-specifier that precedes the name.
3384 NestedNameSpecifierLoc QualifierLoc;
3385
3386 /// Provides source/type location info for the declaration name
3387 /// embedded in the ValueDecl base class.
3388 DeclarationNameLoc DNLoc;
3389
3390 UsingDecl(DeclContext *DC, SourceLocation UL,
3391 NestedNameSpecifierLoc QualifierLoc,
3392 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3393 : BaseUsingDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3394 UsingLocation(UL), QualifierLoc(QualifierLoc),
3395 DNLoc(NameInfo.getInfo()) {
3396 setShadowFlag(HasTypenameKeyword);
3397 }
3398
3399 void anchor() override;
3400
3401public:
3402 friend class ASTDeclReader;
3403 friend class ASTDeclWriter;
3404
3405 /// Return the source location of the 'using' keyword.
3406 SourceLocation getUsingLoc() const { return UsingLocation; }
3407
3408 /// Set the source location of the 'using' keyword.
3409 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3410
3411 /// Retrieve the nested-name-specifier that qualifies the name,
3412 /// with source-location information.
3413 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3414
3415 /// Retrieve the nested-name-specifier that qualifies the name.
3416 NestedNameSpecifier *getQualifier() const {
3417 return QualifierLoc.getNestedNameSpecifier();
3418 }
3419
3420 DeclarationNameInfo getNameInfo() const {
3421 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3422 }
3423
3424 /// Return true if it is a C++03 access declaration (no 'using').
3425 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3426
3427 /// Return true if the using declaration has 'typename'.
3428 bool hasTypename() const { return getShadowFlag(); }
3429
3430 /// Sets whether the using declaration has 'typename'.
3431 void setTypename(bool TN) { setShadowFlag(TN); }
3432
3433 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3434 SourceLocation UsingL,
3435 NestedNameSpecifierLoc QualifierLoc,
3436 const DeclarationNameInfo &NameInfo,
3437 bool HasTypenameKeyword);
3438
3439 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3440
3441 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3442
3443 /// Retrieves the canonical declaration of this declaration.
3444 UsingDecl *getCanonicalDecl() override {
3445 return cast<UsingDecl>(getFirstDecl());
3446 }
3447 const UsingDecl *getCanonicalDecl() const {
3448 return cast<UsingDecl>(getFirstDecl());
3449 }
3450
3451 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3452 static bool classofKind(Kind K) { return K == Using; }
3453};
3454
3455/// Represents a shadow constructor declaration introduced into a
3456/// class by a C++11 using-declaration that names a constructor.
3457///
3458/// For example:
3459/// \code
3460/// struct Base { Base(int); };
3461/// struct Derived {
3462/// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3463/// };
3464/// \endcode
3465class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3466 /// If this constructor using declaration inherted the constructor
3467 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3468 /// in the named direct base class from which the declaration was inherited.
3469 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3470
3471 /// If this constructor using declaration inherted the constructor
3472 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3473 /// that will be used to construct the unique direct or virtual base class
3474 /// that receives the constructor arguments.
3475 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3476
3477 /// \c true if the constructor ultimately named by this using shadow
3478 /// declaration is within a virtual base class subobject of the class that
3479 /// contains this declaration.
3480 unsigned IsVirtual : 1;
3481
3482 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3483 UsingDecl *Using, NamedDecl *Target,
3484 bool TargetInVirtualBase)
3485 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc,
3486 Using->getDeclName(), Using,
3487 Target->getUnderlyingDecl()),
3488 NominatedBaseClassShadowDecl(
3489 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3490 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3491 IsVirtual(TargetInVirtualBase) {
3492 // If we found a constructor that chains to a constructor for a virtual
3493 // base, we should directly call that virtual base constructor instead.
3494 // FIXME: This logic belongs in Sema.
3495 if (NominatedBaseClassShadowDecl &&
3496 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3497 ConstructedBaseClassShadowDecl =
3498 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3499 IsVirtual = true;
3500 }
3501 }
3502
3503 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3504 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3505
3506 void anchor() override;
3507
3508public:
3509 friend class ASTDeclReader;
3510 friend class ASTDeclWriter;
3511
3512 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3513 SourceLocation Loc,
3514 UsingDecl *Using, NamedDecl *Target,
3515 bool IsVirtual);
3516 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3517 unsigned ID);
3518
3519 /// Override the UsingShadowDecl's getIntroducer, returning the UsingDecl that
3520 /// introduced this.
3521 UsingDecl *getIntroducer() const {
3522 return cast<UsingDecl>(UsingShadowDecl::getIntroducer());
3523 }
3524
3525 /// Returns the parent of this using shadow declaration, which
3526 /// is the class in which this is declared.
3527 //@{
3528 const CXXRecordDecl *getParent() const {
3529 return cast<CXXRecordDecl>(getDeclContext());
3530 }
3531 CXXRecordDecl *getParent() {
3532 return cast<CXXRecordDecl>(getDeclContext());
3533 }
3534 //@}
3535
3536 /// Get the inheriting constructor declaration for the direct base
3537 /// class from which this using shadow declaration was inherited, if there is
3538 /// one. This can be different for each redeclaration of the same shadow decl.
3539 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3540 return NominatedBaseClassShadowDecl;
3541 }
3542
3543 /// Get the inheriting constructor declaration for the base class
3544 /// for which we don't have an explicit initializer, if there is one.
3545 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3546 return ConstructedBaseClassShadowDecl;
3547 }
3548
3549 /// Get the base class that was named in the using declaration. This
3550 /// can be different for each redeclaration of this same shadow decl.
3551 CXXRecordDecl *getNominatedBaseClass() const;
3552
3553 /// Get the base class whose constructor or constructor shadow
3554 /// declaration is passed the constructor arguments.
3555 CXXRecordDecl *getConstructedBaseClass() const {
3556 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3557 ? ConstructedBaseClassShadowDecl
3558 : getTargetDecl())
3559 ->getDeclContext());
3560 }
3561
3562 /// Returns \c true if the constructed base class is a virtual base
3563 /// class subobject of this declaration's class.
3564 bool constructsVirtualBase() const {
3565 return IsVirtual;
3566 }
3567
3568 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3569 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3570};
3571
3572/// Represents a C++ using-enum-declaration.
3573///
3574/// For example:
3575/// \code
3576/// using enum SomeEnumTag ;
3577/// \endcode
3578
3579class UsingEnumDecl : public BaseUsingDecl, public Mergeable<UsingEnumDecl> {
3580 /// The source location of the 'using' keyword itself.
3581 SourceLocation UsingLocation;
3582
3583 /// Location of the 'enum' keyword.
3584 SourceLocation EnumLocation;
3585
3586 /// The enum
3587 EnumDecl *Enum;
3588
3589 UsingEnumDecl(DeclContext *DC, DeclarationName DN, SourceLocation UL,
3590 SourceLocation EL, SourceLocation NL, EnumDecl *ED)
3591 : BaseUsingDecl(UsingEnum, DC, NL, DN), UsingLocation(UL),
3592 EnumLocation(EL), Enum(ED) {}
3593
3594 void anchor() override;
3595
3596public:
3597 friend class ASTDeclReader;
3598 friend class ASTDeclWriter;
3599
3600 /// The source location of the 'using' keyword.
3601 SourceLocation getUsingLoc() const { return UsingLocation; }
3602 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3603
3604 /// The source location of the 'enum' keyword.
3605 SourceLocation getEnumLoc() const { return EnumLocation; }
3606 void setEnumLoc(SourceLocation L) { EnumLocation = L; }
3607
3608public:
3609 EnumDecl *getEnumDecl() const { return Enum; }
3610
3611 static UsingEnumDecl *Create(ASTContext &C, DeclContext *DC,
3612 SourceLocation UsingL, SourceLocation EnumL,
3613 SourceLocation NameL, EnumDecl *ED);
3614
3615 static UsingEnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3616
3617 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3618
3619 /// Retrieves the canonical declaration of this declaration.
3620 UsingEnumDecl *getCanonicalDecl() override {
3621 return cast<UsingEnumDecl>(getFirstDecl());
3622 }
3623 const UsingEnumDecl *getCanonicalDecl() const {
3624 return cast<UsingEnumDecl>(getFirstDecl());
3625 }
3626
3627 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3628 static bool classofKind(Kind K) { return K == UsingEnum; }
3629};
3630
3631/// Represents a pack of using declarations that a single
3632/// using-declarator pack-expanded into.
3633///
3634/// \code
3635/// template<typename ...T> struct X : T... {
3636/// using T::operator()...;
3637/// using T::operator T...;
3638/// };
3639/// \endcode
3640///
3641/// In the second case above, the UsingPackDecl will have the name
3642/// 'operator T' (which contains an unexpanded pack), but the individual
3643/// UsingDecls and UsingShadowDecls will have more reasonable names.
3644class UsingPackDecl final
3645 : public NamedDecl, public Mergeable<UsingPackDecl>,
3646 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3647 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3648 /// which this waas instantiated.
3649 NamedDecl *InstantiatedFrom;
3650
3651 /// The number of using-declarations created by this pack expansion.
3652 unsigned NumExpansions;
3653
3654 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3655 ArrayRef<NamedDecl *> UsingDecls)
3656 : NamedDecl(UsingPack, DC,
3657 InstantiatedFrom ? InstantiatedFrom->getLocation()
3658 : SourceLocation(),
3659 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3660 : DeclarationName()),
3661 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3662 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3663 getTrailingObjects<NamedDecl *>());
3664 }
3665
3666 void anchor() override;
3667
3668public:
3669 friend class ASTDeclReader;
3670 friend class ASTDeclWriter;
3671 friend TrailingObjects;
3672
3673 /// Get the using declaration from which this was instantiated. This will
3674 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3675 /// that is a pack expansion.
3676 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3677
3678 /// Get the set of using declarations that this pack expanded into. Note that
3679 /// some of these may still be unresolved.
3680 ArrayRef<NamedDecl *> expansions() const {
3681 return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3682 }
3683
3684 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3685 NamedDecl *InstantiatedFrom,
3686 ArrayRef<NamedDecl *> UsingDecls);
3687
3688 static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3689 unsigned NumExpansions);
3690
3691 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3692 return InstantiatedFrom->getSourceRange();
3693 }
3694
3695 UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3696 const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3697
3698 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3699 static bool classofKind(Kind K) { return K == UsingPack; }
3700};
3701
3702/// Represents a dependent using declaration which was not marked with
3703/// \c typename.
3704///
3705/// Unlike non-dependent using declarations, these *only* bring through
3706/// non-types; otherwise they would break two-phase lookup.
3707///
3708/// \code
3709/// template \<class T> class A : public Base<T> {
3710/// using Base<T>::foo;
3711/// };
3712/// \endcode
3713class UnresolvedUsingValueDecl : public ValueDecl,
3714 public Mergeable<UnresolvedUsingValueDecl> {
3715 /// The source location of the 'using' keyword
3716 SourceLocation UsingLocation;
3717
3718 /// If this is a pack expansion, the location of the '...'.
3719 SourceLocation EllipsisLoc;
3720
3721 /// The nested-name-specifier that precedes the name.
3722 NestedNameSpecifierLoc QualifierLoc;
3723
3724 /// Provides source/type location info for the declaration name
3725 /// embedded in the ValueDecl base class.
3726 DeclarationNameLoc DNLoc;
3727
3728 UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3729 SourceLocation UsingLoc,
3730 NestedNameSpecifierLoc QualifierLoc,
3731 const DeclarationNameInfo &NameInfo,
3732 SourceLocation EllipsisLoc)
3733 : ValueDecl(UnresolvedUsingValue, DC,
3734 NameInfo.getLoc(), NameInfo.getName(), Ty),
3735 UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3736 QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3737
3738 void anchor() override;
3739
3740public:
3741 friend class ASTDeclReader;
3742 friend class ASTDeclWriter;
3743
3744 /// Returns the source location of the 'using' keyword.
3745 SourceLocation getUsingLoc() const { return UsingLocation; }
3746
3747 /// Set the source location of the 'using' keyword.
3748 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3749
3750 /// Return true if it is a C++03 access declaration (no 'using').
3751 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3752
3753 /// Retrieve the nested-name-specifier that qualifies the name,
3754 /// with source-location information.
3755 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3756
3757 /// Retrieve the nested-name-specifier that qualifies the name.
3758 NestedNameSpecifier *getQualifier() const {
3759 return QualifierLoc.getNestedNameSpecifier();
3760 }
3761
3762 DeclarationNameInfo getNameInfo() const {
3763 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3764 }
3765
3766 /// Determine whether this is a pack expansion.
3767 bool isPackExpansion() const {
3768 return EllipsisLoc.isValid();
3769 }
3770
3771 /// Get the location of the ellipsis if this is a pack expansion.
3772 SourceLocation getEllipsisLoc() const {
3773 return EllipsisLoc;
3774 }
3775
3776 static UnresolvedUsingValueDecl *
3777 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3778 NestedNameSpecifierLoc QualifierLoc,
3779 const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3780
3781 static UnresolvedUsingValueDecl *
3782 CreateDeserialized(ASTContext &C, unsigned ID);
3783
3784 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3785
3786 /// Retrieves the canonical declaration of this declaration.
3787 UnresolvedUsingValueDecl *getCanonicalDecl() override {
3788 return getFirstDecl();
3789 }
3790 const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3791 return getFirstDecl();
3792 }
3793
3794 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3795 static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3796};
3797
3798/// Represents a dependent using declaration which was marked with
3799/// \c typename.
3800///
3801/// \code
3802/// template \<class T> class A : public Base<T> {
3803/// using typename Base<T>::foo;
3804/// };
3805/// \endcode
3806///
3807/// The type associated with an unresolved using typename decl is
3808/// currently always a typename type.
3809class UnresolvedUsingTypenameDecl
3810 : public TypeDecl,
3811 public Mergeable<UnresolvedUsingTypenameDecl> {
3812 friend class ASTDeclReader;
3813
3814 /// The source location of the 'typename' keyword
3815 SourceLocation TypenameLocation;
3816
3817 /// If this is a pack expansion, the location of the '...'.
3818 SourceLocation EllipsisLoc;
3819
3820 /// The nested-name-specifier that precedes the name.
3821 NestedNameSpecifierLoc QualifierLoc;
3822
3823 UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3824 SourceLocation TypenameLoc,
3825 NestedNameSpecifierLoc QualifierLoc,
3826 SourceLocation TargetNameLoc,
3827 IdentifierInfo *TargetName,
3828 SourceLocation EllipsisLoc)
3829 : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3830 UsingLoc),
3831 TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3832 QualifierLoc(QualifierLoc) {}
3833
3834 void anchor() override;
3835
3836public:
3837 /// Returns the source location of the 'using' keyword.
3838 SourceLocation getUsingLoc() const { return getBeginLoc(); }
3839
3840 /// Returns the source location of the 'typename' keyword.
3841 SourceLocation getTypenameLoc() const { return TypenameLocation; }
3842
3843 /// Retrieve the nested-name-specifier that qualifies the name,
3844 /// with source-location information.
3845 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3846
3847 /// Retrieve the nested-name-specifier that qualifies the name.
3848 NestedNameSpecifier *getQualifier() const {
3849 return QualifierLoc.getNestedNameSpecifier();
3850 }
3851
3852 DeclarationNameInfo getNameInfo() const {
3853 return DeclarationNameInfo(getDeclName(), getLocation());
3854 }
3855
3856 /// Determine whether this is a pack expansion.
3857 bool isPackExpansion() const {
3858 return EllipsisLoc.isValid();
3859 }
3860
3861 /// Get the location of the ellipsis if this is a pack expansion.
3862 SourceLocation getEllipsisLoc() const {
3863 return EllipsisLoc;
3864 }
3865
3866 static UnresolvedUsingTypenameDecl *
3867 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3868 SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3869 SourceLocation TargetNameLoc, DeclarationName TargetName,
3870 SourceLocation EllipsisLoc);
3871
3872 static UnresolvedUsingTypenameDecl *
3873 CreateDeserialized(ASTContext &C, unsigned ID);
3874
3875 /// Retrieves the canonical declaration of this declaration.
3876 UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3877 return getFirstDecl();
3878 }
3879 const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3880 return getFirstDecl();
3881 }
3882
3883 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3884 static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3885};
3886
3887/// This node is generated when a using-declaration that was annotated with
3888/// __attribute__((using_if_exists)) failed to resolve to a known declaration.
3889/// In that case, Sema builds a UsingShadowDecl whose target is an instance of
3890/// this declaration, adding it to the current scope. Referring to this
3891/// declaration in any way is an error.
3892class UnresolvedUsingIfExistsDecl final : public NamedDecl {
3893 UnresolvedUsingIfExistsDecl(DeclContext *DC, SourceLocation Loc,
3894 DeclarationName Name);
3895
3896 void anchor() override;
3897
3898public:
3899 static UnresolvedUsingIfExistsDecl *Create(ASTContext &Ctx, DeclContext *DC,
3900 SourceLocation Loc,
3901 DeclarationName Name);
3902 static UnresolvedUsingIfExistsDecl *CreateDeserialized(ASTContext &Ctx,
3903 unsigned ID);
3904
3905 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3906 static bool classofKind(Kind K) { return K == Decl::UnresolvedUsingIfExists; }
3907};
3908
3909/// Represents a C++11 static_assert declaration.
3910class StaticAssertDecl : public Decl {
3911 llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
3912 StringLiteral *Message;
3913 SourceLocation RParenLoc;
3914
3915 StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
3916 Expr *AssertExpr, StringLiteral *Message,
3917 SourceLocation RParenLoc, bool Failed)
3918 : Decl(StaticAssert, DC, StaticAssertLoc),
3919 AssertExprAndFailed(AssertExpr, Failed), Message(Message),
3920 RParenLoc(RParenLoc) {}
3921
3922 virtual void anchor();
3923
3924public:
3925 friend class ASTDeclReader;
3926
3927 static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
3928 SourceLocation StaticAssertLoc,
3929 Expr *AssertExpr, StringLiteral *Message,
3930 SourceLocation RParenLoc, bool Failed);
3931 static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3932
3933 Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
3934 const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
3935
3936 StringLiteral *getMessage() { return Message; }
3937 const StringLiteral *getMessage() const { return Message; }
3938
3939 bool isFailed() const { return AssertExprAndFailed.getInt(); }
3940
3941 SourceLocation getRParenLoc() const { return RParenLoc; }
3942
3943 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3944 return SourceRange(getLocation(), getRParenLoc());
3945 }
3946
3947 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3948 static bool classofKind(Kind K) { return K == StaticAssert; }
3949};
3950
3951/// A binding in a decomposition declaration. For instance, given:
3952///
3953/// int n[3];
3954/// auto &[a, b, c] = n;
3955///
3956/// a, b, and c are BindingDecls, whose bindings are the expressions
3957/// x[0], x[1], and x[2] respectively, where x is the implicit
3958/// DecompositionDecl of type 'int (&)[3]'.
3959class BindingDecl : public ValueDecl {
3960 /// The declaration that this binding binds to part of.
3961 ValueDecl *Decomp;
3962 /// The binding represented by this declaration. References to this
3963 /// declaration are effectively equivalent to this expression (except
3964 /// that it is only evaluated once at the point of declaration of the
3965 /// binding).
3966 Expr *Binding = nullptr;
3967
3968 BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
3969 : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
3970
3971 void anchor() override;
3972
3973public:
3974 friend class ASTDeclReader;
3975
3976 static BindingDecl *Create(ASTContext &C, DeclContext *DC,
3977 SourceLocation IdLoc, IdentifierInfo *Id);
3978 static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3979
3980 /// Get the expression to which this declaration is bound. This may be null
3981 /// in two different cases: while parsing the initializer for the
3982 /// decomposition declaration, and when the initializer is type-dependent.
3983 Expr *getBinding() const { return Binding; }
3984
3985 /// Get the decomposition declaration that this binding represents a
3986 /// decomposition of.
3987 ValueDecl *getDecomposedDecl() const { return Decomp; }
3988
3989 /// Get the variable (if any) that holds the value of evaluating the binding.
3990 /// Only present for user-defined bindings for tuple-like types.
3991 VarDecl *getHoldingVar() const;
3992
3993 /// Set the binding for this BindingDecl, along with its declared type (which
3994 /// should be a possibly-cv-qualified form of the type of the binding, or a
3995 /// reference to such a type).
3996 void setBinding(QualType DeclaredType, Expr *Binding) {
3997 setType(DeclaredType);
3998 this->Binding = Binding;
3999 }
4000
4001 /// Set the decomposed variable for this BindingDecl.
4002 void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; }
4003
4004 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4005 static bool classofKind(Kind K) { return K == Decl::Binding; }
4006};
4007
4008/// A decomposition declaration. For instance, given:
4009///
4010/// int n[3];
4011/// auto &[a, b, c] = n;
4012///
4013/// the second line declares a DecompositionDecl of type 'int (&)[3]', and
4014/// three BindingDecls (named a, b, and c). An instance of this class is always
4015/// unnamed, but behaves in almost all other respects like a VarDecl.
4016class DecompositionDecl final
4017 : public VarDecl,
4018 private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
4019 /// The number of BindingDecl*s following this object.
4020 unsigned NumBindings;
4021
4022 DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4023 SourceLocation LSquareLoc, QualType T,
4024 TypeSourceInfo *TInfo, StorageClass SC,
4025 ArrayRef<BindingDecl *> Bindings)
4026 : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
4027 SC),
4028 NumBindings(Bindings.size()) {
4029 std::uninitialized_copy(Bindings.begin(), Bindings.end(),
4030 getTrailingObjects<BindingDecl *>());
4031 for (auto *B : Bindings)
4032 B->setDecomposedDecl(this);
4033 }
4034
4035 void anchor() override;
4036
4037public:
4038 friend class ASTDeclReader;
4039 friend TrailingObjects;
4040
4041 static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
4042 SourceLocation StartLoc,
4043 SourceLocation LSquareLoc,
4044 QualType T, TypeSourceInfo *TInfo,
4045 StorageClass S,
4046 ArrayRef<BindingDecl *> Bindings);
4047 static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
4048 unsigned NumBindings);
4049
4050 ArrayRef<BindingDecl *> bindings() const {
4051 return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
4052 }
4053
4054 void printName(raw_ostream &os) const override;
4055
4056 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4057 static bool classofKind(Kind K) { return K == Decomposition; }
4058};
4059
4060/// An instance of this class represents the declaration of a property
4061/// member. This is a Microsoft extension to C++, first introduced in
4062/// Visual Studio .NET 2003 as a parallel to similar features in C#
4063/// and Managed C++.
4064///
4065/// A property must always be a non-static class member.
4066///
4067/// A property member superficially resembles a non-static data
4068/// member, except preceded by a property attribute:
4069/// __declspec(property(get=GetX, put=PutX)) int x;
4070/// Either (but not both) of the 'get' and 'put' names may be omitted.
4071///
4072/// A reference to a property is always an lvalue. If the lvalue
4073/// undergoes lvalue-to-rvalue conversion, then a getter name is
4074/// required, and that member is called with no arguments.
4075/// If the lvalue is assigned into, then a setter name is required,
4076/// and that member is called with one argument, the value assigned.
4077/// Both operations are potentially overloaded. Compound assignments
4078/// are permitted, as are the increment and decrement operators.
4079///
4080/// The getter and putter methods are permitted to be overloaded,
4081/// although their return and parameter types are subject to certain
4082/// restrictions according to the type of the property.
4083///
4084/// A property declared using an incomplete array type may
4085/// additionally be subscripted, adding extra parameters to the getter
4086/// and putter methods.
4087class MSPropertyDecl : public DeclaratorDecl {
4088 IdentifierInfo *GetterId, *SetterId;
4089
4090 MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
4091 QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
4092 IdentifierInfo *Getter, IdentifierInfo *Setter)
4093 : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
4094 GetterId(Getter), SetterId(Setter) {}
4095
4096 void anchor() override;
4097public:
4098 friend class ASTDeclReader;
4099
4100 static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
4101 SourceLocation L, DeclarationName N, QualType T,
4102 TypeSourceInfo *TInfo, SourceLocation StartL,
4103 IdentifierInfo *Getter, IdentifierInfo *Setter);
4104 static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4105
4106 static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
4107
4108 bool hasGetter() const { return GetterId != nullptr; }
4109 IdentifierInfo* getGetterId() const { return GetterId; }
4110 bool hasSetter() const { return SetterId != nullptr; }
4111 IdentifierInfo* getSetterId() const { return SetterId; }
4112};
4113
4114/// Parts of a decomposed MSGuidDecl. Factored out to avoid unnecessary
4115/// dependencies on DeclCXX.h.
4116struct MSGuidDeclParts {
4117 /// {01234567-...
4118 uint32_t Part1;
4119 /// ...-89ab-...
4120 uint16_t Part2;
4121 /// ...-cdef-...
4122 uint16_t Part3;
4123 /// ...-0123-456789abcdef}
4124 uint8_t Part4And5[8];
4125
4126 uint64_t getPart4And5AsUint64() const {
4127 uint64_t Val;
4128 memcpy(&Val, &Part4And5, sizeof(Part4And5));
4129 return Val;
4130 }
4131};
4132
4133/// A global _GUID constant. These are implicitly created by UuidAttrs.
4134///
4135/// struct _declspec(uuid("01234567-89ab-cdef-0123-456789abcdef")) X{};
4136///
4137/// X is a CXXRecordDecl that contains a UuidAttr that references the (unique)
4138/// MSGuidDecl for the specified UUID.
4139class MSGuidDecl : public ValueDecl,
4140 public Mergeable<MSGuidDecl>,
4141 public llvm::FoldingSetNode {
4142public:
4143 using Parts = MSGuidDeclParts;
4144
4145private:
4146 /// The decomposed form of the UUID.
4147 Parts PartVal;
4148
4149 /// The resolved value of the UUID as an APValue. Computed on demand and
4150 /// cached.
4151 mutable APValue APVal;
4152
4153 void anchor() override;
4154
4155 MSGuidDecl(DeclContext *DC, QualType T, Parts P);
4156
4157 static MSGuidDecl *Create(const ASTContext &C, QualType T, Parts P);
4158 static MSGuidDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4159
4160 // Only ASTContext::getMSGuidDecl and deserialization create these.
4161 friend class ASTContext;
4162 friend class ASTReader;
4163 friend class ASTDeclReader;
4164
4165public:
4166 /// Print this UUID in a human-readable format.
4167 void printName(llvm::raw_ostream &OS) const override;
4168
4169 /// Get the decomposed parts of this declaration.
4170 Parts getParts() const { return PartVal; }
4171
4172 /// Get the value of this MSGuidDecl as an APValue. This may fail and return
4173 /// an absent APValue if the type of the declaration is not of the expected
4174 /// shape.
4175 APValue &getAsAPValue() const;
4176
4177 static void Profile(llvm::FoldingSetNodeID &ID, Parts P) {
4178 ID.AddInteger(P.Part1);
4179 ID.AddInteger(P.Part2);
4180 ID.AddInteger(P.Part3);
4181 ID.AddInteger(P.getPart4And5AsUint64());
4182 }
4183 void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, PartVal); }
4184
4185 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4186 static bool classofKind(Kind K) { return K == Decl::MSGuid; }
4187};
4188
4189/// Insertion operator for diagnostics. This allows sending an AccessSpecifier
4190/// into a diagnostic with <<.
4191const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
4192 AccessSpecifier AS);
4193
4194} // namespace clang
4195
4196#endif // LLVM_CLANG_AST_DECLCXX_H

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/AST/ExternalASTSource.h

1//===- ExternalASTSource.h - Abstract External AST Interface ----*- C++ -*-===//
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 defines the ExternalASTSource interface, which enables
10// construction of AST nodes from some external source.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXTERNALASTSOURCE_H
15#define LLVM_CLANG_AST_EXTERNALASTSOURCE_H
16
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/Basic/LLVM.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/IntrusiveRefCntPtr.h"
23#include "llvm/ADT/Optional.h"
24#include "llvm/ADT/PointerUnion.h"
25#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/iterator.h"
28#include "llvm/Support/PointerLikeTypeTraits.h"
29#include <cassert>
30#include <cstddef>
31#include <cstdint>
32#include <iterator>
33#include <utility>
34
35namespace clang {
36
37class ASTConsumer;
38class ASTContext;
39class ASTSourceDescriptor;
40class CXXBaseSpecifier;
41class CXXCtorInitializer;
42class CXXRecordDecl;
43class DeclarationName;
44class FieldDecl;
45class IdentifierInfo;
46class NamedDecl;
47class ObjCInterfaceDecl;
48class RecordDecl;
49class Selector;
50class Stmt;
51class TagDecl;
52
53/// Abstract interface for external sources of AST nodes.
54///
55/// External AST sources provide AST nodes constructed from some
56/// external source, such as a precompiled header. External AST
57/// sources can resolve types and declarations from abstract IDs into
58/// actual type and declaration nodes, and read parts of declaration
59/// contexts.
60class ExternalASTSource : public RefCountedBase<ExternalASTSource> {
61 friend class ExternalSemaSource;
62
63 /// Generation number for this external AST source. Must be increased
64 /// whenever we might have added new redeclarations for existing decls.
65 uint32_t CurrentGeneration = 0;
66
67 /// LLVM-style RTTI.
68 static char ID;
69
70public:
71 ExternalASTSource() = default;
72 virtual ~ExternalASTSource();
73
74 /// RAII class for safely pairing a StartedDeserializing call
75 /// with FinishedDeserializing.
76 class Deserializing {
77 ExternalASTSource *Source;
78
79 public:
80 explicit Deserializing(ExternalASTSource *source) : Source(source) {
81 assert(Source)(static_cast<void> (0));
82 Source->StartedDeserializing();
83 }
84
85 ~Deserializing() {
86 Source->FinishedDeserializing();
87 }
88 };
89
90 /// Get the current generation of this AST source. This number
91 /// is incremented each time the AST source lazily extends an existing
92 /// entity.
93 uint32_t getGeneration() const { return CurrentGeneration; }
94
95 /// Resolve a declaration ID into a declaration, potentially
96 /// building a new declaration.
97 ///
98 /// This method only needs to be implemented if the AST source ever
99 /// passes back decl sets as VisibleDeclaration objects.
100 ///
101 /// The default implementation of this method is a no-op.
102 virtual Decl *GetExternalDecl(uint32_t ID);
103
104 /// Resolve a selector ID into a selector.
105 ///
106 /// This operation only needs to be implemented if the AST source
107 /// returns non-zero for GetNumKnownSelectors().
108 ///
109 /// The default implementation of this method is a no-op.
110 virtual Selector GetExternalSelector(uint32_t ID);
111
112 /// Returns the number of selectors known to the external AST
113 /// source.
114 ///
115 /// The default implementation of this method is a no-op.
116 virtual uint32_t GetNumExternalSelectors();
117
118 /// Resolve the offset of a statement in the decl stream into
119 /// a statement.
120 ///
121 /// This operation is meant to be used via a LazyOffsetPtr. It only
122 /// needs to be implemented if the AST source uses methods like
123 /// FunctionDecl::setLazyBody when building decls.
124 ///
125 /// The default implementation of this method is a no-op.
126 virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
127
128 /// Resolve the offset of a set of C++ constructor initializers in
129 /// the decl stream into an array of initializers.
130 ///
131 /// The default implementation of this method is a no-op.
132 virtual CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset);
133
134 /// Resolve the offset of a set of C++ base specifiers in the decl
135 /// stream into an array of specifiers.
136 ///
137 /// The default implementation of this method is a no-op.
138 virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
139
140 /// Update an out-of-date identifier.
141 virtual void updateOutOfDateIdentifier(IdentifierInfo &II) {}
142
143 /// Find all declarations with the given name in the given context,
144 /// and add them to the context by calling SetExternalVisibleDeclsForName
145 /// or SetNoExternalVisibleDeclsForName.
146 /// \return \c true if any declarations might have been found, \c false if
147 /// we definitely have no declarations with tbis name.
148 ///
149 /// The default implementation of this method is a no-op returning \c false.
150 virtual bool
151 FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name);
152
153 /// Ensures that the table of all visible declarations inside this
154 /// context is up to date.
155 ///
156 /// The default implementation of this function is a no-op.
157 virtual void completeVisibleDeclsMap(const DeclContext *DC);
158
159 /// Retrieve the module that corresponds to the given module ID.
160 virtual Module *getModule(unsigned ID) { return nullptr; }
161
162 /// Return a descriptor for the corresponding module, if one exists.
163 virtual llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID);
164
165 enum ExtKind { EK_Always, EK_Never, EK_ReplyHazy };
166
167 virtual ExtKind hasExternalDefinitions(const Decl *D);
168
169 /// Finds all declarations lexically contained within the given
170 /// DeclContext, after applying an optional filter predicate.
171 ///
172 /// \param IsKindWeWant a predicate function that returns true if the passed
173 /// declaration kind is one we are looking for.
174 ///
175 /// The default implementation of this method is a no-op.
176 virtual void
177 FindExternalLexicalDecls(const DeclContext *DC,
178 llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
179 SmallVectorImpl<Decl *> &Result);
180
181 /// Finds all declarations lexically contained within the given
182 /// DeclContext.
183 void FindExternalLexicalDecls(const DeclContext *DC,
184 SmallVectorImpl<Decl *> &Result) {
185 FindExternalLexicalDecls(DC, [](Decl::Kind) { return true; }, Result);
186 }
187
188 /// Get the decls that are contained in a file in the Offset/Length
189 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
190 /// a range.
191 virtual void FindFileRegionDecls(FileID File, unsigned Offset,
192 unsigned Length,
193 SmallVectorImpl<Decl *> &Decls);
194
195 /// Gives the external AST source an opportunity to complete
196 /// the redeclaration chain for a declaration. Called each time we
197 /// need the most recent declaration of a declaration after the
198 /// generation count is incremented.
199 virtual void CompleteRedeclChain(const Decl *D);
200
201 /// Gives the external AST source an opportunity to complete
202 /// an incomplete type.
203 virtual void CompleteType(TagDecl *Tag);
204
205 /// Gives the external AST source an opportunity to complete an
206 /// incomplete Objective-C class.
207 ///
208 /// This routine will only be invoked if the "externally completed" bit is
209 /// set on the ObjCInterfaceDecl via the function
210 /// \c ObjCInterfaceDecl::setExternallyCompleted().
211 virtual void CompleteType(ObjCInterfaceDecl *Class);
212
213 /// Loads comment ranges.
214 virtual void ReadComments();
215
216 /// Notify ExternalASTSource that we started deserialization of
217 /// a decl or type so until FinishedDeserializing is called there may be
218 /// decls that are initializing. Must be paired with FinishedDeserializing.
219 ///
220 /// The default implementation of this method is a no-op.
221 virtual void StartedDeserializing();
222
223 /// Notify ExternalASTSource that we finished the deserialization of
224 /// a decl or type. Must be paired with StartedDeserializing.
225 ///
226 /// The default implementation of this method is a no-op.
227 virtual void FinishedDeserializing();
228
229 /// Function that will be invoked when we begin parsing a new
230 /// translation unit involving this external AST source.
231 ///
232 /// The default implementation of this method is a no-op.
233 virtual void StartTranslationUnit(ASTConsumer *Consumer);
234
235 /// Print any statistics that have been gathered regarding
236 /// the external AST source.
237 ///
238 /// The default implementation of this method is a no-op.
239 virtual void PrintStats();
240
241 /// Perform layout on the given record.
242 ///
243 /// This routine allows the external AST source to provide an specific
244 /// layout for a record, overriding the layout that would normally be
245 /// constructed. It is intended for clients who receive specific layout
246 /// details rather than source code (such as LLDB). The client is expected
247 /// to fill in the field offsets, base offsets, virtual base offsets, and
248 /// complete object size.
249 ///
250 /// \param Record The record whose layout is being requested.
251 ///
252 /// \param Size The final size of the record, in bits.
253 ///
254 /// \param Alignment The final alignment of the record, in bits.
255 ///
256 /// \param FieldOffsets The offset of each of the fields within the record,
257 /// expressed in bits. All of the fields must be provided with offsets.
258 ///
259 /// \param BaseOffsets The offset of each of the direct, non-virtual base
260 /// classes. If any bases are not given offsets, the bases will be laid
261 /// out according to the ABI.
262 ///
263 /// \param VirtualBaseOffsets The offset of each of the virtual base classes
264 /// (either direct or not). If any bases are not given offsets, the bases will be laid
265 /// out according to the ABI.
266 ///
267 /// \returns true if the record layout was provided, false otherwise.
268 virtual bool layoutRecordType(
269 const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
270 llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets,
271 llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets,
272 llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets);
273
274 //===--------------------------------------------------------------------===//
275 // Queries for performance analysis.
276 //===--------------------------------------------------------------------===//
277
278 struct MemoryBufferSizes {
279 size_t malloc_bytes;
280 size_t mmap_bytes;
281
282 MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
283 : malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
284 };
285
286 /// Return the amount of memory used by memory buffers, breaking down
287 /// by heap-backed versus mmap'ed memory.
288 MemoryBufferSizes getMemoryBufferSizes() const {
289 MemoryBufferSizes sizes(0, 0);
290 getMemoryBufferSizes(sizes);
291 return sizes;
292 }
293
294 virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
295
296 /// LLVM-style RTTI.
297 /// \{
298 virtual bool isA(const void *ClassID) const { return ClassID == &ID; }
299 static bool classof(const ExternalASTSource *S) { return S->isA(&ID); }
300 /// \}
301
302protected:
303 static DeclContextLookupResult
304 SetExternalVisibleDeclsForName(const DeclContext *DC,
305 DeclarationName Name,
306 ArrayRef<NamedDecl*> Decls);
307
308 static DeclContextLookupResult
309 SetNoExternalVisibleDeclsForName(const DeclContext *DC,
310 DeclarationName Name);
311
312 /// Increment the current generation.
313 uint32_t incrementGeneration(ASTContext &C);
314};
315
316/// A lazy pointer to an AST node (of base type T) that resides
317/// within an external AST source.
318///
319/// The AST node is identified within the external AST source by a
320/// 63-bit offset, and can be retrieved via an operation on the
321/// external AST source itself.
322template<typename T, typename OffsT, T* (ExternalASTSource::*Get)(OffsT Offset)>
323struct LazyOffsetPtr {
324 /// Either a pointer to an AST node or the offset within the
325 /// external AST source where the AST node can be found.
326 ///
327 /// If the low bit is clear, a pointer to the AST node. If the low
328 /// bit is set, the upper 63 bits are the offset.
329 mutable uint64_t Ptr = 0;
330
331public:
332 LazyOffsetPtr() = default;
333 explicit LazyOffsetPtr(T *Ptr) : Ptr(reinterpret_cast<uint64_t>(Ptr)) {}
334
335 explicit LazyOffsetPtr(uint64_t Offset) : Ptr((Offset << 1) | 0x01) {
336 assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits")(static_cast<void> (0));
337 if (Offset == 0)
338 Ptr = 0;
339 }
340
341 LazyOffsetPtr &operator=(T *Ptr) {
342 this->Ptr = reinterpret_cast<uint64_t>(Ptr);
343 return *this;
344 }
345
346 LazyOffsetPtr &operator=(uint64_t Offset) {
347 assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits")(static_cast<void> (0));
348 if (Offset == 0)
349 Ptr = 0;
350 else
351 Ptr = (Offset << 1) | 0x01;
352
353 return *this;
354 }
355
356 /// Whether this pointer is non-NULL.
357 ///
358 /// This operation does not require the AST node to be deserialized.
359 explicit operator bool() const { return Ptr != 0; }
360
361 /// Whether this pointer is non-NULL.
362 ///
363 /// This operation does not require the AST node to be deserialized.
364 bool isValid() const { return Ptr != 0; }
365
366 /// Whether this pointer is currently stored as an offset.
367 bool isOffset() const { return Ptr & 0x01; }
368
369 /// Retrieve the pointer to the AST node that this lazy pointer points to.
370 ///
371 /// \param Source the external AST source.
372 ///
373 /// \returns a pointer to the AST node.
374 T* get(ExternalASTSource *Source) const {
375 if (isOffset()) {
8
Assuming the condition is true
9
Taking true branch
376 assert(Source &&(static_cast<void> (0))
377 "Cannot deserialize a lazy pointer without an AST source")(static_cast<void> (0));
378 Ptr = reinterpret_cast<uint64_t>((Source->*Get)(Ptr >> 1));
10
Called C++ object pointer is null
379 }
380 return reinterpret_cast<T*>(Ptr);
381 }
382};
383
384/// A lazy value (of type T) that is within an AST node of type Owner,
385/// where the value might change in later generations of the external AST
386/// source.
387template<typename Owner, typename T, void (ExternalASTSource::*Update)(Owner)>
388struct LazyGenerationalUpdatePtr {
389 /// A cache of the value of this pointer, in the most recent generation in
390 /// which we queried it.
391 struct LazyData {
392 ExternalASTSource *ExternalSource;
393 uint32_t LastGeneration = 0;
394 T LastValue;
395
396 LazyData(ExternalASTSource *Source, T Value)
397 : ExternalSource(Source), LastValue(Value) {}
398 };
399
400 // Our value is represented as simply T if there is no external AST source.
401 using ValueType = llvm::PointerUnion<T, LazyData*>;
402 ValueType Value;
403
404 LazyGenerationalUpdatePtr(ValueType V) : Value(V) {}
405
406 // Defined in ASTContext.h
407 static ValueType makeValue(const ASTContext &Ctx, T Value);
408
409public:
410 explicit LazyGenerationalUpdatePtr(const ASTContext &Ctx, T Value = T())
411 : Value(makeValue(Ctx, Value)) {}
412
413 /// Create a pointer that is not potentially updated by later generations of
414 /// the external AST source.
415 enum NotUpdatedTag { NotUpdated };
416 LazyGenerationalUpdatePtr(NotUpdatedTag, T Value = T())
417 : Value(Value) {}
418
419 /// Forcibly set this pointer (which must be lazy) as needing updates.
420 void markIncomplete() {
421 Value.template get<LazyData *>()->LastGeneration = 0;
422 }
423
424 /// Set the value of this pointer, in the current generation.
425 void set(T NewValue) {
426 if (auto *LazyVal = Value.template dyn_cast<LazyData *>()) {
427 LazyVal->LastValue = NewValue;
428 return;
429 }
430 Value = NewValue;
431 }
432
433 /// Set the value of this pointer, for this and all future generations.
434 void setNotUpdated(T NewValue) { Value = NewValue; }
435
436 /// Get the value of this pointer, updating its owner if necessary.
437 T get(Owner O) {
438 if (auto *LazyVal = Value.template dyn_cast<LazyData *>()) {
439 if (LazyVal->LastGeneration != LazyVal->ExternalSource->getGeneration()) {
440 LazyVal->LastGeneration = LazyVal->ExternalSource->getGeneration();
441 (LazyVal->ExternalSource->*Update)(O);
442 }
443 return LazyVal->LastValue;
444 }
445 return Value.template get<T>();
446 }
447
448 /// Get the most recently computed value of this pointer without updating it.
449 T getNotUpdated() const {
450 if (auto *LazyVal = Value.template dyn_cast<LazyData *>())
451 return LazyVal->LastValue;
452 return Value.template get<T>();
453 }
454
455 void *getOpaqueValue() { return Value.getOpaqueValue(); }
456 static LazyGenerationalUpdatePtr getFromOpaqueValue(void *Ptr) {
457 return LazyGenerationalUpdatePtr(ValueType::getFromOpaqueValue(Ptr));
458 }
459};
460
461} // namespace clang
462
463namespace llvm {
464
465/// Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be
466/// placed into a PointerUnion.
467template<typename Owner, typename T,
468 void (clang::ExternalASTSource::*Update)(Owner)>
469struct PointerLikeTypeTraits<
470 clang::LazyGenerationalUpdatePtr<Owner, T, Update>> {
471 using Ptr = clang::LazyGenerationalUpdatePtr<Owner, T, Update>;
472
473 static void *getAsVoidPointer(Ptr P) { return P.getOpaqueValue(); }
474 static Ptr getFromVoidPointer(void *P) { return Ptr::getFromOpaqueValue(P); }
475
476 static constexpr int NumLowBitsAvailable =
477 PointerLikeTypeTraits<T>::NumLowBitsAvailable - 1;
478};
479
480} // namespace llvm
481
482namespace clang {
483
484/// Represents a lazily-loaded vector of data.
485///
486/// The lazily-loaded vector of data contains data that is partially loaded
487/// from an external source and partially added by local translation. The
488/// items loaded from the external source are loaded lazily, when needed for
489/// iteration over the complete vector.
490template<typename T, typename Source,
491 void (Source::*Loader)(SmallVectorImpl<T>&),
492 unsigned LoadedStorage = 2, unsigned LocalStorage = 4>
493class LazyVector {
494 SmallVector<T, LoadedStorage> Loaded;
495 SmallVector<T, LocalStorage> Local;
496
497public:
498 /// Iteration over the elements in the vector.
499 ///
500 /// In a complete iteration, the iterator walks the range [-M, N),
501 /// where negative values are used to indicate elements
502 /// loaded from the external source while non-negative values are used to
503 /// indicate elements added via \c push_back().
504 /// However, to provide iteration in source order (for, e.g., chained
505 /// precompiled headers), dereferencing the iterator flips the negative
506 /// values (corresponding to loaded entities), so that position -M
507 /// corresponds to element 0 in the loaded entities vector, position -M+1
508 /// corresponds to element 1 in the loaded entities vector, etc. This
509 /// gives us a reasonably efficient, source-order walk.
510 ///
511 /// We define this as a wrapping iterator around an int. The
512 /// iterator_adaptor_base class forwards the iterator methods to basic integer
513 /// arithmetic.
514 class iterator
515 : public llvm::iterator_adaptor_base<
516 iterator, int, std::random_access_iterator_tag, T, int, T *, T &> {
517 friend class LazyVector;
518
519 LazyVector *Self;
520
521 iterator(LazyVector *Self, int Position)
522 : iterator::iterator_adaptor_base(Position), Self(Self) {}
523
524 bool isLoaded() const { return this->I < 0; }
525
526 public:
527 iterator() : iterator(nullptr, 0) {}
528
529 typename iterator::reference operator*() const {
530 if (isLoaded())
531 return Self->Loaded.end()[this->I];
532 return Self->Local.begin()[this->I];
533 }
534 };
535
536 iterator begin(Source *source, bool LocalOnly = false) {
537 if (LocalOnly)
538 return iterator(this, 0);
539
540 if (source)
541 (source->*Loader)(Loaded);
542 return iterator(this, -(int)Loaded.size());
543 }
544
545 iterator end() {
546 return iterator(this, Local.size());
547 }
548
549 void push_back(const T& LocalValue) {
550 Local.push_back(LocalValue);
551 }
552
553 void erase(iterator From, iterator To) {
554 if (From.isLoaded() && To.isLoaded()) {
555 Loaded.erase(&*From, &*To);
556 return;
557 }
558
559 if (From.isLoaded()) {
560 Loaded.erase(&*From, Loaded.end());
561 From = begin(nullptr, true);
562 }
563
564 Local.erase(&*From, &*To);
565 }
566};
567
568/// A lazy pointer to a statement.
569using LazyDeclStmtPtr =
570 LazyOffsetPtr<Stmt, uint64_t, &ExternalASTSource::GetExternalDeclStmt>;
571
572/// A lazy pointer to a declaration.
573using LazyDeclPtr =
574 LazyOffsetPtr<Decl, uint32_t, &ExternalASTSource::GetExternalDecl>;
575
576/// A lazy pointer to a set of CXXCtorInitializers.
577using LazyCXXCtorInitializersPtr =
578 LazyOffsetPtr<CXXCtorInitializer *, uint64_t,
579 &ExternalASTSource::GetExternalCXXCtorInitializers>;
580
581/// A lazy pointer to a set of CXXBaseSpecifiers.
582using LazyCXXBaseSpecifiersPtr =
583 LazyOffsetPtr<CXXBaseSpecifier, uint64_t,
584 &ExternalASTSource::GetExternalCXXBaseSpecifiers>;
585
586} // namespace clang
587
588#endif // LLVM_CLANG_AST_EXTERNALASTSOURCE_H