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