DeclCXX.cpp revision 80638c5e6395344c1e6096542b0ff3b8bfb2139e
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() == RecordDecl::TK_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
162CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(ASTContext &Context,
163                                                      unsigned TypeQuals) const{
164  QualType ClassType
165    = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
166  DeclarationName ConstructorName
167    = Context.DeclarationNames.getCXXConstructorName(
168                                          Context.getCanonicalType(ClassType));
169  unsigned FoundTQs;
170  DeclContext::lookup_const_iterator Con, ConEnd;
171  for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
172       Con != ConEnd; ++Con) {
173    // C++ [class.copy]p2:
174    //   A non-template constructor for class X is a copy constructor if [...]
175    if (isa<FunctionTemplateDecl>(*Con))
176      continue;
177
178    if (cast<CXXConstructorDecl>(*Con)->isCopyConstructor(FoundTQs)) {
179      if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
180          (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
181        return cast<CXXConstructorDecl>(*Con);
182
183    }
184  }
185  return 0;
186}
187
188bool CXXRecordDecl::hasConstCopyAssignment(ASTContext &Context,
189                                           const CXXMethodDecl *& MD) const {
190  QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
191    const_cast<CXXRecordDecl*>(this)));
192  DeclarationName OpName =Context.DeclarationNames.getCXXOperatorName(OO_Equal);
193
194  DeclContext::lookup_const_iterator Op, OpEnd;
195  for (llvm::tie(Op, OpEnd) = this->lookup(OpName);
196       Op != OpEnd; ++Op) {
197    // C++ [class.copy]p9:
198    //   A user-declared copy assignment operator is a non-static non-template
199    //   member function of class X with exactly one parameter of type X, X&,
200    //   const X&, volatile X& or const volatile X&.
201    const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
202    if (!Method)
203      continue;
204
205    if (Method->isStatic())
206      continue;
207    if (Method->getPrimaryTemplate())
208      continue;
209    const FunctionProtoType *FnType =
210      Method->getType()->getAs<FunctionProtoType>();
211    assert(FnType && "Overloaded operator has no prototype.");
212    // Don't assert on this; an invalid decl might have been left in the AST.
213    if (FnType->getNumArgs() != 1 || FnType->isVariadic())
214      continue;
215    bool AcceptsConst = true;
216    QualType ArgType = FnType->getArgType(0);
217    if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
218      ArgType = Ref->getPointeeType();
219      // Is it a non-const lvalue reference?
220      if (!ArgType.isConstQualified())
221        AcceptsConst = false;
222    }
223    if (!Context.hasSameUnqualifiedType(ArgType, ClassType))
224      continue;
225    MD = Method;
226    // We have a single argument of type cv X or cv X&, i.e. we've found the
227    // copy assignment operator. Return whether it accepts const arguments.
228    return AcceptsConst;
229  }
230  assert(isInvalidDecl() &&
231         "No copy assignment operator declared in valid code.");
232  return false;
233}
234
235void
236CXXRecordDecl::addedConstructor(ASTContext &Context,
237                                CXXConstructorDecl *ConDecl) {
238  assert(!ConDecl->isImplicit() && "addedConstructor - not for implicit decl");
239  // Note that we have a user-declared constructor.
240  data().UserDeclaredConstructor = true;
241
242  // C++ [dcl.init.aggr]p1:
243  //   An aggregate is an array or a class (clause 9) with no
244  //   user-declared constructors (12.1) [...].
245  data().Aggregate = false;
246
247  // C++ [class]p4:
248  //   A POD-struct is an aggregate class [...]
249  data().PlainOldData = false;
250
251  // C++ [class.ctor]p5:
252  //   A constructor is trivial if it is an implicitly-declared default
253  //   constructor.
254  // FIXME: C++0x: don't do this for "= default" default constructors.
255  data().HasTrivialConstructor = false;
256
257  // Note when we have a user-declared copy constructor, which will
258  // suppress the implicit declaration of a copy constructor.
259  if (ConDecl->isCopyConstructor()) {
260    data().UserDeclaredCopyConstructor = true;
261
262    // C++ [class.copy]p6:
263    //   A copy constructor is trivial if it is implicitly declared.
264    // FIXME: C++0x: don't do this for "= default" copy constructors.
265    data().HasTrivialCopyConstructor = false;
266  }
267}
268
269void CXXRecordDecl::addedAssignmentOperator(ASTContext &Context,
270                                            CXXMethodDecl *OpDecl) {
271  // We're interested specifically in copy assignment operators.
272  const FunctionProtoType *FnType = OpDecl->getType()->getAs<FunctionProtoType>();
273  assert(FnType && "Overloaded operator has no proto function type.");
274  assert(FnType->getNumArgs() == 1 && !FnType->isVariadic());
275
276  // Copy assignment operators must be non-templates.
277  if (OpDecl->getPrimaryTemplate() || OpDecl->getDescribedFunctionTemplate())
278    return;
279
280  QualType ArgType = FnType->getArgType(0);
281  if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>())
282    ArgType = Ref->getPointeeType();
283
284  ArgType = ArgType.getUnqualifiedType();
285  QualType ClassType = Context.getCanonicalType(Context.getTypeDeclType(
286    const_cast<CXXRecordDecl*>(this)));
287
288  if (!Context.hasSameUnqualifiedType(ClassType, ArgType))
289    return;
290
291  // This is a copy assignment operator.
292  // Note on the decl that it is a copy assignment operator.
293  OpDecl->setCopyAssignment(true);
294
295  // Suppress the implicit declaration of a copy constructor.
296  data().UserDeclaredCopyAssignment = true;
297
298  // C++ [class.copy]p11:
299  //   A copy assignment operator is trivial if it is implicitly declared.
300  // FIXME: C++0x: don't do this for "= default" copy operators.
301  data().HasTrivialCopyAssignment = false;
302
303  // C++ [class]p4:
304  //   A POD-struct is an aggregate class that [...] has no user-defined copy
305  //   assignment operator [...].
306  data().PlainOldData = false;
307}
308
309static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
310  QualType T;
311  if (isa<UsingShadowDecl>(Conv))
312    Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
313  if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
314    T = ConvTemp->getTemplatedDecl()->getResultType();
315  else
316    T = cast<CXXConversionDecl>(Conv)->getConversionType();
317  return Context.getCanonicalType(T);
318}
319
320/// Collect the visible conversions of a base class.
321///
322/// \param Base a base class of the class we're considering
323/// \param InVirtual whether this base class is a virtual base (or a base
324///   of a virtual base)
325/// \param Access the access along the inheritance path to this base
326/// \param ParentHiddenTypes the conversions provided by the inheritors
327///   of this base
328/// \param Output the set to which to add conversions from non-virtual bases
329/// \param VOutput the set to which to add conversions from virtual bases
330/// \param HiddenVBaseCs the set of conversions which were hidden in a
331///   virtual base along some inheritance path
332static void CollectVisibleConversions(ASTContext &Context,
333                                      CXXRecordDecl *Record,
334                                      bool InVirtual,
335                                      AccessSpecifier Access,
336                  const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
337                                      UnresolvedSetImpl &Output,
338                                      UnresolvedSetImpl &VOutput,
339                           llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
340  // The set of types which have conversions in this class or its
341  // subclasses.  As an optimization, we don't copy the derived set
342  // unless it might change.
343  const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
344  llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
345
346  // Collect the direct conversions and figure out which conversions
347  // will be hidden in the subclasses.
348  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
349  if (!Cs.empty()) {
350    HiddenTypesBuffer = ParentHiddenTypes;
351    HiddenTypes = &HiddenTypesBuffer;
352
353    for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
354      bool Hidden =
355        !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
356
357      // If this conversion is hidden and we're in a virtual base,
358      // remember that it's hidden along some inheritance path.
359      if (Hidden && InVirtual)
360        HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
361
362      // If this conversion isn't hidden, add it to the appropriate output.
363      else if (!Hidden) {
364        AccessSpecifier IAccess
365          = CXXRecordDecl::MergeAccess(Access, I.getAccess());
366
367        if (InVirtual)
368          VOutput.addDecl(I.getDecl(), IAccess);
369        else
370          Output.addDecl(I.getDecl(), IAccess);
371      }
372    }
373  }
374
375  // Collect information recursively from any base classes.
376  for (CXXRecordDecl::base_class_iterator
377         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
378    const RecordType *RT = I->getType()->getAs<RecordType>();
379    if (!RT) continue;
380
381    AccessSpecifier BaseAccess
382      = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
383    bool BaseInVirtual = InVirtual || I->isVirtual();
384
385    CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
386    CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
387                              *HiddenTypes, Output, VOutput, HiddenVBaseCs);
388  }
389}
390
391/// Collect the visible conversions of a class.
392///
393/// This would be extremely straightforward if it weren't for virtual
394/// bases.  It might be worth special-casing that, really.
395static void CollectVisibleConversions(ASTContext &Context,
396                                      CXXRecordDecl *Record,
397                                      UnresolvedSetImpl &Output) {
398  // The collection of all conversions in virtual bases that we've
399  // found.  These will be added to the output as long as they don't
400  // appear in the hidden-conversions set.
401  UnresolvedSet<8> VBaseCs;
402
403  // The set of conversions in virtual bases that we've determined to
404  // be hidden.
405  llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
406
407  // The set of types hidden by classes derived from this one.
408  llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
409
410  // Go ahead and collect the direct conversions and add them to the
411  // hidden-types set.
412  UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
413  Output.append(Cs.begin(), Cs.end());
414  for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
415    HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
416
417  // Recursively collect conversions from base classes.
418  for (CXXRecordDecl::base_class_iterator
419         I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
420    const RecordType *RT = I->getType()->getAs<RecordType>();
421    if (!RT) continue;
422
423    CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
424                              I->isVirtual(), I->getAccessSpecifier(),
425                              HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
426  }
427
428  // Add any unhidden conversions provided by virtual bases.
429  for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
430         I != E; ++I) {
431    if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
432      Output.addDecl(I.getDecl(), I.getAccess());
433  }
434}
435
436/// getVisibleConversionFunctions - get all conversion functions visible
437/// in current class; including conversion function templates.
438const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
439  // If root class, all conversions are visible.
440  if (bases_begin() == bases_end())
441    return &data().Conversions;
442  // If visible conversion list is already evaluated, return it.
443  if (data().ComputedVisibleConversions)
444    return &data().VisibleConversions;
445  CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
446  data().ComputedVisibleConversions = true;
447  return &data().VisibleConversions;
448}
449
450#ifndef NDEBUG
451void CXXRecordDecl::CheckConversionFunction(NamedDecl *ConvDecl) {
452  assert(ConvDecl->getDeclContext() == this &&
453         "conversion function does not belong to this record");
454
455  ConvDecl = ConvDecl->getUnderlyingDecl();
456  if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(ConvDecl)) {
457    assert(isa<CXXConversionDecl>(Temp->getTemplatedDecl()));
458  } else {
459    assert(isa<CXXConversionDecl>(ConvDecl));
460  }
461}
462#endif
463
464void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
465  // This operation is O(N) but extremely rare.  Sema only uses it to
466  // remove UsingShadowDecls in a class that were followed by a direct
467  // declaration, e.g.:
468  //   class A : B {
469  //     using B::operator int;
470  //     operator int();
471  //   };
472  // This is uncommon by itself and even more uncommon in conjunction
473  // with sufficiently large numbers of directly-declared conversions
474  // that asymptotic behavior matters.
475
476  UnresolvedSetImpl &Convs = *getConversionFunctions();
477  for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
478    if (Convs[I].getDecl() == ConvDecl) {
479      Convs.erase(I);
480      assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
481             && "conversion was found multiple times in unresolved set");
482      return;
483    }
484  }
485
486  llvm_unreachable("conversion not found in set!");
487}
488
489void CXXRecordDecl::setMethodAsVirtual(FunctionDecl *Method) {
490  Method->setVirtualAsWritten(true);
491  setAggregate(false);
492  setPOD(false);
493  setEmpty(false);
494  setPolymorphic(true);
495  setHasTrivialConstructor(false);
496  setHasTrivialCopyConstructor(false);
497  setHasTrivialCopyAssignment(false);
498}
499
500CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
501  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
502    return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
503
504  return 0;
505}
506
507MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
508  return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
509}
510
511void
512CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
513                                             TemplateSpecializationKind TSK) {
514  assert(TemplateOrInstantiation.isNull() &&
515         "Previous template or instantiation?");
516  assert(!isa<ClassTemplateSpecializationDecl>(this));
517  TemplateOrInstantiation
518    = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
519}
520
521TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
522  if (const ClassTemplateSpecializationDecl *Spec
523        = dyn_cast<ClassTemplateSpecializationDecl>(this))
524    return Spec->getSpecializationKind();
525
526  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
527    return MSInfo->getTemplateSpecializationKind();
528
529  return TSK_Undeclared;
530}
531
532void
533CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
534  if (ClassTemplateSpecializationDecl *Spec
535      = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
536    Spec->setSpecializationKind(TSK);
537    return;
538  }
539
540  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
541    MSInfo->setTemplateSpecializationKind(TSK);
542    return;
543  }
544
545  assert(false && "Not a class template or member class specialization");
546}
547
548CXXConstructorDecl *
549CXXRecordDecl::getDefaultConstructor(ASTContext &Context) {
550  QualType ClassType = Context.getTypeDeclType(this);
551  DeclarationName ConstructorName
552    = Context.DeclarationNames.getCXXConstructorName(
553                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
554
555  DeclContext::lookup_const_iterator Con, ConEnd;
556  for (llvm::tie(Con, ConEnd) = lookup(ConstructorName);
557       Con != ConEnd; ++Con) {
558    // FIXME: In C++0x, a constructor template can be a default constructor.
559    if (isa<FunctionTemplateDecl>(*Con))
560      continue;
561
562    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
563    if (Constructor->isDefaultConstructor())
564      return Constructor;
565  }
566  return 0;
567}
568
569CXXDestructorDecl *CXXRecordDecl::getDestructor(ASTContext &Context) const {
570  QualType ClassType = Context.getTypeDeclType(this);
571
572  DeclarationName Name
573    = Context.DeclarationNames.getCXXDestructorName(
574                                          Context.getCanonicalType(ClassType));
575
576  DeclContext::lookup_const_iterator I, E;
577  llvm::tie(I, E) = lookup(Name);
578  assert(I != E && "Did not find a destructor!");
579
580  CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
581  assert(++I == E && "Found more than one destructor!");
582
583  return Dtor;
584}
585
586CXXMethodDecl *
587CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
588                      SourceLocation L, DeclarationName N,
589                      QualType T, TypeSourceInfo *TInfo,
590                      bool isStatic, bool isInline) {
591  return new (C) CXXMethodDecl(CXXMethod, RD, L, N, T, TInfo,
592                               isStatic, isInline);
593}
594
595bool CXXMethodDecl::isUsualDeallocationFunction() const {
596  if (getOverloadedOperator() != OO_Delete &&
597      getOverloadedOperator() != OO_Array_Delete)
598    return false;
599
600  // C++ [basic.stc.dynamic.deallocation]p2:
601  //   A template instance is never a usual deallocation function,
602  //   regardless of its signature.
603  if (getPrimaryTemplate())
604    return false;
605
606  // C++ [basic.stc.dynamic.deallocation]p2:
607  //   If a class T has a member deallocation function named operator delete
608  //   with exactly one parameter, then that function is a usual (non-placement)
609  //   deallocation function. [...]
610  if (getNumParams() == 1)
611    return true;
612
613  // C++ [basic.stc.dynamic.deallocation]p2:
614  //   [...] If class T does not declare such an operator delete but does
615  //   declare a member deallocation function named operator delete with
616  //   exactly two parameters, the second of which has type std::size_t (18.1),
617  //   then this function is a usual deallocation function.
618  ASTContext &Context = getASTContext();
619  if (getNumParams() != 2 ||
620      !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
621                                      Context.getSizeType()))
622    return false;
623
624  // This function is a usual deallocation function if there are no
625  // single-parameter deallocation functions of the same kind.
626  for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
627       R.first != R.second; ++R.first) {
628    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
629      if (FD->getNumParams() == 1)
630        return false;
631  }
632
633  return true;
634}
635
636void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
637  assert(MD->isCanonicalDecl() && "Method is not canonical!");
638  assert(!MD->getParent()->isDependentContext() &&
639         "Can't add an overridden method to a class template!");
640
641  getASTContext().addOverriddenMethod(this, MD);
642}
643
644CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
645  return getASTContext().overridden_methods_begin(this);
646}
647
648CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
649  return getASTContext().overridden_methods_end(this);
650}
651
652QualType CXXMethodDecl::getThisType(ASTContext &C) const {
653  // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
654  // If the member function is declared const, the type of this is const X*,
655  // if the member function is declared volatile, the type of this is
656  // volatile X*, and if the member function is declared const volatile,
657  // the type of this is const volatile X*.
658
659  assert(isInstance() && "No 'this' for static methods!");
660
661  QualType ClassTy = C.getTypeDeclType(getParent());
662
663  // Aesthetically we prefer not to synthesize a type as the
664  // InjectedClassNameType of a template pattern: injected class names
665  // are printed without template arguments, which might
666  // surprise/confuse/distract our poor users if they didn't
667  // explicitly write one.
668  if (isa<InjectedClassNameType>(ClassTy))
669    ClassTy = cast<InjectedClassNameType>(ClassTy)->getUnderlyingType();
670
671  ClassTy = C.getQualifiedType(ClassTy,
672                               Qualifiers::fromCVRMask(getTypeQualifiers()));
673  return C.getPointerType(ClassTy);
674}
675
676bool CXXMethodDecl::hasInlineBody() const {
677  // If this function is a template instantiation, look at the template from
678  // which it was instantiated.
679  const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
680  if (!CheckFn)
681    CheckFn = this;
682
683  const FunctionDecl *fn;
684  return CheckFn->getBody(fn) && !fn->isOutOfLine();
685}
686
687CXXBaseOrMemberInitializer::
688CXXBaseOrMemberInitializer(ASTContext &Context,
689                           TypeSourceInfo *TInfo, bool IsVirtual,
690                           SourceLocation L, Expr *Init, SourceLocation R)
691  : BaseOrMember(TInfo), Init(Init), AnonUnionMember(0), IsVirtual(IsVirtual),
692    LParenLoc(L), RParenLoc(R)
693{
694}
695
696CXXBaseOrMemberInitializer::
697CXXBaseOrMemberInitializer(ASTContext &Context,
698                           FieldDecl *Member, SourceLocation MemberLoc,
699                           SourceLocation L, Expr *Init, SourceLocation R)
700  : BaseOrMember(Member), MemberLocation(MemberLoc), Init(Init),
701    AnonUnionMember(0), LParenLoc(L), RParenLoc(R)
702{
703}
704
705void CXXBaseOrMemberInitializer::Destroy(ASTContext &Context) {
706  if (Init)
707    Init->Destroy(Context);
708  this->~CXXBaseOrMemberInitializer();
709}
710
711TypeLoc CXXBaseOrMemberInitializer::getBaseClassLoc() const {
712  if (isBaseInitializer())
713    return BaseOrMember.get<TypeSourceInfo*>()->getTypeLoc();
714  else
715    return TypeLoc();
716}
717
718Type *CXXBaseOrMemberInitializer::getBaseClass() {
719  if (isBaseInitializer())
720    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
721  else
722    return 0;
723}
724
725const Type *CXXBaseOrMemberInitializer::getBaseClass() const {
726  if (isBaseInitializer())
727    return BaseOrMember.get<TypeSourceInfo*>()->getType().getTypePtr();
728  else
729    return 0;
730}
731
732SourceLocation CXXBaseOrMemberInitializer::getSourceLocation() const {
733  if (isMemberInitializer())
734    return getMemberLocation();
735
736  return getBaseClassLoc().getSourceRange().getBegin();
737}
738
739SourceRange CXXBaseOrMemberInitializer::getSourceRange() const {
740  return SourceRange(getSourceLocation(), getRParenLoc());
741}
742
743CXXConstructorDecl *
744CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
745                           SourceLocation L, DeclarationName N,
746                           QualType T, TypeSourceInfo *TInfo,
747                           bool isExplicit,
748                           bool isInline, bool isImplicitlyDeclared) {
749  assert(N.getNameKind() == DeclarationName::CXXConstructorName &&
750         "Name must refer to a constructor");
751  return new (C) CXXConstructorDecl(RD, L, N, T, TInfo, isExplicit, isInline,
752                                      isImplicitlyDeclared);
753}
754
755bool CXXConstructorDecl::isDefaultConstructor() const {
756  // C++ [class.ctor]p5:
757  //   A default constructor for a class X is a constructor of class
758  //   X that can be called without an argument.
759  return (getNumParams() == 0) ||
760         (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
761}
762
763bool
764CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
765  // C++ [class.copy]p2:
766  //   A non-template constructor for class X is a copy constructor
767  //   if its first parameter is of type X&, const X&, volatile X& or
768  //   const volatile X&, and either there are no other parameters
769  //   or else all other parameters have default arguments (8.3.6).
770  if ((getNumParams() < 1) ||
771      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
772      (getPrimaryTemplate() != 0) ||
773      (getDescribedFunctionTemplate() != 0))
774    return false;
775
776  const ParmVarDecl *Param = getParamDecl(0);
777
778  // Do we have a reference type? Rvalue references don't count.
779  const LValueReferenceType *ParamRefType =
780    Param->getType()->getAs<LValueReferenceType>();
781  if (!ParamRefType)
782    return false;
783
784  // Is it a reference to our class type?
785  ASTContext &Context = getASTContext();
786
787  CanQualType PointeeType
788    = Context.getCanonicalType(ParamRefType->getPointeeType());
789  CanQualType ClassTy
790    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
791  if (PointeeType.getUnqualifiedType() != ClassTy)
792    return false;
793
794  // FIXME: other qualifiers?
795
796  // We have a copy constructor.
797  TypeQuals = PointeeType.getCVRQualifiers();
798  return true;
799}
800
801bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
802  // C++ [class.conv.ctor]p1:
803  //   A constructor declared without the function-specifier explicit
804  //   that can be called with a single parameter specifies a
805  //   conversion from the type of its first parameter to the type of
806  //   its class. Such a constructor is called a converting
807  //   constructor.
808  if (isExplicit() && !AllowExplicit)
809    return false;
810
811  return (getNumParams() == 0 &&
812          getType()->getAs<FunctionProtoType>()->isVariadic()) ||
813         (getNumParams() == 1) ||
814         (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
815}
816
817bool CXXConstructorDecl::isCopyConstructorLikeSpecialization() const {
818  if ((getNumParams() < 1) ||
819      (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
820      (getPrimaryTemplate() == 0) ||
821      (getDescribedFunctionTemplate() != 0))
822    return false;
823
824  const ParmVarDecl *Param = getParamDecl(0);
825
826  ASTContext &Context = getASTContext();
827  CanQualType ParamType = Context.getCanonicalType(Param->getType());
828
829  // Strip off the lvalue reference, if any.
830  if (CanQual<LValueReferenceType> ParamRefType
831                                    = ParamType->getAs<LValueReferenceType>())
832    ParamType = ParamRefType->getPointeeType();
833
834
835  // Is it the same as our our class type?
836  CanQualType ClassTy
837    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
838  if (ParamType.getUnqualifiedType() != ClassTy)
839    return false;
840
841  return true;
842}
843
844CXXDestructorDecl *
845CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
846                          SourceLocation L, DeclarationName N,
847                          QualType T, bool isInline,
848                          bool isImplicitlyDeclared) {
849  assert(N.getNameKind() == DeclarationName::CXXDestructorName &&
850         "Name must refer to a destructor");
851  return new (C) CXXDestructorDecl(RD, L, N, T, isInline,
852                                   isImplicitlyDeclared);
853}
854
855void
856CXXConstructorDecl::Destroy(ASTContext& C) {
857  C.Deallocate(BaseOrMemberInitializers);
858  CXXMethodDecl::Destroy(C);
859}
860
861CXXConversionDecl *
862CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
863                          SourceLocation L, DeclarationName N,
864                          QualType T, TypeSourceInfo *TInfo,
865                          bool isInline, bool isExplicit) {
866  assert(N.getNameKind() == DeclarationName::CXXConversionFunctionName &&
867         "Name must refer to a conversion function");
868  return new (C) CXXConversionDecl(RD, L, N, T, TInfo, isInline, isExplicit);
869}
870
871LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
872                                         DeclContext *DC,
873                                         SourceLocation L,
874                                         LanguageIDs Lang, bool Braces) {
875  return new (C) LinkageSpecDecl(DC, L, Lang, Braces);
876}
877
878UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
879                                               SourceLocation L,
880                                               SourceLocation NamespaceLoc,
881                                               SourceRange QualifierRange,
882                                               NestedNameSpecifier *Qualifier,
883                                               SourceLocation IdentLoc,
884                                               NamedDecl *Used,
885                                               DeclContext *CommonAncestor) {
886  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
887    Used = NS->getOriginalNamespace();
888  return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierRange,
889                                    Qualifier, IdentLoc, Used, CommonAncestor);
890}
891
892NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
893  if (NamespaceAliasDecl *NA =
894        dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
895    return NA->getNamespace();
896  return cast_or_null<NamespaceDecl>(NominatedNamespace);
897}
898
899NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
900                                               SourceLocation L,
901                                               SourceLocation AliasLoc,
902                                               IdentifierInfo *Alias,
903                                               SourceRange QualifierRange,
904                                               NestedNameSpecifier *Qualifier,
905                                               SourceLocation IdentLoc,
906                                               NamedDecl *Namespace) {
907  if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
908    Namespace = NS->getOriginalNamespace();
909  return new (C) NamespaceAliasDecl(DC, L, AliasLoc, Alias, QualifierRange,
910                                    Qualifier, IdentLoc, Namespace);
911}
912
913UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC,
914      SourceLocation L, SourceRange NNR, SourceLocation UL,
915      NestedNameSpecifier* TargetNNS, DeclarationName Name,
916      bool IsTypeNameArg) {
917  return new (C) UsingDecl(DC, L, NNR, UL, TargetNNS, Name, IsTypeNameArg);
918}
919
920UnresolvedUsingValueDecl *
921UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
922                                 SourceLocation UsingLoc,
923                                 SourceRange TargetNNR,
924                                 NestedNameSpecifier *TargetNNS,
925                                 SourceLocation TargetNameLoc,
926                                 DeclarationName TargetName) {
927  return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
928                                          TargetNNR, TargetNNS,
929                                          TargetNameLoc, TargetName);
930}
931
932UnresolvedUsingTypenameDecl *
933UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
934                                    SourceLocation UsingLoc,
935                                    SourceLocation TypenameLoc,
936                                    SourceRange TargetNNR,
937                                    NestedNameSpecifier *TargetNNS,
938                                    SourceLocation TargetNameLoc,
939                                    DeclarationName TargetName) {
940  return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
941                                             TargetNNR, TargetNNS,
942                                             TargetNameLoc,
943                                             TargetName.getAsIdentifierInfo());
944}
945
946StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
947                                           SourceLocation L, Expr *AssertExpr,
948                                           StringLiteral *Message) {
949  return new (C) StaticAssertDecl(DC, L, AssertExpr, Message);
950}
951
952void StaticAssertDecl::Destroy(ASTContext& C) {
953  AssertExpr->Destroy(C);
954  Message->Destroy(C);
955  Decl::Destroy(C);
956}
957
958StaticAssertDecl::~StaticAssertDecl() {
959}
960
961static const char *getAccessName(AccessSpecifier AS) {
962  switch (AS) {
963    default:
964    case AS_none:
965      assert("Invalid access specifier!");
966      return 0;
967    case AS_public:
968      return "public";
969    case AS_private:
970      return "private";
971    case AS_protected:
972      return "protected";
973  }
974}
975
976const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
977                                           AccessSpecifier AS) {
978  return DB << getAccessName(AS);
979}
980
981
982