DeclCXX.cpp revision 3fb9e4b89f72823f162096086f0f964e6dcf66d6
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/TypeLoc.h"
21#include "clang/Basic/IdentifierTable.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/SmallPtrSet.h"
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// Decl Allocation/Deallocation Method Implementations
28//===----------------------------------------------------------------------===//
29
30CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
31  : UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false),
32    UserDeclaredCopyAssignment(false), UserDeclaredDestructor(false),
33    Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
34    Abstract(false), HasTrivialConstructor(true),
35    HasTrivialCopyConstructor(true), HasTrivialCopyAssignment(true),
36    HasTrivialDestructor(true), ComputedVisibleConversions(false),
37    DeclaredDefaultConstructor(false), DeclaredCopyConstructor(false),
38    DeclaredCopyAssignment(false), DeclaredDestructor(false),
39    NumBases(0), NumVBases(0), Bases(), VBases(),
40    Definition(D), FirstFriend(0) {
41}
42
43CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
44                             SourceLocation L, IdentifierInfo *Id,
45                             CXXRecordDecl *PrevDecl,
46                             SourceLocation TKL)
47  : RecordDecl(K, TK, DC, L, Id, PrevDecl, TKL),
48    DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
49    TemplateOrInstantiation() { }
50
51CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
52                                     SourceLocation L, IdentifierInfo *Id,
53                                     SourceLocation TKL,
54                                     CXXRecordDecl* PrevDecl,
55                                     bool DelayTypeCreation) {
56  CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, L, Id,
57                                           PrevDecl, TKL);
58
59  // FIXME: DelayTypeCreation seems like such a hack
60  if (!DelayTypeCreation)
61    C.getTypeDeclType(R, PrevDecl);
62  return R;
63}
64
65CXXRecordDecl *CXXRecordDecl::Create(ASTContext &C, EmptyShell Empty) {
66  return new (C) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(), 0, 0,
67                               SourceLocation());
68}
69
70void
71CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
72                        unsigned NumBases) {
73  ASTContext &C = getASTContext();
74
75  // C++ [dcl.init.aggr]p1:
76  //   An aggregate is an array or a class (clause 9) with [...]
77  //   no base classes [...].
78  data().Aggregate = false;
79
80  if (!data().Bases.isOffset() && data().NumBases > 0)
81    C.Deallocate(data().getBases());
82
83  // The set of seen virtual base types.
84  llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
85
86  // The virtual bases of this class.
87  llvm::SmallVector<const CXXBaseSpecifier *, 8> VBases;
88
89  data().Bases = new(C) CXXBaseSpecifier [NumBases];
90  data().NumBases = NumBases;
91  for (unsigned i = 0; i < NumBases; ++i) {
92    data().getBases()[i] = *Bases[i];
93    // Keep track of inherited vbases for this base class.
94    const CXXBaseSpecifier *Base = Bases[i];
95    QualType BaseType = Base->getType();
96    // Skip dependent types; we can't do any checking on them now.
97    if (BaseType->isDependentType())
98      continue;
99    CXXRecordDecl *BaseClassDecl
100      = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
101
102    // C++ [dcl.init.aggr]p1:
103    //   An aggregate is [...] a class with [...] no base classes [...].
104    data().Aggregate = false;
105
106    // C++ [class]p4:
107    //   A POD-struct is an aggregate class...
108    data().PlainOldData = false;
109
110    // A class with a non-empty base class is not empty.
111    // FIXME: Standard ref?
112    if (!BaseClassDecl->isEmpty())
113      data().Empty = false;
114
115    // C++ [class.virtual]p1:
116    //   A class that declares or inherits a virtual function is called a
117    //   polymorphic class.
118    if (BaseClassDecl->isPolymorphic())
119      data().Polymorphic = true;
120
121    // Now go through all virtual bases of this base and add them.
122    for (CXXRecordDecl::base_class_iterator VBase =
123          BaseClassDecl->vbases_begin(),
124         E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
125      // Add this base if it's not already in the list.
126      if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType())))
127        VBases.push_back(VBase);
128    }
129
130    if (Base->isVirtual()) {
131      // Add this base if it's not already in the list.
132      if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
133          VBases.push_back(Base);
134
135      // C++0x [meta.unary.prop] is_empty:
136      //    T is a class type, but not a union type, with ... no virtual base
137      //    classes
138      data().Empty = false;
139
140      // C++ [class.ctor]p5:
141      //   A constructor is trivial if its class has no virtual base classes.
142      data().HasTrivialConstructor = false;
143
144      // C++ [class.copy]p6:
145      //   A copy constructor is trivial if its class has no virtual base
146      //   classes.
147      data().HasTrivialCopyConstructor = false;
148
149      // C++ [class.copy]p11:
150      //   A copy assignment operator is trivial if its class has no virtual
151      //   base classes.
152      data().HasTrivialCopyAssignment = false;
153    } else {
154      // C++ [class.ctor]p5:
155      //   A constructor is trivial if all the direct base classes of its
156      //   class have trivial constructors.
157      if (!BaseClassDecl->hasTrivialConstructor())
158        data().HasTrivialConstructor = false;
159
160      // C++ [class.copy]p6:
161      //   A copy constructor is trivial if all the direct base classes of its
162      //   class have trivial copy constructors.
163      if (!BaseClassDecl->hasTrivialCopyConstructor())
164        data().HasTrivialCopyConstructor = false;
165
166      // C++ [class.copy]p11:
167      //   A copy assignment operator is trivial if all the direct base classes
168      //   of its class have trivial copy assignment operators.
169      if (!BaseClassDecl->hasTrivialCopyAssignment())
170        data().HasTrivialCopyAssignment = false;
171    }
172
173    // C++ [class.ctor]p3:
174    //   A destructor is trivial if all the direct base classes of its class
175    //   have trivial destructors.
176    if (!BaseClassDecl->hasTrivialDestructor())
177      data().HasTrivialDestructor = false;
178  }
179
180  if (VBases.empty())
181    return;
182
183  // Create base specifier for any direct or indirect virtual bases.
184  data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
185  data().NumVBases = VBases.size();
186  for (int I = 0, E = VBases.size(); I != E; ++I) {
187    TypeSourceInfo *VBaseTypeInfo = VBases[I]->getTypeSourceInfo();
188
189    // Skip dependent types; we can't do any checking on them now.
190    if (VBaseTypeInfo->getType()->isDependentType())
191      continue;
192
193    CXXRecordDecl *VBaseClassDecl = cast<CXXRecordDecl>(
194      VBaseTypeInfo->getType()->getAs<RecordType>()->getDecl());
195
196    data().getVBases()[I] =
197      CXXBaseSpecifier(VBaseClassDecl->getSourceRange(), true,
198                       VBaseClassDecl->getTagKind() == TTK_Class,
199                       VBases[I]->getAccessSpecifier(), VBaseTypeInfo,
200                       SourceLocation());
201  }
202}
203
204/// Callback function for CXXRecordDecl::forallBases that acknowledges
205/// that it saw a base class.
206static bool SawBase(const CXXRecordDecl *, void *) {
207  return true;
208}
209
210bool CXXRecordDecl::hasAnyDependentBases() const {
211  if (!isDependentContext())
212    return false;
213
214  return !forallBases(SawBase, 0);
215}
216
217bool CXXRecordDecl::hasConstCopyConstructor(ASTContext &Context) const {
218  return getCopyConstructor(Context, Qualifiers::Const) != 0;
219}
220
221/// \brief Perform a simplistic form of overload resolution that only considers
222/// cv-qualifiers on a single parameter, and return the best overload candidate
223/// (if there is one).
224static CXXMethodDecl *
225GetBestOverloadCandidateSimple(
226  const llvm::SmallVectorImpl<std::pair<CXXMethodDecl *, Qualifiers> > &Cands) {
227  if (Cands.empty())
228    return 0;
229  if (Cands.size() == 1)
230    return Cands[0].first;
231
232  unsigned Best = 0, N = Cands.size();
233  for (unsigned I = 1; I != N; ++I)
234    if (Cands[Best].second.isSupersetOf(Cands[I].second))
235      Best = I;
236
237  for (unsigned I = 1; I != N; ++I)
238    if (Cands[Best].second.isSupersetOf(Cands[I].second))
239      return 0;
240
241  return Cands[Best].first;
242}
243
244CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context,
245                                                      unsigned TypeQuals) const{
246  QualType ClassType
247    = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
248  DeclarationName ConstructorName
249    = Context.DeclarationNames.getCXXConstructorName(
250                                          Context.getCanonicalType(ClassType));
251  unsigned FoundTQs;
252  llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
253  DeclContext::lookup_const_iterator Con, ConEnd;
254  for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
255       Con != ConEnd; ++Con) {
256    // C++ [class.copy]p2:
257    //   A non-template constructor for class X is a copy constructor if [...]
258    if (isa<FunctionTemplateDecl>(*Con))
259      continue;
260
261    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
262    if (Constructor->isCopyConstructor(FoundTQs)) {
263      if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
264          (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
265        Found.push_back(std::make_pair(
266                                 const_cast<CXXConstructorDecl *>(Constructor),
267                                       Qualifiers::fromCVRMask(FoundTQs)));
268    }
269  }
270
271  return cast_or_null<CXXConstructorDecl>(
272                                        GetBestOverloadCandidateSimple(Found));
273}
274
275CXXMethodDecl *CXXRecordDecl::getCopyAssignmentOperator(bool ArgIsConst) const {
276  ASTContext &Context = getASTContext();
277  QualType Class = Context.getTypeDeclType(const_cast<CXXRecordDecl *>(this));
278  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
279
280  llvm::SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
281  DeclContext::lookup_const_iterator Op, OpEnd;
282  for (llvm::tie(Op, OpEnd) = this->lookup(Name); Op != OpEnd; ++Op) {
283    // C++ [class.copy]p9:
284    //   A user-declared copy assignment operator is a non-static non-template
285    //   member function of class X with exactly one parameter of type X, X&,
286    //   const X&, volatile X& or const volatile X&.
287    const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
288    if (!Method || Method->isStatic() || Method->getPrimaryTemplate())
289      continue;
290
291    const FunctionProtoType *FnType
292      = Method->getType()->getAs<FunctionProtoType>();
293    assert(FnType && "Overloaded operator has no prototype.");
294    // Don't assert on this; an invalid decl might have been left in the AST.
295    if (FnType->getNumArgs() != 1 || FnType->isVariadic())
296      continue;
297
298    QualType ArgType = FnType->getArgType(0);
299    Qualifiers Quals;
300    if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
301      ArgType = Ref->getPointeeType();
302      // If we have a const argument and we have a reference to a non-const,
303      // this function does not match.
304      if (ArgIsConst && !ArgType.isConstQualified())
305        continue;
306
307      Quals = ArgType.getQualifiers();
308    } else {
309      // By-value copy-assignment operators are treated like const X&
310      // copy-assignment operators.
311      Quals = Qualifiers::fromCVRMask(Qualifiers::Const);
312    }
313
314    if (!Context.hasSameUnqualifiedType(ArgType, Class))
315      continue;
316
317    // Save this copy-assignment operator. It might be "the one".
318    Found.push_back(std::make_pair(const_cast<CXXMethodDecl *>(Method), Quals));
319  }
320
321  // Use a simplistic form of overload resolution to find the candidate.
322  return GetBestOverloadCandidateSimple(Found);
323}
324
325void CXXRecordDecl::markedVirtualFunctionPure() {
326  // C++ [class.abstract]p2:
327  //   A class is abstract if it has at least one pure virtual function.
328  data().Abstract = true;
329}
330
331void CXXRecordDecl::addedMember(Decl *D) {
332  // Ignore friends and invalid declarations.
333  if (D->getFriendObjectKind() || D->isInvalidDecl())
334    return;
335
336  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
337  if (FunTmpl)
338    D = FunTmpl->getTemplatedDecl();
339
340  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
341    if (Method->isVirtual()) {
342      // C++ [dcl.init.aggr]p1:
343      //   An aggregate is an array or a class with [...] no virtual functions.
344      data().Aggregate = false;
345
346      // C++ [class]p4:
347      //   A POD-struct is an aggregate class...
348      data().PlainOldData = false;
349
350      // Virtual functions make the class non-empty.
351      // FIXME: Standard ref?
352      data().Empty = false;
353
354      // C++ [class.virtual]p1:
355      //   A class that declares or inherits a virtual function is called a
356      //   polymorphic class.
357      data().Polymorphic = true;
358
359      // None of the special member functions are trivial.
360      data().HasTrivialConstructor = false;
361      data().HasTrivialCopyConstructor = false;
362      data().HasTrivialCopyAssignment = false;
363      // FIXME: Destructor?
364    }
365  }
366
367  if (D->isImplicit()) {
368    // Notify that an implicit member was added after the definition
369    // was completed.
370    if (!isBeingDefined())
371      if (ASTMutationListener *L = getASTMutationListener())
372        L->AddedCXXImplicitMember(data().Definition, D);
373
374    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
375      // If this is the implicit default constructor, note that we have now
376      // declared it.
377      if (Constructor->isDefaultConstructor())
378        data().DeclaredDefaultConstructor = true;
379      // If this is the implicit copy constructor, note that we have now
380      // declared it.
381      else if (Constructor->isCopyConstructor())
382        data().DeclaredCopyConstructor = true;
383      return;
384    }
385
386    if (isa<CXXDestructorDecl>(D)) {
387      data().DeclaredDestructor = true;
388      return;
389    }
390
391    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
392      // If this is the implicit copy constructor, note that we have now
393      // declared it.
394      // FIXME: Move constructors
395      if (Method->getOverloadedOperator() == OO_Equal)
396        data().DeclaredCopyAssignment = true;
397      return;
398    }
399
400    // Any other implicit declarations are handled like normal declarations.
401  }
402
403  // Handle (user-declared) constructors.
404  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
405    // Note that we have a user-declared constructor.
406    data().UserDeclaredConstructor = true;
407
408    // Note that we have no need of an implicitly-declared default constructor.
409    data().DeclaredDefaultConstructor = true;
410
411    // C++ [dcl.init.aggr]p1:
412    //   An aggregate is an array or a class (clause 9) with no
413    //   user-declared constructors (12.1) [...].
414    data().Aggregate = false;
415
416    // C++ [class]p4:
417    //   A POD-struct is an aggregate class [...]
418    data().PlainOldData = false;
419
420    // C++ [class.ctor]p5:
421    //   A constructor is trivial if it is an implicitly-declared default
422    //   constructor.
423    // FIXME: C++0x: don't do this for "= default" default constructors.
424    data().HasTrivialConstructor = false;
425
426    // Note when we have a user-declared copy constructor, which will
427    // suppress the implicit declaration of a copy constructor.
428    if (!FunTmpl && Constructor->isCopyConstructor()) {
429      data().UserDeclaredCopyConstructor = true;
430      data().DeclaredCopyConstructor = true;
431
432      // C++ [class.copy]p6:
433      //   A copy constructor is trivial if it is implicitly declared.
434      // FIXME: C++0x: don't do this for "= default" copy constructors.
435      data().HasTrivialCopyConstructor = false;
436    }
437
438    return;
439  }
440
441  // Handle (user-declared) destructors.
442  if (isa<CXXDestructorDecl>(D)) {
443    data().DeclaredDestructor = true;
444    data().UserDeclaredDestructor = true;
445
446    // C++ [class]p4:
447    //   A POD-struct is an aggregate class that has [...] no user-defined
448    //   destructor.
449    data().PlainOldData = false;
450
451    // C++ [class.dtor]p3:
452    //   A destructor is trivial if it is an implicitly-declared destructor and
453    //   [...].
454    //
455    // FIXME: C++0x: don't do this for "= default" destructors
456    data().HasTrivialDestructor = false;
457
458    return;
459  }
460
461  // Handle (user-declared) member functions.
462  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
463    if (Method->getOverloadedOperator() == OO_Equal) {
464      // We're interested specifically in copy assignment operators.
465      const FunctionProtoType *FnType
466        = Method->getType()->getAs<FunctionProtoType>();
467      assert(FnType && "Overloaded operator has no proto function type.");
468      assert(FnType->getNumArgs() == 1 && !FnType->isVariadic());
469
470      // Copy assignment operators must be non-templates.
471      if (Method->getPrimaryTemplate() || FunTmpl)
472        return;
473
474      ASTContext &Context = getASTContext();
475      QualType ArgType = FnType->getArgType(0);
476      if (const LValueReferenceType *Ref =ArgType->getAs<LValueReferenceType>())
477        ArgType = Ref->getPointeeType();
478
479      ArgType = ArgType.getUnqualifiedType();
480      QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
481                                             const_cast<CXXRecordDecl*>(this)));
482
483      if (!Context.hasSameUnqualifiedType(ClassType, ArgType))
484        return;
485
486      // This is a copy assignment operator.
487      // FIXME: Move assignment operators.
488
489      // Suppress the implicit declaration of a copy constructor.
490      data().UserDeclaredCopyAssignment = true;
491      data().DeclaredCopyAssignment = true;
492
493      // C++ [class.copy]p11:
494      //   A copy assignment operator is trivial if it is implicitly declared.
495      // FIXME: C++0x: don't do this for "= default" copy operators.
496      data().HasTrivialCopyAssignment = false;
497
498      // C++ [class]p4:
499      //   A POD-struct is an aggregate class that [...] has no user-defined copy
500      //   assignment operator [...].
501      data().PlainOldData = false;
502    }
503
504    // Keep the list of conversion functions up-to-date.
505    if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
506      // We don't record specializations.
507      if (Conversion->getPrimaryTemplate())
508        return;
509
510      // FIXME: We intentionally don't use the decl's access here because it
511      // hasn't been set yet.  That's really just a misdesign in Sema.
512
513      if (FunTmpl) {
514        if (FunTmpl->getPreviousDeclaration())
515          data().Conversions.replace(FunTmpl->getPreviousDeclaration(),
516                                     FunTmpl);
517        else
518          data().Conversions.addDecl(FunTmpl);
519      } else {
520        if (Conversion->getPreviousDeclaration())
521          data().Conversions.replace(Conversion->getPreviousDeclaration(),
522                                     Conversion);
523        else
524          data().Conversions.addDecl(Conversion);
525      }
526    }
527
528    return;
529  }
530
531  // Handle non-static data members.
532  if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
533    // C++ [dcl.init.aggr]p1:
534    //   An aggregate is an array or a class (clause 9) with [...] no
535    //   private or protected non-static data members (clause 11).
536    //
537    // A POD must be an aggregate.
538    if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
539      data().Aggregate = false;
540      data().PlainOldData = false;
541    }
542
543    // C++ [class]p9:
544    //   A POD struct is a class that is both a trivial class and a
545    //   standard-layout class, and has no non-static data members of type
546    //   non-POD struct, non-POD union (or array of such types).
547    ASTContext &Context = getASTContext();
548    QualType T = Context.getBaseElementType(Field->getType());
549    if (!T->isPODType())
550      data().PlainOldData = false;
551    if (T->isReferenceType())
552      data().HasTrivialConstructor = false;
553
554    if (const RecordType *RecordTy = T->getAs<RecordType>()) {
555      CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
556      if (FieldRec->getDefinition()) {
557        if (!FieldRec->hasTrivialConstructor())
558          data().HasTrivialConstructor = false;
559        if (!FieldRec->hasTrivialCopyConstructor())
560          data().HasTrivialCopyConstructor = false;
561        if (!FieldRec->hasTrivialCopyAssignment())
562          data().HasTrivialCopyAssignment = false;
563        if (!FieldRec->hasTrivialDestructor())
564          data().HasTrivialDestructor = false;
565      }
566    }
567
568    // If this is not a zero-length bit-field, then the class is not empty.
569    if (data().Empty) {
570      if (!Field->getBitWidth())
571        data().Empty = false;
572      else if (!Field->getBitWidth()->isTypeDependent() &&
573               !Field->getBitWidth()->isValueDependent()) {
574        llvm::APSInt Bits;
575        if (Field->getBitWidth()->isIntegerConstantExpr(Bits, Context))
576          if (!!Bits)
577            data().Empty = false;
578      }
579    }
580  }
581
582  // Handle using declarations of conversion functions.
583  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
584    if (Shadow->getDeclName().getNameKind()
585          == DeclarationName::CXXConversionFunctionName)
586      data().Conversions.addDecl(Shadow, Shadow->getAccess());
587}
588
589static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
590  QualType T;
591  if (isa<UsingShadowDecl>(Conv))
592    Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
593  if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
594    T = ConvTemp->getTemplatedDecl()->getResultType();
595  else
596    T = cast<CXXConversionDecl>(Conv)->getConversionType();
597  return Context.getCanonicalType(T);
598}
599
600/// Collect the visible conversions of a base class.
601///
602/// \param Base a base class of the class we're considering
603/// \param InVirtual whether this base class is a virtual base (or a base
604///   of a virtual base)
605/// \param Access the access along the inheritance path to this base
606/// \param ParentHiddenTypes the conversions provided by the inheritors
607///   of this base
608/// \param Output the set to which to add conversions from non-virtual bases
609/// \param VOutput the set to which to add conversions from virtual bases
610/// \param HiddenVBaseCs the set of conversions which were hidden in a
611///   virtual base along some inheritance path
612static void CollectVisibleConversions(ASTContext &Context,
613                                      CXXRecordDecl *Record,
614                                      bool InVirtual,
615                                      AccessSpecifier Access,
616                  const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
617                                      UnresolvedSetImpl &Output,
618                                      UnresolvedSetImpl &VOutput,
619                           llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
620  // The set of types which have conversions in this class or its
621  // subclasses.  As an optimization, we don't copy the derived set
622  // unless it might change.
623  const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
624  llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
625
626  // Collect the direct conversions and figure out which conversions
627  // will be hidden in the subclasses.
628  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
629  if (!Cs.empty()) {
630    HiddenTypesBuffer = ParentHiddenTypes;
631    HiddenTypes = &HiddenTypesBuffer;
632
633    for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
634      bool Hidden =
635        !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
636
637      // If this conversion is hidden and we're in a virtual base,
638      // remember that it's hidden along some inheritance path.
639      if (Hidden && InVirtual)
640        HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
641
642      // If this conversion isn't hidden, add it to the appropriate output.
643      else if (!Hidden) {
644        AccessSpecifier IAccess
645          = CXXRecordDecl::MergeAccess(Access, I.getAccess());
646
647        if (InVirtual)
648          VOutput.addDecl(I.getDecl(), IAccess);
649        else
650          Output.addDecl(I.getDecl(), IAccess);
651      }
652    }
653  }
654
655  // Collect information recursively from any base classes.
656  for (CXXRecordDecl::base_class_iterator
657         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
658    const RecordType *RT = I->getType()->getAs<RecordType>();
659    if (!RT) continue;
660
661    AccessSpecifier BaseAccess
662      = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
663    bool BaseInVirtual = InVirtual || I->isVirtual();
664
665    CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
666    CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
667                              *HiddenTypes, Output, VOutput, HiddenVBaseCs);
668  }
669}
670
671/// Collect the visible conversions of a class.
672///
673/// This would be extremely straightforward if it weren't for virtual
674/// bases.  It might be worth special-casing that, really.
675static void CollectVisibleConversions(ASTContext &Context,
676                                      CXXRecordDecl *Record,
677                                      UnresolvedSetImpl &Output) {
678  // The collection of all conversions in virtual bases that we've
679  // found.  These will be added to the output as long as they don't
680  // appear in the hidden-conversions set.
681  UnresolvedSet<8> VBaseCs;
682
683  // The set of conversions in virtual bases that we've determined to
684  // be hidden.
685  llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
686
687  // The set of types hidden by classes derived from this one.
688  llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
689
690  // Go ahead and collect the direct conversions and add them to the
691  // hidden-types set.
692  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
693  Output.append(Cs.begin(), Cs.end());
694  for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
695    HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
696
697  // Recursively collect conversions from base classes.
698  for (CXXRecordDecl::base_class_iterator
699         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
700    const RecordType *RT = I->getType()->getAs<RecordType>();
701    if (!RT) continue;
702
703    CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
704                              I->isVirtual(), I->getAccessSpecifier(),
705                              HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
706  }
707
708  // Add any unhidden conversions provided by virtual bases.
709  for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
710         I != E; ++I) {
711    if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
712      Output.addDecl(I.getDecl(), I.getAccess());
713  }
714}
715
716/// getVisibleConversionFunctions - get all conversion functions visible
717/// in current class; including conversion function templates.
718const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
719  // If root class, all conversions are visible.
720  if (bases_begin() == bases_end())
721    return &data().Conversions;
722  // If visible conversion list is already evaluated, return it.
723  if (data().ComputedVisibleConversions)
724    return &data().VisibleConversions;
725  CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
726  data().ComputedVisibleConversions = true;
727  return &data().VisibleConversions;
728}
729
730void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
731  // This operation is O(N) but extremely rare.  Sema only uses it to
732  // remove UsingShadowDecls in a class that were followed by a direct
733  // declaration, e.g.:
734  //   class A : B {
735  //     using B::operator int;
736  //     operator int();
737  //   };
738  // This is uncommon by itself and even more uncommon in conjunction
739  // with sufficiently large numbers of directly-declared conversions
740  // that asymptotic behavior matters.
741
742  UnresolvedSetImpl &Convs = *getConversionFunctions();
743  for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
744    if (Convs[I].getDecl() == ConvDecl) {
745      Convs.erase(I);
746      assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
747             && "conversion was found multiple times in unresolved set");
748      return;
749    }
750  }
751
752  llvm_unreachable("conversion not found in set!");
753}
754
755CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
756  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
757    return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
758
759  return 0;
760}
761
762MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
763  return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
764}
765
766void
767CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
768                                             TemplateSpecializationKind TSK) {
769  assert(TemplateOrInstantiation.isNull() &&
770         "Previous template or instantiation?");
771  assert(!isa<ClassTemplateSpecializationDecl>(this));
772  TemplateOrInstantiation
773    = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
774}
775
776TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
777  if (const ClassTemplateSpecializationDecl *Spec
778        = dyn_cast<ClassTemplateSpecializationDecl>(this))
779    return Spec->getSpecializationKind();
780
781  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
782    return MSInfo->getTemplateSpecializationKind();
783
784  return TSK_Undeclared;
785}
786
787void
788CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
789  if (ClassTemplateSpecializationDecl *Spec
790      = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
791    Spec->setSpecializationKind(TSK);
792    return;
793  }
794
795  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
796    MSInfo->setTemplateSpecializationKind(TSK);
797    return;
798  }
799
800  assert(false && "Not a class template or member class specialization");
801}
802
803CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
804  ASTContext &Context = getASTContext();
805  QualType ClassType = Context.getTypeDeclType(this);
806
807  DeclarationName Name
808    = Context.DeclarationNames.getCXXDestructorName(
809                                          Context.getCanonicalType(ClassType));
810
811  DeclContext::lookup_const_iterator I, E;
812  llvm::tie(I, E) = lookup(Name);
813  if (I == E)
814    return 0;
815
816  CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
817  assert(++I == E && "Found more than one destructor!");
818
819  return Dtor;
820}
821
822void CXXRecordDecl::completeDefinition() {
823  completeDefinition(0);
824}
825
826void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
827  RecordDecl::completeDefinition();
828
829  // If the class may be abstract (but hasn't been marked as such), check for
830  // any pure final overriders.
831  if (mayBeAbstract()) {
832    CXXFinalOverriderMap MyFinalOverriders;
833    if (!FinalOverriders) {
834      getFinalOverriders(MyFinalOverriders);
835      FinalOverriders = &MyFinalOverriders;
836    }
837
838    bool Done = false;
839    for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
840                                     MEnd = FinalOverriders->end();
841         M != MEnd && !Done; ++M) {
842      for (OverridingMethods::iterator SO = M->second.begin(),
843                                    SOEnd = M->second.end();
844           SO != SOEnd && !Done; ++SO) {
845        assert(SO->second.size() > 0 &&
846               "All virtual functions have overridding virtual functions");
847
848        // C++ [class.abstract]p4:
849        //   A class is abstract if it contains or inherits at least one
850        //   pure virtual function for which the final overrider is pure
851        //   virtual.
852        if (SO->second.front().Method->isPure()) {
853          data().Abstract = true;
854          Done = true;
855          break;
856        }
857      }
858    }
859  }
860
861  // Set access bits correctly on the directly-declared conversions.
862  for (UnresolvedSetIterator I = data().Conversions.begin(),
863                             E = data().Conversions.end();
864       I != E; ++I)
865    data().Conversions.setAccess(I, (*I)->getAccess());
866}
867
868bool CXXRecordDecl::mayBeAbstract() const {
869  if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
870      isDependentContext())
871    return false;
872
873  for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
874                                             BEnd = bases_end();
875       B != BEnd; ++B) {
876    CXXRecordDecl *BaseDecl
877      = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
878    if (BaseDecl->isAbstract())
879      return true;
880  }
881
882  return false;
883}
884
885CXXMethodDecl *
886CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
887                      const DeclarationNameInfo &NameInfo,
888                      QualType T, TypeSourceInfo *TInfo,
889                      bool isStatic, StorageClass SCAsWritten, bool isInline) {
890  return new (C) CXXMethodDecl(CXXMethod, RD, NameInfo, T, TInfo,
891                               isStatic, SCAsWritten, isInline);
892}
893
894bool CXXMethodDecl::isUsualDeallocationFunction() const {
895  if (getOverloadedOperator() != OO_Delete &&
896      getOverloadedOperator() != OO_Array_Delete)
897    return false;
898
899  // C++ [basic.stc.dynamic.deallocation]p2:
900  //   A template instance is never a usual deallocation function,
901  //   regardless of its signature.
902  if (getPrimaryTemplate())
903    return false;
904
905  // C++ [basic.stc.dynamic.deallocation]p2:
906  //   If a class T has a member deallocation function named operator delete
907  //   with exactly one parameter, then that function is a usual (non-placement)
908  //   deallocation function. [...]
909  if (getNumParams() == 1)
910    return true;
911
912  // C++ [basic.stc.dynamic.deallocation]p2:
913  //   [...] If class T does not declare such an operator delete but does
914  //   declare a member deallocation function named operator delete with
915  //   exactly two parameters, the second of which has type std::size_t (18.1),
916  //   then this function is a usual deallocation function.
917  ASTContext &Context = getASTContext();
918  if (getNumParams() != 2 ||
919      !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
920                                      Context.getSizeType()))
921    return false;
922
923  // This function is a usual deallocation function if there are no
924  // single-parameter deallocation functions of the same kind.
925  for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
926       R.first != R.second; ++R.first) {
927    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
928      if (FD->getNumParams() == 1)
929        return false;
930  }
931
932  return true;
933}
934
935bool CXXMethodDecl::isCopyAssignmentOperator() const {
936  // C++0x [class.copy]p19:
937  //  A user-declared copy assignment operator X::operator= is a non-static
938  //  non-template member function of class X with exactly one parameter of
939  //  type X, X&, const X&, volatile X& or const volatile X&.
940  if (/*operator=*/getOverloadedOperator() != OO_Equal ||
941      /*non-static*/ isStatic() ||
942      /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
943      /*exactly one parameter*/getNumParams() != 1)
944    return false;
945
946  QualType ParamType = getParamDecl(0)->getType();
947  if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
948    ParamType = Ref->getPointeeType();
949
950  ASTContext &Context = getASTContext();
951  QualType ClassType
952    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
953  return Context.hasSameUnqualifiedType(ClassType, ParamType);
954}
955
956void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
957  assert(MD->isCanonicalDecl() && "Method is not canonical!");
958  assert(!MD->getParent()->isDependentContext() &&
959         "Can't add an overridden method to a class template!");
960
961  getASTContext().addOverriddenMethod(this, MD);
962}
963
964CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
965  return getASTContext().overridden_methods_begin(this);
966}
967
968CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
969  return getASTContext().overridden_methods_end(this);
970}
971
972unsigned CXXMethodDecl::size_overridden_methods() const {
973  return getASTContext().overridden_methods_size(this);
974}
975
976QualType CXXMethodDecl::getThisType(ASTContext &C) const {
977  // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
978  // If the member function is declared const, the type of this is const X*,
979  // if the member function is declared volatile, the type of this is
980  // volatile X*, and if the member function is declared const volatile,
981  // the type of this is const volatile X*.
982
983  assert(isInstance() && "No 'this' for static methods!");
984
985  QualType ClassTy = C.getTypeDeclType(getParent());
986  ClassTy = C.getQualifiedType(ClassTy,
987                               Qualifiers::fromCVRMask(getTypeQualifiers()));
988  return C.getPointerType(ClassTy);
989}
990
991bool CXXMethodDecl::hasInlineBody() const {
992  // If this function is a template instantiation, look at the template from
993  // which it was instantiated.
994  const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
995  if (!CheckFn)
996    CheckFn = this;
997
998  const FunctionDecl *fn;
999  return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1000}
1001
1002CXXBaseOrMemberInitializer::
1003CXXBaseOrMemberInitializer(ASTContext &Context,
1004                           TypeSourceInfo *TInfo, bool IsVirtual,
1005                           SourceLocation L, Expr *Init, SourceLocation R,
1006                           SourceLocation EllipsisLoc)
1007  : BaseOrMember(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
1008    LParenLoc(L), RParenLoc(R), IsVirtual(IsVirtual), IsWritten(false),
1009    SourceOrderOrNumArrayIndices(0)
1010{
1011}
1012
1013CXXBaseOrMemberInitializer::
1014CXXBaseOrMemberInitializer(ASTContext &Context,
1015                           FieldDecl *Member, SourceLocation MemberLoc,
1016                           SourceLocation L, Expr *Init, SourceLocation R)
1017  : BaseOrMember(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1018    LParenLoc(L), RParenLoc(R), IsVirtual(false),
1019    IsWritten(false), SourceOrderOrNumArrayIndices(0)
1020{
1021}
1022
1023CXXBaseOrMemberInitializer::
1024CXXBaseOrMemberInitializer(ASTContext &Context,
1025                           IndirectFieldDecl *Member, SourceLocation MemberLoc,
1026                           SourceLocation L, Expr *Init, SourceLocation R)
1027  : BaseOrMember(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1028    LParenLoc(L), RParenLoc(R), IsVirtual(false),
1029    IsWritten(false), SourceOrderOrNumArrayIndices(0)
1030{
1031}
1032
1033CXXBaseOrMemberInitializer::
1034CXXBaseOrMemberInitializer(ASTContext &Context,
1035                           FieldDecl *Member, SourceLocation MemberLoc,
1036                           SourceLocation L, Expr *Init, SourceLocation R,
1037                           VarDecl **Indices,
1038                           unsigned NumIndices)
1039  : BaseOrMember(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1040    LParenLoc(L), RParenLoc(R), IsVirtual(false),
1041    IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1042{
1043  VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1044  memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1045}
1046
1047CXXBaseOrMemberInitializer *
1048CXXBaseOrMemberInitializer::Create(ASTContext &Context,
1049                                   FieldDecl *Member,
1050                                   SourceLocation MemberLoc,
1051                                   SourceLocation L,
1052                                   Expr *Init,
1053                                   SourceLocation R,
1054                                   VarDecl **Indices,
1055                                   unsigned NumIndices) {
1056  void *Mem = Context.Allocate(sizeof(CXXBaseOrMemberInitializer) +
1057                               sizeof(VarDecl *) * NumIndices,
1058                               llvm::alignOf<CXXBaseOrMemberInitializer>());
1059  return new (Mem) CXXBaseOrMemberInitializer(Context, Member, MemberLoc,
1060                                              L, Init, R, Indices, NumIndices);
1061}
1062
1063TypeLoc CXXBaseOrMemberInitializer::getBaseClassLoc() const {
1064  if (isBaseInitializer())
1065    return BaseOrMember.get<TypeSourceInfo*>()->getTypeLoc();
1066  else
1067    return TypeLoc();
1068}
1069
1070Type *CXXBaseOrMemberInitializer::getBaseClass() {
1071  if (isBaseInitializer())
1072    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
1073  else
1074    return 0;
1075}
1076
1077const Type *CXXBaseOrMemberInitializer::getBaseClass() const {
1078  if (isBaseInitializer())
1079    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
1080  else
1081    return 0;
1082}
1083
1084SourceLocation CXXBaseOrMemberInitializer::getSourceLocation() const {
1085  if (isAnyMemberInitializer())
1086    return getMemberLocation();
1087
1088  return getBaseClassLoc().getLocalSourceRange().getBegin();
1089}
1090
1091SourceRange CXXBaseOrMemberInitializer::getSourceRange() const {
1092  return SourceRange(getSourceLocation(), getRParenLoc());
1093}
1094
1095CXXConstructorDecl *
1096CXXConstructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1097  return new (C) CXXConstructorDecl(0, DeclarationNameInfo(),
1098                                    QualType(), 0, false, false, false);
1099}
1100
1101CXXConstructorDecl *
1102CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1103                           const DeclarationNameInfo &NameInfo,
1104                           QualType T, TypeSourceInfo *TInfo,
1105                           bool isExplicit,
1106                           bool isInline,
1107                           bool isImplicitlyDeclared) {
1108  assert(NameInfo.getName().getNameKind()
1109         == DeclarationName::CXXConstructorName &&
1110         "Name must refer to a constructor");
1111  return new (C) CXXConstructorDecl(RD, NameInfo, T, TInfo, isExplicit,
1112                                    isInline, isImplicitlyDeclared);
1113}
1114
1115bool CXXConstructorDecl::isDefaultConstructor() const {
1116  // C++ [class.ctor]p5:
1117  //   A default constructor for a class X is a constructor of class
1118  //   X that can be called without an argument.
1119  return (getNumParams() == 0) ||
1120         (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1121}
1122
1123bool
1124CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1125  // C++ [class.copy]p2:
1126  //   A non-template constructor for class X is a copy constructor
1127  //   if its first parameter is of type X&, const X&, volatile X& or
1128  //   const volatile X&, and either there are no other parameters
1129  //   or else all other parameters have default arguments (8.3.6).
1130  if ((getNumParams() < 1) ||
1131      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1132      (getPrimaryTemplate() != 0) ||
1133      (getDescribedFunctionTemplate() != 0))
1134    return false;
1135
1136  const ParmVarDecl *Param = getParamDecl(0);
1137
1138  // Do we have a reference type? Rvalue references don't count.
1139  const LValueReferenceType *ParamRefType =
1140    Param->getType()->getAs<LValueReferenceType>();
1141  if (!ParamRefType)
1142    return false;
1143
1144  // Is it a reference to our class type?
1145  ASTContext &Context = getASTContext();
1146
1147  CanQualType PointeeType
1148    = Context.getCanonicalType(ParamRefType->getPointeeType());
1149  CanQualType ClassTy
1150    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1151  if (PointeeType.getUnqualifiedType() != ClassTy)
1152    return false;
1153
1154  // FIXME: other qualifiers?
1155
1156  // We have a copy constructor.
1157  TypeQuals = PointeeType.getCVRQualifiers();
1158  return true;
1159}
1160
1161bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1162  // C++ [class.conv.ctor]p1:
1163  //   A constructor declared without the function-specifier explicit
1164  //   that can be called with a single parameter specifies a
1165  //   conversion from the type of its first parameter to the type of
1166  //   its class. Such a constructor is called a converting
1167  //   constructor.
1168  if (isExplicit() && !AllowExplicit)
1169    return false;
1170
1171  return (getNumParams() == 0 &&
1172          getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1173         (getNumParams() == 1) ||
1174         (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
1175}
1176
1177bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1178  if ((getNumParams() < 1) ||
1179      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1180      (getPrimaryTemplate() == 0) ||
1181      (getDescribedFunctionTemplate() != 0))
1182    return false;
1183
1184  const ParmVarDecl *Param = getParamDecl(0);
1185
1186  ASTContext &Context = getASTContext();
1187  CanQualType ParamType = Context.getCanonicalType(Param->getType());
1188
1189  // Is it the same as our our class type?
1190  CanQualType ClassTy
1191    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1192  if (ParamType.getUnqualifiedType() != ClassTy)
1193    return false;
1194
1195  return true;
1196}
1197
1198CXXDestructorDecl *
1199CXXDestructorDecl::Create(ASTContext &C, EmptyShell Empty) {
1200  return new (C) CXXDestructorDecl(0, DeclarationNameInfo(),
1201                                   QualType(), 0, false, false);
1202}
1203
1204CXXDestructorDecl *
1205CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1206                          const DeclarationNameInfo &NameInfo,
1207                          QualType T, TypeSourceInfo *TInfo,
1208                          bool isInline,
1209                          bool isImplicitlyDeclared) {
1210  assert(NameInfo.getName().getNameKind()
1211         == DeclarationName::CXXDestructorName &&
1212         "Name must refer to a destructor");
1213  return new (C) CXXDestructorDecl(RD, NameInfo, T, TInfo, isInline,
1214                                   isImplicitlyDeclared);
1215}
1216
1217CXXConversionDecl *
1218CXXConversionDecl::Create(ASTContext &C, EmptyShell Empty) {
1219  return new (C) CXXConversionDecl(0, DeclarationNameInfo(),
1220                                   QualType(), 0, false, false);
1221}
1222
1223CXXConversionDecl *
1224CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1225                          const DeclarationNameInfo &NameInfo,
1226                          QualType T, TypeSourceInfo *TInfo,
1227                          bool isInline, bool isExplicit) {
1228  assert(NameInfo.getName().getNameKind()
1229         == DeclarationName::CXXConversionFunctionName &&
1230         "Name must refer to a conversion function");
1231  return new (C) CXXConversionDecl(RD, NameInfo, T, TInfo,
1232                                   isInline, isExplicit);
1233}
1234
1235LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1236                                         DeclContext *DC,
1237                                         SourceLocation L,
1238                                         LanguageIDs Lang, bool Braces) {
1239  return new (C) LinkageSpecDecl(DC, L, Lang, Braces);
1240}
1241
1242UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1243                                               SourceLocation L,
1244                                               SourceLocation NamespaceLoc,
1245                                               SourceRange QualifierRange,
1246                                               NestedNameSpecifier *Qualifier,
1247                                               SourceLocation IdentLoc,
1248                                               NamedDecl *Used,
1249                                               DeclContext *CommonAncestor) {
1250  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1251    Used = NS->getOriginalNamespace();
1252  return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierRange,
1253                                    Qualifier, IdentLoc, Used, CommonAncestor);
1254}
1255
1256NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1257  if (NamespaceAliasDecl *NA =
1258        dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1259    return NA->getNamespace();
1260  return cast_or_null<NamespaceDecl>(NominatedNamespace);
1261}
1262
1263NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1264                                               SourceLocation UsingLoc,
1265                                               SourceLocation AliasLoc,
1266                                               IdentifierInfo *Alias,
1267                                               SourceRange QualifierRange,
1268                                               NestedNameSpecifier *Qualifier,
1269                                               SourceLocation IdentLoc,
1270                                               NamedDecl *Namespace) {
1271  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1272    Namespace = NS->getOriginalNamespace();
1273  return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias, QualifierRange,
1274                                    Qualifier, IdentLoc, Namespace);
1275}
1276
1277UsingDecl *UsingShadowDecl::getUsingDecl() const {
1278  const UsingShadowDecl *Shadow = this;
1279  while (const UsingShadowDecl *NextShadow =
1280         dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1281    Shadow = NextShadow;
1282  return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1283}
1284
1285void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1286  assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1287         "declaration already in set");
1288  assert(S->getUsingDecl() == this);
1289
1290  if (FirstUsingShadow)
1291    S->UsingOrNextShadow = FirstUsingShadow;
1292  FirstUsingShadow = S;
1293}
1294
1295void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1296  assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
1297         "declaration not in set");
1298  assert(S->getUsingDecl() == this);
1299
1300  // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
1301
1302  if (FirstUsingShadow == S) {
1303    FirstUsingShadow = dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow);
1304    S->UsingOrNextShadow = this;
1305    return;
1306  }
1307
1308  UsingShadowDecl *Prev = FirstUsingShadow;
1309  while (Prev->UsingOrNextShadow != S)
1310    Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
1311  Prev->UsingOrNextShadow = S->UsingOrNextShadow;
1312  S->UsingOrNextShadow = this;
1313}
1314
1315UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC,
1316                             SourceRange NNR, SourceLocation UL,
1317                             NestedNameSpecifier* TargetNNS,
1318                             const DeclarationNameInfo &NameInfo,
1319                             bool IsTypeNameArg) {
1320  return new (C) UsingDecl(DC, NNR, UL, TargetNNS, NameInfo, IsTypeNameArg);
1321}
1322
1323UnresolvedUsingValueDecl *
1324UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1325                                 SourceLocation UsingLoc,
1326                                 SourceRange TargetNNR,
1327                                 NestedNameSpecifier *TargetNNS,
1328                                 const DeclarationNameInfo &NameInfo) {
1329  return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1330                                          TargetNNR, TargetNNS, NameInfo);
1331}
1332
1333UnresolvedUsingTypenameDecl *
1334UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1335                                    SourceLocation UsingLoc,
1336                                    SourceLocation TypenameLoc,
1337                                    SourceRange TargetNNR,
1338                                    NestedNameSpecifier *TargetNNS,
1339                                    SourceLocation TargetNameLoc,
1340                                    DeclarationName TargetName) {
1341  return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1342                                             TargetNNR, TargetNNS,
1343                                             TargetNameLoc,
1344                                             TargetName.getAsIdentifierInfo());
1345}
1346
1347StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
1348                                           SourceLocation L, Expr *AssertExpr,
1349                                           StringLiteral *Message) {
1350  return new (C) StaticAssertDecl(DC, L, AssertExpr, Message);
1351}
1352
1353static const char *getAccessName(AccessSpecifier AS) {
1354  switch (AS) {
1355    default:
1356    case AS_none:
1357      assert("Invalid access specifier!");
1358      return 0;
1359    case AS_public:
1360      return "public";
1361    case AS_private:
1362      return "private";
1363    case AS_protected:
1364      return "protected";
1365  }
1366}
1367
1368const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
1369                                           AccessSpecifier AS) {
1370  return DB << getAccessName(AS);
1371}
1372