]> CyberLeo.Net >> Repos - FreeBSD/releng/9.1.git/blob - contrib/llvm/tools/clang/lib/AST/DeclCXX.cpp
Copy stable/9 to releng/9.1 as part of the 9.1-RELEASE release process.
[FreeBSD/releng/9.1.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/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Basic/IdentifierTable.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 using namespace clang;
26
27 //===----------------------------------------------------------------------===//
28 // Decl Allocation/Deallocation Method Implementations
29 //===----------------------------------------------------------------------===//
30
31 void AccessSpecDecl::anchor() { }
32
33 AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
34   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(AccessSpecDecl));
35   return new (Mem) AccessSpecDecl(EmptyShell());
36 }
37
38 CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
39   : UserDeclaredConstructor(false), UserDeclaredCopyConstructor(false),
40     UserDeclaredMoveConstructor(false), UserDeclaredCopyAssignment(false),
41     UserDeclaredMoveAssignment(false), UserDeclaredDestructor(false),
42     Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
43     Abstract(false), IsStandardLayout(true), HasNoNonEmptyBases(true),
44     HasPrivateFields(false), HasProtectedFields(false), HasPublicFields(false),
45     HasMutableFields(false), HasOnlyCMembers(true),
46     HasTrivialDefaultConstructor(true),
47     HasConstexprNonCopyMoveConstructor(false),
48     DefaultedDefaultConstructorIsConstexpr(true),
49     DefaultedCopyConstructorIsConstexpr(true),
50     DefaultedMoveConstructorIsConstexpr(true),
51     HasConstexprDefaultConstructor(false), HasConstexprCopyConstructor(false),
52     HasConstexprMoveConstructor(false), HasTrivialCopyConstructor(true),
53     HasTrivialMoveConstructor(true), HasTrivialCopyAssignment(true),
54     HasTrivialMoveAssignment(true), HasTrivialDestructor(true),
55     HasIrrelevantDestructor(true),
56     HasNonLiteralTypeFieldsOrBases(false), ComputedVisibleConversions(false),
57     UserProvidedDefaultConstructor(false), DeclaredDefaultConstructor(false),
58     DeclaredCopyConstructor(false), DeclaredMoveConstructor(false),
59     DeclaredCopyAssignment(false), DeclaredMoveAssignment(false),
60     DeclaredDestructor(false), FailedImplicitMoveConstructor(false),
61     FailedImplicitMoveAssignment(false), IsLambda(false), NumBases(0),
62     NumVBases(0), Bases(), VBases(), Definition(D), FirstFriend(0) {
63 }
64
65 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, DeclContext *DC,
66                              SourceLocation StartLoc, SourceLocation IdLoc,
67                              IdentifierInfo *Id, CXXRecordDecl *PrevDecl)
68   : RecordDecl(K, TK, DC, StartLoc, IdLoc, Id, PrevDecl),
69     DefinitionData(PrevDecl ? PrevDecl->DefinitionData : 0),
70     TemplateOrInstantiation() { }
71
72 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
73                                      DeclContext *DC, SourceLocation StartLoc,
74                                      SourceLocation IdLoc, IdentifierInfo *Id,
75                                      CXXRecordDecl* PrevDecl,
76                                      bool DelayTypeCreation) {
77   CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TK, DC, StartLoc, IdLoc,
78                                            Id, PrevDecl);
79
80   // FIXME: DelayTypeCreation seems like such a hack
81   if (!DelayTypeCreation)
82     C.getTypeDeclType(R, PrevDecl);
83   return R;
84 }
85
86 CXXRecordDecl *CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
87                                            SourceLocation Loc, bool Dependent) {
88   CXXRecordDecl* R = new (C) CXXRecordDecl(CXXRecord, TTK_Class, DC, Loc, Loc,
89                                            0, 0);
90   R->IsBeingDefined = true;
91   R->DefinitionData = new (C) struct LambdaDefinitionData(R, Dependent);
92   C.getTypeDeclType(R, /*PrevDecl=*/0);
93   return R;
94 }
95
96 CXXRecordDecl *
97 CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
98   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXRecordDecl));
99   return new (Mem) CXXRecordDecl(CXXRecord, TTK_Struct, 0, SourceLocation(),
100                                  SourceLocation(), 0, 0);
101 }
102
103 void
104 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
105                         unsigned NumBases) {
106   ASTContext &C = getASTContext();
107
108   if (!data().Bases.isOffset() && data().NumBases > 0)
109     C.Deallocate(data().getBases());
110
111   if (NumBases) {
112     // C++ [dcl.init.aggr]p1:
113     //   An aggregate is [...] a class with [...] no base classes [...].
114     data().Aggregate = false;
115
116     // C++ [class]p4:
117     //   A POD-struct is an aggregate class...
118     data().PlainOldData = false;
119   }
120
121   // The set of seen virtual base types.
122   llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
123   
124   // The virtual bases of this class.
125   SmallVector<const CXXBaseSpecifier *, 8> VBases;
126
127   data().Bases = new(C) CXXBaseSpecifier [NumBases];
128   data().NumBases = NumBases;
129   for (unsigned i = 0; i < NumBases; ++i) {
130     data().getBases()[i] = *Bases[i];
131     // Keep track of inherited vbases for this base class.
132     const CXXBaseSpecifier *Base = Bases[i];
133     QualType BaseType = Base->getType();
134     // Skip dependent types; we can't do any checking on them now.
135     if (BaseType->isDependentType())
136       continue;
137     CXXRecordDecl *BaseClassDecl
138       = cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
139
140     // A class with a non-empty base class is not empty.
141     // FIXME: Standard ref?
142     if (!BaseClassDecl->isEmpty()) {
143       if (!data().Empty) {
144         // C++0x [class]p7:
145         //   A standard-layout class is a class that:
146         //    [...]
147         //    -- either has no non-static data members in the most derived
148         //       class and at most one base class with non-static data members,
149         //       or has no base classes with non-static data members, and
150         // If this is the second non-empty base, then neither of these two
151         // clauses can be true.
152         data().IsStandardLayout = false;
153       }
154
155       data().Empty = false;
156       data().HasNoNonEmptyBases = false;
157     }
158     
159     // C++ [class.virtual]p1:
160     //   A class that declares or inherits a virtual function is called a 
161     //   polymorphic class.
162     if (BaseClassDecl->isPolymorphic())
163       data().Polymorphic = true;
164
165     // C++0x [class]p7:
166     //   A standard-layout class is a class that: [...]
167     //    -- has no non-standard-layout base classes
168     if (!BaseClassDecl->isStandardLayout())
169       data().IsStandardLayout = false;
170
171     // Record if this base is the first non-literal field or base.
172     if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType())
173       data().HasNonLiteralTypeFieldsOrBases = true;
174     
175     // Now go through all virtual bases of this base and add them.
176     for (CXXRecordDecl::base_class_iterator VBase =
177           BaseClassDecl->vbases_begin(),
178          E = BaseClassDecl->vbases_end(); VBase != E; ++VBase) {
179       // Add this base if it's not already in the list.
180       if (SeenVBaseTypes.insert(C.getCanonicalType(VBase->getType())))
181         VBases.push_back(VBase);
182     }
183
184     if (Base->isVirtual()) {
185       // Add this base if it's not already in the list.
186       if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)))
187           VBases.push_back(Base);
188       
189       // C++0x [meta.unary.prop] is_empty:
190       //    T is a class type, but not a union type, with ... no virtual base
191       //    classes
192       data().Empty = false;
193       
194       // C++ [class.ctor]p5:
195       //   A default constructor is trivial [...] if:
196       //    -- its class has [...] no virtual bases
197       data().HasTrivialDefaultConstructor = false;
198
199       // C++0x [class.copy]p13:
200       //   A copy/move constructor for class X is trivial if it is neither
201       //   user-provided nor deleted and if
202       //    -- class X has no virtual functions and no virtual base classes, and
203       data().HasTrivialCopyConstructor = false;
204       data().HasTrivialMoveConstructor = false;
205
206       // C++0x [class.copy]p27:
207       //   A copy/move assignment operator for class X is trivial if it is
208       //   neither user-provided nor deleted and if
209       //    -- class X has no virtual functions and no virtual base classes, and
210       data().HasTrivialCopyAssignment = false;
211       data().HasTrivialMoveAssignment = false;
212
213       // C++0x [class]p7:
214       //   A standard-layout class is a class that: [...]
215       //    -- has [...] no virtual base classes
216       data().IsStandardLayout = false;
217
218       // C++11 [dcl.constexpr]p4:
219       //   In the definition of a constexpr constructor [...]
220       //    -- the class shall not have any virtual base classes
221       data().DefaultedDefaultConstructorIsConstexpr = false;
222       data().DefaultedCopyConstructorIsConstexpr = false;
223       data().DefaultedMoveConstructorIsConstexpr = false;
224     } else {
225       // C++ [class.ctor]p5:
226       //   A default constructor is trivial [...] if:
227       //    -- all the direct base classes of its class have trivial default
228       //       constructors.
229       if (!BaseClassDecl->hasTrivialDefaultConstructor())
230         data().HasTrivialDefaultConstructor = false;
231       
232       // C++0x [class.copy]p13:
233       //   A copy/move constructor for class X is trivial if [...]
234       //    [...]
235       //    -- the constructor selected to copy/move each direct base class
236       //       subobject is trivial, and
237       // FIXME: C++0x: We need to only consider the selected constructor
238       // instead of all of them.
239       if (!BaseClassDecl->hasTrivialCopyConstructor())
240         data().HasTrivialCopyConstructor = false;
241       if (!BaseClassDecl->hasTrivialMoveConstructor())
242         data().HasTrivialMoveConstructor = false;
243
244       // C++0x [class.copy]p27:
245       //   A copy/move assignment operator for class X is trivial if [...]
246       //    [...]
247       //    -- the assignment operator selected to copy/move each direct base
248       //       class subobject is trivial, and
249       // FIXME: C++0x: We need to only consider the selected operator instead
250       // of all of them.
251       if (!BaseClassDecl->hasTrivialCopyAssignment())
252         data().HasTrivialCopyAssignment = false;
253       if (!BaseClassDecl->hasTrivialMoveAssignment())
254         data().HasTrivialMoveAssignment = false;
255
256       // C++11 [class.ctor]p6:
257       //   If that user-written default constructor would satisfy the
258       //   requirements of a constexpr constructor, the implicitly-defined
259       //   default constructor is constexpr.
260       if (!BaseClassDecl->hasConstexprDefaultConstructor())
261         data().DefaultedDefaultConstructorIsConstexpr = false;
262
263       // C++11 [class.copy]p13:
264       //   If the implicitly-defined constructor would satisfy the requirements
265       //   of a constexpr constructor, the implicitly-defined constructor is
266       //   constexpr.
267       // C++11 [dcl.constexpr]p4:
268       //    -- every constructor involved in initializing [...] base class
269       //       sub-objects shall be a constexpr constructor
270       if (!BaseClassDecl->hasConstexprCopyConstructor())
271         data().DefaultedCopyConstructorIsConstexpr = false;
272       if (BaseClassDecl->hasDeclaredMoveConstructor() ||
273           BaseClassDecl->needsImplicitMoveConstructor())
274         // FIXME: If the implicit move constructor generated for the base class
275         // would be ill-formed, the implicit move constructor generated for the
276         // derived class calls the base class' copy constructor.
277         data().DefaultedMoveConstructorIsConstexpr &=
278           BaseClassDecl->hasConstexprMoveConstructor();
279       else if (!BaseClassDecl->hasConstexprCopyConstructor())
280         data().DefaultedMoveConstructorIsConstexpr = false;
281     }
282     
283     // C++ [class.ctor]p3:
284     //   A destructor is trivial if all the direct base classes of its class
285     //   have trivial destructors.
286     if (!BaseClassDecl->hasTrivialDestructor())
287       data().HasTrivialDestructor = false;
288
289     if (!BaseClassDecl->hasIrrelevantDestructor())
290       data().HasIrrelevantDestructor = false;
291
292     // A class has an Objective-C object member if... or any of its bases
293     // has an Objective-C object member.
294     if (BaseClassDecl->hasObjectMember())
295       setHasObjectMember(true);
296
297     // Keep track of the presence of mutable fields.
298     if (BaseClassDecl->hasMutableFields())
299       data().HasMutableFields = true;
300   }
301   
302   if (VBases.empty())
303     return;
304
305   // Create base specifier for any direct or indirect virtual bases.
306   data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
307   data().NumVBases = VBases.size();
308   for (int I = 0, E = VBases.size(); I != E; ++I)
309     data().getVBases()[I] = *VBases[I];
310 }
311
312 /// Callback function for CXXRecordDecl::forallBases that acknowledges
313 /// that it saw a base class.
314 static bool SawBase(const CXXRecordDecl *, void *) {
315   return true;
316 }
317
318 bool CXXRecordDecl::hasAnyDependentBases() const {
319   if (!isDependentContext())
320     return false;
321
322   return !forallBases(SawBase, 0);
323 }
324
325 bool CXXRecordDecl::hasConstCopyConstructor() const {
326   return getCopyConstructor(Qualifiers::Const) != 0;
327 }
328
329 bool CXXRecordDecl::isTriviallyCopyable() const {
330   // C++0x [class]p5:
331   //   A trivially copyable class is a class that:
332   //   -- has no non-trivial copy constructors,
333   if (!hasTrivialCopyConstructor()) return false;
334   //   -- has no non-trivial move constructors,
335   if (!hasTrivialMoveConstructor()) return false;
336   //   -- has no non-trivial copy assignment operators,
337   if (!hasTrivialCopyAssignment()) return false;
338   //   -- has no non-trivial move assignment operators, and
339   if (!hasTrivialMoveAssignment()) return false;
340   //   -- has a trivial destructor.
341   if (!hasTrivialDestructor()) return false;
342
343   return true;
344 }
345
346 /// \brief Perform a simplistic form of overload resolution that only considers
347 /// cv-qualifiers on a single parameter, and return the best overload candidate
348 /// (if there is one).
349 static CXXMethodDecl *
350 GetBestOverloadCandidateSimple(
351   const SmallVectorImpl<std::pair<CXXMethodDecl *, Qualifiers> > &Cands) {
352   if (Cands.empty())
353     return 0;
354   if (Cands.size() == 1)
355     return Cands[0].first;
356   
357   unsigned Best = 0, N = Cands.size();
358   for (unsigned I = 1; I != N; ++I)
359     if (Cands[Best].second.compatiblyIncludes(Cands[I].second))
360       Best = I;
361   
362   for (unsigned I = 1; I != N; ++I)
363     if (Cands[Best].second.compatiblyIncludes(Cands[I].second))
364       return 0;
365   
366   return Cands[Best].first;
367 }
368
369 CXXConstructorDecl *CXXRecordDecl::getCopyConstructor(unsigned TypeQuals) const{
370   ASTContext &Context = getASTContext();
371   QualType ClassType
372     = Context.getTypeDeclType(const_cast<CXXRecordDecl*>(this));
373   DeclarationName ConstructorName
374     = Context.DeclarationNames.getCXXConstructorName(
375                                           Context.getCanonicalType(ClassType));
376   unsigned FoundTQs;
377   SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
378   DeclContext::lookup_const_iterator Con, ConEnd;
379   for (llvm::tie(Con, ConEnd) = this->lookup(ConstructorName);
380        Con != ConEnd; ++Con) {
381     // C++ [class.copy]p2:
382     //   A non-template constructor for class X is a copy constructor if [...]
383     if (isa<FunctionTemplateDecl>(*Con))
384       continue;
385
386     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
387     if (Constructor->isCopyConstructor(FoundTQs)) {
388       if (((TypeQuals & Qualifiers::Const) == (FoundTQs & Qualifiers::Const)) ||
389           (!(TypeQuals & Qualifiers::Const) && (FoundTQs & Qualifiers::Const)))
390         Found.push_back(std::make_pair(
391                                  const_cast<CXXConstructorDecl *>(Constructor), 
392                                        Qualifiers::fromCVRMask(FoundTQs)));
393     }
394   }
395   
396   return cast_or_null<CXXConstructorDecl>(
397                                         GetBestOverloadCandidateSimple(Found));
398 }
399
400 CXXConstructorDecl *CXXRecordDecl::getMoveConstructor() const {
401   for (ctor_iterator I = ctor_begin(), E = ctor_end(); I != E; ++I)
402     if (I->isMoveConstructor())
403       return *I;
404
405   return 0;
406 }
407
408 CXXMethodDecl *CXXRecordDecl::getCopyAssignmentOperator(bool ArgIsConst) const {
409   ASTContext &Context = getASTContext();
410   QualType Class = Context.getTypeDeclType(const_cast<CXXRecordDecl *>(this));
411   DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
412   
413   SmallVector<std::pair<CXXMethodDecl *, Qualifiers>, 4> Found;
414   DeclContext::lookup_const_iterator Op, OpEnd;
415   for (llvm::tie(Op, OpEnd) = this->lookup(Name); Op != OpEnd; ++Op) {
416     // C++ [class.copy]p9:
417     //   A user-declared copy assignment operator is a non-static non-template
418     //   member function of class X with exactly one parameter of type X, X&,
419     //   const X&, volatile X& or const volatile X&.
420     const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
421     if (!Method || Method->isStatic() || Method->getPrimaryTemplate())
422       continue;
423     
424     const FunctionProtoType *FnType 
425       = Method->getType()->getAs<FunctionProtoType>();
426     assert(FnType && "Overloaded operator has no prototype.");
427     // Don't assert on this; an invalid decl might have been left in the AST.
428     if (FnType->getNumArgs() != 1 || FnType->isVariadic())
429       continue;
430     
431     QualType ArgType = FnType->getArgType(0);
432     Qualifiers Quals;
433     if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()) {
434       ArgType = Ref->getPointeeType();
435       // If we have a const argument and we have a reference to a non-const,
436       // this function does not match.
437       if (ArgIsConst && !ArgType.isConstQualified())
438         continue;
439       
440       Quals = ArgType.getQualifiers();
441     } else {
442       // By-value copy-assignment operators are treated like const X&
443       // copy-assignment operators.
444       Quals = Qualifiers::fromCVRMask(Qualifiers::Const);
445     }
446     
447     if (!Context.hasSameUnqualifiedType(ArgType, Class))
448       continue;
449
450     // Save this copy-assignment operator. It might be "the one".
451     Found.push_back(std::make_pair(const_cast<CXXMethodDecl *>(Method), Quals));
452   }
453   
454   // Use a simplistic form of overload resolution to find the candidate.
455   return GetBestOverloadCandidateSimple(Found);
456 }
457
458 CXXMethodDecl *CXXRecordDecl::getMoveAssignmentOperator() const {
459   for (method_iterator I = method_begin(), E = method_end(); I != E; ++I)
460     if (I->isMoveAssignmentOperator())
461       return *I;
462
463   return 0;
464 }
465
466 void CXXRecordDecl::markedVirtualFunctionPure() {
467   // C++ [class.abstract]p2: 
468   //   A class is abstract if it has at least one pure virtual function.
469   data().Abstract = true;
470 }
471
472 void CXXRecordDecl::addedMember(Decl *D) {
473   if (!D->isImplicit() &&
474       !isa<FieldDecl>(D) &&
475       !isa<IndirectFieldDecl>(D) &&
476       (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class))
477     data().HasOnlyCMembers = false;
478
479   // Ignore friends and invalid declarations.
480   if (D->getFriendObjectKind() || D->isInvalidDecl())
481     return;
482   
483   FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
484   if (FunTmpl)
485     D = FunTmpl->getTemplatedDecl();
486   
487   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
488     if (Method->isVirtual()) {
489       // C++ [dcl.init.aggr]p1:
490       //   An aggregate is an array or a class with [...] no virtual functions.
491       data().Aggregate = false;
492       
493       // C++ [class]p4:
494       //   A POD-struct is an aggregate class...
495       data().PlainOldData = false;
496       
497       // Virtual functions make the class non-empty.
498       // FIXME: Standard ref?
499       data().Empty = false;
500
501       // C++ [class.virtual]p1:
502       //   A class that declares or inherits a virtual function is called a 
503       //   polymorphic class.
504       data().Polymorphic = true;
505       
506       // C++0x [class.ctor]p5
507       //   A default constructor is trivial [...] if:
508       //    -- its class has no virtual functions [...]
509       data().HasTrivialDefaultConstructor = false;
510
511       // C++0x [class.copy]p13:
512       //   A copy/move constructor for class X is trivial if [...]
513       //    -- class X has no virtual functions [...]
514       data().HasTrivialCopyConstructor = false;
515       data().HasTrivialMoveConstructor = false;
516
517       // C++0x [class.copy]p27:
518       //   A copy/move assignment operator for class X is trivial if [...]
519       //    -- class X has no virtual functions [...]
520       data().HasTrivialCopyAssignment = false;
521       data().HasTrivialMoveAssignment = false;
522             
523       // C++0x [class]p7:
524       //   A standard-layout class is a class that: [...]
525       //    -- has no virtual functions
526       data().IsStandardLayout = false;
527     }
528   }
529   
530   if (D->isImplicit()) {
531     // Notify that an implicit member was added after the definition
532     // was completed.
533     if (!isBeingDefined())
534       if (ASTMutationListener *L = getASTMutationListener())
535         L->AddedCXXImplicitMember(data().Definition, D);
536
537     // If this is a special member function, note that it was added and then
538     // return early.
539     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
540       if (Constructor->isDefaultConstructor()) {
541         data().DeclaredDefaultConstructor = true;
542         if (Constructor->isConstexpr()) {
543           data().HasConstexprDefaultConstructor = true;
544           data().HasConstexprNonCopyMoveConstructor = true;
545         }
546       } else if (Constructor->isCopyConstructor()) {
547         data().DeclaredCopyConstructor = true;
548         if (Constructor->isConstexpr())
549           data().HasConstexprCopyConstructor = true;
550       } else if (Constructor->isMoveConstructor()) {
551         data().DeclaredMoveConstructor = true;
552         if (Constructor->isConstexpr())
553           data().HasConstexprMoveConstructor = true;
554       } else
555         goto NotASpecialMember;
556       return;
557     } else if (isa<CXXDestructorDecl>(D)) {
558       data().DeclaredDestructor = true;
559       return;
560     } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
561       if (Method->isCopyAssignmentOperator())
562         data().DeclaredCopyAssignment = true;
563       else if (Method->isMoveAssignmentOperator())
564         data().DeclaredMoveAssignment = true;
565       else
566         goto NotASpecialMember;
567       return;
568     }
569
570 NotASpecialMember:;
571     // Any other implicit declarations are handled like normal declarations.
572   }
573   
574   // Handle (user-declared) constructors.
575   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
576     // Note that we have a user-declared constructor.
577     data().UserDeclaredConstructor = true;
578
579     // Technically, "user-provided" is only defined for special member
580     // functions, but the intent of the standard is clearly that it should apply
581     // to all functions.
582     bool UserProvided = Constructor->isUserProvided();
583
584     if (Constructor->isDefaultConstructor()) {
585       data().DeclaredDefaultConstructor = true;
586       if (UserProvided) {
587         // C++0x [class.ctor]p5:
588         //   A default constructor is trivial if it is not user-provided [...]
589         data().HasTrivialDefaultConstructor = false;
590         data().UserProvidedDefaultConstructor = true;
591       }
592       if (Constructor->isConstexpr()) {
593         data().HasConstexprDefaultConstructor = true;
594         data().HasConstexprNonCopyMoveConstructor = true;
595       }
596     }
597
598     // Note when we have a user-declared copy or move constructor, which will
599     // suppress the implicit declaration of those constructors.
600     if (!FunTmpl) {
601       if (Constructor->isCopyConstructor()) {
602         data().UserDeclaredCopyConstructor = true;
603         data().DeclaredCopyConstructor = true;
604
605         // C++0x [class.copy]p13:
606         //   A copy/move constructor for class X is trivial if it is not
607         //   user-provided [...]
608         if (UserProvided)
609           data().HasTrivialCopyConstructor = false;
610
611         if (Constructor->isConstexpr())
612           data().HasConstexprCopyConstructor = true;
613       } else if (Constructor->isMoveConstructor()) {
614         data().UserDeclaredMoveConstructor = true;
615         data().DeclaredMoveConstructor = true;
616
617         // C++0x [class.copy]p13:
618         //   A copy/move constructor for class X is trivial if it is not
619         //   user-provided [...]
620         if (UserProvided)
621           data().HasTrivialMoveConstructor = false;
622
623         if (Constructor->isConstexpr())
624           data().HasConstexprMoveConstructor = true;
625       }
626     }
627     if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor()) {
628       // Record if we see any constexpr constructors which are neither copy
629       // nor move constructors.
630       data().HasConstexprNonCopyMoveConstructor = true;
631     }
632
633     // C++ [dcl.init.aggr]p1:
634     //   An aggregate is an array or a class with no user-declared
635     //   constructors [...].
636     // C++0x [dcl.init.aggr]p1:
637     //   An aggregate is an array or a class with no user-provided
638     //   constructors [...].
639     if (!getASTContext().getLangOpts().CPlusPlus0x || UserProvided)
640       data().Aggregate = false;
641
642     // C++ [class]p4:
643     //   A POD-struct is an aggregate class [...]
644     // Since the POD bit is meant to be C++03 POD-ness, clear it even if the
645     // type is technically an aggregate in C++0x since it wouldn't be in 03.
646     data().PlainOldData = false;
647
648     return;
649   }
650
651   // Handle (user-declared) destructors.
652   if (CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) {
653     data().DeclaredDestructor = true;
654     data().UserDeclaredDestructor = true;
655     data().HasIrrelevantDestructor = false;
656
657     // C++ [class]p4: 
658     //   A POD-struct is an aggregate class that has [...] no user-defined 
659     //   destructor.
660     // This bit is the C++03 POD bit, not the 0x one.
661     data().PlainOldData = false;
662     
663     // C++11 [class.dtor]p5: 
664     //   A destructor is trivial if it is not user-provided and if
665     //    -- the destructor is not virtual.
666     if (DD->isUserProvided() || DD->isVirtual()) {
667       data().HasTrivialDestructor = false;
668       // C++11 [dcl.constexpr]p1:
669       //   The constexpr specifier shall be applied only to [...] the
670       //   declaration of a static data member of a literal type.
671       // C++11 [basic.types]p10:
672       //   A type is a literal type if it is [...] a class type that [...] has
673       //   a trivial destructor.
674       data().DefaultedDefaultConstructorIsConstexpr = false;
675       data().DefaultedCopyConstructorIsConstexpr = false;
676       data().DefaultedMoveConstructorIsConstexpr = false;
677     }
678     
679     return;
680   }
681   
682   // Handle (user-declared) member functions.
683   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
684     if (Method->isCopyAssignmentOperator()) {
685       // C++ [class]p4:
686       //   A POD-struct is an aggregate class that [...] has no user-defined
687       //   copy assignment operator [...].
688       // This is the C++03 bit only.
689       data().PlainOldData = false;
690
691       // This is a copy assignment operator.
692
693       // Suppress the implicit declaration of a copy constructor.
694       data().UserDeclaredCopyAssignment = true;
695       data().DeclaredCopyAssignment = true;
696
697       // C++0x [class.copy]p27:
698       //   A copy/move assignment operator for class X is trivial if it is
699       //   neither user-provided nor deleted [...]
700       if (Method->isUserProvided())
701         data().HasTrivialCopyAssignment = false;
702
703       return;
704     }
705     
706     if (Method->isMoveAssignmentOperator()) {
707       // This is an extension in C++03 mode, but we'll keep consistency by
708       // taking a move assignment operator to induce non-POD-ness
709       data().PlainOldData = false;
710
711       // This is a move assignment operator.
712       data().UserDeclaredMoveAssignment = true;
713       data().DeclaredMoveAssignment = true;
714
715       // C++0x [class.copy]p27:
716       //   A copy/move assignment operator for class X is trivial if it is
717       //   neither user-provided nor deleted [...]
718       if (Method->isUserProvided())
719         data().HasTrivialMoveAssignment = false;
720     }
721
722     // Keep the list of conversion functions up-to-date.
723     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
724       // We don't record specializations.
725       if (Conversion->getPrimaryTemplate())
726         return;
727       
728       // FIXME: We intentionally don't use the decl's access here because it
729       // hasn't been set yet.  That's really just a misdesign in Sema.
730
731       if (FunTmpl) {
732         if (FunTmpl->getPreviousDecl())
733           data().Conversions.replace(FunTmpl->getPreviousDecl(),
734                                      FunTmpl);
735         else
736           data().Conversions.addDecl(FunTmpl);
737       } else {
738         if (Conversion->getPreviousDecl())
739           data().Conversions.replace(Conversion->getPreviousDecl(),
740                                      Conversion);
741         else
742           data().Conversions.addDecl(Conversion);        
743       }
744     }
745     
746     return;
747   }
748   
749   // Handle non-static data members.
750   if (FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
751     // C++ [class.bit]p2:
752     //   A declaration for a bit-field that omits the identifier declares an 
753     //   unnamed bit-field. Unnamed bit-fields are not members and cannot be 
754     //   initialized.
755     if (Field->isUnnamedBitfield())
756       return;
757     
758     // C++ [dcl.init.aggr]p1:
759     //   An aggregate is an array or a class (clause 9) with [...] no
760     //   private or protected non-static data members (clause 11).
761     //
762     // A POD must be an aggregate.    
763     if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
764       data().Aggregate = false;
765       data().PlainOldData = false;
766     }
767
768     // C++0x [class]p7:
769     //   A standard-layout class is a class that:
770     //    [...]
771     //    -- has the same access control for all non-static data members,
772     switch (D->getAccess()) {
773     case AS_private:    data().HasPrivateFields = true;   break;
774     case AS_protected:  data().HasProtectedFields = true; break;
775     case AS_public:     data().HasPublicFields = true;    break;
776     case AS_none:       llvm_unreachable("Invalid access specifier");
777     };
778     if ((data().HasPrivateFields + data().HasProtectedFields +
779          data().HasPublicFields) > 1)
780       data().IsStandardLayout = false;
781
782     // Keep track of the presence of mutable fields.
783     if (Field->isMutable())
784       data().HasMutableFields = true;
785     
786     // C++0x [class]p9:
787     //   A POD struct is a class that is both a trivial class and a 
788     //   standard-layout class, and has no non-static data members of type 
789     //   non-POD struct, non-POD union (or array of such types).
790     //
791     // Automatic Reference Counting: the presence of a member of Objective-C pointer type
792     // that does not explicitly have no lifetime makes the class a non-POD.
793     // However, we delay setting PlainOldData to false in this case so that
794     // Sema has a chance to diagnostic causes where the same class will be
795     // non-POD with Automatic Reference Counting but a POD without Instant Objects.
796     // In this case, the class will become a non-POD class when we complete
797     // the definition.
798     ASTContext &Context = getASTContext();
799     QualType T = Context.getBaseElementType(Field->getType());
800     if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
801       if (!Context.getLangOpts().ObjCAutoRefCount ||
802           T.getObjCLifetime() != Qualifiers::OCL_ExplicitNone)
803         setHasObjectMember(true);
804     } else if (!T.isPODType(Context))
805       data().PlainOldData = false;
806     
807     if (T->isReferenceType()) {
808       data().HasTrivialDefaultConstructor = false;
809
810       // C++0x [class]p7:
811       //   A standard-layout class is a class that:
812       //    -- has no non-static data members of type [...] reference,
813       data().IsStandardLayout = false;
814     }
815
816     // Record if this field is the first non-literal or volatile field or base.
817     if (!T->isLiteralType() || T.isVolatileQualified())
818       data().HasNonLiteralTypeFieldsOrBases = true;
819
820     if (Field->hasInClassInitializer()) {
821       // C++0x [class]p5:
822       //   A default constructor is trivial if [...] no non-static data member
823       //   of its class has a brace-or-equal-initializer.
824       data().HasTrivialDefaultConstructor = false;
825
826       // C++0x [dcl.init.aggr]p1:
827       //   An aggregate is a [...] class with [...] no
828       //   brace-or-equal-initializers for non-static data members.
829       data().Aggregate = false;
830
831       // C++0x [class]p10:
832       //   A POD struct is [...] a trivial class.
833       data().PlainOldData = false;
834     }
835
836     if (const RecordType *RecordTy = T->getAs<RecordType>()) {
837       CXXRecordDecl* FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
838       if (FieldRec->getDefinition()) {
839         // C++0x [class.ctor]p5:
840         //   A default constructor is trivial [...] if:
841         //    -- for all the non-static data members of its class that are of
842         //       class type (or array thereof), each such class has a trivial
843         //       default constructor.
844         if (!FieldRec->hasTrivialDefaultConstructor())
845           data().HasTrivialDefaultConstructor = false;
846
847         // C++0x [class.copy]p13:
848         //   A copy/move constructor for class X is trivial if [...]
849         //    [...]
850         //    -- for each non-static data member of X that is of class type (or
851         //       an array thereof), the constructor selected to copy/move that
852         //       member is trivial;
853         // FIXME: C++0x: We don't correctly model 'selected' constructors.
854         if (!FieldRec->hasTrivialCopyConstructor())
855           data().HasTrivialCopyConstructor = false;
856         if (!FieldRec->hasTrivialMoveConstructor())
857           data().HasTrivialMoveConstructor = false;
858
859         // C++0x [class.copy]p27:
860         //   A copy/move assignment operator for class X is trivial if [...]
861         //    [...]
862         //    -- for each non-static data member of X that is of class type (or
863         //       an array thereof), the assignment operator selected to
864         //       copy/move that member is trivial;
865         // FIXME: C++0x: We don't correctly model 'selected' operators.
866         if (!FieldRec->hasTrivialCopyAssignment())
867           data().HasTrivialCopyAssignment = false;
868         if (!FieldRec->hasTrivialMoveAssignment())
869           data().HasTrivialMoveAssignment = false;
870
871         if (!FieldRec->hasTrivialDestructor())
872           data().HasTrivialDestructor = false;
873         if (!FieldRec->hasIrrelevantDestructor())
874           data().HasIrrelevantDestructor = false;
875         if (FieldRec->hasObjectMember())
876           setHasObjectMember(true);
877
878         // C++0x [class]p7:
879         //   A standard-layout class is a class that:
880         //    -- has no non-static data members of type non-standard-layout
881         //       class (or array of such types) [...]
882         if (!FieldRec->isStandardLayout())
883           data().IsStandardLayout = false;
884
885         // C++0x [class]p7:
886         //   A standard-layout class is a class that:
887         //    [...]
888         //    -- has no base classes of the same type as the first non-static
889         //       data member.
890         // We don't want to expend bits in the state of the record decl
891         // tracking whether this is the first non-static data member so we
892         // cheat a bit and use some of the existing state: the empty bit.
893         // Virtual bases and virtual methods make a class non-empty, but they
894         // also make it non-standard-layout so we needn't check here.
895         // A non-empty base class may leave the class standard-layout, but not
896         // if we have arrived here, and have at least on non-static data
897         // member. If IsStandardLayout remains true, then the first non-static
898         // data member must come through here with Empty still true, and Empty
899         // will subsequently be set to false below.
900         if (data().IsStandardLayout && data().Empty) {
901           for (CXXRecordDecl::base_class_const_iterator BI = bases_begin(),
902                                                         BE = bases_end();
903                BI != BE; ++BI) {
904             if (Context.hasSameUnqualifiedType(BI->getType(), T)) {
905               data().IsStandardLayout = false;
906               break;
907             }
908           }
909         }
910         
911         // Keep track of the presence of mutable fields.
912         if (FieldRec->hasMutableFields())
913           data().HasMutableFields = true;
914
915         // C++11 [class.copy]p13:
916         //   If the implicitly-defined constructor would satisfy the
917         //   requirements of a constexpr constructor, the implicitly-defined
918         //   constructor is constexpr.
919         // C++11 [dcl.constexpr]p4:
920         //    -- every constructor involved in initializing non-static data
921         //       members [...] shall be a constexpr constructor
922         if (!Field->hasInClassInitializer() &&
923             !FieldRec->hasConstexprDefaultConstructor())
924           // The standard requires any in-class initializer to be a constant
925           // expression. We consider this to be a defect.
926           data().DefaultedDefaultConstructorIsConstexpr = false;
927
928         if (!FieldRec->hasConstexprCopyConstructor())
929           data().DefaultedCopyConstructorIsConstexpr = false;
930
931         if (FieldRec->hasDeclaredMoveConstructor() ||
932             FieldRec->needsImplicitMoveConstructor())
933           // FIXME: If the implicit move constructor generated for the member's
934           // class would be ill-formed, the implicit move constructor generated
935           // for this class calls the member's copy constructor.
936           data().DefaultedMoveConstructorIsConstexpr &=
937             FieldRec->hasConstexprMoveConstructor();
938         else if (!FieldRec->hasConstexprCopyConstructor())
939           data().DefaultedMoveConstructorIsConstexpr = false;
940       }
941     } else {
942       // Base element type of field is a non-class type.
943       if (!T->isLiteralType()) {
944         data().DefaultedDefaultConstructorIsConstexpr = false;
945         data().DefaultedCopyConstructorIsConstexpr = false;
946         data().DefaultedMoveConstructorIsConstexpr = false;
947       } else if (!Field->hasInClassInitializer())
948         data().DefaultedDefaultConstructorIsConstexpr = false;
949     }
950
951     // C++0x [class]p7:
952     //   A standard-layout class is a class that:
953     //    [...]
954     //    -- either has no non-static data members in the most derived
955     //       class and at most one base class with non-static data members,
956     //       or has no base classes with non-static data members, and
957     // At this point we know that we have a non-static data member, so the last
958     // clause holds.
959     if (!data().HasNoNonEmptyBases)
960       data().IsStandardLayout = false;
961
962     // If this is not a zero-length bit-field, then the class is not empty.
963     if (data().Empty) {
964       if (!Field->isBitField() ||
965           (!Field->getBitWidth()->isTypeDependent() &&
966            !Field->getBitWidth()->isValueDependent() &&
967            Field->getBitWidthValue(Context) != 0))
968         data().Empty = false;
969     }
970   }
971   
972   // Handle using declarations of conversion functions.
973   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(D))
974     if (Shadow->getDeclName().getNameKind()
975           == DeclarationName::CXXConversionFunctionName)
976       data().Conversions.addDecl(Shadow, Shadow->getAccess());
977 }
978
979 bool CXXRecordDecl::isCLike() const {
980   if (getTagKind() == TTK_Class || !TemplateOrInstantiation.isNull())
981     return false;
982   if (!hasDefinition())
983     return true;
984
985   return isPOD() && data().HasOnlyCMembers;
986 }
987
988 void CXXRecordDecl::getCaptureFields(
989        llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
990        FieldDecl *&ThisCapture) const {
991   Captures.clear();
992   ThisCapture = 0;
993
994   LambdaDefinitionData &Lambda = getLambdaData();
995   RecordDecl::field_iterator Field = field_begin();
996   for (LambdaExpr::Capture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures;
997        C != CEnd; ++C, ++Field) {
998     if (C->capturesThis()) {
999       ThisCapture = *Field;
1000       continue;
1001     }
1002
1003     Captures[C->getCapturedVar()] = *Field;
1004   }
1005 }
1006
1007
1008 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
1009   QualType T;
1010   if (isa<UsingShadowDecl>(Conv))
1011     Conv = cast<UsingShadowDecl>(Conv)->getTargetDecl();
1012   if (FunctionTemplateDecl *ConvTemp = dyn_cast<FunctionTemplateDecl>(Conv))
1013     T = ConvTemp->getTemplatedDecl()->getResultType();
1014   else 
1015     T = cast<CXXConversionDecl>(Conv)->getConversionType();
1016   return Context.getCanonicalType(T);
1017 }
1018
1019 /// Collect the visible conversions of a base class.
1020 ///
1021 /// \param Base a base class of the class we're considering
1022 /// \param InVirtual whether this base class is a virtual base (or a base
1023 ///   of a virtual base)
1024 /// \param Access the access along the inheritance path to this base
1025 /// \param ParentHiddenTypes the conversions provided by the inheritors
1026 ///   of this base
1027 /// \param Output the set to which to add conversions from non-virtual bases
1028 /// \param VOutput the set to which to add conversions from virtual bases
1029 /// \param HiddenVBaseCs the set of conversions which were hidden in a
1030 ///   virtual base along some inheritance path
1031 static void CollectVisibleConversions(ASTContext &Context,
1032                                       CXXRecordDecl *Record,
1033                                       bool InVirtual,
1034                                       AccessSpecifier Access,
1035                   const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
1036                                       UnresolvedSetImpl &Output,
1037                                       UnresolvedSetImpl &VOutput,
1038                            llvm::SmallPtrSet<NamedDecl*, 8> &HiddenVBaseCs) {
1039   // The set of types which have conversions in this class or its
1040   // subclasses.  As an optimization, we don't copy the derived set
1041   // unless it might change.
1042   const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
1043   llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
1044
1045   // Collect the direct conversions and figure out which conversions
1046   // will be hidden in the subclasses.
1047   UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
1048   if (!Cs.empty()) {
1049     HiddenTypesBuffer = ParentHiddenTypes;
1050     HiddenTypes = &HiddenTypesBuffer;
1051
1052     for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I) {
1053       bool Hidden =
1054         !HiddenTypesBuffer.insert(GetConversionType(Context, I.getDecl()));
1055
1056       // If this conversion is hidden and we're in a virtual base,
1057       // remember that it's hidden along some inheritance path.
1058       if (Hidden && InVirtual)
1059         HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1060
1061       // If this conversion isn't hidden, add it to the appropriate output.
1062       else if (!Hidden) {
1063         AccessSpecifier IAccess
1064           = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1065
1066         if (InVirtual)
1067           VOutput.addDecl(I.getDecl(), IAccess);
1068         else
1069           Output.addDecl(I.getDecl(), IAccess);
1070       }
1071     }
1072   }
1073
1074   // Collect information recursively from any base classes.
1075   for (CXXRecordDecl::base_class_iterator
1076          I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1077     const RecordType *RT = I->getType()->getAs<RecordType>();
1078     if (!RT) continue;
1079
1080     AccessSpecifier BaseAccess
1081       = CXXRecordDecl::MergeAccess(Access, I->getAccessSpecifier());
1082     bool BaseInVirtual = InVirtual || I->isVirtual();
1083
1084     CXXRecordDecl *Base = cast<CXXRecordDecl>(RT->getDecl());
1085     CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1086                               *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1087   }
1088 }
1089
1090 /// Collect the visible conversions of a class.
1091 ///
1092 /// This would be extremely straightforward if it weren't for virtual
1093 /// bases.  It might be worth special-casing that, really.
1094 static void CollectVisibleConversions(ASTContext &Context,
1095                                       CXXRecordDecl *Record,
1096                                       UnresolvedSetImpl &Output) {
1097   // The collection of all conversions in virtual bases that we've
1098   // found.  These will be added to the output as long as they don't
1099   // appear in the hidden-conversions set.
1100   UnresolvedSet<8> VBaseCs;
1101   
1102   // The set of conversions in virtual bases that we've determined to
1103   // be hidden.
1104   llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1105
1106   // The set of types hidden by classes derived from this one.
1107   llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1108
1109   // Go ahead and collect the direct conversions and add them to the
1110   // hidden-types set.
1111   UnresolvedSetImpl &Cs = *Record->getConversionFunctions();
1112   Output.append(Cs.begin(), Cs.end());
1113   for (UnresolvedSetIterator I = Cs.begin(), E = Cs.end(); I != E; ++I)
1114     HiddenTypes.insert(GetConversionType(Context, I.getDecl()));
1115
1116   // Recursively collect conversions from base classes.
1117   for (CXXRecordDecl::base_class_iterator
1118          I = Record->bases_begin(), E = Record->bases_end(); I != E; ++I) {
1119     const RecordType *RT = I->getType()->getAs<RecordType>();
1120     if (!RT) continue;
1121
1122     CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1123                               I->isVirtual(), I->getAccessSpecifier(),
1124                               HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1125   }
1126
1127   // Add any unhidden conversions provided by virtual bases.
1128   for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1129          I != E; ++I) {
1130     if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1131       Output.addDecl(I.getDecl(), I.getAccess());
1132   }
1133 }
1134
1135 /// getVisibleConversionFunctions - get all conversion functions visible
1136 /// in current class; including conversion function templates.
1137 const UnresolvedSetImpl *CXXRecordDecl::getVisibleConversionFunctions() {
1138   // If root class, all conversions are visible.
1139   if (bases_begin() == bases_end())
1140     return &data().Conversions;
1141   // If visible conversion list is already evaluated, return it.
1142   if (data().ComputedVisibleConversions)
1143     return &data().VisibleConversions;
1144   CollectVisibleConversions(getASTContext(), this, data().VisibleConversions);
1145   data().ComputedVisibleConversions = true;
1146   return &data().VisibleConversions;
1147 }
1148
1149 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1150   // This operation is O(N) but extremely rare.  Sema only uses it to
1151   // remove UsingShadowDecls in a class that were followed by a direct
1152   // declaration, e.g.:
1153   //   class A : B {
1154   //     using B::operator int;
1155   //     operator int();
1156   //   };
1157   // This is uncommon by itself and even more uncommon in conjunction
1158   // with sufficiently large numbers of directly-declared conversions
1159   // that asymptotic behavior matters.
1160
1161   UnresolvedSetImpl &Convs = *getConversionFunctions();
1162   for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1163     if (Convs[I].getDecl() == ConvDecl) {
1164       Convs.erase(I);
1165       assert(std::find(Convs.begin(), Convs.end(), ConvDecl) == Convs.end()
1166              && "conversion was found multiple times in unresolved set");
1167       return;
1168     }
1169   }
1170
1171   llvm_unreachable("conversion not found in set!");
1172 }
1173
1174 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1175   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1176     return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1177   
1178   return 0;
1179 }
1180
1181 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
1182   return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
1183 }
1184
1185 void 
1186 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1187                                              TemplateSpecializationKind TSK) {
1188   assert(TemplateOrInstantiation.isNull() && 
1189          "Previous template or instantiation?");
1190   assert(!isa<ClassTemplateSpecializationDecl>(this));
1191   TemplateOrInstantiation 
1192     = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1193 }
1194
1195 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1196   if (const ClassTemplateSpecializationDecl *Spec
1197         = dyn_cast<ClassTemplateSpecializationDecl>(this))
1198     return Spec->getSpecializationKind();
1199   
1200   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1201     return MSInfo->getTemplateSpecializationKind();
1202   
1203   return TSK_Undeclared;
1204 }
1205
1206 void 
1207 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1208   if (ClassTemplateSpecializationDecl *Spec
1209       = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1210     Spec->setSpecializationKind(TSK);
1211     return;
1212   }
1213   
1214   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1215     MSInfo->setTemplateSpecializationKind(TSK);
1216     return;
1217   }
1218   
1219   llvm_unreachable("Not a class template or member class specialization");
1220 }
1221
1222 CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1223   ASTContext &Context = getASTContext();
1224   QualType ClassType = Context.getTypeDeclType(this);
1225
1226   DeclarationName Name
1227     = Context.DeclarationNames.getCXXDestructorName(
1228                                           Context.getCanonicalType(ClassType));
1229
1230   DeclContext::lookup_const_iterator I, E;
1231   llvm::tie(I, E) = lookup(Name);
1232   if (I == E)
1233     return 0;
1234
1235   CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(*I);
1236   return Dtor;
1237 }
1238
1239 void CXXRecordDecl::completeDefinition() {
1240   completeDefinition(0);
1241 }
1242
1243 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1244   RecordDecl::completeDefinition();
1245   
1246   if (hasObjectMember() && getASTContext().getLangOpts().ObjCAutoRefCount) {
1247     // Objective-C Automatic Reference Counting:
1248     //   If a class has a non-static data member of Objective-C pointer
1249     //   type (or array thereof), it is a non-POD type and its
1250     //   default constructor (if any), copy constructor, copy assignment
1251     //   operator, and destructor are non-trivial.
1252     struct DefinitionData &Data = data();
1253     Data.PlainOldData = false;
1254     Data.HasTrivialDefaultConstructor = false;
1255     Data.HasTrivialCopyConstructor = false;
1256     Data.HasTrivialCopyAssignment = false;
1257     Data.HasTrivialDestructor = false;
1258     Data.HasIrrelevantDestructor = false;
1259   }
1260   
1261   // If the class may be abstract (but hasn't been marked as such), check for
1262   // any pure final overriders.
1263   if (mayBeAbstract()) {
1264     CXXFinalOverriderMap MyFinalOverriders;
1265     if (!FinalOverriders) {
1266       getFinalOverriders(MyFinalOverriders);
1267       FinalOverriders = &MyFinalOverriders;
1268     }
1269     
1270     bool Done = false;
1271     for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), 
1272                                      MEnd = FinalOverriders->end();
1273          M != MEnd && !Done; ++M) {
1274       for (OverridingMethods::iterator SO = M->second.begin(), 
1275                                     SOEnd = M->second.end();
1276            SO != SOEnd && !Done; ++SO) {
1277         assert(SO->second.size() > 0 && 
1278                "All virtual functions have overridding virtual functions");
1279         
1280         // C++ [class.abstract]p4:
1281         //   A class is abstract if it contains or inherits at least one
1282         //   pure virtual function for which the final overrider is pure
1283         //   virtual.
1284         if (SO->second.front().Method->isPure()) {
1285           data().Abstract = true;
1286           Done = true;
1287           break;
1288         }
1289       }
1290     }
1291   }
1292   
1293   // Set access bits correctly on the directly-declared conversions.
1294   for (UnresolvedSetIterator I = data().Conversions.begin(), 
1295                              E = data().Conversions.end(); 
1296        I != E; ++I)
1297     data().Conversions.setAccess(I, (*I)->getAccess());
1298 }
1299
1300 bool CXXRecordDecl::mayBeAbstract() const {
1301   if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1302       isDependentContext())
1303     return false;
1304   
1305   for (CXXRecordDecl::base_class_const_iterator B = bases_begin(),
1306                                              BEnd = bases_end();
1307        B != BEnd; ++B) {
1308     CXXRecordDecl *BaseDecl 
1309       = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
1310     if (BaseDecl->isAbstract())
1311       return true;
1312   }
1313   
1314   return false;
1315 }
1316
1317 void CXXMethodDecl::anchor() { }
1318
1319 CXXMethodDecl *
1320 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1321                       SourceLocation StartLoc,
1322                       const DeclarationNameInfo &NameInfo,
1323                       QualType T, TypeSourceInfo *TInfo,
1324                       bool isStatic, StorageClass SCAsWritten, bool isInline,
1325                       bool isConstexpr, SourceLocation EndLocation) {
1326   return new (C) CXXMethodDecl(CXXMethod, RD, StartLoc, NameInfo, T, TInfo,
1327                                isStatic, SCAsWritten, isInline, isConstexpr,
1328                                EndLocation);
1329 }
1330
1331 CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1332   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXMethodDecl));
1333   return new (Mem) CXXMethodDecl(CXXMethod, 0, SourceLocation(), 
1334                                  DeclarationNameInfo(), QualType(),
1335                                  0, false, SC_None, false, false,
1336                                  SourceLocation());
1337 }
1338
1339 bool CXXMethodDecl::isUsualDeallocationFunction() const {
1340   if (getOverloadedOperator() != OO_Delete &&
1341       getOverloadedOperator() != OO_Array_Delete)
1342     return false;
1343
1344   // C++ [basic.stc.dynamic.deallocation]p2:
1345   //   A template instance is never a usual deallocation function,
1346   //   regardless of its signature.
1347   if (getPrimaryTemplate())
1348     return false;
1349
1350   // C++ [basic.stc.dynamic.deallocation]p2:
1351   //   If a class T has a member deallocation function named operator delete 
1352   //   with exactly one parameter, then that function is a usual (non-placement)
1353   //   deallocation function. [...]
1354   if (getNumParams() == 1)
1355     return true;
1356   
1357   // C++ [basic.stc.dynamic.deallocation]p2:
1358   //   [...] If class T does not declare such an operator delete but does 
1359   //   declare a member deallocation function named operator delete with 
1360   //   exactly two parameters, the second of which has type std::size_t (18.1),
1361   //   then this function is a usual deallocation function.
1362   ASTContext &Context = getASTContext();
1363   if (getNumParams() != 2 ||
1364       !Context.hasSameUnqualifiedType(getParamDecl(1)->getType(),
1365                                       Context.getSizeType()))
1366     return false;
1367                  
1368   // This function is a usual deallocation function if there are no 
1369   // single-parameter deallocation functions of the same kind.
1370   for (DeclContext::lookup_const_result R = getDeclContext()->lookup(getDeclName());
1371        R.first != R.second; ++R.first) {
1372     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*R.first))
1373       if (FD->getNumParams() == 1)
1374         return false;
1375   }
1376   
1377   return true;
1378 }
1379
1380 bool CXXMethodDecl::isCopyAssignmentOperator() const {
1381   // C++0x [class.copy]p17:
1382   //  A user-declared copy assignment operator X::operator= is a non-static 
1383   //  non-template member function of class X with exactly one parameter of 
1384   //  type X, X&, const X&, volatile X& or const volatile X&.
1385   if (/*operator=*/getOverloadedOperator() != OO_Equal ||
1386       /*non-static*/ isStatic() || 
1387       /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate())
1388     return false;
1389       
1390   QualType ParamType = getParamDecl(0)->getType();
1391   if (const LValueReferenceType *Ref = ParamType->getAs<LValueReferenceType>())
1392     ParamType = Ref->getPointeeType();
1393   
1394   ASTContext &Context = getASTContext();
1395   QualType ClassType
1396     = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1397   return Context.hasSameUnqualifiedType(ClassType, ParamType);
1398 }
1399
1400 bool CXXMethodDecl::isMoveAssignmentOperator() const {
1401   // C++0x [class.copy]p19:
1402   //  A user-declared move assignment operator X::operator= is a non-static
1403   //  non-template member function of class X with exactly one parameter of type
1404   //  X&&, const X&&, volatile X&&, or const volatile X&&.
1405   if (getOverloadedOperator() != OO_Equal || isStatic() ||
1406       getPrimaryTemplate() || getDescribedFunctionTemplate())
1407     return false;
1408
1409   QualType ParamType = getParamDecl(0)->getType();
1410   if (!isa<RValueReferenceType>(ParamType))
1411     return false;
1412   ParamType = ParamType->getPointeeType();
1413
1414   ASTContext &Context = getASTContext();
1415   QualType ClassType
1416     = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
1417   return Context.hasSameUnqualifiedType(ClassType, ParamType);
1418 }
1419
1420 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
1421   assert(MD->isCanonicalDecl() && "Method is not canonical!");
1422   assert(!MD->getParent()->isDependentContext() &&
1423          "Can't add an overridden method to a class template!");
1424   assert(MD->isVirtual() && "Method is not virtual!");
1425
1426   getASTContext().addOverriddenMethod(this, MD);
1427 }
1428
1429 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
1430   if (isa<CXXConstructorDecl>(this)) return 0;
1431   return getASTContext().overridden_methods_begin(this);
1432 }
1433
1434 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
1435   if (isa<CXXConstructorDecl>(this)) return 0;
1436   return getASTContext().overridden_methods_end(this);
1437 }
1438
1439 unsigned CXXMethodDecl::size_overridden_methods() const {
1440   if (isa<CXXConstructorDecl>(this)) return 0;
1441   return getASTContext().overridden_methods_size(this);
1442 }
1443
1444 QualType CXXMethodDecl::getThisType(ASTContext &C) const {
1445   // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
1446   // If the member function is declared const, the type of this is const X*,
1447   // if the member function is declared volatile, the type of this is
1448   // volatile X*, and if the member function is declared const volatile,
1449   // the type of this is const volatile X*.
1450
1451   assert(isInstance() && "No 'this' for static methods!");
1452
1453   QualType ClassTy = C.getTypeDeclType(getParent());
1454   ClassTy = C.getQualifiedType(ClassTy,
1455                                Qualifiers::fromCVRMask(getTypeQualifiers()));
1456   return C.getPointerType(ClassTy);
1457 }
1458
1459 bool CXXMethodDecl::hasInlineBody() const {
1460   // If this function is a template instantiation, look at the template from 
1461   // which it was instantiated.
1462   const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
1463   if (!CheckFn)
1464     CheckFn = this;
1465   
1466   const FunctionDecl *fn;
1467   return CheckFn->hasBody(fn) && !fn->isOutOfLine();
1468 }
1469
1470 bool CXXMethodDecl::isLambdaStaticInvoker() const {
1471   return getParent()->isLambda() && 
1472          getIdentifier() && getIdentifier()->getName() == "__invoke";
1473 }
1474
1475
1476 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1477                                        TypeSourceInfo *TInfo, bool IsVirtual,
1478                                        SourceLocation L, Expr *Init,
1479                                        SourceLocation R,
1480                                        SourceLocation EllipsisLoc)
1481   : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init), 
1482     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual), 
1483     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1484 {
1485 }
1486
1487 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1488                                        FieldDecl *Member,
1489                                        SourceLocation MemberLoc,
1490                                        SourceLocation L, Expr *Init,
1491                                        SourceLocation R)
1492   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1493     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1494     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1495 {
1496 }
1497
1498 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1499                                        IndirectFieldDecl *Member,
1500                                        SourceLocation MemberLoc,
1501                                        SourceLocation L, Expr *Init,
1502                                        SourceLocation R)
1503   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
1504     LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
1505     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1506 {
1507 }
1508
1509 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1510                                        TypeSourceInfo *TInfo,
1511                                        SourceLocation L, Expr *Init, 
1512                                        SourceLocation R)
1513   : Initializee(TInfo), MemberOrEllipsisLocation(), Init(Init),
1514     LParenLoc(L), RParenLoc(R), IsDelegating(true), IsVirtual(false),
1515     IsWritten(false), SourceOrderOrNumArrayIndices(0)
1516 {
1517 }
1518
1519 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
1520                                        FieldDecl *Member,
1521                                        SourceLocation MemberLoc,
1522                                        SourceLocation L, Expr *Init,
1523                                        SourceLocation R,
1524                                        VarDecl **Indices,
1525                                        unsigned NumIndices)
1526   : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init), 
1527     LParenLoc(L), RParenLoc(R), IsVirtual(false),
1528     IsWritten(false), SourceOrderOrNumArrayIndices(NumIndices)
1529 {
1530   VarDecl **MyIndices = reinterpret_cast<VarDecl **> (this + 1);
1531   memcpy(MyIndices, Indices, NumIndices * sizeof(VarDecl *));
1532 }
1533
1534 CXXCtorInitializer *CXXCtorInitializer::Create(ASTContext &Context,
1535                                                FieldDecl *Member, 
1536                                                SourceLocation MemberLoc,
1537                                                SourceLocation L, Expr *Init,
1538                                                SourceLocation R,
1539                                                VarDecl **Indices,
1540                                                unsigned NumIndices) {
1541   void *Mem = Context.Allocate(sizeof(CXXCtorInitializer) +
1542                                sizeof(VarDecl *) * NumIndices,
1543                                llvm::alignOf<CXXCtorInitializer>());
1544   return new (Mem) CXXCtorInitializer(Context, Member, MemberLoc, L, Init, R,
1545                                       Indices, NumIndices);
1546 }
1547
1548 TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
1549   if (isBaseInitializer())
1550     return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
1551   else
1552     return TypeLoc();
1553 }
1554
1555 const Type *CXXCtorInitializer::getBaseClass() const {
1556   if (isBaseInitializer())
1557     return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
1558   else
1559     return 0;
1560 }
1561
1562 SourceLocation CXXCtorInitializer::getSourceLocation() const {
1563   if (isAnyMemberInitializer())
1564     return getMemberLocation();
1565
1566   if (isInClassMemberInitializer())
1567     return getAnyMember()->getLocation();
1568   
1569   if (TypeSourceInfo *TSInfo = Initializee.get<TypeSourceInfo*>())
1570     return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
1571   
1572   return SourceLocation();
1573 }
1574
1575 SourceRange CXXCtorInitializer::getSourceRange() const {
1576   if (isInClassMemberInitializer()) {
1577     FieldDecl *D = getAnyMember();
1578     if (Expr *I = D->getInClassInitializer())
1579       return I->getSourceRange();
1580     return SourceRange();
1581   }
1582
1583   return SourceRange(getSourceLocation(), getRParenLoc());
1584 }
1585
1586 void CXXConstructorDecl::anchor() { }
1587
1588 CXXConstructorDecl *
1589 CXXConstructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1590   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConstructorDecl));
1591   return new (Mem) CXXConstructorDecl(0, SourceLocation(),DeclarationNameInfo(),
1592                                       QualType(), 0, false, false, false,false);
1593 }
1594
1595 CXXConstructorDecl *
1596 CXXConstructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1597                            SourceLocation StartLoc,
1598                            const DeclarationNameInfo &NameInfo,
1599                            QualType T, TypeSourceInfo *TInfo,
1600                            bool isExplicit, bool isInline,
1601                            bool isImplicitlyDeclared, bool isConstexpr) {
1602   assert(NameInfo.getName().getNameKind()
1603          == DeclarationName::CXXConstructorName &&
1604          "Name must refer to a constructor");
1605   return new (C) CXXConstructorDecl(RD, StartLoc, NameInfo, T, TInfo,
1606                                     isExplicit, isInline, isImplicitlyDeclared,
1607                                     isConstexpr);
1608 }
1609
1610 CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
1611   assert(isDelegatingConstructor() && "Not a delegating constructor!");
1612   Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
1613   if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(E))
1614     return Construct->getConstructor();
1615   
1616   return 0;
1617 }
1618
1619 bool CXXConstructorDecl::isDefaultConstructor() const {
1620   // C++ [class.ctor]p5:
1621   //   A default constructor for a class X is a constructor of class
1622   //   X that can be called without an argument.
1623   return (getNumParams() == 0) ||
1624          (getNumParams() > 0 && getParamDecl(0)->hasDefaultArg());
1625 }
1626
1627 bool
1628 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
1629   return isCopyOrMoveConstructor(TypeQuals) &&
1630          getParamDecl(0)->getType()->isLValueReferenceType();
1631 }
1632
1633 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
1634   return isCopyOrMoveConstructor(TypeQuals) &&
1635     getParamDecl(0)->getType()->isRValueReferenceType();
1636 }
1637
1638 /// \brief Determine whether this is a copy or move constructor.
1639 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
1640   // C++ [class.copy]p2:
1641   //   A non-template constructor for class X is a copy constructor
1642   //   if its first parameter is of type X&, const X&, volatile X& or
1643   //   const volatile X&, and either there are no other parameters
1644   //   or else all other parameters have default arguments (8.3.6).
1645   // C++0x [class.copy]p3:
1646   //   A non-template constructor for class X is a move constructor if its
1647   //   first parameter is of type X&&, const X&&, volatile X&&, or 
1648   //   const volatile X&&, and either there are no other parameters or else 
1649   //   all other parameters have default arguments.
1650   if ((getNumParams() < 1) ||
1651       (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1652       (getPrimaryTemplate() != 0) ||
1653       (getDescribedFunctionTemplate() != 0))
1654     return false;
1655   
1656   const ParmVarDecl *Param = getParamDecl(0);
1657   
1658   // Do we have a reference type? 
1659   const ReferenceType *ParamRefType = Param->getType()->getAs<ReferenceType>();
1660   if (!ParamRefType)
1661     return false;
1662   
1663   // Is it a reference to our class type?
1664   ASTContext &Context = getASTContext();
1665   
1666   CanQualType PointeeType
1667     = Context.getCanonicalType(ParamRefType->getPointeeType());
1668   CanQualType ClassTy 
1669     = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1670   if (PointeeType.getUnqualifiedType() != ClassTy)
1671     return false;
1672   
1673   // FIXME: other qualifiers?
1674   
1675   // We have a copy or move constructor.
1676   TypeQuals = PointeeType.getCVRQualifiers();
1677   return true;  
1678 }
1679
1680 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
1681   // C++ [class.conv.ctor]p1:
1682   //   A constructor declared without the function-specifier explicit
1683   //   that can be called with a single parameter specifies a
1684   //   conversion from the type of its first parameter to the type of
1685   //   its class. Such a constructor is called a converting
1686   //   constructor.
1687   if (isExplicit() && !AllowExplicit)
1688     return false;
1689
1690   return (getNumParams() == 0 &&
1691           getType()->getAs<FunctionProtoType>()->isVariadic()) ||
1692          (getNumParams() == 1) ||
1693          (getNumParams() > 1 && getParamDecl(1)->hasDefaultArg());
1694 }
1695
1696 bool CXXConstructorDecl::isSpecializationCopyingObject() const {
1697   if ((getNumParams() < 1) ||
1698       (getNumParams() > 1 && !getParamDecl(1)->hasDefaultArg()) ||
1699       (getPrimaryTemplate() == 0) ||
1700       (getDescribedFunctionTemplate() != 0))
1701     return false;
1702
1703   const ParmVarDecl *Param = getParamDecl(0);
1704
1705   ASTContext &Context = getASTContext();
1706   CanQualType ParamType = Context.getCanonicalType(Param->getType());
1707   
1708   // Is it the same as our our class type?
1709   CanQualType ClassTy 
1710     = Context.getCanonicalType(Context.getTagDeclType(getParent()));
1711   if (ParamType.getUnqualifiedType() != ClassTy)
1712     return false;
1713   
1714   return true;  
1715 }
1716
1717 const CXXConstructorDecl *CXXConstructorDecl::getInheritedConstructor() const {
1718   // Hack: we store the inherited constructor in the overridden method table
1719   method_iterator It = getASTContext().overridden_methods_begin(this);
1720   if (It == getASTContext().overridden_methods_end(this))
1721     return 0;
1722
1723   return cast<CXXConstructorDecl>(*It);
1724 }
1725
1726 void
1727 CXXConstructorDecl::setInheritedConstructor(const CXXConstructorDecl *BaseCtor){
1728   // Hack: we store the inherited constructor in the overridden method table
1729   assert(getASTContext().overridden_methods_size(this) == 0 &&
1730          "Base ctor already set.");
1731   getASTContext().addOverriddenMethod(this, BaseCtor);
1732 }
1733
1734 void CXXDestructorDecl::anchor() { }
1735
1736 CXXDestructorDecl *
1737 CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1738   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXDestructorDecl));
1739   return new (Mem) CXXDestructorDecl(0, SourceLocation(), DeclarationNameInfo(),
1740                                    QualType(), 0, false, false);
1741 }
1742
1743 CXXDestructorDecl *
1744 CXXDestructorDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1745                           SourceLocation StartLoc,
1746                           const DeclarationNameInfo &NameInfo,
1747                           QualType T, TypeSourceInfo *TInfo,
1748                           bool isInline, bool isImplicitlyDeclared) {
1749   assert(NameInfo.getName().getNameKind()
1750          == DeclarationName::CXXDestructorName &&
1751          "Name must refer to a destructor");
1752   return new (C) CXXDestructorDecl(RD, StartLoc, NameInfo, T, TInfo, isInline,
1753                                    isImplicitlyDeclared);
1754 }
1755
1756 void CXXConversionDecl::anchor() { }
1757
1758 CXXConversionDecl *
1759 CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1760   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(CXXConversionDecl));
1761   return new (Mem) CXXConversionDecl(0, SourceLocation(), DeclarationNameInfo(),
1762                                      QualType(), 0, false, false, false,
1763                                      SourceLocation());
1764 }
1765
1766 CXXConversionDecl *
1767 CXXConversionDecl::Create(ASTContext &C, CXXRecordDecl *RD,
1768                           SourceLocation StartLoc,
1769                           const DeclarationNameInfo &NameInfo,
1770                           QualType T, TypeSourceInfo *TInfo,
1771                           bool isInline, bool isExplicit,
1772                           bool isConstexpr, SourceLocation EndLocation) {
1773   assert(NameInfo.getName().getNameKind()
1774          == DeclarationName::CXXConversionFunctionName &&
1775          "Name must refer to a conversion function");
1776   return new (C) CXXConversionDecl(RD, StartLoc, NameInfo, T, TInfo,
1777                                    isInline, isExplicit, isConstexpr,
1778                                    EndLocation);
1779 }
1780
1781 bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
1782   return isImplicit() && getParent()->isLambda() &&
1783          getConversionType()->isBlockPointerType();
1784 }
1785
1786 void LinkageSpecDecl::anchor() { }
1787
1788 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
1789                                          DeclContext *DC,
1790                                          SourceLocation ExternLoc,
1791                                          SourceLocation LangLoc,
1792                                          LanguageIDs Lang,
1793                                          SourceLocation RBraceLoc) {
1794   return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, RBraceLoc);
1795 }
1796
1797 LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1798   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LinkageSpecDecl));
1799   return new (Mem) LinkageSpecDecl(0, SourceLocation(), SourceLocation(),
1800                                    lang_c, SourceLocation());
1801 }
1802
1803 void UsingDirectiveDecl::anchor() { }
1804
1805 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
1806                                                SourceLocation L,
1807                                                SourceLocation NamespaceLoc,
1808                                            NestedNameSpecifierLoc QualifierLoc,
1809                                                SourceLocation IdentLoc,
1810                                                NamedDecl *Used,
1811                                                DeclContext *CommonAncestor) {
1812   if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Used))
1813     Used = NS->getOriginalNamespace();
1814   return new (C) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
1815                                     IdentLoc, Used, CommonAncestor);
1816 }
1817
1818 UsingDirectiveDecl *
1819 UsingDirectiveDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1820   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDirectiveDecl));
1821   return new (Mem) UsingDirectiveDecl(0, SourceLocation(), SourceLocation(),
1822                                       NestedNameSpecifierLoc(),
1823                                       SourceLocation(), 0, 0);
1824 }
1825
1826 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
1827   if (NamespaceAliasDecl *NA =
1828         dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
1829     return NA->getNamespace();
1830   return cast_or_null<NamespaceDecl>(NominatedNamespace);
1831 }
1832
1833 void NamespaceDecl::anchor() { }
1834
1835 NamespaceDecl::NamespaceDecl(DeclContext *DC, bool Inline, 
1836                              SourceLocation StartLoc,
1837                              SourceLocation IdLoc, IdentifierInfo *Id,
1838                              NamespaceDecl *PrevDecl)
1839   : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
1840     LocStart(StartLoc), RBraceLoc(), AnonOrFirstNamespaceAndInline(0, Inline) 
1841 {
1842   setPreviousDeclaration(PrevDecl);
1843   
1844   if (PrevDecl)
1845     AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
1846 }
1847
1848 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
1849                                      bool Inline, SourceLocation StartLoc,
1850                                      SourceLocation IdLoc, IdentifierInfo *Id,
1851                                      NamespaceDecl *PrevDecl) {
1852   return new (C) NamespaceDecl(DC, Inline, StartLoc, IdLoc, Id, PrevDecl);
1853 }
1854
1855 NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1856   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceDecl));
1857   return new (Mem) NamespaceDecl(0, false, SourceLocation(), SourceLocation(), 
1858                                  0, 0);
1859 }
1860
1861 void NamespaceAliasDecl::anchor() { }
1862
1863 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
1864                                                SourceLocation UsingLoc,
1865                                                SourceLocation AliasLoc,
1866                                                IdentifierInfo *Alias,
1867                                            NestedNameSpecifierLoc QualifierLoc,
1868                                                SourceLocation IdentLoc,
1869                                                NamedDecl *Namespace) {
1870   if (NamespaceDecl *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
1871     Namespace = NS->getOriginalNamespace();
1872   return new (C) NamespaceAliasDecl(DC, UsingLoc, AliasLoc, Alias, 
1873                                     QualifierLoc, IdentLoc, Namespace);
1874 }
1875
1876 NamespaceAliasDecl *
1877 NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1878   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(NamespaceAliasDecl));
1879   return new (Mem) NamespaceAliasDecl(0, SourceLocation(), SourceLocation(), 0,
1880                                       NestedNameSpecifierLoc(), 
1881                                       SourceLocation(), 0);
1882 }
1883
1884 void UsingShadowDecl::anchor() { }
1885
1886 UsingShadowDecl *
1887 UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1888   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingShadowDecl));
1889   return new (Mem) UsingShadowDecl(0, SourceLocation(), 0, 0);
1890 }
1891
1892 UsingDecl *UsingShadowDecl::getUsingDecl() const {
1893   const UsingShadowDecl *Shadow = this;
1894   while (const UsingShadowDecl *NextShadow =
1895          dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
1896     Shadow = NextShadow;
1897   return cast<UsingDecl>(Shadow->UsingOrNextShadow);
1898 }
1899
1900 void UsingDecl::anchor() { }
1901
1902 void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
1903   assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
1904          "declaration already in set");
1905   assert(S->getUsingDecl() == this);
1906
1907   if (FirstUsingShadow.getPointer())
1908     S->UsingOrNextShadow = FirstUsingShadow.getPointer();
1909   FirstUsingShadow.setPointer(S);
1910 }
1911
1912 void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
1913   assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
1914          "declaration not in set");
1915   assert(S->getUsingDecl() == this);
1916
1917   // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
1918
1919   if (FirstUsingShadow.getPointer() == S) {
1920     FirstUsingShadow.setPointer(
1921       dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
1922     S->UsingOrNextShadow = this;
1923     return;
1924   }
1925
1926   UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
1927   while (Prev->UsingOrNextShadow != S)
1928     Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
1929   Prev->UsingOrNextShadow = S->UsingOrNextShadow;
1930   S->UsingOrNextShadow = this;
1931 }
1932
1933 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
1934                              NestedNameSpecifierLoc QualifierLoc,
1935                              const DeclarationNameInfo &NameInfo,
1936                              bool IsTypeNameArg) {
1937   return new (C) UsingDecl(DC, UL, QualifierLoc, NameInfo, IsTypeNameArg);
1938 }
1939
1940 UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1941   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UsingDecl));
1942   return new (Mem) UsingDecl(0, SourceLocation(), NestedNameSpecifierLoc(),
1943                              DeclarationNameInfo(), false);
1944 }
1945
1946 void UnresolvedUsingValueDecl::anchor() { }
1947
1948 UnresolvedUsingValueDecl *
1949 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
1950                                  SourceLocation UsingLoc,
1951                                  NestedNameSpecifierLoc QualifierLoc,
1952                                  const DeclarationNameInfo &NameInfo) {
1953   return new (C) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
1954                                           QualifierLoc, NameInfo);
1955 }
1956
1957 UnresolvedUsingValueDecl *
1958 UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1959   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(UnresolvedUsingValueDecl));
1960   return new (Mem) UnresolvedUsingValueDecl(0, QualType(), SourceLocation(),
1961                                             NestedNameSpecifierLoc(),
1962                                             DeclarationNameInfo());
1963 }
1964
1965 void UnresolvedUsingTypenameDecl::anchor() { }
1966
1967 UnresolvedUsingTypenameDecl *
1968 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
1969                                     SourceLocation UsingLoc,
1970                                     SourceLocation TypenameLoc,
1971                                     NestedNameSpecifierLoc QualifierLoc,
1972                                     SourceLocation TargetNameLoc,
1973                                     DeclarationName TargetName) {
1974   return new (C) UnresolvedUsingTypenameDecl(DC, UsingLoc, TypenameLoc,
1975                                              QualifierLoc, TargetNameLoc,
1976                                              TargetName.getAsIdentifierInfo());
1977 }
1978
1979 UnresolvedUsingTypenameDecl *
1980 UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1981   void *Mem = AllocateDeserializedDecl(C, ID, 
1982                                        sizeof(UnresolvedUsingTypenameDecl));
1983   return new (Mem) UnresolvedUsingTypenameDecl(0, SourceLocation(),
1984                                                SourceLocation(),
1985                                                NestedNameSpecifierLoc(),
1986                                                SourceLocation(),
1987                                                0);
1988 }
1989
1990 void StaticAssertDecl::anchor() { }
1991
1992 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
1993                                            SourceLocation StaticAssertLoc,
1994                                            Expr *AssertExpr,
1995                                            StringLiteral *Message,
1996                                            SourceLocation RParenLoc) {
1997   return new (C) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
1998                                   RParenLoc);
1999 }
2000
2001 StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C, 
2002                                                        unsigned ID) {
2003   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(StaticAssertDecl));
2004   return new (Mem) StaticAssertDecl(0, SourceLocation(), 0, 0,SourceLocation());
2005 }
2006
2007 static const char *getAccessName(AccessSpecifier AS) {
2008   switch (AS) {
2009     case AS_none:
2010       llvm_unreachable("Invalid access specifier!");
2011     case AS_public:
2012       return "public";
2013     case AS_private:
2014       return "private";
2015     case AS_protected:
2016       return "protected";
2017   }
2018   llvm_unreachable("Invalid access specifier!");
2019 }
2020
2021 const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
2022                                            AccessSpecifier AS) {
2023   return DB << getAccessName(AS);
2024 }
2025
2026 const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB,
2027                                            AccessSpecifier AS) {
2028   return DB << getAccessName(AS);
2029 }