1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
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 semantic analysis for C++ declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "Sema.h"
15 #include "SemaInherit.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclVisitor.h"
19 #include "clang/AST/TypeOrdering.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Parse/DeclSpec.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include <algorithm> // for std::equal
26 #include <map>
27 
28 using namespace clang;
29 
30 //===----------------------------------------------------------------------===//
31 // CheckDefaultArgumentVisitor
32 //===----------------------------------------------------------------------===//
33 
34 namespace {
35   /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36   /// the default argument of a parameter to determine whether it
37   /// contains any ill-formed subexpressions. For example, this will
38   /// diagnose the use of local variables or parameters within the
39   /// default argument expression.
40   class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
41     : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
42     Expr *DefaultArg;
43     Sema *S;
44 
45   public:
46     CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47       : DefaultArg(defarg), S(s) {}
48 
49     bool VisitExpr(Expr *Node);
50     bool VisitDeclRefExpr(DeclRefExpr *DRE);
51     bool VisitCXXThisExpr(CXXThisExpr *ThisE);
52   };
53 
54   /// VisitExpr - Visit all of the children of this expression.
55   bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56     bool IsInvalid = false;
57     for (Stmt::child_iterator I = Node->child_begin(),
58          E = Node->child_end(); I != E; ++I)
59       IsInvalid |= Visit(*I);
60     return IsInvalid;
61   }
62 
63   /// VisitDeclRefExpr - Visit a reference to a declaration, to
64   /// determine whether this declaration can be used in the default
65   /// argument expression.
66   bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
67     NamedDecl *Decl = DRE->getDecl();
68     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69       // C++ [dcl.fct.default]p9
70       //   Default arguments are evaluated each time the function is
71       //   called. The order of evaluation of function arguments is
72       //   unspecified. Consequently, parameters of a function shall not
73       //   be used in default argument expressions, even if they are not
74       //   evaluated. Parameters of a function declared before a default
75       //   argument expression are in scope and can hide namespace and
76       //   class member names.
77       return S->Diag(DRE->getSourceRange().getBegin(),
78                      diag::err_param_default_argument_references_param)
79          << Param->getDeclName() << DefaultArg->getSourceRange();
80     } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
81       // C++ [dcl.fct.default]p7
82       //   Local variables shall not be used in default argument
83       //   expressions.
84       if (VDecl->isBlockVarDecl())
85         return S->Diag(DRE->getSourceRange().getBegin(),
86                        diag::err_param_default_argument_references_local)
87           << VDecl->getDeclName() << DefaultArg->getSourceRange();
88     }
89 
90     return false;
91   }
92 
93   /// VisitCXXThisExpr - Visit a C++ "this" expression.
94   bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95     // C++ [dcl.fct.default]p8:
96     //   The keyword this shall not be used in a default argument of a
97     //   member function.
98     return S->Diag(ThisE->getSourceRange().getBegin(),
99                    diag::err_param_default_argument_references_this)
100                << ThisE->getSourceRange();
101   }
102 }
103 
104 /// ActOnParamDefaultArgument - Check whether the default argument
105 /// provided for a function parameter is well-formed. If so, attach it
106 /// to the parameter declaration.
107 void
108 Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
109                                 ExprArg defarg) {
110   if (!param || !defarg.get())
111     return;
112 
113   ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
114   UnparsedDefaultArgLocs.erase(Param);
115 
116   ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
117   QualType ParamType = Param->getType();
118 
119   // Default arguments are only permitted in C++
120   if (!getLangOptions().CPlusPlus) {
121     Diag(EqualLoc, diag::err_param_default_argument)
122       << DefaultArg->getSourceRange();
123     Param->setInvalidDecl();
124     return;
125   }
126 
127   // C++ [dcl.fct.default]p5
128   //   A default argument expression is implicitly converted (clause
129   //   4) to the parameter type. The default argument expression has
130   //   the same semantic constraints as the initializer expression in
131   //   a declaration of a variable of the parameter type, using the
132   //   copy-initialization semantics (8.5).
133   Expr *DefaultArgPtr = DefaultArg.get();
134   bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
135                                                  EqualLoc,
136                                                  Param->getDeclName(),
137                                                  /*DirectInit=*/false);
138   if (DefaultArgPtr != DefaultArg.get()) {
139     DefaultArg.take();
140     DefaultArg.reset(DefaultArgPtr);
141   }
142   if (DefaultInitFailed) {
143     return;
144   }
145 
146   // Check that the default argument is well-formed
147   CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
148   if (DefaultArgChecker.Visit(DefaultArg.get())) {
149     Param->setInvalidDecl();
150     return;
151   }
152 
153   DefaultArgPtr = MaybeCreateCXXExprWithTemporaries(DefaultArg.take(),
154                                                     /*DestroyTemps=*/false);
155 
156   // Okay: add the default argument to the parameter
157   Param->setDefaultArg(DefaultArgPtr);
158 }
159 
160 /// ActOnParamUnparsedDefaultArgument - We've seen a default
161 /// argument for a function parameter, but we can't parse it yet
162 /// because we're inside a class definition. Note that this default
163 /// argument will be parsed later.
164 void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
165                                              SourceLocation EqualLoc,
166                                              SourceLocation ArgLoc) {
167   if (!param)
168     return;
169 
170   ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
171   if (Param)
172     Param->setUnparsedDefaultArg();
173 
174   UnparsedDefaultArgLocs[Param] = ArgLoc;
175 }
176 
177 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
178 /// the default argument for the parameter param failed.
179 void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
180   if (!param)
181     return;
182 
183   ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
184 
185   Param->setInvalidDecl();
186 
187   UnparsedDefaultArgLocs.erase(Param);
188 }
189 
190 /// CheckExtraCXXDefaultArguments - Check for any extra default
191 /// arguments in the declarator, which is not a function declaration
192 /// or definition and therefore is not permitted to have default
193 /// arguments. This routine should be invoked for every declarator
194 /// that is not a function declaration or definition.
195 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
196   // C++ [dcl.fct.default]p3
197   //   A default argument expression shall be specified only in the
198   //   parameter-declaration-clause of a function declaration or in a
199   //   template-parameter (14.1). It shall not be specified for a
200   //   parameter pack. If it is specified in a
201   //   parameter-declaration-clause, it shall not occur within a
202   //   declarator or abstract-declarator of a parameter-declaration.
203   for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
204     DeclaratorChunk &chunk = D.getTypeObject(i);
205     if (chunk.Kind == DeclaratorChunk::Function) {
206       for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
207         ParmVarDecl *Param =
208           cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
209         if (Param->hasUnparsedDefaultArg()) {
210           CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
211           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
212             << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
213           delete Toks;
214           chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
215         } else if (Param->getDefaultArg()) {
216           Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
217             << Param->getDefaultArg()->getSourceRange();
218           Param->setDefaultArg(0);
219         }
220       }
221     }
222   }
223 }
224 
225 // MergeCXXFunctionDecl - Merge two declarations of the same C++
226 // function, once we already know that they have the same
227 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
228 // error, false otherwise.
229 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
230   bool Invalid = false;
231 
232   // C++ [dcl.fct.default]p4:
233   //
234   //   For non-template functions, default arguments can be added in
235   //   later declarations of a function in the same
236   //   scope. Declarations in different scopes have completely
237   //   distinct sets of default arguments. That is, declarations in
238   //   inner scopes do not acquire default arguments from
239   //   declarations in outer scopes, and vice versa. In a given
240   //   function declaration, all parameters subsequent to a
241   //   parameter with a default argument shall have default
242   //   arguments supplied in this or previous declarations. A
243   //   default argument shall not be redefined by a later
244   //   declaration (not even to the same value).
245   for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
246     ParmVarDecl *OldParam = Old->getParamDecl(p);
247     ParmVarDecl *NewParam = New->getParamDecl(p);
248 
249     if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
250       Diag(NewParam->getLocation(),
251            diag::err_param_default_argument_redefinition)
252         << NewParam->getDefaultArg()->getSourceRange();
253       Diag(OldParam->getLocation(), diag::note_previous_definition);
254       Invalid = true;
255     } else if (OldParam->getDefaultArg()) {
256       // Merge the old default argument into the new parameter
257       NewParam->setDefaultArg(OldParam->getDefaultArg());
258     }
259   }
260 
261   return Invalid;
262 }
263 
264 /// CheckCXXDefaultArguments - Verify that the default arguments for a
265 /// function declaration are well-formed according to C++
266 /// [dcl.fct.default].
267 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
268   unsigned NumParams = FD->getNumParams();
269   unsigned p;
270 
271   // Find first parameter with a default argument
272   for (p = 0; p < NumParams; ++p) {
273     ParmVarDecl *Param = FD->getParamDecl(p);
274     if (Param->getDefaultArg())
275       break;
276   }
277 
278   // C++ [dcl.fct.default]p4:
279   //   In a given function declaration, all parameters
280   //   subsequent to a parameter with a default argument shall
281   //   have default arguments supplied in this or previous
282   //   declarations. A default argument shall not be redefined
283   //   by a later declaration (not even to the same value).
284   unsigned LastMissingDefaultArg = 0;
285   for(; p < NumParams; ++p) {
286     ParmVarDecl *Param = FD->getParamDecl(p);
287     if (!Param->getDefaultArg()) {
288       if (Param->isInvalidDecl())
289         /* We already complained about this parameter. */;
290       else if (Param->getIdentifier())
291         Diag(Param->getLocation(),
292              diag::err_param_default_argument_missing_name)
293           << Param->getIdentifier();
294       else
295         Diag(Param->getLocation(),
296              diag::err_param_default_argument_missing);
297 
298       LastMissingDefaultArg = p;
299     }
300   }
301 
302   if (LastMissingDefaultArg > 0) {
303     // Some default arguments were missing. Clear out all of the
304     // default arguments up to (and including) the last missing
305     // default argument, so that we leave the function parameters
306     // in a semantically valid state.
307     for (p = 0; p <= LastMissingDefaultArg; ++p) {
308       ParmVarDecl *Param = FD->getParamDecl(p);
309       if (Param->hasDefaultArg()) {
310         if (!Param->hasUnparsedDefaultArg())
311           Param->getDefaultArg()->Destroy(Context);
312         Param->setDefaultArg(0);
313       }
314     }
315   }
316 }
317 
318 /// isCurrentClassName - Determine whether the identifier II is the
319 /// name of the class type currently being defined. In the case of
320 /// nested classes, this will only return true if II is the name of
321 /// the innermost class.
322 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
323                               const CXXScopeSpec *SS) {
324   CXXRecordDecl *CurDecl;
325   if (SS && SS->isSet() && !SS->isInvalid()) {
326     DeclContext *DC = computeDeclContext(*SS);
327     CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
328   } else
329     CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
330 
331   if (CurDecl)
332     return &II == CurDecl->getIdentifier();
333   else
334     return false;
335 }
336 
337 /// \brief Check the validity of a C++ base class specifier.
338 ///
339 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
340 /// and returns NULL otherwise.
341 CXXBaseSpecifier *
342 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
343                          SourceRange SpecifierRange,
344                          bool Virtual, AccessSpecifier Access,
345                          QualType BaseType,
346                          SourceLocation BaseLoc) {
347   // C++ [class.union]p1:
348   //   A union shall not have base classes.
349   if (Class->isUnion()) {
350     Diag(Class->getLocation(), diag::err_base_clause_on_union)
351       << SpecifierRange;
352     return 0;
353   }
354 
355   if (BaseType->isDependentType())
356     return new CXXBaseSpecifier(SpecifierRange, Virtual,
357                                 Class->getTagKind() == RecordDecl::TK_class,
358                                 Access, BaseType);
359 
360   // Base specifiers must be record types.
361   if (!BaseType->isRecordType()) {
362     Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
363     return 0;
364   }
365 
366   // C++ [class.union]p1:
367   //   A union shall not be used as a base class.
368   if (BaseType->isUnionType()) {
369     Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
370     return 0;
371   }
372 
373   // C++ [class.derived]p2:
374   //   The class-name in a base-specifier shall not be an incompletely
375   //   defined class.
376   if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
377                           SpecifierRange))
378     return 0;
379 
380   // If the base class is polymorphic, the new one is, too.
381   RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
382   assert(BaseDecl && "Record type has no declaration");
383   BaseDecl = BaseDecl->getDefinition(Context);
384   assert(BaseDecl && "Base type is not incomplete, but has no definition");
385   if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
386     Class->setPolymorphic(true);
387 
388   // C++ [dcl.init.aggr]p1:
389   //   An aggregate is [...] a class with [...] no base classes [...].
390   Class->setAggregate(false);
391   Class->setPOD(false);
392 
393   if (Virtual) {
394     // C++ [class.ctor]p5:
395     //   A constructor is trivial if its class has no virtual base classes.
396     Class->setHasTrivialConstructor(false);
397   } else {
398     // C++ [class.ctor]p5:
399     //   A constructor is trivial if all the direct base classes of its
400     //   class have trivial constructors.
401     Class->setHasTrivialConstructor(cast<CXXRecordDecl>(BaseDecl)->
402                                     hasTrivialConstructor());
403   }
404 
405   // C++ [class.ctor]p3:
406   //   A destructor is trivial if all the direct base classes of its class
407   //   have trivial destructors.
408   Class->setHasTrivialDestructor(cast<CXXRecordDecl>(BaseDecl)->
409                                  hasTrivialDestructor());
410 
411   // Create the base specifier.
412   // FIXME: Allocate via ASTContext?
413   return new CXXBaseSpecifier(SpecifierRange, Virtual,
414                               Class->getTagKind() == RecordDecl::TK_class,
415                               Access, BaseType);
416 }
417 
418 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
419 /// one entry in the base class list of a class specifier, for
420 /// example:
421 ///    class foo : public bar, virtual private baz {
422 /// 'public bar' and 'virtual private baz' are each base-specifiers.
423 Sema::BaseResult
424 Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
425                          bool Virtual, AccessSpecifier Access,
426                          TypeTy *basetype, SourceLocation BaseLoc) {
427   if (!classdecl)
428     return true;
429 
430   AdjustDeclIfTemplate(classdecl);
431   CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
432   QualType BaseType = QualType::getFromOpaquePtr(basetype);
433   if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
434                                                       Virtual, Access,
435                                                       BaseType, BaseLoc))
436     return BaseSpec;
437 
438   return true;
439 }
440 
441 /// \brief Performs the actual work of attaching the given base class
442 /// specifiers to a C++ class.
443 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
444                                 unsigned NumBases) {
445  if (NumBases == 0)
446     return false;
447 
448   // Used to keep track of which base types we have already seen, so
449   // that we can properly diagnose redundant direct base types. Note
450   // that the key is always the unqualified canonical type of the base
451   // class.
452   std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
453 
454   // Copy non-redundant base specifiers into permanent storage.
455   unsigned NumGoodBases = 0;
456   bool Invalid = false;
457   for (unsigned idx = 0; idx < NumBases; ++idx) {
458     QualType NewBaseType
459       = Context.getCanonicalType(Bases[idx]->getType());
460     NewBaseType = NewBaseType.getUnqualifiedType();
461 
462     if (KnownBaseTypes[NewBaseType]) {
463       // C++ [class.mi]p3:
464       //   A class shall not be specified as a direct base class of a
465       //   derived class more than once.
466       Diag(Bases[idx]->getSourceRange().getBegin(),
467            diag::err_duplicate_base_class)
468         << KnownBaseTypes[NewBaseType]->getType()
469         << Bases[idx]->getSourceRange();
470 
471       // Delete the duplicate base class specifier; we're going to
472       // overwrite its pointer later.
473       delete Bases[idx];
474 
475       Invalid = true;
476     } else {
477       // Okay, add this new base class.
478       KnownBaseTypes[NewBaseType] = Bases[idx];
479       Bases[NumGoodBases++] = Bases[idx];
480     }
481   }
482 
483   // Attach the remaining base class specifiers to the derived class.
484   Class->setBases(Bases, NumGoodBases);
485 
486   // Delete the remaining (good) base class specifiers, since their
487   // data has been copied into the CXXRecordDecl.
488   for (unsigned idx = 0; idx < NumGoodBases; ++idx)
489     delete Bases[idx];
490 
491   return Invalid;
492 }
493 
494 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
495 /// class, after checking whether there are any duplicate base
496 /// classes.
497 void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
498                                unsigned NumBases) {
499   if (!ClassDecl || !Bases || !NumBases)
500     return;
501 
502   AdjustDeclIfTemplate(ClassDecl);
503   AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
504                        (CXXBaseSpecifier**)(Bases), NumBases);
505 }
506 
507 //===----------------------------------------------------------------------===//
508 // C++ class member Handling
509 //===----------------------------------------------------------------------===//
510 
511 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
512 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
513 /// bitfield width if there is one and 'InitExpr' specifies the initializer if
514 /// any.
515 Sema::DeclPtrTy
516 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
517                                ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
518   const DeclSpec &DS = D.getDeclSpec();
519   DeclarationName Name = GetNameForDeclarator(D);
520   Expr *BitWidth = static_cast<Expr*>(BW);
521   Expr *Init = static_cast<Expr*>(InitExpr);
522   SourceLocation Loc = D.getIdentifierLoc();
523 
524   bool isFunc = D.isFunctionDeclarator();
525 
526   // C++ 9.2p6: A member shall not be declared to have automatic storage
527   // duration (auto, register) or with the extern storage-class-specifier.
528   // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
529   // data members and cannot be applied to names declared const or static,
530   // and cannot be applied to reference members.
531   switch (DS.getStorageClassSpec()) {
532     case DeclSpec::SCS_unspecified:
533     case DeclSpec::SCS_typedef:
534     case DeclSpec::SCS_static:
535       // FALL THROUGH.
536       break;
537     case DeclSpec::SCS_mutable:
538       if (isFunc) {
539         if (DS.getStorageClassSpecLoc().isValid())
540           Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
541         else
542           Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
543 
544         // FIXME: It would be nicer if the keyword was ignored only for this
545         // declarator. Otherwise we could get follow-up errors.
546         D.getMutableDeclSpec().ClearStorageClassSpecs();
547       } else {
548         QualType T = GetTypeForDeclarator(D, S);
549         diag::kind err = static_cast<diag::kind>(0);
550         if (T->isReferenceType())
551           err = diag::err_mutable_reference;
552         else if (T.isConstQualified())
553           err = diag::err_mutable_const;
554         if (err != 0) {
555           if (DS.getStorageClassSpecLoc().isValid())
556             Diag(DS.getStorageClassSpecLoc(), err);
557           else
558             Diag(DS.getThreadSpecLoc(), err);
559           // FIXME: It would be nicer if the keyword was ignored only for this
560           // declarator. Otherwise we could get follow-up errors.
561           D.getMutableDeclSpec().ClearStorageClassSpecs();
562         }
563       }
564       break;
565     default:
566       if (DS.getStorageClassSpecLoc().isValid())
567         Diag(DS.getStorageClassSpecLoc(),
568              diag::err_storageclass_invalid_for_member);
569       else
570         Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
571       D.getMutableDeclSpec().ClearStorageClassSpecs();
572   }
573 
574   if (!isFunc &&
575       D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
576       D.getNumTypeObjects() == 0) {
577     // Check also for this case:
578     //
579     // typedef int f();
580     // f a;
581     //
582     QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
583     isFunc = TDType->isFunctionType();
584   }
585 
586   bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
587                        DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
588                       !isFunc);
589 
590   Decl *Member;
591   if (isInstField) {
592     Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
593                          AS);
594     assert(Member && "HandleField never returns null");
595   } else {
596     Member = ActOnDeclarator(S, D).getAs<Decl>();
597     if (!Member) {
598       if (BitWidth) DeleteExpr(BitWidth);
599       return DeclPtrTy();
600     }
601 
602     // Non-instance-fields can't have a bitfield.
603     if (BitWidth) {
604       if (Member->isInvalidDecl()) {
605         // don't emit another diagnostic.
606       } else if (isa<VarDecl>(Member)) {
607         // C++ 9.6p3: A bit-field shall not be a static member.
608         // "static member 'A' cannot be a bit-field"
609         Diag(Loc, diag::err_static_not_bitfield)
610           << Name << BitWidth->getSourceRange();
611       } else if (isa<TypedefDecl>(Member)) {
612         // "typedef member 'x' cannot be a bit-field"
613         Diag(Loc, diag::err_typedef_not_bitfield)
614           << Name << BitWidth->getSourceRange();
615       } else {
616         // A function typedef ("typedef int f(); f a;").
617         // C++ 9.6p3: A bit-field shall have integral or enumeration type.
618         Diag(Loc, diag::err_not_integral_type_bitfield)
619           << Name << cast<ValueDecl>(Member)->getType()
620           << BitWidth->getSourceRange();
621       }
622 
623       DeleteExpr(BitWidth);
624       BitWidth = 0;
625       Member->setInvalidDecl();
626     }
627 
628     Member->setAccess(AS);
629   }
630 
631   assert((Name || isInstField) && "No identifier for non-field ?");
632 
633   if (Init)
634     AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
635   if (Deleted) // FIXME: Source location is not very good.
636     SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
637 
638   if (isInstField) {
639     FieldCollector->Add(cast<FieldDecl>(Member));
640     return DeclPtrTy();
641   }
642   return DeclPtrTy::make(Member);
643 }
644 
645 /// ActOnMemInitializer - Handle a C++ member initializer.
646 Sema::MemInitResult
647 Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
648                           Scope *S,
649                           const CXXScopeSpec &SS,
650                           IdentifierInfo *MemberOrBase,
651                           SourceLocation IdLoc,
652                           SourceLocation LParenLoc,
653                           ExprTy **Args, unsigned NumArgs,
654                           SourceLocation *CommaLocs,
655                           SourceLocation RParenLoc) {
656   if (!ConstructorD)
657     return true;
658 
659   CXXConstructorDecl *Constructor
660     = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
661   if (!Constructor) {
662     // The user wrote a constructor initializer on a function that is
663     // not a C++ constructor. Ignore the error for now, because we may
664     // have more member initializers coming; we'll diagnose it just
665     // once in ActOnMemInitializers.
666     return true;
667   }
668 
669   CXXRecordDecl *ClassDecl = Constructor->getParent();
670 
671   // C++ [class.base.init]p2:
672   //   Names in a mem-initializer-id are looked up in the scope of the
673   //   constructor’s class and, if not found in that scope, are looked
674   //   up in the scope containing the constructor’s
675   //   definition. [Note: if the constructor’s class contains a member
676   //   with the same name as a direct or virtual base class of the
677   //   class, a mem-initializer-id naming the member or base class and
678   //   composed of a single identifier refers to the class member. A
679   //   mem-initializer-id for the hidden base class may be specified
680   //   using a qualified name. ]
681   if (!SS.getScopeRep()) {
682     // Look for a member, first.
683     FieldDecl *Member = 0;
684     DeclContext::lookup_result Result
685       = ClassDecl->lookup(MemberOrBase);
686     if (Result.first != Result.second)
687       Member = dyn_cast<FieldDecl>(*Result.first);
688 
689     // FIXME: Handle members of an anonymous union.
690 
691     if (Member) {
692       // FIXME: Perform direct initialization of the member.
693       return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs,
694                                             IdLoc);
695     }
696   }
697   // It didn't name a member, so see if it names a class.
698   TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, &SS);
699   if (!BaseTy)
700     return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
701       << MemberOrBase << SourceRange(IdLoc, RParenLoc);
702 
703   QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
704   if (!BaseType->isRecordType())
705     return Diag(IdLoc, diag::err_base_init_does_not_name_class)
706       << BaseType << SourceRange(IdLoc, RParenLoc);
707 
708   // C++ [class.base.init]p2:
709   //   [...] Unless the mem-initializer-id names a nonstatic data
710   //   member of the constructor’s class or a direct or virtual base
711   //   of that class, the mem-initializer is ill-formed. A
712   //   mem-initializer-list can initialize a base class using any
713   //   name that denotes that base class type.
714 
715   // First, check for a direct base class.
716   const CXXBaseSpecifier *DirectBaseSpec = 0;
717   for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
718        Base != ClassDecl->bases_end(); ++Base) {
719     if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
720         Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
721       // We found a direct base of this type. That's what we're
722       // initializing.
723       DirectBaseSpec = &*Base;
724       break;
725     }
726   }
727 
728   // Check for a virtual base class.
729   // FIXME: We might be able to short-circuit this if we know in advance that
730   // there are no virtual bases.
731   const CXXBaseSpecifier *VirtualBaseSpec = 0;
732   if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
733     // We haven't found a base yet; search the class hierarchy for a
734     // virtual base class.
735     BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
736                     /*DetectVirtual=*/false);
737     if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
738       for (BasePaths::paths_iterator Path = Paths.begin();
739            Path != Paths.end(); ++Path) {
740         if (Path->back().Base->isVirtual()) {
741           VirtualBaseSpec = Path->back().Base;
742           break;
743         }
744       }
745     }
746   }
747 
748   // C++ [base.class.init]p2:
749   //   If a mem-initializer-id is ambiguous because it designates both
750   //   a direct non-virtual base class and an inherited virtual base
751   //   class, the mem-initializer is ill-formed.
752   if (DirectBaseSpec && VirtualBaseSpec)
753     return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
754       << MemberOrBase << SourceRange(IdLoc, RParenLoc);
755   // C++ [base.class.init]p2:
756   // Unless the mem-initializer-id names a nonstatic data membeer of the
757   // constructor's class ot a direst or virtual base of that class, the
758   // mem-initializer is ill-formed.
759   if (!DirectBaseSpec && !VirtualBaseSpec)
760     return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
761     << BaseType << ClassDecl->getNameAsCString()
762     << SourceRange(IdLoc, RParenLoc);
763 
764 
765   return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs,
766                                         IdLoc);
767 }
768 
769 void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
770                                 SourceLocation ColonLoc,
771                                 MemInitTy **MemInits, unsigned NumMemInits) {
772   if (!ConstructorDecl)
773     return;
774 
775   CXXConstructorDecl *Constructor
776     = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
777 
778   if (!Constructor) {
779     Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
780     return;
781   }
782   llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
783 
784   for (unsigned i = 0; i < NumMemInits; i++) {
785     CXXBaseOrMemberInitializer *Member =
786       static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
787     void *KeyToMember = Member->getBaseOrMember();
788     // For fields injected into the class via declaration of an anonymous union,
789     // use its anonymous union class declaration as the unique key.
790     if (FieldDecl *Field = Member->getMember())
791       if (Field->getDeclContext()->isRecord() &&
792           cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
793         KeyToMember = static_cast<void *>(Field->getDeclContext());
794     CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
795     if (!PrevMember) {
796       PrevMember = Member;
797       continue;
798     }
799     if (FieldDecl *Field = Member->getMember())
800       Diag(Member->getSourceLocation(),
801            diag::error_multiple_mem_initialization)
802       << Field->getNameAsString();
803     else {
804       Type *BaseClass = Member->getBaseClass();
805       assert(BaseClass && "ActOnMemInitializers - neither field or base");
806       Diag(Member->getSourceLocation(),
807            diag::error_multiple_base_initialization)
808         << BaseClass->getDesugaredType(true);
809     }
810     Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
811       << 0;
812   }
813 }
814 
815 namespace {
816   /// PureVirtualMethodCollector - traverses a class and its superclasses
817   /// and determines if it has any pure virtual methods.
818   class VISIBILITY_HIDDEN PureVirtualMethodCollector {
819     ASTContext &Context;
820 
821   public:
822     typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
823 
824   private:
825     MethodList Methods;
826 
827     void Collect(const CXXRecordDecl* RD, MethodList& Methods);
828 
829   public:
830     PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
831       : Context(Ctx) {
832 
833       MethodList List;
834       Collect(RD, List);
835 
836       // Copy the temporary list to methods, and make sure to ignore any
837       // null entries.
838       for (size_t i = 0, e = List.size(); i != e; ++i) {
839         if (List[i])
840           Methods.push_back(List[i]);
841       }
842     }
843 
844     bool empty() const { return Methods.empty(); }
845 
846     MethodList::const_iterator methods_begin() { return Methods.begin(); }
847     MethodList::const_iterator methods_end() { return Methods.end(); }
848   };
849 
850   void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
851                                            MethodList& Methods) {
852     // First, collect the pure virtual methods for the base classes.
853     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
854          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
855       if (const RecordType *RT = Base->getType()->getAsRecordType()) {
856         const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
857         if (BaseDecl && BaseDecl->isAbstract())
858           Collect(BaseDecl, Methods);
859       }
860     }
861 
862     // Next, zero out any pure virtual methods that this class overrides.
863     typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
864 
865     MethodSetTy OverriddenMethods;
866     size_t MethodsSize = Methods.size();
867 
868     for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
869          i != e; ++i) {
870       // Traverse the record, looking for methods.
871       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
872         // If the method is pre virtual, add it to the methods vector.
873         if (MD->isPure()) {
874           Methods.push_back(MD);
875           continue;
876         }
877 
878         // Otherwise, record all the overridden methods in our set.
879         for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
880              E = MD->end_overridden_methods(); I != E; ++I) {
881           // Keep track of the overridden methods.
882           OverriddenMethods.insert(*I);
883         }
884       }
885     }
886 
887     // Now go through the methods and zero out all the ones we know are
888     // overridden.
889     for (size_t i = 0, e = MethodsSize; i != e; ++i) {
890       if (OverriddenMethods.count(Methods[i]))
891         Methods[i] = 0;
892     }
893 
894   }
895 }
896 
897 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
898                                   unsigned DiagID, AbstractDiagSelID SelID,
899                                   const CXXRecordDecl *CurrentRD) {
900 
901   if (!getLangOptions().CPlusPlus)
902     return false;
903 
904   if (const ArrayType *AT = Context.getAsArrayType(T))
905     return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
906                                   CurrentRD);
907 
908   if (const PointerType *PT = T->getAsPointerType()) {
909     // Find the innermost pointer type.
910     while (const PointerType *T = PT->getPointeeType()->getAsPointerType())
911       PT = T;
912 
913     if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
914       return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
915                                     CurrentRD);
916   }
917 
918   const RecordType *RT = T->getAsRecordType();
919   if (!RT)
920     return false;
921 
922   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
923   if (!RD)
924     return false;
925 
926   if (CurrentRD && CurrentRD != RD)
927     return false;
928 
929   if (!RD->isAbstract())
930     return false;
931 
932   Diag(Loc, DiagID) << RD->getDeclName() << SelID;
933 
934   // Check if we've already emitted the list of pure virtual functions for this
935   // class.
936   if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
937     return true;
938 
939   PureVirtualMethodCollector Collector(Context, RD);
940 
941   for (PureVirtualMethodCollector::MethodList::const_iterator I =
942        Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
943     const CXXMethodDecl *MD = *I;
944 
945     Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
946       MD->getDeclName();
947   }
948 
949   if (!PureVirtualClassDiagSet)
950     PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
951   PureVirtualClassDiagSet->insert(RD);
952 
953   return true;
954 }
955 
956 namespace {
957   class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
958     : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
959     Sema &SemaRef;
960     CXXRecordDecl *AbstractClass;
961 
962     bool VisitDeclContext(const DeclContext *DC) {
963       bool Invalid = false;
964 
965       for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
966            E = DC->decls_end(); I != E; ++I)
967         Invalid |= Visit(*I);
968 
969       return Invalid;
970     }
971 
972   public:
973     AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
974       : SemaRef(SemaRef), AbstractClass(ac) {
975         Visit(SemaRef.Context.getTranslationUnitDecl());
976     }
977 
978     bool VisitFunctionDecl(const FunctionDecl *FD) {
979       if (FD->isThisDeclarationADefinition()) {
980         // No need to do the check if we're in a definition, because it requires
981         // that the return/param types are complete.
982         // because that requires
983         return VisitDeclContext(FD);
984       }
985 
986       // Check the return type.
987       QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
988       bool Invalid =
989         SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
990                                        diag::err_abstract_type_in_decl,
991                                        Sema::AbstractReturnType,
992                                        AbstractClass);
993 
994       for (FunctionDecl::param_const_iterator I = FD->param_begin(),
995            E = FD->param_end(); I != E; ++I) {
996         const ParmVarDecl *VD = *I;
997         Invalid |=
998           SemaRef.RequireNonAbstractType(VD->getLocation(),
999                                          VD->getOriginalType(),
1000                                          diag::err_abstract_type_in_decl,
1001                                          Sema::AbstractParamType,
1002                                          AbstractClass);
1003       }
1004 
1005       return Invalid;
1006     }
1007 
1008     bool VisitDecl(const Decl* D) {
1009       if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1010         return VisitDeclContext(DC);
1011 
1012       return false;
1013     }
1014   };
1015 }
1016 
1017 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
1018                                              DeclPtrTy TagDecl,
1019                                              SourceLocation LBrac,
1020                                              SourceLocation RBrac) {
1021   if (!TagDecl)
1022     return;
1023 
1024   AdjustDeclIfTemplate(TagDecl);
1025   ActOnFields(S, RLoc, TagDecl,
1026               (DeclPtrTy*)FieldCollector->getCurFields(),
1027               FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
1028 
1029   CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
1030   if (!RD->isAbstract()) {
1031     // Collect all the pure virtual methods and see if this is an abstract
1032     // class after all.
1033     PureVirtualMethodCollector Collector(Context, RD);
1034     if (!Collector.empty())
1035       RD->setAbstract(true);
1036   }
1037 
1038   if (RD->isAbstract())
1039     AbstractClassUsageDiagnoser(*this, RD);
1040 
1041   if (RD->hasTrivialConstructor() || RD->hasTrivialDestructor()) {
1042     for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
1043          i != e; ++i) {
1044       // All the nonstatic data members must have trivial constructors.
1045       QualType FTy = i->getType();
1046       while (const ArrayType *AT = Context.getAsArrayType(FTy))
1047         FTy = AT->getElementType();
1048 
1049       if (const RecordType *RT = FTy->getAsRecordType()) {
1050         CXXRecordDecl *FieldRD = cast<CXXRecordDecl>(RT->getDecl());
1051 
1052         if (!FieldRD->hasTrivialConstructor())
1053           RD->setHasTrivialConstructor(false);
1054         if (!FieldRD->hasTrivialDestructor())
1055           RD->setHasTrivialDestructor(false);
1056 
1057         // If RD has neither a trivial constructor nor a trivial destructor
1058         // we don't need to continue checking.
1059         if (!RD->hasTrivialConstructor() && !RD->hasTrivialDestructor())
1060           break;
1061       }
1062     }
1063   }
1064 
1065   if (!RD->isDependentType())
1066     AddImplicitlyDeclaredMembersToClass(RD);
1067 }
1068 
1069 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1070 /// special functions, such as the default constructor, copy
1071 /// constructor, or destructor, to the given C++ class (C++
1072 /// [special]p1).  This routine can only be executed just before the
1073 /// definition of the class is complete.
1074 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
1075   QualType ClassType = Context.getTypeDeclType(ClassDecl);
1076   ClassType = Context.getCanonicalType(ClassType);
1077 
1078   // FIXME: Implicit declarations have exception specifications, which are
1079   // the union of the specifications of the implicitly called functions.
1080 
1081   if (!ClassDecl->hasUserDeclaredConstructor()) {
1082     // C++ [class.ctor]p5:
1083     //   A default constructor for a class X is a constructor of class X
1084     //   that can be called without an argument. If there is no
1085     //   user-declared constructor for class X, a default constructor is
1086     //   implicitly declared. An implicitly-declared default constructor
1087     //   is an inline public member of its class.
1088     DeclarationName Name
1089       = Context.DeclarationNames.getCXXConstructorName(ClassType);
1090     CXXConstructorDecl *DefaultCon =
1091       CXXConstructorDecl::Create(Context, ClassDecl,
1092                                  ClassDecl->getLocation(), Name,
1093                                  Context.getFunctionType(Context.VoidTy,
1094                                                          0, 0, false, 0),
1095                                  /*isExplicit=*/false,
1096                                  /*isInline=*/true,
1097                                  /*isImplicitlyDeclared=*/true);
1098     DefaultCon->setAccess(AS_public);
1099     DefaultCon->setImplicit();
1100     ClassDecl->addDecl(DefaultCon);
1101   }
1102 
1103   if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1104     // C++ [class.copy]p4:
1105     //   If the class definition does not explicitly declare a copy
1106     //   constructor, one is declared implicitly.
1107 
1108     // C++ [class.copy]p5:
1109     //   The implicitly-declared copy constructor for a class X will
1110     //   have the form
1111     //
1112     //       X::X(const X&)
1113     //
1114     //   if
1115     bool HasConstCopyConstructor = true;
1116 
1117     //     -- each direct or virtual base class B of X has a copy
1118     //        constructor whose first parameter is of type const B& or
1119     //        const volatile B&, and
1120     for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1121          HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1122       const CXXRecordDecl *BaseClassDecl
1123         = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1124       HasConstCopyConstructor
1125         = BaseClassDecl->hasConstCopyConstructor(Context);
1126     }
1127 
1128     //     -- for all the nonstatic data members of X that are of a
1129     //        class type M (or array thereof), each such class type
1130     //        has a copy constructor whose first parameter is of type
1131     //        const M& or const volatile M&.
1132     for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1133          HasConstCopyConstructor && Field != ClassDecl->field_end();
1134          ++Field) {
1135       QualType FieldType = (*Field)->getType();
1136       if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1137         FieldType = Array->getElementType();
1138       if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1139         const CXXRecordDecl *FieldClassDecl
1140           = cast<CXXRecordDecl>(FieldClassType->getDecl());
1141         HasConstCopyConstructor
1142           = FieldClassDecl->hasConstCopyConstructor(Context);
1143       }
1144     }
1145 
1146     //   Otherwise, the implicitly declared copy constructor will have
1147     //   the form
1148     //
1149     //       X::X(X&)
1150     QualType ArgType = ClassType;
1151     if (HasConstCopyConstructor)
1152       ArgType = ArgType.withConst();
1153     ArgType = Context.getLValueReferenceType(ArgType);
1154 
1155     //   An implicitly-declared copy constructor is an inline public
1156     //   member of its class.
1157     DeclarationName Name
1158       = Context.DeclarationNames.getCXXConstructorName(ClassType);
1159     CXXConstructorDecl *CopyConstructor
1160       = CXXConstructorDecl::Create(Context, ClassDecl,
1161                                    ClassDecl->getLocation(), Name,
1162                                    Context.getFunctionType(Context.VoidTy,
1163                                                            &ArgType, 1,
1164                                                            false, 0),
1165                                    /*isExplicit=*/false,
1166                                    /*isInline=*/true,
1167                                    /*isImplicitlyDeclared=*/true);
1168     CopyConstructor->setAccess(AS_public);
1169     CopyConstructor->setImplicit();
1170 
1171     // Add the parameter to the constructor.
1172     ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1173                                                  ClassDecl->getLocation(),
1174                                                  /*IdentifierInfo=*/0,
1175                                                  ArgType, VarDecl::None, 0);
1176     CopyConstructor->setParams(Context, &FromParam, 1);
1177     ClassDecl->addDecl(CopyConstructor);
1178   }
1179 
1180   if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1181     // Note: The following rules are largely analoguous to the copy
1182     // constructor rules. Note that virtual bases are not taken into account
1183     // for determining the argument type of the operator. Note also that
1184     // operators taking an object instead of a reference are allowed.
1185     //
1186     // C++ [class.copy]p10:
1187     //   If the class definition does not explicitly declare a copy
1188     //   assignment operator, one is declared implicitly.
1189     //   The implicitly-defined copy assignment operator for a class X
1190     //   will have the form
1191     //
1192     //       X& X::operator=(const X&)
1193     //
1194     //   if
1195     bool HasConstCopyAssignment = true;
1196 
1197     //       -- each direct base class B of X has a copy assignment operator
1198     //          whose parameter is of type const B&, const volatile B& or B,
1199     //          and
1200     for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1201          HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1202       const CXXRecordDecl *BaseClassDecl
1203         = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1204       HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
1205     }
1206 
1207     //       -- for all the nonstatic data members of X that are of a class
1208     //          type M (or array thereof), each such class type has a copy
1209     //          assignment operator whose parameter is of type const M&,
1210     //          const volatile M& or M.
1211     for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1212          HasConstCopyAssignment && Field != ClassDecl->field_end();
1213          ++Field) {
1214       QualType FieldType = (*Field)->getType();
1215       if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1216         FieldType = Array->getElementType();
1217       if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1218         const CXXRecordDecl *FieldClassDecl
1219           = cast<CXXRecordDecl>(FieldClassType->getDecl());
1220         HasConstCopyAssignment
1221           = FieldClassDecl->hasConstCopyAssignment(Context);
1222       }
1223     }
1224 
1225     //   Otherwise, the implicitly declared copy assignment operator will
1226     //   have the form
1227     //
1228     //       X& X::operator=(X&)
1229     QualType ArgType = ClassType;
1230     QualType RetType = Context.getLValueReferenceType(ArgType);
1231     if (HasConstCopyAssignment)
1232       ArgType = ArgType.withConst();
1233     ArgType = Context.getLValueReferenceType(ArgType);
1234 
1235     //   An implicitly-declared copy assignment operator is an inline public
1236     //   member of its class.
1237     DeclarationName Name =
1238       Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1239     CXXMethodDecl *CopyAssignment =
1240       CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1241                             Context.getFunctionType(RetType, &ArgType, 1,
1242                                                     false, 0),
1243                             /*isStatic=*/false, /*isInline=*/true);
1244     CopyAssignment->setAccess(AS_public);
1245     CopyAssignment->setImplicit();
1246 
1247     // Add the parameter to the operator.
1248     ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1249                                                  ClassDecl->getLocation(),
1250                                                  /*IdentifierInfo=*/0,
1251                                                  ArgType, VarDecl::None, 0);
1252     CopyAssignment->setParams(Context, &FromParam, 1);
1253 
1254     // Don't call addedAssignmentOperator. There is no way to distinguish an
1255     // implicit from an explicit assignment operator.
1256     ClassDecl->addDecl(CopyAssignment);
1257   }
1258 
1259   if (!ClassDecl->hasUserDeclaredDestructor()) {
1260     // C++ [class.dtor]p2:
1261     //   If a class has no user-declared destructor, a destructor is
1262     //   declared implicitly. An implicitly-declared destructor is an
1263     //   inline public member of its class.
1264     DeclarationName Name
1265       = Context.DeclarationNames.getCXXDestructorName(ClassType);
1266     CXXDestructorDecl *Destructor
1267       = CXXDestructorDecl::Create(Context, ClassDecl,
1268                                   ClassDecl->getLocation(), Name,
1269                                   Context.getFunctionType(Context.VoidTy,
1270                                                           0, 0, false, 0),
1271                                   /*isInline=*/true,
1272                                   /*isImplicitlyDeclared=*/true);
1273     Destructor->setAccess(AS_public);
1274     Destructor->setImplicit();
1275     ClassDecl->addDecl(Destructor);
1276   }
1277 }
1278 
1279 void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1280   TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1281   if (!Template)
1282     return;
1283 
1284   TemplateParameterList *Params = Template->getTemplateParameters();
1285   for (TemplateParameterList::iterator Param = Params->begin(),
1286                                     ParamEnd = Params->end();
1287        Param != ParamEnd; ++Param) {
1288     NamedDecl *Named = cast<NamedDecl>(*Param);
1289     if (Named->getDeclName()) {
1290       S->AddDecl(DeclPtrTy::make(Named));
1291       IdResolver.AddDecl(Named);
1292     }
1293   }
1294 }
1295 
1296 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
1297 /// parsing a top-level (non-nested) C++ class, and we are now
1298 /// parsing those parts of the given Method declaration that could
1299 /// not be parsed earlier (C++ [class.mem]p2), such as default
1300 /// arguments. This action should enter the scope of the given
1301 /// Method declaration as if we had just parsed the qualified method
1302 /// name. However, it should not bring the parameters into scope;
1303 /// that will be performed by ActOnDelayedCXXMethodParameter.
1304 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1305   if (!MethodD)
1306     return;
1307 
1308   CXXScopeSpec SS;
1309   FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1310   QualType ClassTy
1311     = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1312   SS.setScopeRep(
1313     NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1314   ActOnCXXEnterDeclaratorScope(S, SS);
1315 }
1316 
1317 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
1318 /// C++ method declaration. We're (re-)introducing the given
1319 /// function parameter into scope for use in parsing later parts of
1320 /// the method declaration. For example, we could see an
1321 /// ActOnParamDefaultArgument event for this parameter.
1322 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
1323   if (!ParamD)
1324     return;
1325 
1326   ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
1327 
1328   // If this parameter has an unparsed default argument, clear it out
1329   // to make way for the parsed default argument.
1330   if (Param->hasUnparsedDefaultArg())
1331     Param->setDefaultArg(0);
1332 
1333   S->AddDecl(DeclPtrTy::make(Param));
1334   if (Param->getDeclName())
1335     IdResolver.AddDecl(Param);
1336 }
1337 
1338 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1339 /// processing the delayed method declaration for Method. The method
1340 /// declaration is now considered finished. There may be a separate
1341 /// ActOnStartOfFunctionDef action later (not necessarily
1342 /// immediately!) for this method, if it was also defined inside the
1343 /// class body.
1344 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1345   if (!MethodD)
1346     return;
1347 
1348   FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
1349   CXXScopeSpec SS;
1350   QualType ClassTy
1351     = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1352   SS.setScopeRep(
1353     NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
1354   ActOnCXXExitDeclaratorScope(S, SS);
1355 
1356   // Now that we have our default arguments, check the constructor
1357   // again. It could produce additional diagnostics or affect whether
1358   // the class has implicitly-declared destructors, among other
1359   // things.
1360   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1361     CheckConstructor(Constructor);
1362 
1363   // Check the default arguments, which we may have added.
1364   if (!Method->isInvalidDecl())
1365     CheckCXXDefaultArguments(Method);
1366 }
1367 
1368 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
1369 /// the well-formedness of the constructor declarator @p D with type @p
1370 /// R. If there are any errors in the declarator, this routine will
1371 /// emit diagnostics and set the invalid bit to true.  In any case, the type
1372 /// will be updated to reflect a well-formed type for the constructor and
1373 /// returned.
1374 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1375                                           FunctionDecl::StorageClass &SC) {
1376   bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1377 
1378   // C++ [class.ctor]p3:
1379   //   A constructor shall not be virtual (10.3) or static (9.4). A
1380   //   constructor can be invoked for a const, volatile or const
1381   //   volatile object. A constructor shall not be declared const,
1382   //   volatile, or const volatile (9.3.2).
1383   if (isVirtual) {
1384     if (!D.isInvalidType())
1385       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1386         << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1387         << SourceRange(D.getIdentifierLoc());
1388     D.setInvalidType();
1389   }
1390   if (SC == FunctionDecl::Static) {
1391     if (!D.isInvalidType())
1392       Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1393         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1394         << SourceRange(D.getIdentifierLoc());
1395     D.setInvalidType();
1396     SC = FunctionDecl::None;
1397   }
1398 
1399   DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1400   if (FTI.TypeQuals != 0) {
1401     if (FTI.TypeQuals & QualType::Const)
1402       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1403         << "const" << SourceRange(D.getIdentifierLoc());
1404     if (FTI.TypeQuals & QualType::Volatile)
1405       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1406         << "volatile" << SourceRange(D.getIdentifierLoc());
1407     if (FTI.TypeQuals & QualType::Restrict)
1408       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1409         << "restrict" << SourceRange(D.getIdentifierLoc());
1410   }
1411 
1412   // Rebuild the function type "R" without any type qualifiers (in
1413   // case any of the errors above fired) and with "void" as the
1414   // return type, since constructors don't have return types. We
1415   // *always* have to do this, because GetTypeForDeclarator will
1416   // put in a result type of "int" when none was specified.
1417   const FunctionProtoType *Proto = R->getAsFunctionProtoType();
1418   return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1419                                  Proto->getNumArgs(),
1420                                  Proto->isVariadic(), 0);
1421 }
1422 
1423 /// CheckConstructor - Checks a fully-formed constructor for
1424 /// well-formedness, issuing any diagnostics required. Returns true if
1425 /// the constructor declarator is invalid.
1426 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1427   CXXRecordDecl *ClassDecl
1428     = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1429   if (!ClassDecl)
1430     return Constructor->setInvalidDecl();
1431 
1432   // C++ [class.copy]p3:
1433   //   A declaration of a constructor for a class X is ill-formed if
1434   //   its first parameter is of type (optionally cv-qualified) X and
1435   //   either there are no other parameters or else all other
1436   //   parameters have default arguments.
1437   if (!Constructor->isInvalidDecl() &&
1438       ((Constructor->getNumParams() == 1) ||
1439        (Constructor->getNumParams() > 1 &&
1440         Constructor->getParamDecl(1)->hasDefaultArg()))) {
1441     QualType ParamType = Constructor->getParamDecl(0)->getType();
1442     QualType ClassTy = Context.getTagDeclType(ClassDecl);
1443     if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1444       SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1445       Diag(ParamLoc, diag::err_constructor_byvalue_arg)
1446         << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
1447       Constructor->setInvalidDecl();
1448     }
1449   }
1450 
1451   // Notify the class that we've added a constructor.
1452   ClassDecl->addedConstructor(Context, Constructor);
1453 }
1454 
1455 static inline bool
1456 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1457   return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1458           FTI.ArgInfo[0].Param &&
1459           FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1460 }
1461 
1462 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1463 /// the well-formednes of the destructor declarator @p D with type @p
1464 /// R. If there are any errors in the declarator, this routine will
1465 /// emit diagnostics and set the declarator to invalid.  Even if this happens,
1466 /// will be updated to reflect a well-formed type for the destructor and
1467 /// returned.
1468 QualType Sema::CheckDestructorDeclarator(Declarator &D,
1469                                          FunctionDecl::StorageClass& SC) {
1470   // C++ [class.dtor]p1:
1471   //   [...] A typedef-name that names a class is a class-name
1472   //   (7.1.3); however, a typedef-name that names a class shall not
1473   //   be used as the identifier in the declarator for a destructor
1474   //   declaration.
1475   QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1476   if (isa<TypedefType>(DeclaratorType)) {
1477     Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
1478       << DeclaratorType;
1479     D.setInvalidType();
1480   }
1481 
1482   // C++ [class.dtor]p2:
1483   //   A destructor is used to destroy objects of its class type. A
1484   //   destructor takes no parameters, and no return type can be
1485   //   specified for it (not even void). The address of a destructor
1486   //   shall not be taken. A destructor shall not be static. A
1487   //   destructor can be invoked for a const, volatile or const
1488   //   volatile object. A destructor shall not be declared const,
1489   //   volatile or const volatile (9.3.2).
1490   if (SC == FunctionDecl::Static) {
1491     if (!D.isInvalidType())
1492       Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1493         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1494         << SourceRange(D.getIdentifierLoc());
1495     SC = FunctionDecl::None;
1496     D.setInvalidType();
1497   }
1498   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1499     // Destructors don't have return types, but the parser will
1500     // happily parse something like:
1501     //
1502     //   class X {
1503     //     float ~X();
1504     //   };
1505     //
1506     // The return type will be eliminated later.
1507     Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1508       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1509       << SourceRange(D.getIdentifierLoc());
1510   }
1511 
1512   DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1513   if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
1514     if (FTI.TypeQuals & QualType::Const)
1515       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1516         << "const" << SourceRange(D.getIdentifierLoc());
1517     if (FTI.TypeQuals & QualType::Volatile)
1518       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1519         << "volatile" << SourceRange(D.getIdentifierLoc());
1520     if (FTI.TypeQuals & QualType::Restrict)
1521       Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1522         << "restrict" << SourceRange(D.getIdentifierLoc());
1523     D.setInvalidType();
1524   }
1525 
1526   // Make sure we don't have any parameters.
1527   if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
1528     Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1529 
1530     // Delete the parameters.
1531     FTI.freeArgs();
1532     D.setInvalidType();
1533   }
1534 
1535   // Make sure the destructor isn't variadic.
1536   if (FTI.isVariadic) {
1537     Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1538     D.setInvalidType();
1539   }
1540 
1541   // Rebuild the function type "R" without any type qualifiers or
1542   // parameters (in case any of the errors above fired) and with
1543   // "void" as the return type, since destructors don't have return
1544   // types. We *always* have to do this, because GetTypeForDeclarator
1545   // will put in a result type of "int" when none was specified.
1546   return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1547 }
1548 
1549 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1550 /// well-formednes of the conversion function declarator @p D with
1551 /// type @p R. If there are any errors in the declarator, this routine
1552 /// will emit diagnostics and return true. Otherwise, it will return
1553 /// false. Either way, the type @p R will be updated to reflect a
1554 /// well-formed type for the conversion operator.
1555 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1556                                      FunctionDecl::StorageClass& SC) {
1557   // C++ [class.conv.fct]p1:
1558   //   Neither parameter types nor return type can be specified. The
1559   //   type of a conversion function (8.3.5) is “function taking no
1560   //   parameter returning conversion-type-id.”
1561   if (SC == FunctionDecl::Static) {
1562     if (!D.isInvalidType())
1563       Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1564         << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1565         << SourceRange(D.getIdentifierLoc());
1566     D.setInvalidType();
1567     SC = FunctionDecl::None;
1568   }
1569   if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
1570     // Conversion functions don't have return types, but the parser will
1571     // happily parse something like:
1572     //
1573     //   class X {
1574     //     float operator bool();
1575     //   };
1576     //
1577     // The return type will be changed later anyway.
1578     Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1579       << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1580       << SourceRange(D.getIdentifierLoc());
1581   }
1582 
1583   // Make sure we don't have any parameters.
1584   if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1585     Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1586 
1587     // Delete the parameters.
1588     D.getTypeObject(0).Fun.freeArgs();
1589     D.setInvalidType();
1590   }
1591 
1592   // Make sure the conversion function isn't variadic.
1593   if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
1594     Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1595     D.setInvalidType();
1596   }
1597 
1598   // C++ [class.conv.fct]p4:
1599   //   The conversion-type-id shall not represent a function type nor
1600   //   an array type.
1601   QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1602   if (ConvType->isArrayType()) {
1603     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1604     ConvType = Context.getPointerType(ConvType);
1605     D.setInvalidType();
1606   } else if (ConvType->isFunctionType()) {
1607     Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1608     ConvType = Context.getPointerType(ConvType);
1609     D.setInvalidType();
1610   }
1611 
1612   // Rebuild the function type "R" without any parameters (in case any
1613   // of the errors above fired) and with the conversion type as the
1614   // return type.
1615   R = Context.getFunctionType(ConvType, 0, 0, false,
1616                               R->getAsFunctionProtoType()->getTypeQuals());
1617 
1618   // C++0x explicit conversion operators.
1619   if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1620     Diag(D.getDeclSpec().getExplicitSpecLoc(),
1621          diag::warn_explicit_conversion_functions)
1622       << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1623 }
1624 
1625 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1626 /// the declaration of the given C++ conversion function. This routine
1627 /// is responsible for recording the conversion function in the C++
1628 /// class, if possible.
1629 Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1630   assert(Conversion && "Expected to receive a conversion function declaration");
1631 
1632   // Set the lexical context of this conversion function
1633   Conversion->setLexicalDeclContext(CurContext);
1634 
1635   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
1636 
1637   // Make sure we aren't redeclaring the conversion function.
1638   QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1639 
1640   // C++ [class.conv.fct]p1:
1641   //   [...] A conversion function is never used to convert a
1642   //   (possibly cv-qualified) object to the (possibly cv-qualified)
1643   //   same object type (or a reference to it), to a (possibly
1644   //   cv-qualified) base class of that type (or a reference to it),
1645   //   or to (possibly cv-qualified) void.
1646   // FIXME: Suppress this warning if the conversion function ends up being a
1647   // virtual function that overrides a virtual function in a base class.
1648   QualType ClassType
1649     = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1650   if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1651     ConvType = ConvTypeRef->getPointeeType();
1652   if (ConvType->isRecordType()) {
1653     ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1654     if (ConvType == ClassType)
1655       Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
1656         << ClassType;
1657     else if (IsDerivedFrom(ClassType, ConvType))
1658       Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
1659         <<  ClassType << ConvType;
1660   } else if (ConvType->isVoidType()) {
1661     Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
1662       << ClassType << ConvType;
1663   }
1664 
1665   if (Conversion->getPreviousDeclaration()) {
1666     OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1667     for (OverloadedFunctionDecl::function_iterator
1668            Conv = Conversions->function_begin(),
1669            ConvEnd = Conversions->function_end();
1670          Conv != ConvEnd; ++Conv) {
1671       if (*Conv
1672             == cast_or_null<NamedDecl>(Conversion->getPreviousDeclaration())) {
1673         *Conv = Conversion;
1674         return DeclPtrTy::make(Conversion);
1675       }
1676     }
1677     assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1678   } else
1679     ClassDecl->addConversionFunction(Context, Conversion);
1680 
1681   return DeclPtrTy::make(Conversion);
1682 }
1683 
1684 //===----------------------------------------------------------------------===//
1685 // Namespace Handling
1686 //===----------------------------------------------------------------------===//
1687 
1688 /// ActOnStartNamespaceDef - This is called at the start of a namespace
1689 /// definition.
1690 Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1691                                              SourceLocation IdentLoc,
1692                                              IdentifierInfo *II,
1693                                              SourceLocation LBrace) {
1694   NamespaceDecl *Namespc =
1695       NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1696   Namespc->setLBracLoc(LBrace);
1697 
1698   Scope *DeclRegionScope = NamespcScope->getParent();
1699 
1700   if (II) {
1701     // C++ [namespace.def]p2:
1702     // The identifier in an original-namespace-definition shall not have been
1703     // previously defined in the declarative region in which the
1704     // original-namespace-definition appears. The identifier in an
1705     // original-namespace-definition is the name of the namespace. Subsequently
1706     // in that declarative region, it is treated as an original-namespace-name.
1707 
1708     NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1709                                      true);
1710 
1711     if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1712       // This is an extended namespace definition.
1713       // Attach this namespace decl to the chain of extended namespace
1714       // definitions.
1715       OrigNS->setNextNamespace(Namespc);
1716       Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
1717 
1718       // Remove the previous declaration from the scope.
1719       if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
1720         IdResolver.RemoveDecl(OrigNS);
1721         DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
1722       }
1723     } else if (PrevDecl) {
1724       // This is an invalid name redefinition.
1725       Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1726        << Namespc->getDeclName();
1727       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1728       Namespc->setInvalidDecl();
1729       // Continue on to push Namespc as current DeclContext and return it.
1730     }
1731 
1732     PushOnScopeChains(Namespc, DeclRegionScope);
1733   } else {
1734     // FIXME: Handle anonymous namespaces
1735   }
1736 
1737   // Although we could have an invalid decl (i.e. the namespace name is a
1738   // redefinition), push it as current DeclContext and try to continue parsing.
1739   // FIXME: We should be able to push Namespc here, so that the each DeclContext
1740   // for the namespace has the declarations that showed up in that particular
1741   // namespace definition.
1742   PushDeclContext(NamespcScope, Namespc);
1743   return DeclPtrTy::make(Namespc);
1744 }
1745 
1746 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
1747 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1748 void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1749   Decl *Dcl = D.getAs<Decl>();
1750   NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1751   assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1752   Namespc->setRBracLoc(RBrace);
1753   PopDeclContext();
1754 }
1755 
1756 Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
1757                                           SourceLocation UsingLoc,
1758                                           SourceLocation NamespcLoc,
1759                                           const CXXScopeSpec &SS,
1760                                           SourceLocation IdentLoc,
1761                                           IdentifierInfo *NamespcName,
1762                                           AttributeList *AttrList) {
1763   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1764   assert(NamespcName && "Invalid NamespcName.");
1765   assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1766   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1767 
1768   UsingDirectiveDecl *UDir = 0;
1769 
1770   // Lookup namespace name.
1771   LookupResult R = LookupParsedName(S, &SS, NamespcName,
1772                                     LookupNamespaceName, false);
1773   if (R.isAmbiguous()) {
1774     DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1775     return DeclPtrTy();
1776   }
1777   if (NamedDecl *NS = R) {
1778     assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1779     // C++ [namespace.udir]p1:
1780     //   A using-directive specifies that the names in the nominated
1781     //   namespace can be used in the scope in which the
1782     //   using-directive appears after the using-directive. During
1783     //   unqualified name lookup (3.4.1), the names appear as if they
1784     //   were declared in the nearest enclosing namespace which
1785     //   contains both the using-directive and the nominated
1786     //   namespace. [Note: in this context, “contains” means “contains
1787     //   directly or indirectly”. ]
1788 
1789     // Find enclosing context containing both using-directive and
1790     // nominated namespace.
1791     DeclContext *CommonAncestor = cast<DeclContext>(NS);
1792     while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1793       CommonAncestor = CommonAncestor->getParent();
1794 
1795     UDir = UsingDirectiveDecl::Create(Context,
1796                                       CurContext, UsingLoc,
1797                                       NamespcLoc,
1798                                       SS.getRange(),
1799                                       (NestedNameSpecifier *)SS.getScopeRep(),
1800                                       IdentLoc,
1801                                       cast<NamespaceDecl>(NS),
1802                                       CommonAncestor);
1803     PushUsingDirective(S, UDir);
1804   } else {
1805     Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
1806   }
1807 
1808   // FIXME: We ignore attributes for now.
1809   delete AttrList;
1810   return DeclPtrTy::make(UDir);
1811 }
1812 
1813 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1814   // If scope has associated entity, then using directive is at namespace
1815   // or translation unit scope. We add UsingDirectiveDecls, into
1816   // it's lookup structure.
1817   if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1818     Ctx->addDecl(UDir);
1819   else
1820     // Otherwise it is block-sope. using-directives will affect lookup
1821     // only to the end of scope.
1822     S->PushUsingDirective(DeclPtrTy::make(UDir));
1823 }
1824 
1825 
1826 Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
1827                                           SourceLocation UsingLoc,
1828                                           const CXXScopeSpec &SS,
1829                                           SourceLocation IdentLoc,
1830                                           IdentifierInfo *TargetName,
1831                                           OverloadedOperatorKind Op,
1832                                           AttributeList *AttrList,
1833                                           bool IsTypeName) {
1834   assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1835   assert((TargetName || Op) && "Invalid TargetName.");
1836   assert(IdentLoc.isValid() && "Invalid TargetName location.");
1837   assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1838 
1839   UsingDecl *UsingAlias = 0;
1840 
1841   DeclarationName Name;
1842   if (TargetName)
1843     Name = TargetName;
1844   else
1845     Name = Context.DeclarationNames.getCXXOperatorName(Op);
1846 
1847   // Lookup target name.
1848   LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false);
1849 
1850   if (NamedDecl *NS = R) {
1851     if (IsTypeName && !isa<TypeDecl>(NS)) {
1852       Diag(IdentLoc, diag::err_using_typename_non_type);
1853     }
1854     UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
1855         NS->getLocation(), UsingLoc, NS,
1856         static_cast<NestedNameSpecifier *>(SS.getScopeRep()),
1857         IsTypeName);
1858     PushOnScopeChains(UsingAlias, S);
1859   } else {
1860     Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange();
1861   }
1862 
1863   // FIXME: We ignore attributes for now.
1864   delete AttrList;
1865   return DeclPtrTy::make(UsingAlias);
1866 }
1867 
1868 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
1869 /// is a namespace alias, returns the namespace it points to.
1870 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
1871   if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
1872     return AD->getNamespace();
1873   return dyn_cast_or_null<NamespaceDecl>(D);
1874 }
1875 
1876 Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
1877                                              SourceLocation NamespaceLoc,
1878                                              SourceLocation AliasLoc,
1879                                              IdentifierInfo *Alias,
1880                                              const CXXScopeSpec &SS,
1881                                              SourceLocation IdentLoc,
1882                                              IdentifierInfo *Ident) {
1883 
1884   // Lookup the namespace name.
1885   LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
1886 
1887   // Check if we have a previous declaration with the same name.
1888   if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
1889     if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
1890       // We already have an alias with the same name that points to the same
1891       // namespace, so don't create a new one.
1892       if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
1893         return DeclPtrTy();
1894     }
1895 
1896     unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
1897       diag::err_redefinition_different_kind;
1898     Diag(AliasLoc, DiagID) << Alias;
1899     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1900     return DeclPtrTy();
1901   }
1902 
1903   if (R.isAmbiguous()) {
1904     DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
1905     return DeclPtrTy();
1906   }
1907 
1908   if (!R) {
1909     Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
1910     return DeclPtrTy();
1911   }
1912 
1913   NamespaceAliasDecl *AliasDecl =
1914     NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
1915                                Alias, SS.getRange(),
1916                                (NestedNameSpecifier *)SS.getScopeRep(),
1917                                IdentLoc, R);
1918 
1919   CurContext->addDecl(AliasDecl);
1920   return DeclPtrTy::make(AliasDecl);
1921 }
1922 
1923 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
1924                                             CXXConstructorDecl *Constructor) {
1925   assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
1926           !Constructor->isUsed()) &&
1927     "DefineImplicitDefaultConstructor - call it for implicit default ctor");
1928 
1929   CXXRecordDecl *ClassDecl
1930     = cast<CXXRecordDecl>(Constructor->getDeclContext());
1931   assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
1932   // Before the implicitly-declared default constructor for a class is
1933   // implicitly defined, all the implicitly-declared default constructors
1934   // for its base class and its non-static data members shall have been
1935   // implicitly defined.
1936   bool err = false;
1937   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1938        E = ClassDecl->bases_end(); Base != E; ++Base) {
1939     CXXRecordDecl *BaseClassDecl
1940       = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1941     if (!BaseClassDecl->hasTrivialConstructor()) {
1942       if (CXXConstructorDecl *BaseCtor =
1943             BaseClassDecl->getDefaultConstructor(Context))
1944         MarkDeclarationReferenced(CurrentLocation, BaseCtor);
1945       else {
1946         Diag(CurrentLocation, diag::err_defining_default_ctor)
1947           << Context.getTagDeclType(ClassDecl) << 1
1948           << Context.getTagDeclType(BaseClassDecl);
1949         Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
1950               << Context.getTagDeclType(BaseClassDecl);
1951         err = true;
1952       }
1953     }
1954   }
1955   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1956        E = ClassDecl->field_end(); Field != E; ++Field) {
1957     QualType FieldType = Context.getCanonicalType((*Field)->getType());
1958     if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1959       FieldType = Array->getElementType();
1960     if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1961       CXXRecordDecl *FieldClassDecl
1962         = cast<CXXRecordDecl>(FieldClassType->getDecl());
1963       if (!FieldClassDecl->hasTrivialConstructor()) {
1964         if (CXXConstructorDecl *FieldCtor =
1965             FieldClassDecl->getDefaultConstructor(Context))
1966           MarkDeclarationReferenced(CurrentLocation, FieldCtor);
1967         else {
1968           Diag(CurrentLocation, diag::err_defining_default_ctor)
1969           << Context.getTagDeclType(ClassDecl) << 0 <<
1970               Context.getTagDeclType(FieldClassDecl);
1971           Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
1972           << Context.getTagDeclType(FieldClassDecl);
1973           err = true;
1974         }
1975       }
1976     }
1977     else if (FieldType->isReferenceType()) {
1978       Diag(CurrentLocation, diag::err_unintialized_member)
1979         << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getNameAsCString();
1980       Diag((*Field)->getLocation(), diag::note_declared_at);
1981       err = true;
1982     }
1983     else if (FieldType.isConstQualified()) {
1984       Diag(CurrentLocation, diag::err_unintialized_member)
1985         << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getNameAsCString();
1986        Diag((*Field)->getLocation(), diag::note_declared_at);
1987       err = true;
1988     }
1989   }
1990   if (!err)
1991     Constructor->setUsed();
1992   else
1993     Constructor->setInvalidDecl();
1994 }
1995 
1996 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
1997                                             CXXDestructorDecl *Destructor) {
1998   assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
1999          "DefineImplicitDestructor - call it for implicit default dtor");
2000 
2001   CXXRecordDecl *ClassDecl
2002   = cast<CXXRecordDecl>(Destructor->getDeclContext());
2003   assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2004   // C++ [class.dtor] p5
2005   // Before the implicitly-declared default destructor for a class is
2006   // implicitly defined, all the implicitly-declared default destructors
2007   // for its base class and its non-static data members shall have been
2008   // implicitly defined.
2009   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2010        E = ClassDecl->bases_end(); Base != E; ++Base) {
2011     CXXRecordDecl *BaseClassDecl
2012       = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2013     if (!BaseClassDecl->hasTrivialDestructor()) {
2014       if (CXXDestructorDecl *BaseDtor =
2015           const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2016         MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2017       else
2018         assert(false &&
2019                "DefineImplicitDestructor - missing dtor in a base class");
2020     }
2021   }
2022 
2023   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2024        E = ClassDecl->field_end(); Field != E; ++Field) {
2025     QualType FieldType = Context.getCanonicalType((*Field)->getType());
2026     if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2027       FieldType = Array->getElementType();
2028     if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2029       CXXRecordDecl *FieldClassDecl
2030         = cast<CXXRecordDecl>(FieldClassType->getDecl());
2031       if (!FieldClassDecl->hasTrivialDestructor()) {
2032         if (CXXDestructorDecl *FieldDtor =
2033             const_cast<CXXDestructorDecl*>(
2034                                         FieldClassDecl->getDestructor(Context)))
2035           MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2036         else
2037           assert(false &&
2038           "DefineImplicitDestructor - missing dtor in class of a data member");
2039       }
2040     }
2041   }
2042   Destructor->setUsed();
2043 }
2044 
2045 void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2046                                           CXXMethodDecl *MethodDecl) {
2047   assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2048           MethodDecl->getOverloadedOperator() == OO_Equal &&
2049           !MethodDecl->isUsed()) &&
2050          "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2051 
2052   CXXRecordDecl *ClassDecl
2053     = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
2054 
2055   // C++[class.copy] p12
2056   // Before the implicitly-declared copy assignment operator for a class is
2057   // implicitly defined, all implicitly-declared copy assignment operators
2058   // for its direct base classes and its nonstatic data members shall have
2059   // been implicitly defined.
2060   bool err = false;
2061   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2062        E = ClassDecl->bases_end(); Base != E; ++Base) {
2063     CXXRecordDecl *BaseClassDecl
2064       = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2065     if (CXXMethodDecl *BaseAssignOpMethod =
2066           getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2067       MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2068   }
2069   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2070        E = ClassDecl->field_end(); Field != E; ++Field) {
2071     QualType FieldType = Context.getCanonicalType((*Field)->getType());
2072     if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2073       FieldType = Array->getElementType();
2074     if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2075       CXXRecordDecl *FieldClassDecl
2076         = cast<CXXRecordDecl>(FieldClassType->getDecl());
2077       if (CXXMethodDecl *FieldAssignOpMethod =
2078           getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2079         MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
2080     }
2081     else if (FieldType->isReferenceType()) {
2082       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
2083       << Context.getTagDeclType(ClassDecl) << 0 << (*Field)->getNameAsCString();
2084       Diag((*Field)->getLocation(), diag::note_declared_at);
2085       Diag(CurrentLocation, diag::note_first_required_here);
2086       err = true;
2087     }
2088     else if (FieldType.isConstQualified()) {
2089       Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
2090       << Context.getTagDeclType(ClassDecl) << 1 << (*Field)->getNameAsCString();
2091       Diag((*Field)->getLocation(), diag::note_declared_at);
2092       Diag(CurrentLocation, diag::note_first_required_here);
2093       err = true;
2094     }
2095   }
2096   if (!err)
2097     MethodDecl->setUsed();
2098 }
2099 
2100 CXXMethodDecl *
2101 Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2102                               CXXRecordDecl *ClassDecl) {
2103   QualType LHSType = Context.getTypeDeclType(ClassDecl);
2104   QualType RHSType(LHSType);
2105   // If class's assignment operator argument is const/volatile qualified,
2106   // look for operator = (const/volatile B&). Otherwise, look for
2107   // operator = (B&).
2108   if (ParmDecl->getType().isConstQualified())
2109     RHSType.addConst();
2110   if (ParmDecl->getType().isVolatileQualified())
2111     RHSType.addVolatile();
2112   ExprOwningPtr<Expr> LHS(this,  new (Context) DeclRefExpr(ParmDecl,
2113                                                           LHSType,
2114                                                           SourceLocation()));
2115   ExprOwningPtr<Expr> RHS(this,  new (Context) DeclRefExpr(ParmDecl,
2116                                                           RHSType,
2117                                                           SourceLocation()));
2118   Expr *Args[2] = { &*LHS, &*RHS };
2119   OverloadCandidateSet CandidateSet;
2120   AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2121                               CandidateSet);
2122   OverloadCandidateSet::iterator Best;
2123   if (BestViableFunction(CandidateSet,
2124                          ClassDecl->getLocation(), Best) == OR_Success)
2125     return cast<CXXMethodDecl>(Best->Function);
2126   assert(false &&
2127          "getAssignOperatorMethod - copy assignment operator method not found");
2128   return 0;
2129 }
2130 
2131 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2132                                    CXXConstructorDecl *CopyConstructor,
2133                                    unsigned TypeQuals) {
2134   assert((CopyConstructor->isImplicit() &&
2135           CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2136           !CopyConstructor->isUsed()) &&
2137          "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2138 
2139   CXXRecordDecl *ClassDecl
2140     = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2141   assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
2142   // C++ [class.copy] p209
2143   // Before the implicitly-declared copy constructor for a class is
2144   // implicitly defined, all the implicitly-declared copy constructors
2145   // for its base class and its non-static data members shall have been
2146   // implicitly defined.
2147   for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2148        Base != ClassDecl->bases_end(); ++Base) {
2149     CXXRecordDecl *BaseClassDecl
2150       = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
2151     if (CXXConstructorDecl *BaseCopyCtor =
2152         BaseClassDecl->getCopyConstructor(Context, TypeQuals))
2153       MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
2154   }
2155   for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2156                                   FieldEnd = ClassDecl->field_end();
2157        Field != FieldEnd; ++Field) {
2158     QualType FieldType = Context.getCanonicalType((*Field)->getType());
2159     if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2160       FieldType = Array->getElementType();
2161     if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
2162       CXXRecordDecl *FieldClassDecl
2163         = cast<CXXRecordDecl>(FieldClassType->getDecl());
2164       if (CXXConstructorDecl *FieldCopyCtor =
2165           FieldClassDecl->getCopyConstructor(Context, TypeQuals))
2166         MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
2167     }
2168   }
2169   CopyConstructor->setUsed();
2170 }
2171 
2172 void Sema::InitializeVarWithConstructor(VarDecl *VD,
2173                                         CXXConstructorDecl *Constructor,
2174                                         QualType DeclInitType,
2175                                         Expr **Exprs, unsigned NumExprs) {
2176   Expr *Temp = CXXConstructExpr::Create(Context, DeclInitType, Constructor,
2177                                         false, Exprs, NumExprs);
2178   MarkDeclarationReferenced(VD->getLocation(), Constructor);
2179   VD->setInit(Context, Temp);
2180 }
2181 
2182 void Sema::MarkDestructorReferenced(SourceLocation Loc, QualType DeclInitType)
2183 {
2184   CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
2185                                   DeclInitType->getAsRecordType()->getDecl());
2186   if (!ClassDecl->hasTrivialDestructor())
2187     if (CXXDestructorDecl *Destructor =
2188         const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
2189       MarkDeclarationReferenced(Loc, Destructor);
2190 }
2191 
2192 /// AddCXXDirectInitializerToDecl - This action is called immediately after
2193 /// ActOnDeclarator, when a C++ direct initializer is present.
2194 /// e.g: "int x(1);"
2195 void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2196                                          SourceLocation LParenLoc,
2197                                          MultiExprArg Exprs,
2198                                          SourceLocation *CommaLocs,
2199                                          SourceLocation RParenLoc) {
2200   unsigned NumExprs = Exprs.size();
2201   assert(NumExprs != 0 && Exprs.get() && "missing expressions");
2202   Decl *RealDecl = Dcl.getAs<Decl>();
2203 
2204   // If there is no declaration, there was an error parsing it.  Just ignore
2205   // the initializer.
2206   if (RealDecl == 0)
2207     return;
2208 
2209   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2210   if (!VDecl) {
2211     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2212     RealDecl->setInvalidDecl();
2213     return;
2214   }
2215 
2216   // FIXME: Need to handle dependent types and expressions here.
2217 
2218   // We will treat direct-initialization as a copy-initialization:
2219   //    int x(1);  -as-> int x = 1;
2220   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2221   //
2222   // Clients that want to distinguish between the two forms, can check for
2223   // direct initializer using VarDecl::hasCXXDirectInitializer().
2224   // A major benefit is that clients that don't particularly care about which
2225   // exactly form was it (like the CodeGen) can handle both cases without
2226   // special case code.
2227 
2228   // C++ 8.5p11:
2229   // The form of initialization (using parentheses or '=') is generally
2230   // insignificant, but does matter when the entity being initialized has a
2231   // class type.
2232   QualType DeclInitType = VDecl->getType();
2233   if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2234     DeclInitType = Array->getElementType();
2235 
2236   // FIXME: This isn't the right place to complete the type.
2237   if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2238                           diag::err_typecheck_decl_incomplete_type)) {
2239     VDecl->setInvalidDecl();
2240     return;
2241   }
2242 
2243   if (VDecl->getType()->isRecordType()) {
2244     CXXConstructorDecl *Constructor
2245       = PerformInitializationByConstructor(DeclInitType,
2246                                            (Expr **)Exprs.get(), NumExprs,
2247                                            VDecl->getLocation(),
2248                                            SourceRange(VDecl->getLocation(),
2249                                                        RParenLoc),
2250                                            VDecl->getDeclName(),
2251                                            IK_Direct);
2252     if (!Constructor)
2253       RealDecl->setInvalidDecl();
2254     else {
2255       VDecl->setCXXDirectInitializer(true);
2256       InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2257                                    (Expr**)Exprs.release(), NumExprs);
2258       // FIXME. Must do all that is needed to destroy the object
2259       // on scope exit. For now, just mark the destructor as used.
2260       MarkDestructorReferenced(VDecl->getLocation(), DeclInitType);
2261     }
2262     return;
2263   }
2264 
2265   if (NumExprs > 1) {
2266     Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2267       << SourceRange(VDecl->getLocation(), RParenLoc);
2268     RealDecl->setInvalidDecl();
2269     return;
2270   }
2271 
2272   // Let clients know that initialization was done with a direct initializer.
2273   VDecl->setCXXDirectInitializer(true);
2274 
2275   assert(NumExprs == 1 && "Expected 1 expression");
2276   // Set the init expression, handles conversions.
2277   AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2278                        /*DirectInit=*/true);
2279 }
2280 
2281 /// PerformInitializationByConstructor - Perform initialization by
2282 /// constructor (C++ [dcl.init]p14), which may occur as part of
2283 /// direct-initialization or copy-initialization. We are initializing
2284 /// an object of type @p ClassType with the given arguments @p
2285 /// Args. @p Loc is the location in the source code where the
2286 /// initializer occurs (e.g., a declaration, member initializer,
2287 /// functional cast, etc.) while @p Range covers the whole
2288 /// initialization. @p InitEntity is the entity being initialized,
2289 /// which may by the name of a declaration or a type. @p Kind is the
2290 /// kind of initialization we're performing, which affects whether
2291 /// explicit constructors will be considered. When successful, returns
2292 /// the constructor that will be used to perform the initialization;
2293 /// when the initialization fails, emits a diagnostic and returns
2294 /// null.
2295 CXXConstructorDecl *
2296 Sema::PerformInitializationByConstructor(QualType ClassType,
2297                                          Expr **Args, unsigned NumArgs,
2298                                          SourceLocation Loc, SourceRange Range,
2299                                          DeclarationName InitEntity,
2300                                          InitializationKind Kind) {
2301   const RecordType *ClassRec = ClassType->getAsRecordType();
2302   assert(ClassRec && "Can only initialize a class type here");
2303 
2304   // C++ [dcl.init]p14:
2305   //
2306   //   If the initialization is direct-initialization, or if it is
2307   //   copy-initialization where the cv-unqualified version of the
2308   //   source type is the same class as, or a derived class of, the
2309   //   class of the destination, constructors are considered. The
2310   //   applicable constructors are enumerated (13.3.1.3), and the
2311   //   best one is chosen through overload resolution (13.3). The
2312   //   constructor so selected is called to initialize the object,
2313   //   with the initializer expression(s) as its argument(s). If no
2314   //   constructor applies, or the overload resolution is ambiguous,
2315   //   the initialization is ill-formed.
2316   const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2317   OverloadCandidateSet CandidateSet;
2318 
2319   // Add constructors to the overload set.
2320   DeclarationName ConstructorName
2321     = Context.DeclarationNames.getCXXConstructorName(
2322                        Context.getCanonicalType(ClassType.getUnqualifiedType()));
2323   DeclContext::lookup_const_iterator Con, ConEnd;
2324   for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
2325        Con != ConEnd; ++Con) {
2326     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
2327     if ((Kind == IK_Direct) ||
2328         (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
2329         (Kind == IK_Default && Constructor->isDefaultConstructor()))
2330       AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2331   }
2332 
2333   // FIXME: When we decide not to synthesize the implicitly-declared
2334   // constructors, we'll need to make them appear here.
2335 
2336   OverloadCandidateSet::iterator Best;
2337   switch (BestViableFunction(CandidateSet, Loc, Best)) {
2338   case OR_Success:
2339     // We found a constructor. Return it.
2340     return cast<CXXConstructorDecl>(Best->Function);
2341 
2342   case OR_No_Viable_Function:
2343     if (InitEntity)
2344       Diag(Loc, diag::err_ovl_no_viable_function_in_init)
2345         << InitEntity << Range;
2346     else
2347       Diag(Loc, diag::err_ovl_no_viable_function_in_init)
2348         << ClassType << Range;
2349     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
2350     return 0;
2351 
2352   case OR_Ambiguous:
2353     if (InitEntity)
2354       Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2355     else
2356       Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
2357     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2358     return 0;
2359 
2360   case OR_Deleted:
2361     if (InitEntity)
2362       Diag(Loc, diag::err_ovl_deleted_init)
2363         << Best->Function->isDeleted()
2364         << InitEntity << Range;
2365     else
2366       Diag(Loc, diag::err_ovl_deleted_init)
2367         << Best->Function->isDeleted()
2368         << InitEntity << Range;
2369     PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2370     return 0;
2371   }
2372 
2373   return 0;
2374 }
2375 
2376 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
2377 /// determine whether they are reference-related,
2378 /// reference-compatible, reference-compatible with added
2379 /// qualification, or incompatible, for use in C++ initialization by
2380 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2381 /// type, and the first type (T1) is the pointee type of the reference
2382 /// type being initialized.
2383 Sema::ReferenceCompareResult
2384 Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2385                                    bool& DerivedToBase) {
2386   assert(!T1->isReferenceType() &&
2387     "T1 must be the pointee type of the reference type");
2388   assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2389 
2390   T1 = Context.getCanonicalType(T1);
2391   T2 = Context.getCanonicalType(T2);
2392   QualType UnqualT1 = T1.getUnqualifiedType();
2393   QualType UnqualT2 = T2.getUnqualifiedType();
2394 
2395   // C++ [dcl.init.ref]p4:
2396   //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
2397   //   reference-related to “cv2 T2” if T1 is the same type as T2, or
2398   //   T1 is a base class of T2.
2399   if (UnqualT1 == UnqualT2)
2400     DerivedToBase = false;
2401   else if (IsDerivedFrom(UnqualT2, UnqualT1))
2402     DerivedToBase = true;
2403   else
2404     return Ref_Incompatible;
2405 
2406   // At this point, we know that T1 and T2 are reference-related (at
2407   // least).
2408 
2409   // C++ [dcl.init.ref]p4:
2410   //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
2411   //   reference-related to T2 and cv1 is the same cv-qualification
2412   //   as, or greater cv-qualification than, cv2. For purposes of
2413   //   overload resolution, cases for which cv1 is greater
2414   //   cv-qualification than cv2 are identified as
2415   //   reference-compatible with added qualification (see 13.3.3.2).
2416   if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2417     return Ref_Compatible;
2418   else if (T1.isMoreQualifiedThan(T2))
2419     return Ref_Compatible_With_Added_Qualification;
2420   else
2421     return Ref_Related;
2422 }
2423 
2424 /// CheckReferenceInit - Check the initialization of a reference
2425 /// variable with the given initializer (C++ [dcl.init.ref]). Init is
2426 /// the initializer (either a simple initializer or an initializer
2427 /// list), and DeclType is the type of the declaration. When ICS is
2428 /// non-null, this routine will compute the implicit conversion
2429 /// sequence according to C++ [over.ics.ref] and will not produce any
2430 /// diagnostics; when ICS is null, it will emit diagnostics when any
2431 /// errors are found. Either way, a return value of true indicates
2432 /// that there was a failure, a return value of false indicates that
2433 /// the reference initialization succeeded.
2434 ///
2435 /// When @p SuppressUserConversions, user-defined conversions are
2436 /// suppressed.
2437 /// When @p AllowExplicit, we also permit explicit user-defined
2438 /// conversion functions.
2439 /// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
2440 bool
2441 Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
2442                          ImplicitConversionSequence *ICS,
2443                          bool SuppressUserConversions,
2444                          bool AllowExplicit, bool ForceRValue) {
2445   assert(DeclType->isReferenceType() && "Reference init needs a reference");
2446 
2447   QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
2448   QualType T2 = Init->getType();
2449 
2450   // If the initializer is the address of an overloaded function, try
2451   // to resolve the overloaded function. If all goes well, T2 is the
2452   // type of the resulting function.
2453   if (Context.getCanonicalType(T2) == Context.OverloadTy) {
2454     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2455                                                           ICS != 0);
2456     if (Fn) {
2457       // Since we're performing this reference-initialization for
2458       // real, update the initializer with the resulting function.
2459       if (!ICS) {
2460         if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2461           return true;
2462 
2463         FixOverloadedFunctionReference(Init, Fn);
2464       }
2465 
2466       T2 = Fn->getType();
2467     }
2468   }
2469 
2470   // Compute some basic properties of the types and the initializer.
2471   bool isRValRef = DeclType->isRValueReferenceType();
2472   bool DerivedToBase = false;
2473   Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2474                                                   Init->isLvalue(Context);
2475   ReferenceCompareResult RefRelationship
2476     = CompareReferenceRelationship(T1, T2, DerivedToBase);
2477 
2478   // Most paths end in a failed conversion.
2479   if (ICS)
2480     ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
2481 
2482   // C++ [dcl.init.ref]p5:
2483   //   A reference to type “cv1 T1” is initialized by an expression
2484   //   of type “cv2 T2” as follows:
2485 
2486   //     -- If the initializer expression
2487 
2488   // Rvalue references cannot bind to lvalues (N2812).
2489   // There is absolutely no situation where they can. In particular, note that
2490   // this is ill-formed, even if B has a user-defined conversion to A&&:
2491   //   B b;
2492   //   A&& r = b;
2493   if (isRValRef && InitLvalue == Expr::LV_Valid) {
2494     if (!ICS)
2495       Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2496         << Init->getSourceRange();
2497     return true;
2498   }
2499 
2500   bool BindsDirectly = false;
2501   //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
2502   //          reference-compatible with “cv2 T2,” or
2503   //
2504   // Note that the bit-field check is skipped if we are just computing
2505   // the implicit conversion sequence (C++ [over.best.ics]p2).
2506   if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
2507       RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2508     BindsDirectly = true;
2509 
2510     if (ICS) {
2511       // C++ [over.ics.ref]p1:
2512       //   When a parameter of reference type binds directly (8.5.3)
2513       //   to an argument expression, the implicit conversion sequence
2514       //   is the identity conversion, unless the argument expression
2515       //   has a type that is a derived class of the parameter type,
2516       //   in which case the implicit conversion sequence is a
2517       //   derived-to-base Conversion (13.3.3.1).
2518       ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2519       ICS->Standard.First = ICK_Identity;
2520       ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2521       ICS->Standard.Third = ICK_Identity;
2522       ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2523       ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2524       ICS->Standard.ReferenceBinding = true;
2525       ICS->Standard.DirectBinding = true;
2526       ICS->Standard.RRefBinding = false;
2527       ICS->Standard.CopyConstructor = 0;
2528 
2529       // Nothing more to do: the inaccessibility/ambiguity check for
2530       // derived-to-base conversions is suppressed when we're
2531       // computing the implicit conversion sequence (C++
2532       // [over.best.ics]p2).
2533       return false;
2534     } else {
2535       // Perform the conversion.
2536       // FIXME: Binding to a subobject of the lvalue is going to require more
2537       // AST annotation than this.
2538       ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2539     }
2540   }
2541 
2542   //       -- has a class type (i.e., T2 is a class type) and can be
2543   //          implicitly converted to an lvalue of type “cv3 T3,”
2544   //          where “cv1 T1” is reference-compatible with “cv3 T3”
2545   //          92) (this conversion is selected by enumerating the
2546   //          applicable conversion functions (13.3.1.6) and choosing
2547   //          the best one through overload resolution (13.3)),
2548   if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
2549     // FIXME: Look for conversions in base classes!
2550     CXXRecordDecl *T2RecordDecl
2551       = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
2552 
2553     OverloadCandidateSet CandidateSet;
2554     OverloadedFunctionDecl *Conversions
2555       = T2RecordDecl->getConversionFunctions();
2556     for (OverloadedFunctionDecl::function_iterator Func
2557            = Conversions->function_begin();
2558          Func != Conversions->function_end(); ++Func) {
2559       CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2560 
2561       // If the conversion function doesn't return a reference type,
2562       // it can't be considered for this conversion.
2563       if (Conv->getConversionType()->isLValueReferenceType() &&
2564           (AllowExplicit || !Conv->isExplicit()))
2565         AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2566     }
2567 
2568     OverloadCandidateSet::iterator Best;
2569     switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
2570     case OR_Success:
2571       // This is a direct binding.
2572       BindsDirectly = true;
2573 
2574       if (ICS) {
2575         // C++ [over.ics.ref]p1:
2576         //
2577         //   [...] If the parameter binds directly to the result of
2578         //   applying a conversion function to the argument
2579         //   expression, the implicit conversion sequence is a
2580         //   user-defined conversion sequence (13.3.3.1.2), with the
2581         //   second standard conversion sequence either an identity
2582         //   conversion or, if the conversion function returns an
2583         //   entity of a type that is a derived class of the parameter
2584         //   type, a derived-to-base Conversion.
2585         ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2586         ICS->UserDefined.Before = Best->Conversions[0].Standard;
2587         ICS->UserDefined.After = Best->FinalConversion;
2588         ICS->UserDefined.ConversionFunction = Best->Function;
2589         assert(ICS->UserDefined.After.ReferenceBinding &&
2590                ICS->UserDefined.After.DirectBinding &&
2591                "Expected a direct reference binding!");
2592         return false;
2593       } else {
2594         // Perform the conversion.
2595         // FIXME: Binding to a subobject of the lvalue is going to require more
2596         // AST annotation than this.
2597         ImpCastExprToType(Init, T1, /*isLvalue=*/true);
2598       }
2599       break;
2600 
2601     case OR_Ambiguous:
2602       assert(false && "Ambiguous reference binding conversions not implemented.");
2603       return true;
2604 
2605     case OR_No_Viable_Function:
2606     case OR_Deleted:
2607       // There was no suitable conversion, or we found a deleted
2608       // conversion; continue with other checks.
2609       break;
2610     }
2611   }
2612 
2613   if (BindsDirectly) {
2614     // C++ [dcl.init.ref]p4:
2615     //   [...] In all cases where the reference-related or
2616     //   reference-compatible relationship of two types is used to
2617     //   establish the validity of a reference binding, and T1 is a
2618     //   base class of T2, a program that necessitates such a binding
2619     //   is ill-formed if T1 is an inaccessible (clause 11) or
2620     //   ambiguous (10.2) base class of T2.
2621     //
2622     // Note that we only check this condition when we're allowed to
2623     // complain about errors, because we should not be checking for
2624     // ambiguity (or inaccessibility) unless the reference binding
2625     // actually happens.
2626     if (DerivedToBase)
2627       return CheckDerivedToBaseConversion(T2, T1,
2628                                           Init->getSourceRange().getBegin(),
2629                                           Init->getSourceRange());
2630     else
2631       return false;
2632   }
2633 
2634   //     -- Otherwise, the reference shall be to a non-volatile const
2635   //        type (i.e., cv1 shall be const), or the reference shall be an
2636   //        rvalue reference and the initializer expression shall be an rvalue.
2637   if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
2638     if (!ICS)
2639       Diag(Init->getSourceRange().getBegin(),
2640            diag::err_not_reference_to_const_init)
2641         << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2642         << T2 << Init->getSourceRange();
2643     return true;
2644   }
2645 
2646   //       -- If the initializer expression is an rvalue, with T2 a
2647   //          class type, and “cv1 T1” is reference-compatible with
2648   //          “cv2 T2,” the reference is bound in one of the
2649   //          following ways (the choice is implementation-defined):
2650   //
2651   //          -- The reference is bound to the object represented by
2652   //             the rvalue (see 3.10) or to a sub-object within that
2653   //             object.
2654   //
2655   //          -- A temporary of type “cv1 T2” [sic] is created, and
2656   //             a constructor is called to copy the entire rvalue
2657   //             object into the temporary. The reference is bound to
2658   //             the temporary or to a sub-object within the
2659   //             temporary.
2660   //
2661   //          The constructor that would be used to make the copy
2662   //          shall be callable whether or not the copy is actually
2663   //          done.
2664   //
2665   // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2666   // freedom, so we will always take the first option and never build
2667   // a temporary in this case. FIXME: We will, however, have to check
2668   // for the presence of a copy constructor in C++98/03 mode.
2669   if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2670       RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2671     if (ICS) {
2672       ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2673       ICS->Standard.First = ICK_Identity;
2674       ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2675       ICS->Standard.Third = ICK_Identity;
2676       ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2677       ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
2678       ICS->Standard.ReferenceBinding = true;
2679       ICS->Standard.DirectBinding = false;
2680       ICS->Standard.RRefBinding = isRValRef;
2681       ICS->Standard.CopyConstructor = 0;
2682     } else {
2683       // FIXME: Binding to a subobject of the rvalue is going to require more
2684       // AST annotation than this.
2685       ImpCastExprToType(Init, T1, /*isLvalue=*/false);
2686     }
2687     return false;
2688   }
2689 
2690   //       -- Otherwise, a temporary of type “cv1 T1” is created and
2691   //          initialized from the initializer expression using the
2692   //          rules for a non-reference copy initialization (8.5). The
2693   //          reference is then bound to the temporary. If T1 is
2694   //          reference-related to T2, cv1 must be the same
2695   //          cv-qualification as, or greater cv-qualification than,
2696   //          cv2; otherwise, the program is ill-formed.
2697   if (RefRelationship == Ref_Related) {
2698     // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2699     // we would be reference-compatible or reference-compatible with
2700     // added qualification. But that wasn't the case, so the reference
2701     // initialization fails.
2702     if (!ICS)
2703       Diag(Init->getSourceRange().getBegin(),
2704            diag::err_reference_init_drops_quals)
2705         << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2706         << T2 << Init->getSourceRange();
2707     return true;
2708   }
2709 
2710   // If at least one of the types is a class type, the types are not
2711   // related, and we aren't allowed any user conversions, the
2712   // reference binding fails. This case is important for breaking
2713   // recursion, since TryImplicitConversion below will attempt to
2714   // create a temporary through the use of a copy constructor.
2715   if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2716       (T1->isRecordType() || T2->isRecordType())) {
2717     if (!ICS)
2718       Diag(Init->getSourceRange().getBegin(),
2719            diag::err_typecheck_convert_incompatible)
2720         << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2721     return true;
2722   }
2723 
2724   // Actually try to convert the initializer to T1.
2725   if (ICS) {
2726     // C++ [over.ics.ref]p2:
2727     //
2728     //   When a parameter of reference type is not bound directly to
2729     //   an argument expression, the conversion sequence is the one
2730     //   required to convert the argument expression to the
2731     //   underlying type of the reference according to
2732     //   13.3.3.1. Conceptually, this conversion sequence corresponds
2733     //   to copy-initializing a temporary of the underlying type with
2734     //   the argument expression. Any difference in top-level
2735     //   cv-qualification is subsumed by the initialization itself
2736     //   and does not constitute a conversion.
2737     *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
2738     // Of course, that's still a reference binding.
2739     if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
2740       ICS->Standard.ReferenceBinding = true;
2741       ICS->Standard.RRefBinding = isRValRef;
2742     } else if(ICS->ConversionKind ==
2743               ImplicitConversionSequence::UserDefinedConversion) {
2744       ICS->UserDefined.After.ReferenceBinding = true;
2745       ICS->UserDefined.After.RRefBinding = isRValRef;
2746     }
2747     return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2748   } else {
2749     return PerformImplicitConversion(Init, T1, "initializing");
2750   }
2751 }
2752 
2753 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
2754 /// of this overloaded operator is well-formed. If so, returns false;
2755 /// otherwise, emits appropriate diagnostics and returns true.
2756 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
2757   assert(FnDecl && FnDecl->isOverloadedOperator() &&
2758          "Expected an overloaded operator declaration");
2759 
2760   OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2761 
2762   // C++ [over.oper]p5:
2763   //   The allocation and deallocation functions, operator new,
2764   //   operator new[], operator delete and operator delete[], are
2765   //   described completely in 3.7.3. The attributes and restrictions
2766   //   found in the rest of this subclause do not apply to them unless
2767   //   explicitly stated in 3.7.3.
2768   // FIXME: Write a separate routine for checking this. For now, just allow it.
2769   if (Op == OO_New || Op == OO_Array_New ||
2770       Op == OO_Delete || Op == OO_Array_Delete)
2771     return false;
2772 
2773   // C++ [over.oper]p6:
2774   //   An operator function shall either be a non-static member
2775   //   function or be a non-member function and have at least one
2776   //   parameter whose type is a class, a reference to a class, an
2777   //   enumeration, or a reference to an enumeration.
2778   if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2779     if (MethodDecl->isStatic())
2780       return Diag(FnDecl->getLocation(),
2781                   diag::err_operator_overload_static) << FnDecl->getDeclName();
2782   } else {
2783     bool ClassOrEnumParam = false;
2784     for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2785                                    ParamEnd = FnDecl->param_end();
2786          Param != ParamEnd; ++Param) {
2787       QualType ParamType = (*Param)->getType().getNonReferenceType();
2788       if (ParamType->isDependentType() || ParamType->isRecordType() ||
2789           ParamType->isEnumeralType()) {
2790         ClassOrEnumParam = true;
2791         break;
2792       }
2793     }
2794 
2795     if (!ClassOrEnumParam)
2796       return Diag(FnDecl->getLocation(),
2797                   diag::err_operator_overload_needs_class_or_enum)
2798         << FnDecl->getDeclName();
2799   }
2800 
2801   // C++ [over.oper]p8:
2802   //   An operator function cannot have default arguments (8.3.6),
2803   //   except where explicitly stated below.
2804   //
2805   // Only the function-call operator allows default arguments
2806   // (C++ [over.call]p1).
2807   if (Op != OO_Call) {
2808     for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2809          Param != FnDecl->param_end(); ++Param) {
2810       if ((*Param)->hasUnparsedDefaultArg())
2811         return Diag((*Param)->getLocation(),
2812                     diag::err_operator_overload_default_arg)
2813           << FnDecl->getDeclName();
2814       else if (Expr *DefArg = (*Param)->getDefaultArg())
2815         return Diag((*Param)->getLocation(),
2816                     diag::err_operator_overload_default_arg)
2817           << FnDecl->getDeclName() << DefArg->getSourceRange();
2818     }
2819   }
2820 
2821   static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2822     { false, false, false }
2823 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2824     , { Unary, Binary, MemberOnly }
2825 #include "clang/Basic/OperatorKinds.def"
2826   };
2827 
2828   bool CanBeUnaryOperator = OperatorUses[Op][0];
2829   bool CanBeBinaryOperator = OperatorUses[Op][1];
2830   bool MustBeMemberOperator = OperatorUses[Op][2];
2831 
2832   // C++ [over.oper]p8:
2833   //   [...] Operator functions cannot have more or fewer parameters
2834   //   than the number required for the corresponding operator, as
2835   //   described in the rest of this subclause.
2836   unsigned NumParams = FnDecl->getNumParams()
2837                      + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
2838   if (Op != OO_Call &&
2839       ((NumParams == 1 && !CanBeUnaryOperator) ||
2840        (NumParams == 2 && !CanBeBinaryOperator) ||
2841        (NumParams < 1) || (NumParams > 2))) {
2842     // We have the wrong number of parameters.
2843     unsigned ErrorKind;
2844     if (CanBeUnaryOperator && CanBeBinaryOperator) {
2845       ErrorKind = 2;  // 2 -> unary or binary.
2846     } else if (CanBeUnaryOperator) {
2847       ErrorKind = 0;  // 0 -> unary
2848     } else {
2849       assert(CanBeBinaryOperator &&
2850              "All non-call overloaded operators are unary or binary!");
2851       ErrorKind = 1;  // 1 -> binary
2852     }
2853 
2854     return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
2855       << FnDecl->getDeclName() << NumParams << ErrorKind;
2856   }
2857 
2858   // Overloaded operators other than operator() cannot be variadic.
2859   if (Op != OO_Call &&
2860       FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
2861     return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
2862       << FnDecl->getDeclName();
2863   }
2864 
2865   // Some operators must be non-static member functions.
2866   if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2867     return Diag(FnDecl->getLocation(),
2868                 diag::err_operator_overload_must_be_member)
2869       << FnDecl->getDeclName();
2870   }
2871 
2872   // C++ [over.inc]p1:
2873   //   The user-defined function called operator++ implements the
2874   //   prefix and postfix ++ operator. If this function is a member
2875   //   function with no parameters, or a non-member function with one
2876   //   parameter of class or enumeration type, it defines the prefix
2877   //   increment operator ++ for objects of that type. If the function
2878   //   is a member function with one parameter (which shall be of type
2879   //   int) or a non-member function with two parameters (the second
2880   //   of which shall be of type int), it defines the postfix
2881   //   increment operator ++ for objects of that type.
2882   if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2883     ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2884     bool ParamIsInt = false;
2885     if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2886       ParamIsInt = BT->getKind() == BuiltinType::Int;
2887 
2888     if (!ParamIsInt)
2889       return Diag(LastParam->getLocation(),
2890                   diag::err_operator_overload_post_incdec_must_be_int)
2891         << LastParam->getType() << (Op == OO_MinusMinus);
2892   }
2893 
2894   // Notify the class if it got an assignment operator.
2895   if (Op == OO_Equal) {
2896     // Would have returned earlier otherwise.
2897     assert(isa<CXXMethodDecl>(FnDecl) &&
2898       "Overloaded = not member, but not filtered.");
2899     CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2900     Method->getParent()->addedAssignmentOperator(Context, Method);
2901   }
2902 
2903   return false;
2904 }
2905 
2906 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2907 /// linkage specification, including the language and (if present)
2908 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2909 /// the location of the language string literal, which is provided
2910 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2911 /// the '{' brace. Otherwise, this linkage specification does not
2912 /// have any braces.
2913 Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
2914                                                      SourceLocation ExternLoc,
2915                                                      SourceLocation LangLoc,
2916                                                      const char *Lang,
2917                                                      unsigned StrSize,
2918                                                      SourceLocation LBraceLoc) {
2919   LinkageSpecDecl::LanguageIDs Language;
2920   if (strncmp(Lang, "\"C\"", StrSize) == 0)
2921     Language = LinkageSpecDecl::lang_c;
2922   else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2923     Language = LinkageSpecDecl::lang_cxx;
2924   else {
2925     Diag(LangLoc, diag::err_bad_language);
2926     return DeclPtrTy();
2927   }
2928 
2929   // FIXME: Add all the various semantics of linkage specifications
2930 
2931   LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2932                                                LangLoc, Language,
2933                                                LBraceLoc.isValid());
2934   CurContext->addDecl(D);
2935   PushDeclContext(S, D);
2936   return DeclPtrTy::make(D);
2937 }
2938 
2939 /// ActOnFinishLinkageSpecification - Completely the definition of
2940 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
2941 /// valid, it's the position of the closing '}' brace in a linkage
2942 /// specification that uses braces.
2943 Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
2944                                                       DeclPtrTy LinkageSpec,
2945                                                       SourceLocation RBraceLoc) {
2946   if (LinkageSpec)
2947     PopDeclContext();
2948   return LinkageSpec;
2949 }
2950 
2951 /// \brief Perform semantic analysis for the variable declaration that
2952 /// occurs within a C++ catch clause, returning the newly-created
2953 /// variable.
2954 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
2955                                          IdentifierInfo *Name,
2956                                          SourceLocation Loc,
2957                                          SourceRange Range) {
2958   bool Invalid = false;
2959 
2960   // Arrays and functions decay.
2961   if (ExDeclType->isArrayType())
2962     ExDeclType = Context.getArrayDecayedType(ExDeclType);
2963   else if (ExDeclType->isFunctionType())
2964     ExDeclType = Context.getPointerType(ExDeclType);
2965 
2966   // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2967   // The exception-declaration shall not denote a pointer or reference to an
2968   // incomplete type, other than [cv] void*.
2969   // N2844 forbids rvalue references.
2970   if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
2971     Diag(Loc, diag::err_catch_rvalue_ref) << Range;
2972     Invalid = true;
2973   }
2974 
2975   QualType BaseType = ExDeclType;
2976   int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2977   unsigned DK = diag::err_catch_incomplete;
2978   if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2979     BaseType = Ptr->getPointeeType();
2980     Mode = 1;
2981     DK = diag::err_catch_incomplete_ptr;
2982   } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2983     // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
2984     BaseType = Ref->getPointeeType();
2985     Mode = 2;
2986     DK = diag::err_catch_incomplete_ref;
2987   }
2988   if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
2989       !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
2990     Invalid = true;
2991 
2992   if (!Invalid && !ExDeclType->isDependentType() &&
2993       RequireNonAbstractType(Loc, ExDeclType,
2994                              diag::err_abstract_type_in_decl,
2995                              AbstractVariableType))
2996     Invalid = true;
2997 
2998   // FIXME: Need to test for ability to copy-construct and destroy the
2999   // exception variable.
3000 
3001   // FIXME: Need to check for abstract classes.
3002 
3003   VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
3004                                     Name, ExDeclType, VarDecl::None,
3005                                     Range.getBegin());
3006 
3007   if (Invalid)
3008     ExDecl->setInvalidDecl();
3009 
3010   return ExDecl;
3011 }
3012 
3013 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3014 /// handler.
3015 Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
3016   QualType ExDeclType = GetTypeForDeclarator(D, S);
3017 
3018   bool Invalid = D.isInvalidType();
3019   IdentifierInfo *II = D.getIdentifier();
3020   if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
3021     // The scope should be freshly made just for us. There is just no way
3022     // it contains any previous declaration.
3023     assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
3024     if (PrevDecl->isTemplateParameter()) {
3025       // Maybe we will complain about the shadowed template parameter.
3026       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
3027     }
3028   }
3029 
3030   if (D.getCXXScopeSpec().isSet() && !Invalid) {
3031     Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3032       << D.getCXXScopeSpec().getRange();
3033     Invalid = true;
3034   }
3035 
3036   VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType,
3037                                               D.getIdentifier(),
3038                                               D.getIdentifierLoc(),
3039                                             D.getDeclSpec().getSourceRange());
3040 
3041   if (Invalid)
3042     ExDecl->setInvalidDecl();
3043 
3044   // Add the exception declaration into this scope.
3045   if (II)
3046     PushOnScopeChains(ExDecl, S);
3047   else
3048     CurContext->addDecl(ExDecl);
3049 
3050   ProcessDeclAttributes(S, ExDecl, D);
3051   return DeclPtrTy::make(ExDecl);
3052 }
3053 
3054 Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3055                                                    ExprArg assertexpr,
3056                                                    ExprArg assertmessageexpr) {
3057   Expr *AssertExpr = (Expr *)assertexpr.get();
3058   StringLiteral *AssertMessage =
3059     cast<StringLiteral>((Expr *)assertmessageexpr.get());
3060 
3061   if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3062     llvm::APSInt Value(32);
3063     if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3064       Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3065         AssertExpr->getSourceRange();
3066       return DeclPtrTy();
3067     }
3068 
3069     if (Value == 0) {
3070       std::string str(AssertMessage->getStrData(),
3071                       AssertMessage->getByteLength());
3072       Diag(AssertLoc, diag::err_static_assert_failed)
3073         << str << AssertExpr->getSourceRange();
3074     }
3075   }
3076 
3077   assertexpr.release();
3078   assertmessageexpr.release();
3079   Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3080                                         AssertExpr, AssertMessage);
3081 
3082   CurContext->addDecl(Decl);
3083   return DeclPtrTy::make(Decl);
3084 }
3085 
3086 bool Sema::ActOnFriendDecl(Scope *S, SourceLocation FriendLoc, DeclPtrTy Dcl) {
3087   if (!(S->getFlags() & Scope::ClassScope)) {
3088     Diag(FriendLoc, diag::err_friend_decl_outside_class);
3089     return true;
3090   }
3091 
3092   return false;
3093 }
3094 
3095 void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
3096   Decl *Dcl = dcl.getAs<Decl>();
3097   FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3098   if (!Fn) {
3099     Diag(DelLoc, diag::err_deleted_non_function);
3100     return;
3101   }
3102   if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3103     Diag(DelLoc, diag::err_deleted_decl_not_first);
3104     Diag(Prev->getLocation(), diag::note_previous_declaration);
3105     // If the declaration wasn't the first, we delete the function anyway for
3106     // recovery.
3107   }
3108   Fn->setDeleted();
3109 }
3110 
3111 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3112   for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3113        ++CI) {
3114     Stmt *SubStmt = *CI;
3115     if (!SubStmt)
3116       continue;
3117     if (isa<ReturnStmt>(SubStmt))
3118       Self.Diag(SubStmt->getSourceRange().getBegin(),
3119            diag::err_return_in_constructor_handler);
3120     if (!isa<Expr>(SubStmt))
3121       SearchForReturnInStmt(Self, SubStmt);
3122   }
3123 }
3124 
3125 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3126   for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3127     CXXCatchStmt *Handler = TryBlock->getHandler(I);
3128     SearchForReturnInStmt(*this, Handler);
3129   }
3130 }
3131 
3132 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3133                                              const CXXMethodDecl *Old) {
3134   QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3135   QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3136 
3137   QualType CNewTy = Context.getCanonicalType(NewTy);
3138   QualType COldTy = Context.getCanonicalType(OldTy);
3139 
3140   if (CNewTy == COldTy &&
3141       CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3142     return false;
3143 
3144   // Check if the return types are covariant
3145   QualType NewClassTy, OldClassTy;
3146 
3147   /// Both types must be pointers or references to classes.
3148   if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3149     if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3150       NewClassTy = NewPT->getPointeeType();
3151       OldClassTy = OldPT->getPointeeType();
3152     }
3153   } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3154     if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3155       NewClassTy = NewRT->getPointeeType();
3156       OldClassTy = OldRT->getPointeeType();
3157     }
3158   }
3159 
3160   // The return types aren't either both pointers or references to a class type.
3161   if (NewClassTy.isNull()) {
3162     Diag(New->getLocation(),
3163          diag::err_different_return_type_for_overriding_virtual_function)
3164       << New->getDeclName() << NewTy << OldTy;
3165     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3166 
3167     return true;
3168   }
3169 
3170   if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3171     // Check if the new class derives from the old class.
3172     if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3173       Diag(New->getLocation(),
3174            diag::err_covariant_return_not_derived)
3175       << New->getDeclName() << NewTy << OldTy;
3176       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3177       return true;
3178     }
3179 
3180     // Check if we the conversion from derived to base is valid.
3181     if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3182                       diag::err_covariant_return_inaccessible_base,
3183                       diag::err_covariant_return_ambiguous_derived_to_base_conv,
3184                       // FIXME: Should this point to the return type?
3185                       New->getLocation(), SourceRange(), New->getDeclName())) {
3186       Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3187       return true;
3188     }
3189   }
3190 
3191   // The qualifiers of the return types must be the same.
3192   if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3193     Diag(New->getLocation(),
3194          diag::err_covariant_return_type_different_qualifications)
3195     << New->getDeclName() << NewTy << OldTy;
3196     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3197     return true;
3198   };
3199 
3200 
3201   // The new class type must have the same or less qualifiers as the old type.
3202   if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3203     Diag(New->getLocation(),
3204          diag::err_covariant_return_type_class_type_more_qualified)
3205     << New->getDeclName() << NewTy << OldTy;
3206     Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3207     return true;
3208   };
3209 
3210   return false;
3211 }
3212 
3213 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3214 /// initializer for the declaration 'Dcl'.
3215 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3216 /// static data member of class X, names should be looked up in the scope of
3217 /// class X.
3218 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
3219   Decl *D = Dcl.getAs<Decl>();
3220   // If there is no declaration, there was an error parsing it.
3221   if (D == 0)
3222     return;
3223 
3224   // Check whether it is a declaration with a nested name specifier like
3225   // int foo::bar;
3226   if (!D->isOutOfLine())
3227     return;
3228 
3229   // C++ [basic.lookup.unqual]p13
3230   //
3231   // A name used in the definition of a static data member of class X
3232   // (after the qualified-id of the static member) is looked up as if the name
3233   // was used in a member function of X.
3234 
3235   // Change current context into the context of the initializing declaration.
3236   EnterDeclaratorContext(S, D->getDeclContext());
3237 }
3238 
3239 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3240 /// initializer for the declaration 'Dcl'.
3241 void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
3242   Decl *D = Dcl.getAs<Decl>();
3243   // If there is no declaration, there was an error parsing it.
3244   if (D == 0)
3245     return;
3246 
3247   // Check whether it is a declaration with a nested name specifier like
3248   // int foo::bar;
3249   if (!D->isOutOfLine())
3250     return;
3251 
3252   assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
3253   ExitDeclaratorContext(S);
3254 }
3255