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