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