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