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