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