1 //===--- DeclCXX.cpp - C++ Declaration AST Node Implementation ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the C++ related Decl classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Basic/IdentifierTable.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 using namespace clang;
26
27 //===----------------------------------------------------------------------===//
28 // Decl Allocation/Deallocation Method Implementations
29 //===----------------------------------------------------------------------===//
30
anchor()31 void AccessSpecDecl::anchor() { }
32
CreateDeserialized(ASTContext & C,unsigned ID)33 AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
34 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(AccessSpecDecl));
35 return new (Mem) AccessSpecDecl(EmptyShell());
36 }
37
DefinitionData(CXXRecordDecl * D)38 CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
39 : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
40 Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
41 Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true),
42 HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false),
43 HasMutableFields(false), HasOnlyCMembers(true),
44 HasInClassInitializer(false), HasUninitializedReferenceMember(false),
45 NeedOverloadResolutionForMoveConstructor(false),
46 NeedOverloadResolutionForMoveAssignment(false),
47 NeedOverloadResolutionForDestructor(false),
48 DefaultedMoveConstructorIsDeleted(false),
49 DefaultedMoveAssignmentIsDeleted(false),
50 DefaultedDestructorIsDeleted(false),
51 HasTrivialSpecialMembers(SMF_All),
52 DeclaredNonTrivialSpecialMembers(0),
53 HasIrrelevantDestructor(true),
54 HasConstexprNonCopyMoveConstructor(false),
55 DefaultedDefaultConstructorIsConstexpr(true),
56 HasConstexprDefaultConstructor(false),
57 HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(false),
58 UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
59 ImplicitCopyConstructorHasConstParam(true),
60 ImplicitCopyAssignmentHasConstParam(true),
61 HasDeclaredCopyConstructorWithConstParam(false),
62 HasDeclaredCopyAssignmentWithConstParam(false),
63 FailedImplicitMoveConstructor(false), FailedImplicitMoveAssignment(false),
64 IsLambda(false), NumBases(0), NumVBases(0), Bases(), VBases(),
65 Definition(D), FirstFriend(0) {
66 }
67
getBasesSlowCase() const68 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
69 return Bases.get(Definition->getASTContext().getExternalSource());
70 }
71
getVBasesSlowCase() const72 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
73 return VBases.get(Definition->getASTContext().getExternalSource());
74 }
75
CXXRecordDecl(Kind K,TagKind TK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,CXXRecordDecl * PrevDecl)76 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
77 SourceLocation StartLoc, SourceLocation IdLoc,
78 IdentifierInfo *Id, CXXRecordDecl *PrevDecl)
79 : RecordDecl(K, TK, DC, StartLoc, IdLoc, Id, PrevDecl),
80 DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
81 TemplateOrInstantiation() { }
82
Create(const ASTContext & C,TagKind TK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,CXXRecordDecl * PrevDecl,bool DelayTypeCreation)83 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
84 DeclContext *DC, SourceLocation StartLoc,
85 SourceLocation IdLoc, IdentifierInfo *Id,
86 CXXRecordDecl* PrevDecl,
87 bool DelayTypeCreation) {
88 CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, StartLoc, IdLoc,
89 Id, PrevDecl);
90 R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
91
92 // FIXME: DelayTypeCreation seems like such a hack
93 if (!DelayTypeCreation)
94 C.getTypeDeclType(R, PrevDecl);
95 return R;
96 }
97
CreateLambda(const ASTContext & C,DeclContext * DC,TypeSourceInfo * Info,SourceLocation Loc,bool Dependent)98 CXXRecordDecl *CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
99 TypeSourceInfo *Info, SourceLocation Loc,
100 bool Dependent) {
101 CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TTK_Class, DC, Loc, Loc,
102 0, 0);
103 R->IsBeingDefined = true;
104 R->DefinitionData = new (C) struct LambdaDefinitionData(R, Info, Dependent);
105 R->MayHaveOutOfDateDef = false;
106 C.getTypeDeclType(R, /*PrevDecl=*/0);
107 return R;
108 }
109
110 CXXRecordDecl *
CreateDeserialized(const ASTContext & C,unsigned ID)111 CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
112 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXRecordDecl));
113 CXXRecordDecl *R = new (Mem) CXXRecordDecl(CXXRecord, TTK_Struct, 0,
114 SourceLocation(), SourceLocation(),
115 0, 0);
116 R->MayHaveOutOfDateDef = false;
117 return R;
118 }
119
120 void
setBases(CXXBaseSpecifier const * const * Bases,unsigned NumBases)121 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
122 unsigned NumBases) {
123 ASTContext &C = getASTContext();
124
125 if (!data().Bases.isOffset() && data().NumBases > 0)
126 C.Deallocate(data().getBases());
127
128 if (NumBases) {
129 // C++ [dcl.init.aggr]p1:
130 // An aggregate is [...] a class with [...] no base classes [...].
131 data().Aggregate = false;
132
133 // C++ [class]p4:
134 // A POD-struct is an aggregate class...
135 data().PlainOldData = false;
136 }
137
138 // The set of seen virtual base types.
139 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
140
141 // The virtual bases of this class.
142 SmallVector<const CXXBaseSpecifier *, 8> VBases;
143
144 data().Bases = new(C) CXXBaseSpecifier [NumBases];
145 data().NumBases = NumBases;
146 for (unsigned i = 0; i < NumBases; ++i) {
147 data().getBases()[i] = *Bases[i];
148 // Keep track of inherited vbases for this base class.
149 const CXXBaseSpecifier *Base = Bases[i];
150 QualType BaseType = Base->getType();
151 // Skip dependent types; we can't do any checking on them now.
152 if (BaseType->isDependentType())
153 continue;
154 CXXRecordDecl *BaseClassDecl
155 = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
156
157 // A class with a non-empty base class is not empty.
158 // FIXME: Standard ref?
159 if (!BaseClassDecl->isEmpty()) {
160 if (!data().Empty) {
161 // C++0x [class]p7:
162 // A standard-layout class is a class that:
163 // [...]
164 // -- either has no non-static data members in the most derived
165 // class and at most one base class with non-static data members,
166 // or has no base classes with non-static data members, and
167 // If this is the second non-empty base, then neither of these two
168 // clauses can be true.
169 data().IsStandardLayout = false;
170 }
171
172 data().Empty = false;
173 data().HasNoNonEmptyBases = false;
174 }
175
176 // C++ [class.virtual]p1:
177 // A class that declares or inherits a virtual function is called a
178 // polymorphic class.
179 if (BaseClassDecl->isPolymorphic())
180 data().Polymorphic = true;
181
182 // C++0x [class]p7:
183 // A standard-layout class is a class that: [...]
184 // -- has no non-standard-layout base classes
185 if (!BaseClassDecl->isStandardLayout())
186 data().IsStandardLayout = false;
187
188 // Record if this base is the first non-literal field or base.
189 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType())
190 data().HasNonLiteralTypeFieldsOrBases = true;
191
192 // Now go through all virtual bases of this base and add them.
193 for (CXXRecordDecl::base_class_iterator VBase =
194 BaseClassDecl->vbases_begin(),
195 E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
196 // Add this base if it's not already in the list.
197 if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType()))) {
198 VBases.push_back(VBase);
199
200 // C++11 [class.copy]p8:
201 // The implicitly-declared copy constructor for a class X will have
202 // the form 'X::X(const X&)' if each [...] virtual base class B of X
203 // has a copy constructor whose first parameter is of type
204 // 'const B&' or 'const volatile B&' [...]
205 if (CXXRecordDecl *VBaseDecl = VBase->getType()->getAsCXXRecordDecl())
206 if (!VBaseDecl->hasCopyConstructorWithConstParam())
207 data().ImplicitCopyConstructorHasConstParam = false;
208 }
209 }
210
211 if (Base->isVirtual()) {
212 // Add this base if it's not already in the list.
213 if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
214 VBases.push_back(Base);
215
216 // C++0x [meta.unary.prop] is_empty:
217 // T is a class type, but not a union type, with ... no virtual base
218 // classes
219 data().Empty = false;
220
221 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
222 // A [default constructor, copy/move constructor, or copy/move assignment
223 // operator for a class X] is trivial [...] if:
224 // -- class X has [...] no virtual base classes
225 data().HasTrivialSpecialMembers &= SMF_Destructor;
226
227 // C++0x [class]p7:
228 // A standard-layout class is a class that: [...]
229 // -- has [...] no virtual base classes
230 data().IsStandardLayout = false;
231
232 // C++11 [dcl.constexpr]p4:
233 // In the definition of a constexpr constructor [...]
234 // -- the class shall not have any virtual base classes
235 data().DefaultedDefaultConstructorIsConstexpr = false;
236 } else {
237 // C++ [class.ctor]p5:
238 // A default constructor is trivial [...] if:
239 // -- all the direct base classes of its class have trivial default
240 // constructors.
241 if (!BaseClassDecl->hasTrivialDefaultConstructor())
242 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
243
244 // C++0x [class.copy]p13:
245 // A copy/move constructor for class X is trivial if [...]
246 // [...]
247 // -- the constructor selected to copy/move each direct base class
248 // subobject is trivial, and
249 if (!BaseClassDecl->hasTrivialCopyConstructor())
250 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
251 // If the base class doesn't have a simple move constructor, we'll eagerly
252 // declare it and perform overload resolution to determine which function
253 // it actually calls. If it does have a simple move constructor, this
254 // check is correct.
255 if (!BaseClassDecl->hasTrivialMoveConstructor())
256 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
257
258 // C++0x [class.copy]p27:
259 // A copy/move assignment operator for class X is trivial if [...]
260 // [...]
261 // -- the assignment operator selected to copy/move each direct base
262 // class subobject is trivial, and
263 if (!BaseClassDecl->hasTrivialCopyAssignment())
264 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
265 // If the base class doesn't have a simple move assignment, we'll eagerly
266 // declare it and perform overload resolution to determine which function
267 // it actually calls. If it does have a simple move assignment, this
268 // check is correct.
269 if (!BaseClassDecl->hasTrivialMoveAssignment())
270 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
271
272 // C++11 [class.ctor]p6:
273 // If that user-written default constructor would satisfy the
274 // requirements of a constexpr constructor, the implicitly-defined
275 // default constructor is constexpr.
276 if (!BaseClassDecl->hasConstexprDefaultConstructor())
277 data().DefaultedDefaultConstructorIsConstexpr = false;
278 }
279
280 // C++ [class.ctor]p3:
281 // A destructor is trivial if all the direct base classes of its class
282 // have trivial destructors.
283 if (!BaseClassDecl->hasTrivialDestructor())
284 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
285
286 if (!BaseClassDecl->hasIrrelevantDestructor())
287 data().HasIrrelevantDestructor = false;
288
289 // C++11 [class.copy]p18:
290 // The implicitly-declared copy assignment oeprator for a class X will
291 // have the form 'X& X::operator=(const X&)' if each direct base class B
292 // of X has a copy assignment operator whose parameter is of type 'const
293 // B&', 'const volatile B&', or 'B' [...]
294 if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
295 data().ImplicitCopyAssignmentHasConstParam = false;
296
297 // C++11 [class.copy]p8:
298 // The implicitly-declared copy constructor for a class X will have
299 // the form 'X::X(const X&)' if each direct [...] base class B of X
300 // has a copy constructor whose first parameter is of type
301 // 'const B&' or 'const volatile B&' [...]
302 if (!BaseClassDecl->hasCopyConstructorWithConstParam())
303 data().ImplicitCopyConstructorHasConstParam = false;
304
305 // A class has an Objective-C object member if... or any of its bases
306 // has an Objective-C object member.
307 if (BaseClassDecl->hasObjectMember())
308 setHasObjectMember(true);
309
310 if (BaseClassDecl->hasVolatileMember())
311 setHasVolatileMember(true);
312
313 // Keep track of the presence of mutable fields.
314 if (BaseClassDecl->hasMutableFields())
315 data().HasMutableFields = true;
316
317 if (BaseClassDecl->hasUninitializedReferenceMember())
318 data().HasUninitializedReferenceMember = true;
319
320 addedClassSubobject(BaseClassDecl);
321 }
322
323 if (VBases.empty())
324 return;
325
326 // Create base specifier for any direct or indirect virtual bases.
327 data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
328 data().NumVBases = VBases.size();
329 for (int I = 0, E = VBases.size(); I != E; ++I) {
330 QualType Type = VBases[I]->getType();
331 if (!Type->isDependentType())
332 addedClassSubobject(Type->getAsCXXRecordDecl());
333 data().getVBases()[I] = *VBases[I];
334 }
335 }
336
addedClassSubobject(CXXRecordDecl * Subobj)337 void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
338 // C++11 [class.copy]p11:
339 // A defaulted copy/move constructor for a class X is defined as
340 // deleted if X has:
341 // -- a direct or virtual base class B that cannot be copied/moved [...]
342 // -- a non-static data member of class type M (or array thereof)
343 // that cannot be copied or moved [...]
344 if (!Subobj->hasSimpleMoveConstructor())
345 data().NeedOverloadResolutionForMoveConstructor = true;
346
347 // C++11 [class.copy]p23:
348 // A defaulted copy/move assignment operator for a class X is defined as
349 // deleted if X has:
350 // -- a direct or virtual base class B that cannot be copied/moved [...]
351 // -- a non-static data member of class type M (or array thereof)
352 // that cannot be copied or moved [...]
353 if (!Subobj->hasSimpleMoveAssignment())
354 data().NeedOverloadResolutionForMoveAssignment = true;
355
356 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
357 // A defaulted [ctor or dtor] for a class X is defined as
358 // deleted if X has:
359 // -- any direct or virtual base class [...] has a type with a destructor
360 // that is deleted or inaccessible from the defaulted [ctor or dtor].
361 // -- any non-static data member has a type with a destructor
362 // that is deleted or inaccessible from the defaulted [ctor or dtor].
363 if (!Subobj->hasSimpleDestructor()) {
364 data().NeedOverloadResolutionForMoveConstructor = true;
365 data().NeedOverloadResolutionForDestructor = true;
366 }
367 }
368
369 /// Callback function for CXXRecordDecl::forallBases that acknowledges
370 /// that it saw a base class.
SawBase(const CXXRecordDecl *,void *)371 static bool SawBase(const CXXRecordDecl *, void *) {
372 return true;
373 }
374
hasAnyDependentBases() const375 bool CXXRecordDecl::hasAnyDependentBases() const {
376 if (!isDependentContext())
377 return false;
378
379 return !forallBases(SawBase, 0);
380 }
381
isTriviallyCopyable() const382 bool CXXRecordDecl::isTriviallyCopyable() const {
383 // C++0x [class]p5:
384 // A trivially copyable class is a class that:
385 // -- has no non-trivial copy constructors,
386 if (hasNonTrivialCopyConstructor()) return false;
387 // -- has no non-trivial move constructors,
388 if (hasNonTrivialMoveConstructor()) return false;
389 // -- has no non-trivial copy assignment operators,
390 if (hasNonTrivialCopyAssignment()) return false;
391 // -- has no non-trivial move assignment operators, and
392 if (hasNonTrivialMoveAssignment()) return false;
393 // -- has a trivial destructor.
394 if (!hasTrivialDestructor()) return false;
395
396 return true;
397 }
398
markedVirtualFunctionPure()399 void CXXRecordDecl::markedVirtualFunctionPure() {
400 // C++ [class.abstract]p2:
401 // A class is abstract if it has at least one pure virtual function.
402 data().Abstract = true;
403 }
404
addedMember(Decl * D)405 void CXXRecordDecl::addedMember(Decl *D) {
406 if (!D->isImplicit() &&
407 !isa<FieldDecl>(D) &&
408 !isa<IndirectFieldDecl>(D) &&
409 (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class ||
410 cast<TagDecl>(D)->getTagKind() == TTK_Interface))
411 data().HasOnlyCMembers = false;
412
413 // Ignore friends and invalid declarations.
414 if (D->getFriendObjectKind() || D->isInvalidDecl())
415 return;
416
417 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
418 if (FunTmpl)
419 D = FunTmpl->getTemplatedDecl();
420
421 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
422 if (Method->isVirtual()) {
423 // C++ [dcl.init.aggr]p1:
424 // An aggregate is an array or a class with [...] no virtual functions.
425 data().Aggregate = false;
426
427 // C++ [class]p4:
428 // A POD-struct is an aggregate class...
429 data().PlainOldData = false;
430
431 // Virtual functions make the class non-empty.
432 // FIXME: Standard ref?
433 data().Empty = false;
434
435 // C++ [class.virtual]p1:
436 // A class that declares or inherits a virtual function is called a
437 // polymorphic class.
438 data().Polymorphic = true;
439
440 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
441 // A [default constructor, copy/move constructor, or copy/move
442 // assignment operator for a class X] is trivial [...] if:
443 // -- class X has no virtual functions [...]
444 data().HasTrivialSpecialMembers &= SMF_Destructor;
445
446 // C++0x [class]p7:
447 // A standard-layout class is a class that: [...]
448 // -- has no virtual functions
449 data().IsStandardLayout = false;
450 }
451 }
452
453 // Notify the listener if an implicit member was added after the definition
454 // was completed.
455 if (!isBeingDefined() && D->isImplicit())
456 if (ASTMutationListener *L = getASTMutationListener())
457 L->AddedCXXImplicitMember(data().Definition, D);
458
459 // The kind of special member this declaration is, if any.
460 unsigned SMKind = 0;
461
462 // Handle constructors.
463 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
464 if (!Constructor->isImplicit()) {
465 // Note that we have a user-declared constructor.
466 data().UserDeclaredConstructor = true;
467
468 // C++ [class]p4:
469 // A POD-struct is an aggregate class [...]
470 // Since the POD bit is meant to be C++03 POD-ness, clear it even if the
471 // type is technically an aggregate in C++0x since it wouldn't be in 03.
472 data().PlainOldData = false;
473 }
474
475 // Technically, "user-provided" is only defined for special member
476 // functions, but the intent of the standard is clearly that it should apply
477 // to all functions.
478 bool UserProvided = Constructor->isUserProvided();
479
480 if (Constructor->isDefaultConstructor()) {
481 SMKind |= SMF_DefaultConstructor;
482
483 if (UserProvided)
484 data().UserProvidedDefaultConstructor = true;
485 if (Constructor->isConstexpr())
486 data().HasConstexprDefaultConstructor = true;
487 }
488
489 if (!FunTmpl) {
490 unsigned Quals;
491 if (Constructor->isCopyConstructor(Quals)) {
492 SMKind |= SMF_CopyConstructor;
493
494 if (Quals & Qualifiers::Const)
495 data().HasDeclaredCopyConstructorWithConstParam = true;
496 } else if (Constructor->isMoveConstructor())
497 SMKind |= SMF_MoveConstructor;
498 }
499
500 // Record if we see any constexpr constructors which are neither copy
501 // nor move constructors.
502 if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
503 data().HasConstexprNonCopyMoveConstructor = true;
504
505 // C++ [dcl.init.aggr]p1:
506 // An aggregate is an array or a class with no user-declared
507 // constructors [...].
508 // C++0x [dcl.init.aggr]p1:
509 // An aggregate is an array or a class with no user-provided
510 // constructors [...].
511 if (getASTContext().getLangOpts().CPlusPlus11
512 ? UserProvided : !Constructor->isImplicit())
513 data().Aggregate = false;
514 }
515
516 // Handle destructors.
517 if (CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) {
518 SMKind |= SMF_Destructor;
519
520 if (!DD->isImplicit())
521 data().HasIrrelevantDestructor = false;
522
523 // C++11 [class.dtor]p5:
524 // A destructor is trivial if [...] the destructor is not virtual.
525 if (DD->isVirtual())
526 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
527 }
528
529 // Handle member functions.
530 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
531 if (Method->isCopyAssignmentOperator()) {
532 SMKind |= SMF_CopyAssignment;
533
534 const ReferenceType *ParamTy =
535 Method->getParamDecl(0)->getType()->getAs<ReferenceType>();
536 if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
537 data().HasDeclaredCopyAssignmentWithConstParam = true;
538 }
539
540 if (Method->isMoveAssignmentOperator())
541 SMKind |= SMF_MoveAssignment;
542
543 // Keep the list of conversion functions up-to-date.
544 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
545 // FIXME: We intentionally don't use the decl's access here because it
546 // hasn't been set yet. That's really just a misdesign in Sema.
547 if (Conversion->getPrimaryTemplate()) {
548 // We don't record specializations.
549 } else if (FunTmpl) {
550 if (FunTmpl->getPreviousDecl())
551 data().Conversions.replace(FunTmpl->getPreviousDecl(),
552 FunTmpl);
553 else
554 data().Conversions.addDecl(getASTContext(), FunTmpl);
555 } else {
556 if (Conversion->getPreviousDecl())
557 data().Conversions.replace(Conversion->getPreviousDecl(),
558 Conversion);
559 else
560 data().Conversions.addDecl(getASTContext(), Conversion);
561 }
562 }
563
564 if (SMKind) {
565 // If this is the first declaration of a special member, we no longer have
566 // an implicit trivial special member.
567 data().HasTrivialSpecialMembers &=
568 data().DeclaredSpecialMembers | ~SMKind;
569
570 if (!Method->isImplicit() && !Method->isUserProvided()) {
571 // This method is user-declared but not user-provided. We can't work out
572 // whether it's trivial yet (not until we get to the end of the class).
573 // We'll handle this method in finishedDefaultedOrDeletedMember.
574 } else if (Method->isTrivial())
575 data().HasTrivialSpecialMembers |= SMKind;
576 else
577 data().DeclaredNonTrivialSpecialMembers |= SMKind;
578
579 // Note when we have declared a declared special member, and suppress the
580 // implicit declaration of this special member.
581 data().DeclaredSpecialMembers |= SMKind;
582
583 if (!Method->isImplicit()) {
584 data().UserDeclaredSpecialMembers |= SMKind;
585
586 // C++03 [class]p4:
587 // A POD-struct is an aggregate class that has [...] no user-defined
588 // copy assignment operator and no user-defined destructor.
589 //
590 // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
591 // aggregates could not have any constructors, clear it even for an
592 // explicitly defaulted or deleted constructor.
593 // type is technically an aggregate in C++0x since it wouldn't be in 03.
594 //
595 // Also, a user-declared move assignment operator makes a class non-POD.
596 // This is an extension in C++03.
597 data().PlainOldData = false;
598 }
599 }
600
601 return;
602 }
603
604 // Handle non-static data members.
605 if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
606 // C++ [class.bit]p2:
607 // A declaration for a bit-field that omits the identifier declares an
608 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
609 // initialized.
610 if (Field->isUnnamedBitfield())
611 return;
612
613 // C++ [dcl.init.aggr]p1:
614 // An aggregate is an array or a class (clause 9) with [...] no
615 // private or protected non-static data members (clause 11).
616 //
617 // A POD must be an aggregate.
618 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
619 data().Aggregate = false;
620 data().PlainOldData = false;
621 }
622
623 // C++0x [class]p7:
624 // A standard-layout class is a class that:
625 // [...]
626 // -- has the same access control for all non-static data members,
627 switch (D->getAccess()) {
628 case AS_private: data().HasPrivateFields = true; break;
629 case AS_protected: data().HasProtectedFields = true; break;
630 case AS_public: data().HasPublicFields = true; break;
631 case AS_none: llvm_unreachable("Invalid access specifier");
632 };
633 if ((data().HasPrivateFields + data().HasProtectedFields +
634 data().HasPublicFields) > 1)
635 data().IsStandardLayout = false;
636
637 // Keep track of the presence of mutable fields.
638 if (Field->isMutable())
639 data().HasMutableFields = true;
640
641 // C++0x [class]p9:
642 // A POD struct is a class that is both a trivial class and a
643 // standard-layout class, and has no non-static data members of type
644 // non-POD struct, non-POD union (or array of such types).
645 //
646 // Automatic Reference Counting: the presence of a member of Objective-C pointer type
647 // that does not explicitly have no lifetime makes the class a non-POD.
648 // However, we delay setting PlainOldData to false in this case so that
649 // Sema has a chance to diagnostic causes where the same class will be
650 // non-POD with Automatic Reference Counting but a POD without ARC.
651 // In this case, the class will become a non-POD class when we complete
652 // the definition.
653 ASTContext &Context = getASTContext();
654 QualType T = Context.getBaseElementType(Field->getType());
655 if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
656 if (!Context.getLangOpts().ObjCAutoRefCount ||
657 T.getObjCLifetime() != Qualifiers::OCL_ExplicitNone)
658 setHasObjectMember(true);
659 } else if (!T.isPODType(Context))
660 data().PlainOldData = false;
661
662 if (T->isReferenceType()) {
663 if (!Field->hasInClassInitializer())
664 data().HasUninitializedReferenceMember = true;
665
666 // C++0x [class]p7:
667 // A standard-layout class is a class that:
668 // -- has no non-static data members of type [...] reference,
669 data().IsStandardLayout = false;
670 }
671
672 // Record if this field is the first non-literal or volatile field or base.
673 if (!T->isLiteralType() || T.isVolatileQualified())
674 data().HasNonLiteralTypeFieldsOrBases = true;
675
676 if (Field->hasInClassInitializer()) {
677 data().HasInClassInitializer = true;
678
679 // C++11 [class]p5:
680 // A default constructor is trivial if [...] no non-static data member
681 // of its class has a brace-or-equal-initializer.
682 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
683
684 // C++11 [dcl.init.aggr]p1:
685 // An aggregate is a [...] class with [...] no
686 // brace-or-equal-initializers for non-static data members.
687 data().Aggregate = false;
688
689 // C++11 [class]p10:
690 // A POD struct is [...] a trivial class.
691 data().PlainOldData = false;
692 }
693
694 // C++11 [class.copy]p23:
695 // A defaulted copy/move assignment operator for a class X is defined
696 // as deleted if X has:
697 // -- a non-static data member of reference type
698 if (T->isReferenceType())
699 data().DefaultedMoveAssignmentIsDeleted = true;
700
701 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
702 CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
703 if (FieldRec->getDefinition()) {
704 addedClassSubobject(FieldRec);
705
706 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
707 // A defaulted [special member] for a class X is defined as
708 // deleted if:
709 // -- X is a union-like class that has a variant member with a
710 // non-trivial [corresponding special member]
711 if (isUnion()) {
712 if (FieldRec->hasNonTrivialMoveConstructor())
713 data().DefaultedMoveConstructorIsDeleted = true;
714 if (FieldRec->hasNonTrivialMoveAssignment())
715 data().DefaultedMoveAssignmentIsDeleted = true;
716 if (FieldRec->hasNonTrivialDestructor())
717 data().DefaultedDestructorIsDeleted = true;
718 }
719
720 // C++0x [class.ctor]p5:
721 // A default constructor is trivial [...] if:
722 // -- for all the non-static data members of its class that are of
723 // class type (or array thereof), each such class has a trivial
724 // default constructor.
725 if (!FieldRec->hasTrivialDefaultConstructor())
726 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
727
728 // C++0x [class.copy]p13:
729 // A copy/move constructor for class X is trivial if [...]
730 // [...]
731 // -- for each non-static data member of X that is of class type (or
732 // an array thereof), the constructor selected to copy/move that
733 // member is trivial;
734 if (!FieldRec->hasTrivialCopyConstructor())
735 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
736 // If the field doesn't have a simple move constructor, we'll eagerly
737 // declare the move constructor for this class and we'll decide whether
738 // it's trivial then.
739 if (!FieldRec->hasTrivialMoveConstructor())
740 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
741
742 // C++0x [class.copy]p27:
743 // A copy/move assignment operator for class X is trivial if [...]
744 // [...]
745 // -- for each non-static data member of X that is of class type (or
746 // an array thereof), the assignment operator selected to
747 // copy/move that member is trivial;
748 if (!FieldRec->hasTrivialCopyAssignment())
749 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
750 // If the field doesn't have a simple move assignment, we'll eagerly
751 // declare the move assignment for this class and we'll decide whether
752 // it's trivial then.
753 if (!FieldRec->hasTrivialMoveAssignment())
754 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
755
756 if (!FieldRec->hasTrivialDestructor())
757 data().HasTrivialSpecialMembers &= ~SMF_Destructor;
758 if (!FieldRec->hasIrrelevantDestructor())
759 data().HasIrrelevantDestructor = false;
760 if (FieldRec->hasObjectMember())
761 setHasObjectMember(true);
762 if (FieldRec->hasVolatileMember())
763 setHasVolatileMember(true);
764
765 // C++0x [class]p7:
766 // A standard-layout class is a class that:
767 // -- has no non-static data members of type non-standard-layout
768 // class (or array of such types) [...]
769 if (!FieldRec->isStandardLayout())
770 data().IsStandardLayout = false;
771
772 // C++0x [class]p7:
773 // A standard-layout class is a class that:
774 // [...]
775 // -- has no base classes of the same type as the first non-static
776 // data member.
777 // We don't want to expend bits in the state of the record decl
778 // tracking whether this is the first non-static data member so we
779 // cheat a bit and use some of the existing state: the empty bit.
780 // Virtual bases and virtual methods make a class non-empty, but they
781 // also make it non-standard-layout so we needn't check here.
782 // A non-empty base class may leave the class standard-layout, but not
783 // if we have arrived here, and have at least on non-static data
784 // member. If IsStandardLayout remains true, then the first non-static
785 // data member must come through here with Empty still true, and Empty
786 // will subsequently be set to false below.
787 if (data().IsStandardLayout && data().Empty) {
788 for (CXXRecordDecl::base_class_const_iterator BI = bases_begin(),
789 BE = bases_end();
790 BI != BE; ++BI) {
791 if (Context.hasSameUnqualifiedType(BI->getType(), T)) {
792 data().IsStandardLayout = false;
793 break;
794 }
795 }
796 }
797
798 // Keep track of the presence of mutable fields.
799 if (FieldRec->hasMutableFields())
800 data().HasMutableFields = true;
801
802 // C++11 [class.copy]p13:
803 // If the implicitly-defined constructor would satisfy the
804 // requirements of a constexpr constructor, the implicitly-defined
805 // constructor is constexpr.
806 // C++11 [dcl.constexpr]p4:
807 // -- every constructor involved in initializing non-static data
808 // members [...] shall be a constexpr constructor
809 if (!Field->hasInClassInitializer() &&
810 !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
811 // The standard requires any in-class initializer to be a constant
812 // expression. We consider this to be a defect.
813 data().DefaultedDefaultConstructorIsConstexpr = false;
814
815 // C++11 [class.copy]p8:
816 // The implicitly-declared copy constructor for a class X will have
817 // the form 'X::X(const X&)' if [...] for all the non-static data
818 // members of X that are of a class type M (or array thereof), each
819 // such class type has a copy constructor whose first parameter is
820 // of type 'const M&' or 'const volatile M&'.
821 if (!FieldRec->hasCopyConstructorWithConstParam())
822 data().ImplicitCopyConstructorHasConstParam = false;
823
824 // C++11 [class.copy]p18:
825 // The implicitly-declared copy assignment oeprator for a class X will
826 // have the form 'X& X::operator=(const X&)' if [...] for all the
827 // non-static data members of X that are of a class type M (or array
828 // thereof), each such class type has a copy assignment operator whose
829 // parameter is of type 'const M&', 'const volatile M&' or 'M'.
830 if (!FieldRec->hasCopyAssignmentWithConstParam())
831 data().ImplicitCopyAssignmentHasConstParam = false;
832
833 if (FieldRec->hasUninitializedReferenceMember() &&
834 !Field->hasInClassInitializer())
835 data().HasUninitializedReferenceMember = true;
836 }
837 } else {
838 // Base element type of field is a non-class type.
839 if (!T->isLiteralType() ||
840 (!Field->hasInClassInitializer() && !isUnion()))
841 data().DefaultedDefaultConstructorIsConstexpr = false;
842
843 // C++11 [class.copy]p23:
844 // A defaulted copy/move assignment operator for a class X is defined
845 // as deleted if X has:
846 // -- a non-static data member of const non-class type (or array
847 // thereof)
848 if (T.isConstQualified())
849 data().DefaultedMoveAssignmentIsDeleted = true;
850 }
851
852 // C++0x [class]p7:
853 // A standard-layout class is a class that:
854 // [...]
855 // -- either has no non-static data members in the most derived
856 // class and at most one base class with non-static data members,
857 // or has no base classes with non-static data members, and
858 // At this point we know that we have a non-static data member, so the last
859 // clause holds.
860 if (!data().HasNoNonEmptyBases)
861 data().IsStandardLayout = false;
862
863 // If this is not a zero-length bit-field, then the class is not empty.
864 if (data().Empty) {
865 if (!Field->isBitField() ||
866 (!Field->getBitWidth()->isTypeDependent() &&
867 !Field->getBitWidth()->isValueDependent() &&
868 Field->getBitWidthValue(Context) != 0))
869 data().Empty = false;
870 }
871 }
872
873 // Handle using declarations of conversion functions.
874 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
875 if (Shadow->getDeclName().getNameKind()
876 == DeclarationName::CXXConversionFunctionName)
877 data().Conversions.addDecl(getASTContext(), Shadow, Shadow->getAccess());
878 }
879
finishedDefaultedOrDeletedMember(CXXMethodDecl * D)880 void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
881 assert(!D->isImplicit() && !D->isUserProvided());
882
883 // The kind of special member this declaration is, if any.
884 unsigned SMKind = 0;
885
886 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
887 if (Constructor->isDefaultConstructor()) {
888 SMKind |= SMF_DefaultConstructor;
889 if (Constructor->isConstexpr())
890 data().HasConstexprDefaultConstructor = true;
891 }
892 if (Constructor->isCopyConstructor())
893 SMKind |= SMF_CopyConstructor;
894 else if (Constructor->isMoveConstructor())
895 SMKind |= SMF_MoveConstructor;
896 else if (Constructor->isConstexpr())
897 // We may now know that the constructor is constexpr.
898 data().HasConstexprNonCopyMoveConstructor = true;
899 } else if (isa<CXXDestructorDecl>(D))
900 SMKind |= SMF_Destructor;
901 else if (D->isCopyAssignmentOperator())
902 SMKind |= SMF_CopyAssignment;
903 else if (D->isMoveAssignmentOperator())
904 SMKind |= SMF_MoveAssignment;
905
906 // Update which trivial / non-trivial special members we have.
907 // addedMember will have skipped this step for this member.
908 if (D->isTrivial())
909 data().HasTrivialSpecialMembers |= SMKind;
910 else
911 data().DeclaredNonTrivialSpecialMembers |= SMKind;
912 }
913
isCLike() const914 bool CXXRecordDecl::isCLike() const {
915 if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface ||
916 !TemplateOrInstantiation.isNull())
917 return false;
918 if (!hasDefinition())
919 return true;
920
921 return isPOD() && data().HasOnlyCMembers;
922 }
923
getCaptureFields(llvm::DenseMap<const VarDecl *,FieldDecl * > & Captures,FieldDecl * & ThisCapture) const924 void CXXRecordDecl::getCaptureFields(
925 llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
926 FieldDecl *&ThisCapture) const {
927 Captures.clear();
928 ThisCapture = 0;
929
930 LambdaDefinitionData &Lambda = getLambdaData();
931 RecordDecl::field_iterator Field = field_begin();
932 for (LambdaExpr::Capture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures;
933 C != CEnd; ++C, ++Field) {
934 if (C->capturesThis()) {
935 ThisCapture = *Field;
936 continue;
937 }
938
939 Captures[C->getCapturedVar()] = *Field;
940 }
941 }
942
943
GetConversionType(ASTContext & Context,NamedDecl * Conv)944 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
945 QualType T;
946 if (isa<UsingShadowDecl>(Conv))
947 Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
948 if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
949 T = ConvTemp->getTemplatedDecl()->getResultType();
950 else
951 T = cast<CXXConversionDecl>(Conv)->getConversionType();
952 return Context.getCanonicalType(T);
953 }
954
955 /// Collect the visible conversions of a base class.
956 ///
957 /// \param Record a base class of the class we're considering
958 /// \param InVirtual whether this base class is a virtual base (or a base
959 /// of a virtual base)
960 /// \param Access the access along the inheritance path to this base
961 /// \param ParentHiddenTypes the conversions provided by the inheritors
962 /// of this base
963 /// \param Output the set to which to add conversions from non-virtual bases
964 /// \param VOutput the set to which to add conversions from virtual bases
965 /// \param HiddenVBaseCs the set of conversions which were hidden in a
966 /// virtual base along some inheritance path
CollectVisibleConversions(ASTContext & Context,CXXRecordDecl * Record,bool InVirtual,AccessSpecifier Access,const llvm::SmallPtrSet<CanQualType,8> & ParentHiddenTypes,ASTUnresolvedSet & Output,UnresolvedSetImpl & VOutput,llvm::SmallPtrSet<NamedDecl *,8> & HiddenVBaseCs)967 static void CollectVisibleConversions(ASTContext &Context,
968 CXXRecordDecl *Record,
969 bool InVirtual,
970 AccessSpecifier Access,
971 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
972 ASTUnresolvedSet &Output,
973 UnresolvedSetImpl &VOutput,
974 llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
975 // The set of types which have conversions in this class or its
976 // subclasses. As an optimization, we don't copy the derived set
977 // unless it might change.
978 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
979 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
980
981 // Collect the direct conversions and figure out which conversions
982 // will be hidden in the subclasses.
983 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
984 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
985 if (ConvI != ConvE) {
986 HiddenTypesBuffer = ParentHiddenTypes;
987 HiddenTypes = &HiddenTypesBuffer;
988
989 for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
990 CanQualType ConvType(GetConversionType(Context, I.getDecl()));
991 bool Hidden = ParentHiddenTypes.count(ConvType);
992 if (!Hidden)
993 HiddenTypesBuffer.insert(ConvType);
994
995 // If this conversion is hidden and we're in a virtual base,
996 // remember that it's hidden along some inheritance path.
997 if (Hidden && InVirtual)
998 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
999
1000 // If this conversion isn't hidden, add it to the appropriate output.
1001 else if (!Hidden) {
1002 AccessSpecifier IAccess
1003 = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1004
1005 if (InVirtual)
1006 VOutput.addDecl(I.getDecl(), IAccess);
1007 else
1008 Output.addDecl(Context, I.getDecl(), IAccess);
1009 }
1010 }
1011 }
1012
1013 // Collect information recursively from any base classes.
1014 for (CXXRecordDecl::base_class_iterator
1015 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1016 const RecordType *RT = I->getType()->getAs<RecordType>();
1017 if (!RT) continue;
1018
1019 AccessSpecifier BaseAccess
1020 = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
1021 bool BaseInVirtual = InVirtual || I->isVirtual();
1022
1023 CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1024 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1025 *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1026 }
1027 }
1028
1029 /// Collect the visible conversions of a class.
1030 ///
1031 /// This would be extremely straightforward if it weren't for virtual
1032 /// bases. It might be worth special-casing that, really.
CollectVisibleConversions(ASTContext & Context,CXXRecordDecl * Record,ASTUnresolvedSet & Output)1033 static void CollectVisibleConversions(ASTContext &Context,
1034 CXXRecordDecl *Record,
1035 ASTUnresolvedSet &Output) {
1036 // The collection of all conversions in virtual bases that we've
1037 // found. These will be added to the output as long as they don't
1038 // appear in the hidden-conversions set.
1039 UnresolvedSet<8> VBaseCs;
1040
1041 // The set of conversions in virtual bases that we've determined to
1042 // be hidden.
1043 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1044
1045 // The set of types hidden by classes derived from this one.
1046 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1047
1048 // Go ahead and collect the direct conversions and add them to the
1049 // hidden-types set.
1050 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1051 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1052 Output.append(Context, ConvI, ConvE);
1053 for (; ConvI != ConvE; ++ConvI)
1054 HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));
1055
1056 // Recursively collect conversions from base classes.
1057 for (CXXRecordDecl::base_class_iterator
1058 I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1059 const RecordType *RT = I->getType()->getAs<RecordType>();
1060 if (!RT) continue;
1061
1062 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1063 I->isVirtual(), I->getAccessSpecifier(),
1064 HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1065 }
1066
1067 // Add any unhidden conversions provided by virtual bases.
1068 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1069 I != E; ++I) {
1070 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1071 Output.addDecl(Context, I.getDecl(), I.getAccess());
1072 }
1073 }
1074
1075 /// getVisibleConversionFunctions - get all conversion functions visible
1076 /// in current class; including conversion function templates.
1077 std::pair<CXXRecordDecl::conversion_iterator,CXXRecordDecl::conversion_iterator>
getVisibleConversionFunctions()1078 CXXRecordDecl::getVisibleConversionFunctions() {
1079 // If root class, all conversions are visible.
1080 if (bases_begin() == bases_end())
1081 return std::make_pair(data().Conversions.begin(), data().Conversions.end());
1082 // If visible conversion list is already evaluated, return it.
1083 if (!data().ComputedVisibleConversions) {
1084 CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
1085 data().ComputedVisibleConversions = true;
1086 }
1087 return std::make_pair(data().VisibleConversions.begin(),
1088 data().VisibleConversions.end());
1089 }
1090
removeConversion(const NamedDecl * ConvDecl)1091 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1092 // This operation is O(N) but extremely rare. Sema only uses it to
1093 // remove UsingShadowDecls in a class that were followed by a direct
1094 // declaration, e.g.:
1095 // class A : B {
1096 // using B::operator int;
1097 // operator int();
1098 // };
1099 // This is uncommon by itself and even more uncommon in conjunction
1100 // with sufficiently large numbers of directly-declared conversions
1101 // that asymptotic behavior matters.
1102
1103 ASTUnresolvedSet &Convs = data().Conversions;
1104 for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1105 if (Convs[I].getDecl() == ConvDecl) {
1106 Convs.erase(I);
1107 assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
1108 && "conversion was found multiple times in unresolved set");
1109 return;
1110 }
1111 }
1112
1113 llvm_unreachable("conversion not found in set!");
1114 }
1115
getInstantiatedFromMemberClass() const1116 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1117 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1118 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1119
1120 return 0;
1121 }
1122
1123 void
setInstantiationOfMemberClass(CXXRecordDecl * RD,TemplateSpecializationKind TSK)1124 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1125 TemplateSpecializationKind TSK) {
1126 assert(TemplateOrInstantiation.isNull() &&
1127 "Previous template or instantiation?");
1128 assert(!isa<ClassTemplateSpecializationDecl>(this));
1129 TemplateOrInstantiation
1130 = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1131 }
1132
getTemplateSpecializationKind() const1133 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1134 if (const ClassTemplateSpecializationDecl *Spec
1135 = dyn_cast<ClassTemplateSpecializationDecl>(this))
1136 return Spec->getSpecializationKind();
1137
1138 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1139 return MSInfo->getTemplateSpecializationKind();
1140
1141 return TSK_Undeclared;
1142 }
1143
1144 void
setTemplateSpecializationKind(TemplateSpecializationKind TSK)1145 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1146 if (ClassTemplateSpecializationDecl *Spec
1147 = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1148 Spec->setSpecializationKind(TSK);
1149 return;
1150 }
1151
1152 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1153 MSInfo->setTemplateSpecializationKind(TSK);
1154 return;
1155 }
1156
1157 llvm_unreachable("Not a class template or member class specialization");
1158 }
1159
getDestructor() const1160 CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1161 ASTContext &Context = getASTContext();
1162 QualType ClassType = Context.getTypeDeclType(this);
1163
1164 DeclarationName Name
1165 = Context.DeclarationNames.getCXXDestructorName(
1166 Context.getCanonicalType(ClassType));
1167
1168 DeclContext::lookup_const_result R = lookup(Name);
1169 if (R.empty())
1170 return 0;
1171
1172 CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(R.front());
1173 return Dtor;
1174 }
1175
completeDefinition()1176 void CXXRecordDecl::completeDefinition() {
1177 completeDefinition(0);
1178 }
1179
completeDefinition(CXXFinalOverriderMap * FinalOverriders)1180 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1181 RecordDecl::completeDefinition();
1182
1183 if (hasObjectMember() && getASTContext().getLangOpts().ObjCAutoRefCount) {
1184 // Objective-C Automatic Reference Counting:
1185 // If a class has a non-static data member of Objective-C pointer
1186 // type (or array thereof), it is a non-POD type and its
1187 // default constructor (if any), copy constructor, move constructor,
1188 // copy assignment operator, move assignment operator, and destructor are
1189 // non-trivial.
1190 struct DefinitionData &Data = data();
1191 Data.PlainOldData = false;
1192 Data.HasTrivialSpecialMembers = 0;
1193 Data.HasIrrelevantDestructor = false;
1194 }
1195
1196 // If the class may be abstract (but hasn't been marked as such), check for
1197 // any pure final overriders.
1198 if (mayBeAbstract()) {
1199 CXXFinalOverriderMap MyFinalOverriders;
1200 if (!FinalOverriders) {
1201 getFinalOverriders(MyFinalOverriders);
1202 FinalOverriders = &MyFinalOverriders;
1203 }
1204
1205 bool Done = false;
1206 for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
1207 MEnd = FinalOverriders->end();
1208 M != MEnd && !Done; ++M) {
1209 for (OverridingMethods::iterator SO = M->second.begin(),
1210 SOEnd = M->second.end();
1211 SO != SOEnd && !Done; ++SO) {
1212 assert(SO->second.size() > 0 &&
1213 "All virtual functions have overridding virtual functions");
1214
1215 // C++ [class.abstract]p4:
1216 // A class is abstract if it contains or inherits at least one
1217 // pure virtual function for which the final overrider is pure
1218 // virtual.
1219 if (SO->second.front().Method->isPure()) {
1220 data().Abstract = true;
1221 Done = true;
1222 break;
1223 }
1224 }
1225 }
1226 }
1227
1228 // Set access bits correctly on the directly-declared conversions.
1229 for (UnresolvedSetIterator I = data().Conversions.begin(),
1230 E = data().Conversions.end();
1231 I != E; ++I)
1232 I.setAccess((*I)->getAccess());
1233 }
1234
mayBeAbstract() const1235 bool CXXRecordDecl::mayBeAbstract() const {
1236 if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1237 isDependentContext())
1238 return false;
1239
1240 for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
1241 BEnd = bases_end();
1242 B != BEnd; ++B) {
1243 CXXRecordDecl *BaseDecl
1244 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
1245 if (BaseDecl->isAbstract())
1246 return true;
1247 }
1248
1249 return false;
1250 }
1251
anchor()1252 void CXXMethodDecl::anchor() { }
1253
recursivelyOverrides(const CXXMethodDecl * DerivedMD,const CXXMethodDecl * BaseMD)1254 static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
1255 const CXXMethodDecl *BaseMD) {
1256 for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),
1257 E = DerivedMD->end_overridden_methods(); I != E; ++I) {
1258 const CXXMethodDecl *MD = *I;
1259 if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
1260 return true;
1261 if (recursivelyOverrides(MD, BaseMD))
1262 return true;
1263 }
1264 return false;
1265 }
1266
1267 CXXMethodDecl *
getCorrespondingMethodInClass(const CXXRecordDecl * RD,bool MayBeBase)1268 CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
1269 bool MayBeBase) {
1270 if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
1271 return this;
1272
1273 // Lookup doesn't work for destructors, so handle them separately.
1274 if (isa<CXXDestructorDecl>(this)) {
1275 CXXMethodDecl *MD = RD->getDestructor();
1276 if (MD) {
1277 if (recursivelyOverrides(MD, this))
1278 return MD;
1279 if (MayBeBase && recursivelyOverrides(this, MD))
1280 return MD;
1281 }
1282 return NULL;
1283 }
1284
1285 lookup_const_result Candidates = RD->lookup(getDeclName());
1286 for (NamedDecl * const * I = Candidates.begin(); I != Candidates.end(); ++I) {
1287 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*I);
1288 if (!MD)
1289 continue;
1290 if (recursivelyOverrides(MD, this))
1291 return MD;
1292 if (MayBeBase && recursivelyOverrides(this, MD))
1293 return MD;
1294 }
1295
1296 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1297 E = RD->bases_end(); I != E; ++I) {
1298 const RecordType *RT = I->getType()->getAs<RecordType>();
1299 if (!RT)
1300 continue;
1301 const CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1302 CXXMethodDecl *T = this->getCorrespondingMethodInClass(Base);
1303 if (T)
1304 return T;
1305 }
1306
1307 return NULL;
1308 }
1309
1310 CXXMethodDecl *
Create(ASTContext & C,CXXRecordDecl * RD,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,bool isStatic,StorageClass SCAsWritten,bool isInline,bool isConstexpr,SourceLocation EndLocation)1311 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1312 SourceLocation StartLoc,
1313 const DeclarationNameInfo &NameInfo,
1314 QualType T, TypeSourceInfo *TInfo,
1315 bool isStatic, StorageClass SCAsWritten, bool isInline,
1316 bool isConstexpr, SourceLocation EndLocation) {
1317 return new (C) CXXMethodDecl(CXXMethod, RD, StartLoc, NameInfo, T, TInfo,
1318 isStatic, SCAsWritten, isInline, isConstexpr,
1319 EndLocation);
1320 }
1321
CreateDeserialized(ASTContext & C,unsigned ID)1322 CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1323 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXMethodDecl));
1324 return new (Mem) CXXMethodDecl(CXXMethod, 0, SourceLocation(),
1325 DeclarationNameInfo(), QualType(),
1326 0, false, SC_None, false, false,
1327 SourceLocation());
1328 }
1329
isUsualDeallocationFunction() const1330 bool CXXMethodDecl::isUsualDeallocationFunction() const {
1331 if (getOverloadedOperator() != OO_Delete &&
1332 getOverloadedOperator() != OO_Array_Delete)
1333 return false;
1334
1335 // C++ [basic.stc.dynamic.deallocation]p2:
1336 // A template instance is never a usual deallocation function,
1337 // regardless of its signature.
1338 if (getPrimaryTemplate())
1339 return false;
1340
1341 // C++ [basic.stc.dynamic.deallocation]p2:
1342 // If a class T has a member deallocation function named operator delete
1343 // with exactly one parameter, then that function is a usual (non-placement)
1344 // deallocation function. [...]
1345 if (getNumParams() == 1)
1346 return true;
1347
1348 // C++ [basic.stc.dynamic.deallocation]p2:
1349 // [...] If class T does not declare such an operator delete but does
1350 // declare a member deallocation function named operator delete with
1351 // exactly two parameters, the second of which has type std::size_t (18.1),
1352 // then this function is a usual deallocation function.
1353 ASTContext &Context = getASTContext();
1354 if (getNumParams() != 2 ||
1355 !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
1356 Context.getSizeType()))
1357 return false;
1358
1359 // This function is a usual deallocation function if there are no
1360 // single-parameter deallocation functions of the same kind.
1361 DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
1362 for (DeclContext::lookup_const_result::iterator I = R.begin(), E = R.end();
1363 I != E; ++I) {
1364 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I))
1365 if (FD->getNumParams() == 1)
1366 return false;
1367 }
1368
1369 return true;
1370 }
1371
isCopyAssignmentOperator() const1372 bool CXXMethodDecl::isCopyAssignmentOperator() const {
1373 // C++0x [class.copy]p17:
1374 // A user-declared copy assignment operator X::operator= is a non-static
1375 // non-template member function of class X with exactly one parameter of
1376 // type X, X&, const X&, volatile X& or const volatile X&.
1377 if (/*operator=*/getOverloadedOperator() != OO_Equal ||
1378 /*non-static*/ isStatic() ||
1379 /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate())
1380 return false;
1381
1382 QualType ParamType = getParamDecl(0)->getType();
1383 if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
1384 ParamType = Ref->getPointeeType();
1385
1386 ASTContext &Context = getASTContext();
1387 QualType ClassType
1388 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1389 return Context.hasSameUnqualifiedType(ClassType, ParamType);
1390 }
1391
isMoveAssignmentOperator() const1392 bool CXXMethodDecl::isMoveAssignmentOperator() const {
1393 // C++0x [class.copy]p19:
1394 // A user-declared move assignment operator X::operator= is a non-static
1395 // non-template member function of class X with exactly one parameter of type
1396 // X&&, const X&&, volatile X&&, or const volatile X&&.
1397 if (getOverloadedOperator() != OO_Equal || isStatic() ||
1398 getPrimaryTemplate() || getDescribedFunctionTemplate())
1399 return false;
1400
1401 QualType ParamType = getParamDecl(0)->getType();
1402 if (!isa<RValueReferenceType>(ParamType))
1403 return false;
1404 ParamType = ParamType->getPointeeType();
1405
1406 ASTContext &Context = getASTContext();
1407 QualType ClassType
1408 = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1409 return Context.hasSameUnqualifiedType(ClassType, ParamType);
1410 }
1411
addOverriddenMethod(const CXXMethodDecl * MD)1412 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
1413 assert(MD->isCanonicalDecl() && "Method is not canonical!");
1414 assert(!MD->getParent()->isDependentContext() &&
1415 "Can't add an overridden method to a class template!");
1416 assert(MD->isVirtual() && "Method is not virtual!");
1417
1418 getASTContext().addOverriddenMethod(this, MD);
1419 }
1420
begin_overridden_methods() const1421 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
1422 if (isa<CXXConstructorDecl>(this)) return 0;
1423 return getASTContext().overridden_methods_begin(this);
1424 }
1425
end_overridden_methods() const1426 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
1427 if (isa<CXXConstructorDecl>(this)) return 0;
1428 return getASTContext().overridden_methods_end(this);
1429 }
1430
size_overridden_methods() const1431 unsigned CXXMethodDecl::size_overridden_methods() const {
1432 if (isa<CXXConstructorDecl>(this)) return 0;
1433 return getASTContext().overridden_methods_size(this);
1434 }
1435
getThisType(ASTContext & C) const1436 QualType CXXMethodDecl::getThisType(ASTContext &C) const {
1437 // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
1438 // If the member function is declared const, the type of this is const X*,
1439 // if the member function is declared volatile, the type of this is
1440 // volatile X*, and if the member function is declared const volatile,
1441 // the type of this is const volatile X*.
1442
1443 assert(isInstance() && "No 'this' for static methods!");
1444
1445 QualType ClassTy = C.getTypeDeclType(getParent());
1446 ClassTy = C.getQualifiedType(ClassTy,
1447 Qualifiers::fromCVRMask(getTypeQualifiers()));
1448 return C.getPointerType(ClassTy);
1449 }
1450
hasInlineBody() const1451 bool CXXMethodDecl::hasInlineBody() const {
1452 // If this function is a template instantiation, look at the template from
1453 // which it was instantiated.
1454 const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1455 if (!CheckFn)
1456 CheckFn = this;
1457
1458 const FunctionDecl *fn;
1459 return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1460 }
1461
isLambdaStaticInvoker() const1462 bool CXXMethodDecl::isLambdaStaticInvoker() const {
1463 return getParent()->isLambda() &&
1464 getIdentifier() && getIdentifier()->getName() == "__invoke";
1465 }
1466
1467
CXXCtorInitializer(ASTContext & Context,TypeSourceInfo * TInfo,bool IsVirtual,SourceLocation L,Expr * Init,SourceLocation R,SourceLocation EllipsisLoc)1468 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1469 TypeSourceInfo *TInfo, bool IsVirtual,
1470 SourceLocation L, Expr *Init,
1471 SourceLocation R,
1472 SourceLocation EllipsisLoc)
1473 : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
1474 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
1475 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1476 {
1477 }
1478
CXXCtorInitializer(ASTContext & Context,FieldDecl * Member,SourceLocation MemberLoc,SourceLocation L,Expr * Init,SourceLocation R)1479 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1480 FieldDecl *Member,
1481 SourceLocation MemberLoc,
1482 SourceLocation L, Expr *Init,
1483 SourceLocation R)
1484 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1485 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1486 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1487 {
1488 }
1489
CXXCtorInitializer(ASTContext & Context,IndirectFieldDecl * Member,SourceLocation MemberLoc,SourceLocation L,Expr * Init,SourceLocation R)1490 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1491 IndirectFieldDecl *Member,
1492 SourceLocation MemberLoc,
1493 SourceLocation L, Expr *Init,
1494 SourceLocation R)
1495 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1496 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1497 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1498 {
1499 }
1500
CXXCtorInitializer(ASTContext & Context,TypeSourceInfo * TInfo,SourceLocation L,Expr * Init,SourceLocation R)1501 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1502 TypeSourceInfo *TInfo,
1503 SourceLocation L, Expr *Init,
1504 SourceLocation R)
1505 : Initializee(TInfo), MemberOrEllipsisLocation(), Init(Init),
1506 LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false),
1507 IsWritten(false), SourceOrderOrNumArrayIndices(0)
1508 {
1509 }
1510
CXXCtorInitializer(ASTContext & Context,FieldDecl * Member,SourceLocation MemberLoc,SourceLocation L,Expr * Init,SourceLocation R,VarDecl ** Indices,unsigned NumIndices)1511 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1512 FieldDecl *Member,
1513 SourceLocation MemberLoc,
1514 SourceLocation L, Expr *Init,
1515 SourceLocation R,
1516 VarDecl **Indices,
1517 unsigned NumIndices)
1518 : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1519 LParenLoc(L), RParenLoc(R), IsVirtual(false),
1520 IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1521 {
1522 VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1523 memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1524 }
1525
Create(ASTContext & Context,FieldDecl * Member,SourceLocation MemberLoc,SourceLocation L,Expr * Init,SourceLocation R,VarDecl ** Indices,unsigned NumIndices)1526 CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context,
1527 FieldDecl *Member,
1528 SourceLocation MemberLoc,
1529 SourceLocation L, Expr *Init,
1530 SourceLocation R,
1531 VarDecl **Indices,
1532 unsigned NumIndices) {
1533 void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) +
1534 sizeof(VarDecl *) * NumIndices,
1535 llvm::alignOf<CXXCtorInitializer>());
1536 return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R,
1537 Indices, NumIndices);
1538 }
1539
getBaseClassLoc() const1540 TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
1541 if (isBaseInitializer())
1542 return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
1543 else
1544 return TypeLoc();
1545 }
1546
getBaseClass() const1547 const Type *CXXCtorInitializer::getBaseClass() const {
1548 if (isBaseInitializer())
1549 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
1550 else
1551 return 0;
1552 }
1553
getSourceLocation() const1554 SourceLocation CXXCtorInitializer::getSourceLocation() const {
1555 if (isAnyMemberInitializer())
1556 return getMemberLocation();
1557
1558 if (isInClassMemberInitializer())
1559 return getAnyMember()->getLocation();
1560
1561 if (TypeSourceInfo *TSInfo = Initializee.get<TypeSourceInfo*>())
1562 return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
1563
1564 return SourceLocation();
1565 }
1566
getSourceRange() const1567 SourceRange CXXCtorInitializer::getSourceRange() const {
1568 if (isInClassMemberInitializer()) {
1569 FieldDecl *D = getAnyMember();
1570 if (Expr *I = D->getInClassInitializer())
1571 return I->getSourceRange();
1572 return SourceRange();
1573 }
1574
1575 return SourceRange(getSourceLocation(), getRParenLoc());
1576 }
1577
anchor()1578 void CXXConstructorDecl::anchor() { }
1579
1580 CXXConstructorDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1581 CXXConstructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1582 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConstructorDecl));
1583 return new (Mem) CXXConstructorDecl(0, SourceLocation(),DeclarationNameInfo(),
1584 QualType(), 0, false, false, false,false);
1585 }
1586
1587 CXXConstructorDecl *
Create(ASTContext & C,CXXRecordDecl * RD,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,bool isExplicit,bool isInline,bool isImplicitlyDeclared,bool isConstexpr)1588 CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1589 SourceLocation StartLoc,
1590 const DeclarationNameInfo &NameInfo,
1591 QualType T, TypeSourceInfo *TInfo,
1592 bool isExplicit, bool isInline,
1593 bool isImplicitlyDeclared, bool isConstexpr) {
1594 assert(NameInfo.getName().getNameKind()
1595 == DeclarationName::CXXConstructorName &&
1596 "Name must refer to a constructor");
1597 return new (C) CXXConstructorDecl(RD, StartLoc, NameInfo, T, TInfo,
1598 isExplicit, isInline, isImplicitlyDeclared,
1599 isConstexpr);
1600 }
1601
getTargetConstructor() const1602 CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
1603 assert(isDelegatingConstructor() && "Not a delegating constructor!");
1604 Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
1605 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(E))
1606 return Construct->getConstructor();
1607
1608 return 0;
1609 }
1610
isDefaultConstructor() const1611 bool CXXConstructorDecl::isDefaultConstructor() const {
1612 // C++ [class.ctor]p5:
1613 // A default constructor for a class X is a constructor of class
1614 // X that can be called without an argument.
1615 return (getNumParams() == 0) ||
1616 (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1617 }
1618
1619 bool
isCopyConstructor(unsigned & TypeQuals) const1620 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1621 return isCopyOrMoveConstructor(TypeQuals) &&
1622 getParamDecl(0)->getType()->isLValueReferenceType();
1623 }
1624
isMoveConstructor(unsigned & TypeQuals) const1625 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
1626 return isCopyOrMoveConstructor(TypeQuals) &&
1627 getParamDecl(0)->getType()->isRValueReferenceType();
1628 }
1629
1630 /// \brief Determine whether this is a copy or move constructor.
isCopyOrMoveConstructor(unsigned & TypeQuals) const1631 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
1632 // C++ [class.copy]p2:
1633 // A non-template constructor for class X is a copy constructor
1634 // if its first parameter is of type X&, const X&, volatile X& or
1635 // const volatile X&, and either there are no other parameters
1636 // or else all other parameters have default arguments (8.3.6).
1637 // C++0x [class.copy]p3:
1638 // A non-template constructor for class X is a move constructor if its
1639 // first parameter is of type X&&, const X&&, volatile X&&, or
1640 // const volatile X&&, and either there are no other parameters or else
1641 // all other parameters have default arguments.
1642 if ((getNumParams() < 1) ||
1643 (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1644 (getPrimaryTemplate() != 0) ||
1645 (getDescribedFunctionTemplate() != 0))
1646 return false;
1647
1648 const ParmVarDecl *Param = getParamDecl(0);
1649
1650 // Do we have a reference type?
1651 const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>();
1652 if (!ParamRefType)
1653 return false;
1654
1655 // Is it a reference to our class type?
1656 ASTContext &Context = getASTContext();
1657
1658 CanQualType PointeeType
1659 = Context.getCanonicalType(ParamRefType->getPointeeType());
1660 CanQualType ClassTy
1661 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1662 if (PointeeType.getUnqualifiedType() != ClassTy)
1663 return false;
1664
1665 // FIXME: other qualifiers?
1666
1667 // We have a copy or move constructor.
1668 TypeQuals = PointeeType.getCVRQualifiers();
1669 return true;
1670 }
1671
isConvertingConstructor(bool AllowExplicit) const1672 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1673 // C++ [class.conv.ctor]p1:
1674 // A constructor declared without the function-specifier explicit
1675 // that can be called with a single parameter specifies a
1676 // conversion from the type of its first parameter to the type of
1677 // its class. Such a constructor is called a converting
1678 // constructor.
1679 if (isExplicit() && !AllowExplicit)
1680 return false;
1681
1682 return (getNumParams() == 0 &&
1683 getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1684 (getNumParams() == 1) ||
1685 (getNumParams() > 1 &&
1686 (getParamDecl(1)->hasDefaultArg() ||
1687 getParamDecl(1)->isParameterPack()));
1688 }
1689
isSpecializationCopyingObject() const1690 bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1691 if ((getNumParams() < 1) ||
1692 (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1693 (getPrimaryTemplate() == 0) ||
1694 (getDescribedFunctionTemplate() != 0))
1695 return false;
1696
1697 const ParmVarDecl *Param = getParamDecl(0);
1698
1699 ASTContext &Context = getASTContext();
1700 CanQualType ParamType = Context.getCanonicalType(Param->getType());
1701
1702 // Is it the same as our our class type?
1703 CanQualType ClassTy
1704 = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1705 if (ParamType.getUnqualifiedType() != ClassTy)
1706 return false;
1707
1708 return true;
1709 }
1710
getInheritedConstructor() const1711 const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const {
1712 // Hack: we store the inherited constructor in the overridden method table
1713 method_iterator It = getASTContext().overridden_methods_begin(this);
1714 if (It == getASTContext().overridden_methods_end(this))
1715 return 0;
1716
1717 return cast<CXXConstructorDecl>(*It);
1718 }
1719
1720 void
setInheritedConstructor(const CXXConstructorDecl * BaseCtor)1721 CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){
1722 // Hack: we store the inherited constructor in the overridden method table
1723 assert(getASTContext().overridden_methods_size(this) == 0 &&
1724 "Base ctor already set.");
1725 getASTContext().addOverriddenMethod(this, BaseCtor);
1726 }
1727
anchor()1728 void CXXDestructorDecl::anchor() { }
1729
1730 CXXDestructorDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1731 CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1732 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXDestructorDecl));
1733 return new (Mem) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1734 QualType(), 0, false, false);
1735 }
1736
1737 CXXDestructorDecl *
Create(ASTContext & C,CXXRecordDecl * RD,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,bool isInline,bool isImplicitlyDeclared)1738 CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1739 SourceLocation StartLoc,
1740 const DeclarationNameInfo &NameInfo,
1741 QualType T, TypeSourceInfo *TInfo,
1742 bool isInline, bool isImplicitlyDeclared) {
1743 assert(NameInfo.getName().getNameKind()
1744 == DeclarationName::CXXDestructorName &&
1745 "Name must refer to a destructor");
1746 return new (C) CXXDestructorDecl(RD, StartLoc, NameInfo, T, TInfo, isInline,
1747 isImplicitlyDeclared);
1748 }
1749
anchor()1750 void CXXConversionDecl::anchor() { }
1751
1752 CXXConversionDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1753 CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1754 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConversionDecl));
1755 return new (Mem) CXXConversionDecl(0, SourceLocation(), DeclarationNameInfo(),
1756 QualType(), 0, false, false, false,
1757 SourceLocation());
1758 }
1759
1760 CXXConversionDecl *
Create(ASTContext & C,CXXRecordDecl * RD,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,bool isInline,bool isExplicit,bool isConstexpr,SourceLocation EndLocation)1761 CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1762 SourceLocation StartLoc,
1763 const DeclarationNameInfo &NameInfo,
1764 QualType T, TypeSourceInfo *TInfo,
1765 bool isInline, bool isExplicit,
1766 bool isConstexpr, SourceLocation EndLocation) {
1767 assert(NameInfo.getName().getNameKind()
1768 == DeclarationName::CXXConversionFunctionName &&
1769 "Name must refer to a conversion function");
1770 return new (C) CXXConversionDecl(RD, StartLoc, NameInfo, T, TInfo,
1771 isInline, isExplicit, isConstexpr,
1772 EndLocation);
1773 }
1774
isLambdaToBlockPointerConversion() const1775 bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
1776 return isImplicit() && getParent()->isLambda() &&
1777 getConversionType()->isBlockPointerType();
1778 }
1779
anchor()1780 void LinkageSpecDecl::anchor() { }
1781
Create(ASTContext & C,DeclContext * DC,SourceLocation ExternLoc,SourceLocation LangLoc,LanguageIDs Lang,SourceLocation RBraceLoc)1782 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1783 DeclContext *DC,
1784 SourceLocation ExternLoc,
1785 SourceLocation LangLoc,
1786 LanguageIDs Lang,
1787 SourceLocation RBraceLoc) {
1788 return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, RBraceLoc);
1789 }
1790
CreateDeserialized(ASTContext & C,unsigned ID)1791 LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1792 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LinkageSpecDecl));
1793 return new (Mem) LinkageSpecDecl(0, SourceLocation(), SourceLocation(),
1794 lang_c, SourceLocation());
1795 }
1796
anchor()1797 void UsingDirectiveDecl::anchor() { }
1798
Create(ASTContext & C,DeclContext * DC,SourceLocation L,SourceLocation NamespaceLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation IdentLoc,NamedDecl * Used,DeclContext * CommonAncestor)1799 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1800 SourceLocation L,
1801 SourceLocation NamespaceLoc,
1802 NestedNameSpecifierLoc QualifierLoc,
1803 SourceLocation IdentLoc,
1804 NamedDecl *Used,
1805 DeclContext *CommonAncestor) {
1806 if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1807 Used = NS->getOriginalNamespace();
1808 return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
1809 IdentLoc, Used, CommonAncestor);
1810 }
1811
1812 UsingDirectiveDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1813 UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1814 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDirectiveDecl));
1815 return new (Mem) UsingDirectiveDecl(0, SourceLocation(), SourceLocation(),
1816 NestedNameSpecifierLoc(),
1817 SourceLocation(), 0, 0);
1818 }
1819
getNominatedNamespace()1820 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1821 if (NamespaceAliasDecl *NA =
1822 dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1823 return NA->getNamespace();
1824 return cast_or_null<NamespaceDecl>(NominatedNamespace);
1825 }
1826
anchor()1827 void NamespaceDecl::anchor() { }
1828
NamespaceDecl(DeclContext * DC,bool Inline,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,NamespaceDecl * PrevDecl)1829 NamespaceDecl::NamespaceDecl(DeclContext *DC, bool Inline,
1830 SourceLocation StartLoc,
1831 SourceLocation IdLoc, IdentifierInfo *Id,
1832 NamespaceDecl *PrevDecl)
1833 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
1834 LocStart(StartLoc), RBraceLoc(), AnonOrFirstNamespaceAndInline(0, Inline)
1835 {
1836 setPreviousDeclaration(PrevDecl);
1837
1838 if (PrevDecl)
1839 AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
1840 }
1841
Create(ASTContext & C,DeclContext * DC,bool Inline,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,NamespaceDecl * PrevDecl)1842 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
1843 bool Inline, SourceLocation StartLoc,
1844 SourceLocation IdLoc, IdentifierInfo *Id,
1845 NamespaceDecl *PrevDecl) {
1846 return new (C) NamespaceDecl(DC, Inline, StartLoc, IdLoc, Id, PrevDecl);
1847 }
1848
CreateDeserialized(ASTContext & C,unsigned ID)1849 NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1850 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceDecl));
1851 return new (Mem) NamespaceDecl(0, false, SourceLocation(), SourceLocation(),
1852 0, 0);
1853 }
1854
anchor()1855 void NamespaceAliasDecl::anchor() { }
1856
Create(ASTContext & C,DeclContext * DC,SourceLocation UsingLoc,SourceLocation AliasLoc,IdentifierInfo * Alias,NestedNameSpecifierLoc QualifierLoc,SourceLocation IdentLoc,NamedDecl * Namespace)1857 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1858 SourceLocation UsingLoc,
1859 SourceLocation AliasLoc,
1860 IdentifierInfo *Alias,
1861 NestedNameSpecifierLoc QualifierLoc,
1862 SourceLocation IdentLoc,
1863 NamedDecl *Namespace) {
1864 if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1865 Namespace = NS->getOriginalNamespace();
1866 return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias,
1867 QualifierLoc, IdentLoc, Namespace);
1868 }
1869
1870 NamespaceAliasDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1871 NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1872 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceAliasDecl));
1873 return new (Mem) NamespaceAliasDecl(0, SourceLocation(), SourceLocation(), 0,
1874 NestedNameSpecifierLoc(),
1875 SourceLocation(), 0);
1876 }
1877
anchor()1878 void UsingShadowDecl::anchor() { }
1879
1880 UsingShadowDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1881 UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1882 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingShadowDecl));
1883 return new (Mem) UsingShadowDecl(0, SourceLocation(), 0, 0);
1884 }
1885
getUsingDecl() const1886 UsingDecl *UsingShadowDecl::getUsingDecl() const {
1887 const UsingShadowDecl *Shadow = this;
1888 while (const UsingShadowDecl *NextShadow =
1889 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1890 Shadow = NextShadow;
1891 return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1892 }
1893
anchor()1894 void UsingDecl::anchor() { }
1895
addShadowDecl(UsingShadowDecl * S)1896 void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1897 assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1898 "declaration already in set");
1899 assert(S->getUsingDecl() == this);
1900
1901 if (FirstUsingShadow.getPointer())
1902 S->UsingOrNextShadow = FirstUsingShadow.getPointer();
1903 FirstUsingShadow.setPointer(S);
1904 }
1905
removeShadowDecl(UsingShadowDecl * S)1906 void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1907 assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
1908 "declaration not in set");
1909 assert(S->getUsingDecl() == this);
1910
1911 // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
1912
1913 if (FirstUsingShadow.getPointer() == S) {
1914 FirstUsingShadow.setPointer(
1915 dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
1916 S->UsingOrNextShadow = this;
1917 return;
1918 }
1919
1920 UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
1921 while (Prev->UsingOrNextShadow != S)
1922 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
1923 Prev->UsingOrNextShadow = S->UsingOrNextShadow;
1924 S->UsingOrNextShadow = this;
1925 }
1926
Create(ASTContext & C,DeclContext * DC,SourceLocation UL,NestedNameSpecifierLoc QualifierLoc,const DeclarationNameInfo & NameInfo,bool IsTypeNameArg)1927 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
1928 NestedNameSpecifierLoc QualifierLoc,
1929 const DeclarationNameInfo &NameInfo,
1930 bool IsTypeNameArg) {
1931 return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, IsTypeNameArg);
1932 }
1933
CreateDeserialized(ASTContext & C,unsigned ID)1934 UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1935 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDecl));
1936 return new (Mem) UsingDecl(0, SourceLocation(), NestedNameSpecifierLoc(),
1937 DeclarationNameInfo(), false);
1938 }
1939
anchor()1940 void UnresolvedUsingValueDecl::anchor() { }
1941
1942 UnresolvedUsingValueDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation UsingLoc,NestedNameSpecifierLoc QualifierLoc,const DeclarationNameInfo & NameInfo)1943 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1944 SourceLocation UsingLoc,
1945 NestedNameSpecifierLoc QualifierLoc,
1946 const DeclarationNameInfo &NameInfo) {
1947 return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1948 QualifierLoc, NameInfo);
1949 }
1950
1951 UnresolvedUsingValueDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1952 UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1953 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UnresolvedUsingValueDecl));
1954 return new (Mem) UnresolvedUsingValueDecl(0, QualType(), SourceLocation(),
1955 NestedNameSpecifierLoc(),
1956 DeclarationNameInfo());
1957 }
1958
anchor()1959 void UnresolvedUsingTypenameDecl::anchor() { }
1960
1961 UnresolvedUsingTypenameDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation UsingLoc,SourceLocation TypenameLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation TargetNameLoc,DeclarationName TargetName)1962 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1963 SourceLocation UsingLoc,
1964 SourceLocation TypenameLoc,
1965 NestedNameSpecifierLoc QualifierLoc,
1966 SourceLocation TargetNameLoc,
1967 DeclarationName TargetName) {
1968 return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1969 QualifierLoc, TargetNameLoc,
1970 TargetName.getAsIdentifierInfo());
1971 }
1972
1973 UnresolvedUsingTypenameDecl *
CreateDeserialized(ASTContext & C,unsigned ID)1974 UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1975 void *Mem = AllocateDeserializedDecl(C, ID,
1976 sizeof(UnresolvedUsingTypenameDecl));
1977 return new (Mem) UnresolvedUsingTypenameDecl(0, SourceLocation(),
1978 SourceLocation(),
1979 NestedNameSpecifierLoc(),
1980 SourceLocation(),
1981 0);
1982 }
1983
anchor()1984 void StaticAssertDecl::anchor() { }
1985
Create(ASTContext & C,DeclContext * DC,SourceLocation StaticAssertLoc,Expr * AssertExpr,StringLiteral * Message,SourceLocation RParenLoc,bool Failed)1986 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
1987 SourceLocation StaticAssertLoc,
1988 Expr *AssertExpr,
1989 StringLiteral *Message,
1990 SourceLocation RParenLoc,
1991 bool Failed) {
1992 return new (C) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
1993 RParenLoc, Failed);
1994 }
1995
CreateDeserialized(ASTContext & C,unsigned ID)1996 StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
1997 unsigned ID) {
1998 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(StaticAssertDecl));
1999 return new (Mem) StaticAssertDecl(0, SourceLocation(), 0, 0,
2000 SourceLocation(), false);
2001 }
2002
getAccessName(AccessSpecifier AS)2003 static const char *getAccessName(AccessSpecifier AS) {
2004 switch (AS) {
2005 case AS_none:
2006 llvm_unreachable("Invalid access specifier!");
2007 case AS_public:
2008 return "public";
2009 case AS_private:
2010 return "private";
2011 case AS_protected:
2012 return "protected";
2013 }
2014 llvm_unreachable("Invalid access specifier!");
2015 }
2016
operator <<(const DiagnosticBuilder & DB,AccessSpecifier AS)2017 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
2018 AccessSpecifier AS) {
2019 return DB << getAccessName(AS);
2020 }
2021
operator <<(const PartialDiagnostic & DB,AccessSpecifier AS)2022 const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB,
2023 AccessSpecifier AS) {
2024 return DB << getAccessName(AS);
2025 }
2026