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