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