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