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