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