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