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