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