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