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