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