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