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