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