SemaDeclCXX.cpp revision 3cf538d5c49bbebac1afa6f4a5010e3d877440bb
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/TypeOrdering.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Parse/DeclSpec.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/Support/Compiler.h"
24#include <algorithm> // for std::equal
25#include <map>
26
27using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
33namespace {
34  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35  /// the default argument of a parameter to determine whether it
36  /// contains any ill-formed subexpressions. For example, this will
37  /// diagnose the use of local variables or parameters within the
38  /// default argument expression.
39  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
40    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
41    Expr *DefaultArg;
42    Sema *S;
43
44  public:
45    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46      : DefaultArg(defarg), S(s) {}
47
48    bool VisitExpr(Expr *Node);
49    bool VisitDeclRefExpr(DeclRefExpr *DRE);
50    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
51  };
52
53  /// VisitExpr - Visit all of the children of this expression.
54  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55    bool IsInvalid = false;
56    for (Stmt::child_iterator I = Node->child_begin(),
57         E = Node->child_end(); I != E; ++I)
58      IsInvalid |= Visit(*I);
59    return IsInvalid;
60  }
61
62  /// VisitDeclRefExpr - Visit a reference to a declaration, to
63  /// determine whether this declaration can be used in the default
64  /// argument expression.
65  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
66    NamedDecl *Decl = DRE->getDecl();
67    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68      // C++ [dcl.fct.default]p9
69      //   Default arguments are evaluated each time the function is
70      //   called. The order of evaluation of function arguments is
71      //   unspecified. Consequently, parameters of a function shall not
72      //   be used in default argument expressions, even if they are not
73      //   evaluated. Parameters of a function declared before a default
74      //   argument expression are in scope and can hide namespace and
75      //   class member names.
76      return S->Diag(DRE->getSourceRange().getBegin(),
77                     diag::err_param_default_argument_references_param)
78         << Param->getDeclName() << DefaultArg->getSourceRange();
79    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
80      // C++ [dcl.fct.default]p7
81      //   Local variables shall not be used in default argument
82      //   expressions.
83      if (VDecl->isBlockVarDecl())
84        return S->Diag(DRE->getSourceRange().getBegin(),
85                       diag::err_param_default_argument_references_local)
86          << VDecl->getDeclName() << DefaultArg->getSourceRange();
87    }
88
89    return false;
90  }
91
92  /// VisitCXXThisExpr - Visit a C++ "this" expression.
93  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94    // C++ [dcl.fct.default]p8:
95    //   The keyword this shall not be used in a default argument of a
96    //   member function.
97    return S->Diag(ThisE->getSourceRange().getBegin(),
98                   diag::err_param_default_argument_references_this)
99               << ThisE->getSourceRange();
100  }
101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108                                ExprTy *defarg) {
109  ParmVarDecl *Param = (ParmVarDecl *)param;
110  ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
111  QualType ParamType = Param->getType();
112
113  // Default arguments are only permitted in C++
114  if (!getLangOptions().CPlusPlus) {
115    Diag(EqualLoc, diag::err_param_default_argument)
116      << DefaultArg->getSourceRange();
117    Param->setInvalidDecl();
118    return;
119  }
120
121  // C++ [dcl.fct.default]p5
122  //   A default argument expression is implicitly converted (clause
123  //   4) to the parameter type. The default argument expression has
124  //   the same semantic constraints as the initializer expression in
125  //   a declaration of a variable of the parameter type, using the
126  //   copy-initialization semantics (8.5).
127  Expr *DefaultArgPtr = DefaultArg.get();
128  bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129                                                 EqualLoc,
130                                                 Param->getDeclName(),
131                                                 /*DirectInit=*/false);
132  if (DefaultArgPtr != DefaultArg.get()) {
133    DefaultArg.take();
134    DefaultArg.reset(DefaultArgPtr);
135  }
136  if (DefaultInitFailed) {
137    return;
138  }
139
140  // Check that the default argument is well-formed
141  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
142  if (DefaultArgChecker.Visit(DefaultArg.get())) {
143    Param->setInvalidDecl();
144    return;
145  }
146
147  // Okay: add the default argument to the parameter
148  Param->setDefaultArg(DefaultArg.take());
149}
150
151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156                                             SourceLocation EqualLoc) {
157  ParmVarDecl *Param = (ParmVarDecl*)param;
158  if (Param)
159    Param->setUnparsedDefaultArg();
160}
161
162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165  ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174  // C++ [dcl.fct.default]p3
175  //   A default argument expression shall be specified only in the
176  //   parameter-declaration-clause of a function declaration or in a
177  //   template-parameter (14.1). It shall not be specified for a
178  //   parameter pack. If it is specified in a
179  //   parameter-declaration-clause, it shall not occur within a
180  //   declarator or abstract-declarator of a parameter-declaration.
181  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182    DeclaratorChunk &chunk = D.getTypeObject(i);
183    if (chunk.Kind == DeclaratorChunk::Function) {
184      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
186        if (Param->hasUnparsedDefaultArg()) {
187          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
188          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190          delete Toks;
191          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
192        } else if (Param->getDefaultArg()) {
193          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194            << Param->getDefaultArg()->getSourceRange();
195          Param->setDefaultArg(0);
196        }
197      }
198    }
199  }
200}
201
202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
204// type. Subroutine of MergeFunctionDecl. Returns true if there was an
205// error, false otherwise.
206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207  bool Invalid = false;
208
209  // C++ [dcl.fct.default]p4:
210  //
211  //   For non-template functions, default arguments can be added in
212  //   later declarations of a function in the same
213  //   scope. Declarations in different scopes have completely
214  //   distinct sets of default arguments. That is, declarations in
215  //   inner scopes do not acquire default arguments from
216  //   declarations in outer scopes, and vice versa. In a given
217  //   function declaration, all parameters subsequent to a
218  //   parameter with a default argument shall have default
219  //   arguments supplied in this or previous declarations. A
220  //   default argument shall not be redefined by a later
221  //   declaration (not even to the same value).
222  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
223    ParmVarDecl *OldParam = Old->getParamDecl(p);
224    ParmVarDecl *NewParam = New->getParamDecl(p);
225
226    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
227      Diag(NewParam->getLocation(),
228           diag::err_param_default_argument_redefinition)
229        << NewParam->getDefaultArg()->getSourceRange();
230      Diag(OldParam->getLocation(), diag::note_previous_definition);
231      Invalid = true;
232    } else if (OldParam->getDefaultArg()) {
233      // Merge the old default argument into the new parameter
234      NewParam->setDefaultArg(OldParam->getDefaultArg());
235    }
236  }
237
238  return Invalid;
239}
240
241/// CheckCXXDefaultArguments - Verify that the default arguments for a
242/// function declaration are well-formed according to C++
243/// [dcl.fct.default].
244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
245  unsigned NumParams = FD->getNumParams();
246  unsigned p;
247
248  // Find first parameter with a default argument
249  for (p = 0; p < NumParams; ++p) {
250    ParmVarDecl *Param = FD->getParamDecl(p);
251    if (Param->getDefaultArg())
252      break;
253  }
254
255  // C++ [dcl.fct.default]p4:
256  //   In a given function declaration, all parameters
257  //   subsequent to a parameter with a default argument shall
258  //   have default arguments supplied in this or previous
259  //   declarations. A default argument shall not be redefined
260  //   by a later declaration (not even to the same value).
261  unsigned LastMissingDefaultArg = 0;
262  for(; p < NumParams; ++p) {
263    ParmVarDecl *Param = FD->getParamDecl(p);
264    if (!Param->getDefaultArg()) {
265      if (Param->isInvalidDecl())
266        /* We already complained about this parameter. */;
267      else if (Param->getIdentifier())
268        Diag(Param->getLocation(),
269             diag::err_param_default_argument_missing_name)
270          << Param->getIdentifier();
271      else
272        Diag(Param->getLocation(),
273             diag::err_param_default_argument_missing);
274
275      LastMissingDefaultArg = p;
276    }
277  }
278
279  if (LastMissingDefaultArg > 0) {
280    // Some default arguments were missing. Clear out all of the
281    // default arguments up to (and including) the last missing
282    // default argument, so that we leave the function parameters
283    // in a semantically valid state.
284    for (p = 0; p <= LastMissingDefaultArg; ++p) {
285      ParmVarDecl *Param = FD->getParamDecl(p);
286      if (Param->getDefaultArg()) {
287        if (!Param->hasUnparsedDefaultArg())
288          Param->getDefaultArg()->Destroy(Context);
289        Param->setDefaultArg(0);
290      }
291    }
292  }
293}
294
295/// isCurrentClassName - Determine whether the identifier II is the
296/// name of the class type currently being defined. In the case of
297/// nested classes, this will only return true if II is the name of
298/// the innermost class.
299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300                              const CXXScopeSpec *SS) {
301  CXXRecordDecl *CurDecl;
302  if (SS) {
303    DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
304    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
305  } else
306    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
307
308  if (CurDecl)
309    return &II == CurDecl->getIdentifier();
310  else
311    return false;
312}
313
314/// \brief Check the validity of a C++ base class specifier.
315///
316/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
317/// and returns NULL otherwise.
318CXXBaseSpecifier *
319Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
320                         SourceRange SpecifierRange,
321                         bool Virtual, AccessSpecifier Access,
322                         QualType BaseType,
323                         SourceLocation BaseLoc) {
324  // C++ [class.union]p1:
325  //   A union shall not have base classes.
326  if (Class->isUnion()) {
327    Diag(Class->getLocation(), diag::err_base_clause_on_union)
328      << SpecifierRange;
329    return 0;
330  }
331
332  if (BaseType->isDependentType())
333    return new CXXBaseSpecifier(SpecifierRange, Virtual,
334                                Class->getTagKind() == RecordDecl::TK_class,
335                                Access, BaseType);
336
337  // Base specifiers must be record types.
338  if (!BaseType->isRecordType()) {
339    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
340    return 0;
341  }
342
343  // C++ [class.union]p1:
344  //   A union shall not be used as a base class.
345  if (BaseType->isUnionType()) {
346    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
347    return 0;
348  }
349
350  // C++ [class.derived]p2:
351  //   The class-name in a base-specifier shall not be an incompletely
352  //   defined class.
353  if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
354                          SpecifierRange))
355    return 0;
356
357  // If the base class is polymorphic, the new one is, too.
358  RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
359  assert(BaseDecl && "Record type has no declaration");
360  BaseDecl = BaseDecl->getDefinition(Context);
361  assert(BaseDecl && "Base type is not incomplete, but has no definition");
362  if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
363    Class->setPolymorphic(true);
364
365  // C++ [dcl.init.aggr]p1:
366  //   An aggregate is [...] a class with [...] no base classes [...].
367  Class->setAggregate(false);
368  Class->setPOD(false);
369
370  // Create the base specifier.
371  // FIXME: Allocate via ASTContext?
372  return new CXXBaseSpecifier(SpecifierRange, Virtual,
373                              Class->getTagKind() == RecordDecl::TK_class,
374                              Access, BaseType);
375}
376
377/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
378/// one entry in the base class list of a class specifier, for
379/// example:
380///    class foo : public bar, virtual private baz {
381/// 'public bar' and 'virtual private baz' are each base-specifiers.
382Sema::BaseResult
383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
384                         bool Virtual, AccessSpecifier Access,
385                         TypeTy *basetype, SourceLocation BaseLoc) {
386  AdjustDeclIfTemplate(classdecl);
387  CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl);
388  QualType BaseType = QualType::getFromOpaquePtr(basetype);
389  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
390                                                      Virtual, Access,
391                                                      BaseType, BaseLoc))
392    return BaseSpec;
393
394  return true;
395}
396
397/// \brief Performs the actual work of attaching the given base class
398/// specifiers to a C++ class.
399bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
400                                unsigned NumBases) {
401 if (NumBases == 0)
402    return false;
403
404  // Used to keep track of which base types we have already seen, so
405  // that we can properly diagnose redundant direct base types. Note
406  // that the key is always the unqualified canonical type of the base
407  // class.
408  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
409
410  // Copy non-redundant base specifiers into permanent storage.
411  unsigned NumGoodBases = 0;
412  bool Invalid = false;
413  for (unsigned idx = 0; idx < NumBases; ++idx) {
414    QualType NewBaseType
415      = Context.getCanonicalType(Bases[idx]->getType());
416    NewBaseType = NewBaseType.getUnqualifiedType();
417
418    if (KnownBaseTypes[NewBaseType]) {
419      // C++ [class.mi]p3:
420      //   A class shall not be specified as a direct base class of a
421      //   derived class more than once.
422      Diag(Bases[idx]->getSourceRange().getBegin(),
423           diag::err_duplicate_base_class)
424        << KnownBaseTypes[NewBaseType]->getType()
425        << Bases[idx]->getSourceRange();
426
427      // Delete the duplicate base class specifier; we're going to
428      // overwrite its pointer later.
429      delete Bases[idx];
430
431      Invalid = true;
432    } else {
433      // Okay, add this new base class.
434      KnownBaseTypes[NewBaseType] = Bases[idx];
435      Bases[NumGoodBases++] = Bases[idx];
436    }
437  }
438
439  // Attach the remaining base class specifiers to the derived class.
440  Class->setBases(Bases, NumGoodBases);
441
442  // Delete the remaining (good) base class specifiers, since their
443  // data has been copied into the CXXRecordDecl.
444  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
445    delete Bases[idx];
446
447  return Invalid;
448}
449
450/// ActOnBaseSpecifiers - Attach the given base specifiers to the
451/// class, after checking whether there are any duplicate base
452/// classes.
453void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
454                               unsigned NumBases) {
455  if (!ClassDecl || !Bases || !NumBases)
456    return;
457
458  AdjustDeclIfTemplate(ClassDecl);
459  AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
460                       (CXXBaseSpecifier**)(Bases), NumBases);
461}
462
463//===----------------------------------------------------------------------===//
464// C++ class member Handling
465//===----------------------------------------------------------------------===//
466
467/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
468/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
469/// bitfield width if there is one and 'InitExpr' specifies the initializer if
470/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
471/// declarators on it.
472Sema::DeclTy *
473Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
474                               ExprTy *BW, ExprTy *InitExpr,
475                               DeclTy *LastInGroup) {
476  const DeclSpec &DS = D.getDeclSpec();
477  DeclarationName Name = GetNameForDeclarator(D);
478  Expr *BitWidth = static_cast<Expr*>(BW);
479  Expr *Init = static_cast<Expr*>(InitExpr);
480  SourceLocation Loc = D.getIdentifierLoc();
481
482  bool isFunc = D.isFunctionDeclarator();
483
484  // C++ 9.2p6: A member shall not be declared to have automatic storage
485  // duration (auto, register) or with the extern storage-class-specifier.
486  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
487  // data members and cannot be applied to names declared const or static,
488  // and cannot be applied to reference members.
489  switch (DS.getStorageClassSpec()) {
490    case DeclSpec::SCS_unspecified:
491    case DeclSpec::SCS_typedef:
492    case DeclSpec::SCS_static:
493      // FALL THROUGH.
494      break;
495    case DeclSpec::SCS_mutable:
496      if (isFunc) {
497        if (DS.getStorageClassSpecLoc().isValid())
498          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
499        else
500          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
501
502        // FIXME: It would be nicer if the keyword was ignored only for this
503        // declarator. Otherwise we could get follow-up errors.
504        D.getMutableDeclSpec().ClearStorageClassSpecs();
505      } else {
506        QualType T = GetTypeForDeclarator(D, S);
507        diag::kind err = static_cast<diag::kind>(0);
508        if (T->isReferenceType())
509          err = diag::err_mutable_reference;
510        else if (T.isConstQualified())
511          err = diag::err_mutable_const;
512        if (err != 0) {
513          if (DS.getStorageClassSpecLoc().isValid())
514            Diag(DS.getStorageClassSpecLoc(), err);
515          else
516            Diag(DS.getThreadSpecLoc(), err);
517          // FIXME: It would be nicer if the keyword was ignored only for this
518          // declarator. Otherwise we could get follow-up errors.
519          D.getMutableDeclSpec().ClearStorageClassSpecs();
520        }
521      }
522      break;
523    default:
524      if (DS.getStorageClassSpecLoc().isValid())
525        Diag(DS.getStorageClassSpecLoc(),
526             diag::err_storageclass_invalid_for_member);
527      else
528        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
529      D.getMutableDeclSpec().ClearStorageClassSpecs();
530  }
531
532  if (!isFunc &&
533      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
534      D.getNumTypeObjects() == 0) {
535    // Check also for this case:
536    //
537    // typedef int f();
538    // f a;
539    //
540    QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
541    isFunc = TDType->isFunctionType();
542  }
543
544  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
545                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
546                      !isFunc);
547
548  Decl *Member;
549  if (isInstField) {
550    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth);
551    assert(Member && "HandleField never returns null");
552  } else {
553    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
554    if (!Member) {
555      if (BitWidth) DeleteExpr(BitWidth);
556      return LastInGroup;
557    }
558
559    // Non-instance-fields can't have a bitfield.
560    if (BitWidth) {
561      if (Member->isInvalidDecl()) {
562        // don't emit another diagnostic.
563      } else if (isa<CXXClassVarDecl>(Member)) {
564        // C++ 9.6p3: A bit-field shall not be a static member.
565        // "static member 'A' cannot be a bit-field"
566        Diag(Loc, diag::err_static_not_bitfield)
567          << Name << BitWidth->getSourceRange();
568      } else if (isa<TypedefDecl>(Member)) {
569        // "typedef member 'x' cannot be a bit-field"
570        Diag(Loc, diag::err_typedef_not_bitfield)
571          << Name << BitWidth->getSourceRange();
572      } else {
573        // A function typedef ("typedef int f(); f a;").
574        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
575        Diag(Loc, diag::err_not_integral_type_bitfield)
576          << Name << cast<ValueDecl>(Member)->getType()
577          << BitWidth->getSourceRange();
578      }
579
580      DeleteExpr(BitWidth);
581      BitWidth = 0;
582      Member->setInvalidDecl();
583    }
584  }
585
586  assert((Name || isInstField) && "No identifier for non-field ?");
587
588  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
589  // specific methods. Use a wrapper class that can be used with all C++ class
590  // member decls.
591  CXXClassMemberWrapper(Member).setAccess(AS);
592
593  // C++ [dcl.init.aggr]p1:
594  //   An aggregate is an array or a class (clause 9) with [...] no
595  //   private or protected non-static data members (clause 11).
596  // A POD must be an aggregate.
597  if (isInstField && (AS == AS_private || AS == AS_protected)) {
598    CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
599    Record->setAggregate(false);
600    Record->setPOD(false);
601  }
602
603  if (DS.isVirtualSpecified()) {
604    if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
605      Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
606      Member->setInvalidDecl();
607    } else {
608      cast<CXXMethodDecl>(Member)->setVirtual();
609      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
610      CurClass->setAggregate(false);
611      CurClass->setPOD(false);
612      CurClass->setPolymorphic(true);
613    }
614  }
615
616  // FIXME: The above definition of virtual is not sufficient. A function is
617  // also virtual if it overrides an already virtual function. This is important
618  // to do here because it decides the validity of a pure specifier.
619
620  if (Init) {
621    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
622    // if it declares a static member of const integral or const enumeration
623    // type.
624    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
625      // ...static member of...
626      CVD->setInit(Init);
627      // ...const integral or const enumeration type.
628      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
629          CVD->getType()->isIntegralType()) {
630        // constant-initializer
631        if (CheckForConstantInitializer(Init, CVD->getType()))
632          Member->setInvalidDecl();
633
634      } else {
635        // not const integral.
636        Diag(Loc, diag::err_member_initialization)
637          << Name << Init->getSourceRange();
638        Member->setInvalidDecl();
639      }
640
641    } else {
642      // not static member. perhaps virtual function?
643      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
644        // With declarators parsed the way they are, the parser cannot
645        // distinguish between a normal initializer and a pure-specifier.
646        // Thus this grotesque test.
647        IntegerLiteral *IL;
648        if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
649            Context.getCanonicalType(IL->getType()) == Context.IntTy) {
650          if (MD->isVirtual())
651            MD->setPure();
652          else {
653            Diag(Loc, diag::err_non_virtual_pure)
654              << Name << Init->getSourceRange();
655            Member->setInvalidDecl();
656          }
657        } else {
658          Diag(Loc, diag::err_member_function_initialization)
659            << Name << Init->getSourceRange();
660          Member->setInvalidDecl();
661        }
662      } else {
663        Diag(Loc, diag::err_member_initialization)
664          << Name << Init->getSourceRange();
665        Member->setInvalidDecl();
666      }
667    }
668  }
669
670  if (isInstField) {
671    FieldCollector->Add(cast<FieldDecl>(Member));
672    return LastInGroup;
673  }
674  return Member;
675}
676
677/// ActOnMemInitializer - Handle a C++ member initializer.
678Sema::MemInitResult
679Sema::ActOnMemInitializer(DeclTy *ConstructorD,
680                          Scope *S,
681                          IdentifierInfo *MemberOrBase,
682                          SourceLocation IdLoc,
683                          SourceLocation LParenLoc,
684                          ExprTy **Args, unsigned NumArgs,
685                          SourceLocation *CommaLocs,
686                          SourceLocation RParenLoc) {
687  CXXConstructorDecl *Constructor
688    = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
689  if (!Constructor) {
690    // The user wrote a constructor initializer on a function that is
691    // not a C++ constructor. Ignore the error for now, because we may
692    // have more member initializers coming; we'll diagnose it just
693    // once in ActOnMemInitializers.
694    return true;
695  }
696
697  CXXRecordDecl *ClassDecl = Constructor->getParent();
698
699  // C++ [class.base.init]p2:
700  //   Names in a mem-initializer-id are looked up in the scope of the
701  //   constructor’s class and, if not found in that scope, are looked
702  //   up in the scope containing the constructor’s
703  //   definition. [Note: if the constructor’s class contains a member
704  //   with the same name as a direct or virtual base class of the
705  //   class, a mem-initializer-id naming the member or base class and
706  //   composed of a single identifier refers to the class member. A
707  //   mem-initializer-id for the hidden base class may be specified
708  //   using a qualified name. ]
709  // Look for a member, first.
710  FieldDecl *Member = 0;
711  DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
712  if (Result.first != Result.second)
713    Member = dyn_cast<FieldDecl>(*Result.first);
714
715  // FIXME: Handle members of an anonymous union.
716
717  if (Member) {
718    // FIXME: Perform direct initialization of the member.
719    return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
720  }
721
722  // It didn't name a member, so see if it names a class.
723  TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
724  if (!BaseTy)
725    return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
726      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
727
728  QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
729  if (!BaseType->isRecordType())
730    return Diag(IdLoc, diag::err_base_init_does_not_name_class)
731      << BaseType << SourceRange(IdLoc, RParenLoc);
732
733  // C++ [class.base.init]p2:
734  //   [...] Unless the mem-initializer-id names a nonstatic data
735  //   member of the constructor’s class or a direct or virtual base
736  //   of that class, the mem-initializer is ill-formed. A
737  //   mem-initializer-list can initialize a base class using any
738  //   name that denotes that base class type.
739
740  // First, check for a direct base class.
741  const CXXBaseSpecifier *DirectBaseSpec = 0;
742  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
743       Base != ClassDecl->bases_end(); ++Base) {
744    if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
745        Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
746      // We found a direct base of this type. That's what we're
747      // initializing.
748      DirectBaseSpec = &*Base;
749      break;
750    }
751  }
752
753  // Check for a virtual base class.
754  // FIXME: We might be able to short-circuit this if we know in
755  // advance that there are no virtual bases.
756  const CXXBaseSpecifier *VirtualBaseSpec = 0;
757  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
758    // We haven't found a base yet; search the class hierarchy for a
759    // virtual base class.
760    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
761                    /*DetectVirtual=*/false);
762    if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
763      for (BasePaths::paths_iterator Path = Paths.begin();
764           Path != Paths.end(); ++Path) {
765        if (Path->back().Base->isVirtual()) {
766          VirtualBaseSpec = Path->back().Base;
767          break;
768        }
769      }
770    }
771  }
772
773  // C++ [base.class.init]p2:
774  //   If a mem-initializer-id is ambiguous because it designates both
775  //   a direct non-virtual base class and an inherited virtual base
776  //   class, the mem-initializer is ill-formed.
777  if (DirectBaseSpec && VirtualBaseSpec)
778    return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
779      << MemberOrBase << SourceRange(IdLoc, RParenLoc);
780
781  return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
782}
783
784
785void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
786                                             DeclTy *TagDecl,
787                                             SourceLocation LBrac,
788                                             SourceLocation RBrac) {
789  TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
790  ActOnFields(S, RLoc, TagDecl,
791              (DeclTy**)FieldCollector->getCurFields(),
792              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
793
794  if (!Template)
795    AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
796}
797
798/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
799/// special functions, such as the default constructor, copy
800/// constructor, or destructor, to the given C++ class (C++
801/// [special]p1).  This routine can only be executed just before the
802/// definition of the class is complete.
803void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
804  QualType ClassType = Context.getTypeDeclType(ClassDecl);
805  ClassType = Context.getCanonicalType(ClassType);
806
807  if (!ClassDecl->hasUserDeclaredConstructor()) {
808    // C++ [class.ctor]p5:
809    //   A default constructor for a class X is a constructor of class X
810    //   that can be called without an argument. If there is no
811    //   user-declared constructor for class X, a default constructor is
812    //   implicitly declared. An implicitly-declared default constructor
813    //   is an inline public member of its class.
814    DeclarationName Name
815      = Context.DeclarationNames.getCXXConstructorName(ClassType);
816    CXXConstructorDecl *DefaultCon =
817      CXXConstructorDecl::Create(Context, ClassDecl,
818                                 ClassDecl->getLocation(), Name,
819                                 Context.getFunctionType(Context.VoidTy,
820                                                         0, 0, false, 0),
821                                 /*isExplicit=*/false,
822                                 /*isInline=*/true,
823                                 /*isImplicitlyDeclared=*/true);
824    DefaultCon->setAccess(AS_public);
825    DefaultCon->setImplicit();
826    ClassDecl->addDecl(DefaultCon);
827
828    // Notify the class that we've added a constructor.
829    ClassDecl->addedConstructor(Context, DefaultCon);
830  }
831
832  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
833    // C++ [class.copy]p4:
834    //   If the class definition does not explicitly declare a copy
835    //   constructor, one is declared implicitly.
836
837    // C++ [class.copy]p5:
838    //   The implicitly-declared copy constructor for a class X will
839    //   have the form
840    //
841    //       X::X(const X&)
842    //
843    //   if
844    bool HasConstCopyConstructor = true;
845
846    //     -- each direct or virtual base class B of X has a copy
847    //        constructor whose first parameter is of type const B& or
848    //        const volatile B&, and
849    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
850         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
851      const CXXRecordDecl *BaseClassDecl
852        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
853      HasConstCopyConstructor
854        = BaseClassDecl->hasConstCopyConstructor(Context);
855    }
856
857    //     -- for all the nonstatic data members of X that are of a
858    //        class type M (or array thereof), each such class type
859    //        has a copy constructor whose first parameter is of type
860    //        const M& or const volatile M&.
861    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
862         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
863      QualType FieldType = (*Field)->getType();
864      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
865        FieldType = Array->getElementType();
866      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
867        const CXXRecordDecl *FieldClassDecl
868          = cast<CXXRecordDecl>(FieldClassType->getDecl());
869        HasConstCopyConstructor
870          = FieldClassDecl->hasConstCopyConstructor(Context);
871      }
872    }
873
874    //   Otherwise, the implicitly declared copy constructor will have
875    //   the form
876    //
877    //       X::X(X&)
878    QualType ArgType = ClassType;
879    if (HasConstCopyConstructor)
880      ArgType = ArgType.withConst();
881    ArgType = Context.getReferenceType(ArgType);
882
883    //   An implicitly-declared copy constructor is an inline public
884    //   member of its class.
885    DeclarationName Name
886      = Context.DeclarationNames.getCXXConstructorName(ClassType);
887    CXXConstructorDecl *CopyConstructor
888      = CXXConstructorDecl::Create(Context, ClassDecl,
889                                   ClassDecl->getLocation(), Name,
890                                   Context.getFunctionType(Context.VoidTy,
891                                                           &ArgType, 1,
892                                                           false, 0),
893                                   /*isExplicit=*/false,
894                                   /*isInline=*/true,
895                                   /*isImplicitlyDeclared=*/true);
896    CopyConstructor->setAccess(AS_public);
897    CopyConstructor->setImplicit();
898
899    // Add the parameter to the constructor.
900    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
901                                                 ClassDecl->getLocation(),
902                                                 /*IdentifierInfo=*/0,
903                                                 ArgType, VarDecl::None, 0);
904    CopyConstructor->setParams(Context, &FromParam, 1);
905
906    ClassDecl->addedConstructor(Context, CopyConstructor);
907    ClassDecl->addDecl(CopyConstructor);
908  }
909
910  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
911    // Note: The following rules are largely analoguous to the copy
912    // constructor rules. Note that virtual bases are not taken into account
913    // for determining the argument type of the operator. Note also that
914    // operators taking an object instead of a reference are allowed.
915    //
916    // C++ [class.copy]p10:
917    //   If the class definition does not explicitly declare a copy
918    //   assignment operator, one is declared implicitly.
919    //   The implicitly-defined copy assignment operator for a class X
920    //   will have the form
921    //
922    //       X& X::operator=(const X&)
923    //
924    //   if
925    bool HasConstCopyAssignment = true;
926
927    //       -- each direct base class B of X has a copy assignment operator
928    //          whose parameter is of type const B&, const volatile B& or B,
929    //          and
930    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
931         HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
932      const CXXRecordDecl *BaseClassDecl
933        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
934      HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
935    }
936
937    //       -- for all the nonstatic data members of X that are of a class
938    //          type M (or array thereof), each such class type has a copy
939    //          assignment operator whose parameter is of type const M&,
940    //          const volatile M& or M.
941    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
942         HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
943      QualType FieldType = (*Field)->getType();
944      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
945        FieldType = Array->getElementType();
946      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
947        const CXXRecordDecl *FieldClassDecl
948          = cast<CXXRecordDecl>(FieldClassType->getDecl());
949        HasConstCopyAssignment
950          = FieldClassDecl->hasConstCopyAssignment(Context);
951      }
952    }
953
954    //   Otherwise, the implicitly declared copy assignment operator will
955    //   have the form
956    //
957    //       X& X::operator=(X&)
958    QualType ArgType = ClassType;
959    QualType RetType = Context.getReferenceType(ArgType);
960    if (HasConstCopyAssignment)
961      ArgType = ArgType.withConst();
962    ArgType = Context.getReferenceType(ArgType);
963
964    //   An implicitly-declared copy assignment operator is an inline public
965    //   member of its class.
966    DeclarationName Name =
967      Context.DeclarationNames.getCXXOperatorName(OO_Equal);
968    CXXMethodDecl *CopyAssignment =
969      CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
970                            Context.getFunctionType(RetType, &ArgType, 1,
971                                                    false, 0),
972                            /*isStatic=*/false, /*isInline=*/true);
973    CopyAssignment->setAccess(AS_public);
974    CopyAssignment->setImplicit();
975
976    // Add the parameter to the operator.
977    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
978                                                 ClassDecl->getLocation(),
979                                                 /*IdentifierInfo=*/0,
980                                                 ArgType, VarDecl::None, 0);
981    CopyAssignment->setParams(Context, &FromParam, 1);
982
983    // Don't call addedAssignmentOperator. There is no way to distinguish an
984    // implicit from an explicit assignment operator.
985    ClassDecl->addDecl(CopyAssignment);
986  }
987
988  if (!ClassDecl->hasUserDeclaredDestructor()) {
989    // C++ [class.dtor]p2:
990    //   If a class has no user-declared destructor, a destructor is
991    //   declared implicitly. An implicitly-declared destructor is an
992    //   inline public member of its class.
993    DeclarationName Name
994      = Context.DeclarationNames.getCXXDestructorName(ClassType);
995    CXXDestructorDecl *Destructor
996      = CXXDestructorDecl::Create(Context, ClassDecl,
997                                  ClassDecl->getLocation(), Name,
998                                  Context.getFunctionType(Context.VoidTy,
999                                                          0, 0, false, 0),
1000                                  /*isInline=*/true,
1001                                  /*isImplicitlyDeclared=*/true);
1002    Destructor->setAccess(AS_public);
1003    Destructor->setImplicit();
1004    ClassDecl->addDecl(Destructor);
1005  }
1006}
1007
1008/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1009/// parsing a top-level (non-nested) C++ class, and we are now
1010/// parsing those parts of the given Method declaration that could
1011/// not be parsed earlier (C++ [class.mem]p2), such as default
1012/// arguments. This action should enter the scope of the given
1013/// Method declaration as if we had just parsed the qualified method
1014/// name. However, it should not bring the parameters into scope;
1015/// that will be performed by ActOnDelayedCXXMethodParameter.
1016void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1017  CXXScopeSpec SS;
1018  SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1019  ActOnCXXEnterDeclaratorScope(S, SS);
1020}
1021
1022/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1023/// C++ method declaration. We're (re-)introducing the given
1024/// function parameter into scope for use in parsing later parts of
1025/// the method declaration. For example, we could see an
1026/// ActOnParamDefaultArgument event for this parameter.
1027void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1028  ParmVarDecl *Param = (ParmVarDecl*)ParamD;
1029
1030  // If this parameter has an unparsed default argument, clear it out
1031  // to make way for the parsed default argument.
1032  if (Param->hasUnparsedDefaultArg())
1033    Param->setDefaultArg(0);
1034
1035  S->AddDecl(Param);
1036  if (Param->getDeclName())
1037    IdResolver.AddDecl(Param);
1038}
1039
1040/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1041/// processing the delayed method declaration for Method. The method
1042/// declaration is now considered finished. There may be a separate
1043/// ActOnStartOfFunctionDef action later (not necessarily
1044/// immediately!) for this method, if it was also defined inside the
1045/// class body.
1046void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1047  FunctionDecl *Method = (FunctionDecl*)MethodD;
1048  CXXScopeSpec SS;
1049  SS.setScopeRep(Method->getDeclContext());
1050  ActOnCXXExitDeclaratorScope(S, SS);
1051
1052  // Now that we have our default arguments, check the constructor
1053  // again. It could produce additional diagnostics or affect whether
1054  // the class has implicitly-declared destructors, among other
1055  // things.
1056  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1057    if (CheckConstructor(Constructor))
1058      Constructor->setInvalidDecl();
1059  }
1060
1061  // Check the default arguments, which we may have added.
1062  if (!Method->isInvalidDecl())
1063    CheckCXXDefaultArguments(Method);
1064}
1065
1066/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
1067/// the well-formedness of the constructor declarator @p D with type @p
1068/// R. If there are any errors in the declarator, this routine will
1069/// emit diagnostics and return true. Otherwise, it will return
1070/// false. Either way, the type @p R will be updated to reflect a
1071/// well-formed type for the constructor.
1072bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1073                                      FunctionDecl::StorageClass& SC) {
1074  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1075  bool isInvalid = false;
1076
1077  // C++ [class.ctor]p3:
1078  //   A constructor shall not be virtual (10.3) or static (9.4). A
1079  //   constructor can be invoked for a const, volatile or const
1080  //   volatile object. A constructor shall not be declared const,
1081  //   volatile, or const volatile (9.3.2).
1082  if (isVirtual) {
1083    Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1084      << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1085      << SourceRange(D.getIdentifierLoc());
1086    isInvalid = true;
1087  }
1088  if (SC == FunctionDecl::Static) {
1089    Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1090      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1091      << SourceRange(D.getIdentifierLoc());
1092    isInvalid = true;
1093    SC = FunctionDecl::None;
1094  }
1095  if (D.getDeclSpec().hasTypeSpecifier()) {
1096    // Constructors don't have return types, but the parser will
1097    // happily parse something like:
1098    //
1099    //   class X {
1100    //     float X(float);
1101    //   };
1102    //
1103    // The return type will be eliminated later.
1104    Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1105      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1106      << SourceRange(D.getIdentifierLoc());
1107  }
1108  if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
1109    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1110    if (FTI.TypeQuals & QualType::Const)
1111      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1112        << "const" << SourceRange(D.getIdentifierLoc());
1113    if (FTI.TypeQuals & QualType::Volatile)
1114      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1115        << "volatile" << SourceRange(D.getIdentifierLoc());
1116    if (FTI.TypeQuals & QualType::Restrict)
1117      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1118        << "restrict" << SourceRange(D.getIdentifierLoc());
1119  }
1120
1121  // Rebuild the function type "R" without any type qualifiers (in
1122  // case any of the errors above fired) and with "void" as the
1123  // return type, since constructors don't have return types. We
1124  // *always* have to do this, because GetTypeForDeclarator will
1125  // put in a result type of "int" when none was specified.
1126  const FunctionProtoType *Proto = R->getAsFunctionProtoType();
1127  R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1128                              Proto->getNumArgs(),
1129                              Proto->isVariadic(),
1130                              0);
1131
1132  return isInvalid;
1133}
1134
1135/// CheckConstructor - Checks a fully-formed constructor for
1136/// well-formedness, issuing any diagnostics required. Returns true if
1137/// the constructor declarator is invalid.
1138bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1139  if (Constructor->isInvalidDecl())
1140    return true;
1141
1142  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1143  bool Invalid = false;
1144
1145  // C++ [class.copy]p3:
1146  //   A declaration of a constructor for a class X is ill-formed if
1147  //   its first parameter is of type (optionally cv-qualified) X and
1148  //   either there are no other parameters or else all other
1149  //   parameters have default arguments.
1150  if ((Constructor->getNumParams() == 1) ||
1151      (Constructor->getNumParams() > 1 &&
1152       Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1153    QualType ParamType = Constructor->getParamDecl(0)->getType();
1154    QualType ClassTy = Context.getTagDeclType(ClassDecl);
1155    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1156      Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1157        << SourceRange(Constructor->getParamDecl(0)->getLocation());
1158      Invalid = true;
1159    }
1160  }
1161
1162  // Notify the class that we've added a constructor.
1163  ClassDecl->addedConstructor(Context, Constructor);
1164
1165  return Invalid;
1166}
1167
1168/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1169/// the well-formednes of the destructor declarator @p D with type @p
1170/// R. If there are any errors in the declarator, this routine will
1171/// emit diagnostics and return true. Otherwise, it will return
1172/// false. Either way, the type @p R will be updated to reflect a
1173/// well-formed type for the destructor.
1174bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1175                                     FunctionDecl::StorageClass& SC) {
1176  bool isInvalid = false;
1177
1178  // C++ [class.dtor]p1:
1179  //   [...] A typedef-name that names a class is a class-name
1180  //   (7.1.3); however, a typedef-name that names a class shall not
1181  //   be used as the identifier in the declarator for a destructor
1182  //   declaration.
1183  QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1184  if (DeclaratorType->getAsTypedefType()) {
1185    Diag(D.getIdentifierLoc(),  diag::err_destructor_typedef_name)
1186      << DeclaratorType;
1187    isInvalid = true;
1188  }
1189
1190  // C++ [class.dtor]p2:
1191  //   A destructor is used to destroy objects of its class type. A
1192  //   destructor takes no parameters, and no return type can be
1193  //   specified for it (not even void). The address of a destructor
1194  //   shall not be taken. A destructor shall not be static. A
1195  //   destructor can be invoked for a const, volatile or const
1196  //   volatile object. A destructor shall not be declared const,
1197  //   volatile or const volatile (9.3.2).
1198  if (SC == FunctionDecl::Static) {
1199    Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1200      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1201      << SourceRange(D.getIdentifierLoc());
1202    isInvalid = true;
1203    SC = FunctionDecl::None;
1204  }
1205  if (D.getDeclSpec().hasTypeSpecifier()) {
1206    // Destructors don't have return types, but the parser will
1207    // happily parse something like:
1208    //
1209    //   class X {
1210    //     float ~X();
1211    //   };
1212    //
1213    // The return type will be eliminated later.
1214    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1215      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1216      << SourceRange(D.getIdentifierLoc());
1217  }
1218  if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
1219    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1220    if (FTI.TypeQuals & QualType::Const)
1221      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1222        << "const" << SourceRange(D.getIdentifierLoc());
1223    if (FTI.TypeQuals & QualType::Volatile)
1224      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1225        << "volatile" << SourceRange(D.getIdentifierLoc());
1226    if (FTI.TypeQuals & QualType::Restrict)
1227      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1228        << "restrict" << SourceRange(D.getIdentifierLoc());
1229  }
1230
1231  // Make sure we don't have any parameters.
1232  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1233    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1234
1235    // Delete the parameters.
1236    D.getTypeObject(0).Fun.freeArgs();
1237  }
1238
1239  // Make sure the destructor isn't variadic.
1240  if (R->getAsFunctionProtoType()->isVariadic())
1241    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1242
1243  // Rebuild the function type "R" without any type qualifiers or
1244  // parameters (in case any of the errors above fired) and with
1245  // "void" as the return type, since destructors don't have return
1246  // types. We *always* have to do this, because GetTypeForDeclarator
1247  // will put in a result type of "int" when none was specified.
1248  R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1249
1250  return isInvalid;
1251}
1252
1253/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1254/// well-formednes of the conversion function declarator @p D with
1255/// type @p R. If there are any errors in the declarator, this routine
1256/// will emit diagnostics and return true. Otherwise, it will return
1257/// false. Either way, the type @p R will be updated to reflect a
1258/// well-formed type for the conversion operator.
1259bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1260                                     FunctionDecl::StorageClass& SC) {
1261  bool isInvalid = false;
1262
1263  // C++ [class.conv.fct]p1:
1264  //   Neither parameter types nor return type can be specified. The
1265  //   type of a conversion function (8.3.5) is “function taking no
1266  //   parameter returning conversion-type-id.”
1267  if (SC == FunctionDecl::Static) {
1268    Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1269      << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1270      << SourceRange(D.getIdentifierLoc());
1271    isInvalid = true;
1272    SC = FunctionDecl::None;
1273  }
1274  if (D.getDeclSpec().hasTypeSpecifier()) {
1275    // Conversion functions don't have return types, but the parser will
1276    // happily parse something like:
1277    //
1278    //   class X {
1279    //     float operator bool();
1280    //   };
1281    //
1282    // The return type will be changed later anyway.
1283    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1284      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1285      << SourceRange(D.getIdentifierLoc());
1286  }
1287
1288  // Make sure we don't have any parameters.
1289  if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
1290    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1291
1292    // Delete the parameters.
1293    D.getTypeObject(0).Fun.freeArgs();
1294  }
1295
1296  // Make sure the conversion function isn't variadic.
1297  if (R->getAsFunctionProtoType()->isVariadic())
1298    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1299
1300  // C++ [class.conv.fct]p4:
1301  //   The conversion-type-id shall not represent a function type nor
1302  //   an array type.
1303  QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1304  if (ConvType->isArrayType()) {
1305    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1306    ConvType = Context.getPointerType(ConvType);
1307  } else if (ConvType->isFunctionType()) {
1308    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1309    ConvType = Context.getPointerType(ConvType);
1310  }
1311
1312  // Rebuild the function type "R" without any parameters (in case any
1313  // of the errors above fired) and with the conversion type as the
1314  // return type.
1315  R = Context.getFunctionType(ConvType, 0, 0, false,
1316                              R->getAsFunctionProtoType()->getTypeQuals());
1317
1318  // C++0x explicit conversion operators.
1319  if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1320    Diag(D.getDeclSpec().getExplicitSpecLoc(),
1321         diag::warn_explicit_conversion_functions)
1322      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1323
1324  return isInvalid;
1325}
1326
1327/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1328/// the declaration of the given C++ conversion function. This routine
1329/// is responsible for recording the conversion function in the C++
1330/// class, if possible.
1331Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1332  assert(Conversion && "Expected to receive a conversion function declaration");
1333
1334  // Set the lexical context of this conversion function
1335  Conversion->setLexicalDeclContext(CurContext);
1336
1337  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
1338
1339  // Make sure we aren't redeclaring the conversion function.
1340  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
1341
1342  // C++ [class.conv.fct]p1:
1343  //   [...] A conversion function is never used to convert a
1344  //   (possibly cv-qualified) object to the (possibly cv-qualified)
1345  //   same object type (or a reference to it), to a (possibly
1346  //   cv-qualified) base class of that type (or a reference to it),
1347  //   or to (possibly cv-qualified) void.
1348  // FIXME: Suppress this warning if the conversion function ends up
1349  // being a virtual function that overrides a virtual function in a
1350  // base class.
1351  QualType ClassType
1352    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1353  if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1354    ConvType = ConvTypeRef->getPointeeType();
1355  if (ConvType->isRecordType()) {
1356    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1357    if (ConvType == ClassType)
1358      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
1359        << ClassType;
1360    else if (IsDerivedFrom(ClassType, ConvType))
1361      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
1362        <<  ClassType << ConvType;
1363  } else if (ConvType->isVoidType()) {
1364    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
1365      << ClassType << ConvType;
1366  }
1367
1368  if (Conversion->getPreviousDeclaration()) {
1369    OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1370    for (OverloadedFunctionDecl::function_iterator
1371           Conv = Conversions->function_begin(),
1372           ConvEnd = Conversions->function_end();
1373         Conv != ConvEnd; ++Conv) {
1374      if (*Conv == Conversion->getPreviousDeclaration()) {
1375        *Conv = Conversion;
1376        return (DeclTy *)Conversion;
1377      }
1378    }
1379    assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1380  } else
1381    ClassDecl->addConversionFunction(Context, Conversion);
1382
1383  return (DeclTy *)Conversion;
1384}
1385
1386//===----------------------------------------------------------------------===//
1387// Namespace Handling
1388//===----------------------------------------------------------------------===//
1389
1390/// ActOnStartNamespaceDef - This is called at the start of a namespace
1391/// definition.
1392Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1393                                           SourceLocation IdentLoc,
1394                                           IdentifierInfo *II,
1395                                           SourceLocation LBrace) {
1396  NamespaceDecl *Namespc =
1397      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1398  Namespc->setLBracLoc(LBrace);
1399
1400  Scope *DeclRegionScope = NamespcScope->getParent();
1401
1402  if (II) {
1403    // C++ [namespace.def]p2:
1404    // The identifier in an original-namespace-definition shall not have been
1405    // previously defined in the declarative region in which the
1406    // original-namespace-definition appears. The identifier in an
1407    // original-namespace-definition is the name of the namespace. Subsequently
1408    // in that declarative region, it is treated as an original-namespace-name.
1409
1410    NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1411                                     true);
1412
1413    if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1414      // This is an extended namespace definition.
1415      // Attach this namespace decl to the chain of extended namespace
1416      // definitions.
1417      OrigNS->setNextNamespace(Namespc);
1418      Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
1419
1420      // Remove the previous declaration from the scope.
1421      if (DeclRegionScope->isDeclScope(OrigNS)) {
1422        IdResolver.RemoveDecl(OrigNS);
1423        DeclRegionScope->RemoveDecl(OrigNS);
1424      }
1425    } else if (PrevDecl) {
1426      // This is an invalid name redefinition.
1427      Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1428       << Namespc->getDeclName();
1429      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1430      Namespc->setInvalidDecl();
1431      // Continue on to push Namespc as current DeclContext and return it.
1432    }
1433
1434    PushOnScopeChains(Namespc, DeclRegionScope);
1435  } else {
1436    // FIXME: Handle anonymous namespaces
1437  }
1438
1439  // Although we could have an invalid decl (i.e. the namespace name is a
1440  // redefinition), push it as current DeclContext and try to continue parsing.
1441  // FIXME: We should be able to push Namespc here, so that the
1442  // each DeclContext for the namespace has the declarations
1443  // that showed up in that particular namespace definition.
1444  PushDeclContext(NamespcScope, Namespc);
1445  return Namespc;
1446}
1447
1448/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1449/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1450void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1451  Decl *Dcl = static_cast<Decl *>(D);
1452  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1453  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1454  Namespc->setRBracLoc(RBrace);
1455  PopDeclContext();
1456}
1457
1458Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1459                                        SourceLocation UsingLoc,
1460                                        SourceLocation NamespcLoc,
1461                                        const CXXScopeSpec &SS,
1462                                        SourceLocation IdentLoc,
1463                                        IdentifierInfo *NamespcName,
1464                                        AttributeList *AttrList) {
1465  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1466  assert(NamespcName && "Invalid NamespcName.");
1467  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
1468  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
1469
1470  UsingDirectiveDecl *UDir = 0;
1471
1472  // Lookup namespace name.
1473  LookupResult R = LookupParsedName(S, &SS, NamespcName,
1474                                    LookupNamespaceName, false);
1475  if (R.isAmbiguous()) {
1476    DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1477    return 0;
1478  }
1479  if (NamedDecl *NS = R) {
1480    assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
1481    // C++ [namespace.udir]p1:
1482    //   A using-directive specifies that the names in the nominated
1483    //   namespace can be used in the scope in which the
1484    //   using-directive appears after the using-directive. During
1485    //   unqualified name lookup (3.4.1), the names appear as if they
1486    //   were declared in the nearest enclosing namespace which
1487    //   contains both the using-directive and the nominated
1488    //   namespace. [Note: in this context, “contains” means “contains
1489    //   directly or indirectly”. ]
1490
1491    // Find enclosing context containing both using-directive and
1492    // nominated namespace.
1493    DeclContext *CommonAncestor = cast<DeclContext>(NS);
1494    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1495      CommonAncestor = CommonAncestor->getParent();
1496
1497    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1498                                      NamespcLoc, IdentLoc,
1499                                      cast<NamespaceDecl>(NS),
1500                                      CommonAncestor);
1501    PushUsingDirective(S, UDir);
1502  } else {
1503    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
1504  }
1505
1506  // FIXME: We ignore attributes for now.
1507  delete AttrList;
1508  return UDir;
1509}
1510
1511void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1512  // If scope has associated entity, then using directive is at namespace
1513  // or translation unit scope. We add UsingDirectiveDecls, into
1514  // it's lookup structure.
1515  if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1516    Ctx->addDecl(UDir);
1517  else
1518    // Otherwise it is block-sope. using-directives will affect lookup
1519    // only to the end of scope.
1520    S->PushUsingDirective(UDir);
1521}
1522
1523/// AddCXXDirectInitializerToDecl - This action is called immediately after
1524/// ActOnDeclarator, when a C++ direct initializer is present.
1525/// e.g: "int x(1);"
1526void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1527                                         ExprTy **ExprTys, unsigned NumExprs,
1528                                         SourceLocation *CommaLocs,
1529                                         SourceLocation RParenLoc) {
1530  assert(NumExprs != 0 && ExprTys && "missing expressions");
1531  Decl *RealDecl = static_cast<Decl *>(Dcl);
1532
1533  // If there is no declaration, there was an error parsing it.  Just ignore
1534  // the initializer.
1535  if (RealDecl == 0) {
1536    for (unsigned i = 0; i != NumExprs; ++i)
1537      static_cast<Expr *>(ExprTys[i])->Destroy(Context);
1538    return;
1539  }
1540
1541  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1542  if (!VDecl) {
1543    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1544    RealDecl->setInvalidDecl();
1545    return;
1546  }
1547
1548  // We will treat direct-initialization as a copy-initialization:
1549  //    int x(1);  -as-> int x = 1;
1550  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1551  //
1552  // Clients that want to distinguish between the two forms, can check for
1553  // direct initializer using VarDecl::hasCXXDirectInitializer().
1554  // A major benefit is that clients that don't particularly care about which
1555  // exactly form was it (like the CodeGen) can handle both cases without
1556  // special case code.
1557
1558  // C++ 8.5p11:
1559  // The form of initialization (using parentheses or '=') is generally
1560  // insignificant, but does matter when the entity being initialized has a
1561  // class type.
1562  QualType DeclInitType = VDecl->getType();
1563  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1564    DeclInitType = Array->getElementType();
1565
1566  if (VDecl->getType()->isRecordType()) {
1567    CXXConstructorDecl *Constructor
1568      = PerformInitializationByConstructor(DeclInitType,
1569                                           (Expr **)ExprTys, NumExprs,
1570                                           VDecl->getLocation(),
1571                                           SourceRange(VDecl->getLocation(),
1572                                                       RParenLoc),
1573                                           VDecl->getDeclName(),
1574                                           IK_Direct);
1575    if (!Constructor) {
1576      RealDecl->setInvalidDecl();
1577    }
1578
1579    // Let clients know that initialization was done with a direct
1580    // initializer.
1581    VDecl->setCXXDirectInitializer(true);
1582
1583    // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1584    // the initializer.
1585    return;
1586  }
1587
1588  if (NumExprs > 1) {
1589    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1590      << SourceRange(VDecl->getLocation(), RParenLoc);
1591    RealDecl->setInvalidDecl();
1592    return;
1593  }
1594
1595  // Let clients know that initialization was done with a direct initializer.
1596  VDecl->setCXXDirectInitializer(true);
1597
1598  assert(NumExprs == 1 && "Expected 1 expression");
1599  // Set the init expression, handles conversions.
1600  AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
1601}
1602
1603/// PerformInitializationByConstructor - Perform initialization by
1604/// constructor (C++ [dcl.init]p14), which may occur as part of
1605/// direct-initialization or copy-initialization. We are initializing
1606/// an object of type @p ClassType with the given arguments @p
1607/// Args. @p Loc is the location in the source code where the
1608/// initializer occurs (e.g., a declaration, member initializer,
1609/// functional cast, etc.) while @p Range covers the whole
1610/// initialization. @p InitEntity is the entity being initialized,
1611/// which may by the name of a declaration or a type. @p Kind is the
1612/// kind of initialization we're performing, which affects whether
1613/// explicit constructors will be considered. When successful, returns
1614/// the constructor that will be used to perform the initialization;
1615/// when the initialization fails, emits a diagnostic and returns
1616/// null.
1617CXXConstructorDecl *
1618Sema::PerformInitializationByConstructor(QualType ClassType,
1619                                         Expr **Args, unsigned NumArgs,
1620                                         SourceLocation Loc, SourceRange Range,
1621                                         DeclarationName InitEntity,
1622                                         InitializationKind Kind) {
1623  const RecordType *ClassRec = ClassType->getAsRecordType();
1624  assert(ClassRec && "Can only initialize a class type here");
1625
1626  // C++ [dcl.init]p14:
1627  //
1628  //   If the initialization is direct-initialization, or if it is
1629  //   copy-initialization where the cv-unqualified version of the
1630  //   source type is the same class as, or a derived class of, the
1631  //   class of the destination, constructors are considered. The
1632  //   applicable constructors are enumerated (13.3.1.3), and the
1633  //   best one is chosen through overload resolution (13.3). The
1634  //   constructor so selected is called to initialize the object,
1635  //   with the initializer expression(s) as its argument(s). If no
1636  //   constructor applies, or the overload resolution is ambiguous,
1637  //   the initialization is ill-formed.
1638  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1639  OverloadCandidateSet CandidateSet;
1640
1641  // Add constructors to the overload set.
1642  DeclarationName ConstructorName
1643    = Context.DeclarationNames.getCXXConstructorName(
1644                       Context.getCanonicalType(ClassType.getUnqualifiedType()));
1645  DeclContext::lookup_const_iterator Con, ConEnd;
1646  for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
1647       Con != ConEnd; ++Con) {
1648    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
1649    if ((Kind == IK_Direct) ||
1650        (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1651        (Kind == IK_Default && Constructor->isDefaultConstructor()))
1652      AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1653  }
1654
1655  // FIXME: When we decide not to synthesize the implicitly-declared
1656  // constructors, we'll need to make them appear here.
1657
1658  OverloadCandidateSet::iterator Best;
1659  switch (BestViableFunction(CandidateSet, Best)) {
1660  case OR_Success:
1661    // We found a constructor. Return it.
1662    return cast<CXXConstructorDecl>(Best->Function);
1663
1664  case OR_No_Viable_Function:
1665    if (InitEntity)
1666      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1667        << InitEntity << Range;
1668    else
1669      Diag(Loc, diag::err_ovl_no_viable_function_in_init)
1670        << ClassType << Range;
1671    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1672    return 0;
1673
1674  case OR_Ambiguous:
1675    if (InitEntity)
1676      Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1677    else
1678      Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
1679    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1680    return 0;
1681
1682  case OR_Deleted:
1683    if (InitEntity)
1684      Diag(Loc, diag::err_ovl_deleted_init)
1685        << Best->Function->isDeleted()
1686        << InitEntity << Range;
1687    else
1688      Diag(Loc, diag::err_ovl_deleted_init)
1689        << Best->Function->isDeleted()
1690        << InitEntity << Range;
1691    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1692    return 0;
1693  }
1694
1695  return 0;
1696}
1697
1698/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1699/// determine whether they are reference-related,
1700/// reference-compatible, reference-compatible with added
1701/// qualification, or incompatible, for use in C++ initialization by
1702/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1703/// type, and the first type (T1) is the pointee type of the reference
1704/// type being initialized.
1705Sema::ReferenceCompareResult
1706Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1707                                   bool& DerivedToBase) {
1708  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1709  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1710
1711  T1 = Context.getCanonicalType(T1);
1712  T2 = Context.getCanonicalType(T2);
1713  QualType UnqualT1 = T1.getUnqualifiedType();
1714  QualType UnqualT2 = T2.getUnqualifiedType();
1715
1716  // C++ [dcl.init.ref]p4:
1717  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1718  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
1719  //   T1 is a base class of T2.
1720  if (UnqualT1 == UnqualT2)
1721    DerivedToBase = false;
1722  else if (IsDerivedFrom(UnqualT2, UnqualT1))
1723    DerivedToBase = true;
1724  else
1725    return Ref_Incompatible;
1726
1727  // At this point, we know that T1 and T2 are reference-related (at
1728  // least).
1729
1730  // C++ [dcl.init.ref]p4:
1731  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1732  //   reference-related to T2 and cv1 is the same cv-qualification
1733  //   as, or greater cv-qualification than, cv2. For purposes of
1734  //   overload resolution, cases for which cv1 is greater
1735  //   cv-qualification than cv2 are identified as
1736  //   reference-compatible with added qualification (see 13.3.3.2).
1737  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1738    return Ref_Compatible;
1739  else if (T1.isMoreQualifiedThan(T2))
1740    return Ref_Compatible_With_Added_Qualification;
1741  else
1742    return Ref_Related;
1743}
1744
1745/// CheckReferenceInit - Check the initialization of a reference
1746/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1747/// the initializer (either a simple initializer or an initializer
1748/// list), and DeclType is the type of the declaration. When ICS is
1749/// non-null, this routine will compute the implicit conversion
1750/// sequence according to C++ [over.ics.ref] and will not produce any
1751/// diagnostics; when ICS is null, it will emit diagnostics when any
1752/// errors are found. Either way, a return value of true indicates
1753/// that there was a failure, a return value of false indicates that
1754/// the reference initialization succeeded.
1755///
1756/// When @p SuppressUserConversions, user-defined conversions are
1757/// suppressed.
1758/// When @p AllowExplicit, we also permit explicit user-defined
1759/// conversion functions.
1760bool
1761Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
1762                         ImplicitConversionSequence *ICS,
1763                         bool SuppressUserConversions,
1764                         bool AllowExplicit) {
1765  assert(DeclType->isReferenceType() && "Reference init needs a reference");
1766
1767  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1768  QualType T2 = Init->getType();
1769
1770  // If the initializer is the address of an overloaded function, try
1771  // to resolve the overloaded function. If all goes well, T2 is the
1772  // type of the resulting function.
1773  if (T2->isOverloadType()) {
1774    FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1775                                                          ICS != 0);
1776    if (Fn) {
1777      // Since we're performing this reference-initialization for
1778      // real, update the initializer with the resulting function.
1779      if (!ICS) {
1780        if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1781          return true;
1782
1783        FixOverloadedFunctionReference(Init, Fn);
1784      }
1785
1786      T2 = Fn->getType();
1787    }
1788  }
1789
1790  // Compute some basic properties of the types and the initializer.
1791  bool DerivedToBase = false;
1792  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
1793  ReferenceCompareResult RefRelationship
1794    = CompareReferenceRelationship(T1, T2, DerivedToBase);
1795
1796  // Most paths end in a failed conversion.
1797  if (ICS)
1798    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
1799
1800  // C++ [dcl.init.ref]p5:
1801  //   A reference to type “cv1 T1” is initialized by an expression
1802  //   of type “cv2 T2” as follows:
1803
1804  //     -- If the initializer expression
1805
1806  bool BindsDirectly = false;
1807  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1808  //          reference-compatible with “cv2 T2,” or
1809  //
1810  // Note that the bit-field check is skipped if we are just computing
1811  // the implicit conversion sequence (C++ [over.best.ics]p2).
1812  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1813      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1814    BindsDirectly = true;
1815
1816    if (ICS) {
1817      // C++ [over.ics.ref]p1:
1818      //   When a parameter of reference type binds directly (8.5.3)
1819      //   to an argument expression, the implicit conversion sequence
1820      //   is the identity conversion, unless the argument expression
1821      //   has a type that is a derived class of the parameter type,
1822      //   in which case the implicit conversion sequence is a
1823      //   derived-to-base Conversion (13.3.3.1).
1824      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1825      ICS->Standard.First = ICK_Identity;
1826      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1827      ICS->Standard.Third = ICK_Identity;
1828      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1829      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1830      ICS->Standard.ReferenceBinding = true;
1831      ICS->Standard.DirectBinding = true;
1832
1833      // Nothing more to do: the inaccessibility/ambiguity check for
1834      // derived-to-base conversions is suppressed when we're
1835      // computing the implicit conversion sequence (C++
1836      // [over.best.ics]p2).
1837      return false;
1838    } else {
1839      // Perform the conversion.
1840      // FIXME: Binding to a subobject of the lvalue is going to require
1841      // more AST annotation than this.
1842      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1843    }
1844  }
1845
1846  //       -- has a class type (i.e., T2 is a class type) and can be
1847  //          implicitly converted to an lvalue of type “cv3 T3,”
1848  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1849  //          92) (this conversion is selected by enumerating the
1850  //          applicable conversion functions (13.3.1.6) and choosing
1851  //          the best one through overload resolution (13.3)),
1852  if (!SuppressUserConversions && T2->isRecordType()) {
1853    // FIXME: Look for conversions in base classes!
1854    CXXRecordDecl *T2RecordDecl
1855      = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
1856
1857    OverloadCandidateSet CandidateSet;
1858    OverloadedFunctionDecl *Conversions
1859      = T2RecordDecl->getConversionFunctions();
1860    for (OverloadedFunctionDecl::function_iterator Func
1861           = Conversions->function_begin();
1862         Func != Conversions->function_end(); ++Func) {
1863      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1864
1865      // If the conversion function doesn't return a reference type,
1866      // it can't be considered for this conversion.
1867      // FIXME: This will change when we support rvalue references.
1868      if (Conv->getConversionType()->isReferenceType() &&
1869          (AllowExplicit || !Conv->isExplicit()))
1870        AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1871    }
1872
1873    OverloadCandidateSet::iterator Best;
1874    switch (BestViableFunction(CandidateSet, Best)) {
1875    case OR_Success:
1876      // This is a direct binding.
1877      BindsDirectly = true;
1878
1879      if (ICS) {
1880        // C++ [over.ics.ref]p1:
1881        //
1882        //   [...] If the parameter binds directly to the result of
1883        //   applying a conversion function to the argument
1884        //   expression, the implicit conversion sequence is a
1885        //   user-defined conversion sequence (13.3.3.1.2), with the
1886        //   second standard conversion sequence either an identity
1887        //   conversion or, if the conversion function returns an
1888        //   entity of a type that is a derived class of the parameter
1889        //   type, a derived-to-base Conversion.
1890        ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1891        ICS->UserDefined.Before = Best->Conversions[0].Standard;
1892        ICS->UserDefined.After = Best->FinalConversion;
1893        ICS->UserDefined.ConversionFunction = Best->Function;
1894        assert(ICS->UserDefined.After.ReferenceBinding &&
1895               ICS->UserDefined.After.DirectBinding &&
1896               "Expected a direct reference binding!");
1897        return false;
1898      } else {
1899        // Perform the conversion.
1900        // FIXME: Binding to a subobject of the lvalue is going to require
1901        // more AST annotation than this.
1902        ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1903      }
1904      break;
1905
1906    case OR_Ambiguous:
1907      assert(false && "Ambiguous reference binding conversions not implemented.");
1908      return true;
1909
1910    case OR_No_Viable_Function:
1911    case OR_Deleted:
1912      // There was no suitable conversion, or we found a deleted
1913      // conversion; continue with other checks.
1914      break;
1915    }
1916  }
1917
1918  if (BindsDirectly) {
1919    // C++ [dcl.init.ref]p4:
1920    //   [...] In all cases where the reference-related or
1921    //   reference-compatible relationship of two types is used to
1922    //   establish the validity of a reference binding, and T1 is a
1923    //   base class of T2, a program that necessitates such a binding
1924    //   is ill-formed if T1 is an inaccessible (clause 11) or
1925    //   ambiguous (10.2) base class of T2.
1926    //
1927    // Note that we only check this condition when we're allowed to
1928    // complain about errors, because we should not be checking for
1929    // ambiguity (or inaccessibility) unless the reference binding
1930    // actually happens.
1931    if (DerivedToBase)
1932      return CheckDerivedToBaseConversion(T2, T1,
1933                                          Init->getSourceRange().getBegin(),
1934                                          Init->getSourceRange());
1935    else
1936      return false;
1937  }
1938
1939  //     -- Otherwise, the reference shall be to a non-volatile const
1940  //        type (i.e., cv1 shall be const).
1941  if (T1.getCVRQualifiers() != QualType::Const) {
1942    if (!ICS)
1943      Diag(Init->getSourceRange().getBegin(),
1944           diag::err_not_reference_to_const_init)
1945        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1946        << T2 << Init->getSourceRange();
1947    return true;
1948  }
1949
1950  //       -- If the initializer expression is an rvalue, with T2 a
1951  //          class type, and “cv1 T1” is reference-compatible with
1952  //          “cv2 T2,” the reference is bound in one of the
1953  //          following ways (the choice is implementation-defined):
1954  //
1955  //          -- The reference is bound to the object represented by
1956  //             the rvalue (see 3.10) or to a sub-object within that
1957  //             object.
1958  //
1959  //          -- A temporary of type “cv1 T2” [sic] is created, and
1960  //             a constructor is called to copy the entire rvalue
1961  //             object into the temporary. The reference is bound to
1962  //             the temporary or to a sub-object within the
1963  //             temporary.
1964  //
1965  //          The constructor that would be used to make the copy
1966  //          shall be callable whether or not the copy is actually
1967  //          done.
1968  //
1969  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1970  // freedom, so we will always take the first option and never build
1971  // a temporary in this case. FIXME: We will, however, have to check
1972  // for the presence of a copy constructor in C++98/03 mode.
1973  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
1974      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1975    if (ICS) {
1976      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1977      ICS->Standard.First = ICK_Identity;
1978      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1979      ICS->Standard.Third = ICK_Identity;
1980      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1981      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1982      ICS->Standard.ReferenceBinding = true;
1983      ICS->Standard.DirectBinding = false;
1984    } else {
1985      // FIXME: Binding to a subobject of the rvalue is going to require
1986      // more AST annotation than this.
1987      ImpCastExprToType(Init, T1, /*isLvalue=*/true);
1988    }
1989    return false;
1990  }
1991
1992  //       -- Otherwise, a temporary of type “cv1 T1” is created and
1993  //          initialized from the initializer expression using the
1994  //          rules for a non-reference copy initialization (8.5). The
1995  //          reference is then bound to the temporary. If T1 is
1996  //          reference-related to T2, cv1 must be the same
1997  //          cv-qualification as, or greater cv-qualification than,
1998  //          cv2; otherwise, the program is ill-formed.
1999  if (RefRelationship == Ref_Related) {
2000    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2001    // we would be reference-compatible or reference-compatible with
2002    // added qualification. But that wasn't the case, so the reference
2003    // initialization fails.
2004    if (!ICS)
2005      Diag(Init->getSourceRange().getBegin(),
2006           diag::err_reference_init_drops_quals)
2007        << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2008        << T2 << Init->getSourceRange();
2009    return true;
2010  }
2011
2012  // If at least one of the types is a class type, the types are not
2013  // related, and we aren't allowed any user conversions, the
2014  // reference binding fails. This case is important for breaking
2015  // recursion, since TryImplicitConversion below will attempt to
2016  // create a temporary through the use of a copy constructor.
2017  if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2018      (T1->isRecordType() || T2->isRecordType())) {
2019    if (!ICS)
2020      Diag(Init->getSourceRange().getBegin(),
2021           diag::err_typecheck_convert_incompatible)
2022        << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2023    return true;
2024  }
2025
2026  // Actually try to convert the initializer to T1.
2027  if (ICS) {
2028    /// C++ [over.ics.ref]p2:
2029    ///
2030    ///   When a parameter of reference type is not bound directly to
2031    ///   an argument expression, the conversion sequence is the one
2032    ///   required to convert the argument expression to the
2033    ///   underlying type of the reference according to
2034    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
2035    ///   to copy-initializing a temporary of the underlying type with
2036    ///   the argument expression. Any difference in top-level
2037    ///   cv-qualification is subsumed by the initialization itself
2038    ///   and does not constitute a conversion.
2039    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
2040    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2041  } else {
2042    return PerformImplicitConversion(Init, T1, "initializing");
2043  }
2044}
2045
2046/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2047/// of this overloaded operator is well-formed. If so, returns false;
2048/// otherwise, emits appropriate diagnostics and returns true.
2049bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
2050  assert(FnDecl && FnDecl->isOverloadedOperator() &&
2051         "Expected an overloaded operator declaration");
2052
2053  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2054
2055  // C++ [over.oper]p5:
2056  //   The allocation and deallocation functions, operator new,
2057  //   operator new[], operator delete and operator delete[], are
2058  //   described completely in 3.7.3. The attributes and restrictions
2059  //   found in the rest of this subclause do not apply to them unless
2060  //   explicitly stated in 3.7.3.
2061  // FIXME: Write a separate routine for checking this. For now, just
2062  // allow it.
2063  if (Op == OO_New || Op == OO_Array_New ||
2064      Op == OO_Delete || Op == OO_Array_Delete)
2065    return false;
2066
2067  // C++ [over.oper]p6:
2068  //   An operator function shall either be a non-static member
2069  //   function or be a non-member function and have at least one
2070  //   parameter whose type is a class, a reference to a class, an
2071  //   enumeration, or a reference to an enumeration.
2072  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2073    if (MethodDecl->isStatic())
2074      return Diag(FnDecl->getLocation(),
2075                  diag::err_operator_overload_static) << FnDecl->getDeclName();
2076  } else {
2077    bool ClassOrEnumParam = false;
2078    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2079                                   ParamEnd = FnDecl->param_end();
2080         Param != ParamEnd; ++Param) {
2081      QualType ParamType = (*Param)->getType().getNonReferenceType();
2082      if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2083        ClassOrEnumParam = true;
2084        break;
2085      }
2086    }
2087
2088    if (!ClassOrEnumParam)
2089      return Diag(FnDecl->getLocation(),
2090                  diag::err_operator_overload_needs_class_or_enum)
2091        << FnDecl->getDeclName();
2092  }
2093
2094  // C++ [over.oper]p8:
2095  //   An operator function cannot have default arguments (8.3.6),
2096  //   except where explicitly stated below.
2097  //
2098  // Only the function-call operator allows default arguments
2099  // (C++ [over.call]p1).
2100  if (Op != OO_Call) {
2101    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2102         Param != FnDecl->param_end(); ++Param) {
2103      if ((*Param)->hasUnparsedDefaultArg())
2104        return Diag((*Param)->getLocation(),
2105                    diag::err_operator_overload_default_arg)
2106          << FnDecl->getDeclName();
2107      else if (Expr *DefArg = (*Param)->getDefaultArg())
2108        return Diag((*Param)->getLocation(),
2109                    diag::err_operator_overload_default_arg)
2110          << FnDecl->getDeclName() << DefArg->getSourceRange();
2111    }
2112  }
2113
2114  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2115    { false, false, false }
2116#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2117    , { Unary, Binary, MemberOnly }
2118#include "clang/Basic/OperatorKinds.def"
2119  };
2120
2121  bool CanBeUnaryOperator = OperatorUses[Op][0];
2122  bool CanBeBinaryOperator = OperatorUses[Op][1];
2123  bool MustBeMemberOperator = OperatorUses[Op][2];
2124
2125  // C++ [over.oper]p8:
2126  //   [...] Operator functions cannot have more or fewer parameters
2127  //   than the number required for the corresponding operator, as
2128  //   described in the rest of this subclause.
2129  unsigned NumParams = FnDecl->getNumParams()
2130                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
2131  if (Op != OO_Call &&
2132      ((NumParams == 1 && !CanBeUnaryOperator) ||
2133       (NumParams == 2 && !CanBeBinaryOperator) ||
2134       (NumParams < 1) || (NumParams > 2))) {
2135    // We have the wrong number of parameters.
2136    unsigned ErrorKind;
2137    if (CanBeUnaryOperator && CanBeBinaryOperator) {
2138      ErrorKind = 2;  // 2 -> unary or binary.
2139    } else if (CanBeUnaryOperator) {
2140      ErrorKind = 0;  // 0 -> unary
2141    } else {
2142      assert(CanBeBinaryOperator &&
2143             "All non-call overloaded operators are unary or binary!");
2144      ErrorKind = 1;  // 1 -> binary
2145    }
2146
2147    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
2148      << FnDecl->getDeclName() << NumParams << ErrorKind;
2149  }
2150
2151  // Overloaded operators other than operator() cannot be variadic.
2152  if (Op != OO_Call &&
2153      FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
2154    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
2155      << FnDecl->getDeclName();
2156  }
2157
2158  // Some operators must be non-static member functions.
2159  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2160    return Diag(FnDecl->getLocation(),
2161                diag::err_operator_overload_must_be_member)
2162      << FnDecl->getDeclName();
2163  }
2164
2165  // C++ [over.inc]p1:
2166  //   The user-defined function called operator++ implements the
2167  //   prefix and postfix ++ operator. If this function is a member
2168  //   function with no parameters, or a non-member function with one
2169  //   parameter of class or enumeration type, it defines the prefix
2170  //   increment operator ++ for objects of that type. If the function
2171  //   is a member function with one parameter (which shall be of type
2172  //   int) or a non-member function with two parameters (the second
2173  //   of which shall be of type int), it defines the postfix
2174  //   increment operator ++ for objects of that type.
2175  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2176    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2177    bool ParamIsInt = false;
2178    if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2179      ParamIsInt = BT->getKind() == BuiltinType::Int;
2180
2181    if (!ParamIsInt)
2182      return Diag(LastParam->getLocation(),
2183                  diag::err_operator_overload_post_incdec_must_be_int)
2184        << LastParam->getType() << (Op == OO_MinusMinus);
2185  }
2186
2187  // Notify the class if it got an assignment operator.
2188  if (Op == OO_Equal) {
2189    // Would have returned earlier otherwise.
2190    assert(isa<CXXMethodDecl>(FnDecl) &&
2191      "Overloaded = not member, but not filtered.");
2192    CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2193    Method->getParent()->addedAssignmentOperator(Context, Method);
2194  }
2195
2196  return false;
2197}
2198
2199/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2200/// linkage specification, including the language and (if present)
2201/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2202/// the location of the language string literal, which is provided
2203/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2204/// the '{' brace. Otherwise, this linkage specification does not
2205/// have any braces.
2206Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2207                                                   SourceLocation ExternLoc,
2208                                                   SourceLocation LangLoc,
2209                                                   const char *Lang,
2210                                                   unsigned StrSize,
2211                                                   SourceLocation LBraceLoc) {
2212  LinkageSpecDecl::LanguageIDs Language;
2213  if (strncmp(Lang, "\"C\"", StrSize) == 0)
2214    Language = LinkageSpecDecl::lang_c;
2215  else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2216    Language = LinkageSpecDecl::lang_cxx;
2217  else {
2218    Diag(LangLoc, diag::err_bad_language);
2219    return 0;
2220  }
2221
2222  // FIXME: Add all the various semantics of linkage specifications
2223
2224  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2225                                               LangLoc, Language,
2226                                               LBraceLoc.isValid());
2227  CurContext->addDecl(D);
2228  PushDeclContext(S, D);
2229  return D;
2230}
2231
2232/// ActOnFinishLinkageSpecification - Completely the definition of
2233/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2234/// valid, it's the position of the closing '}' brace in a linkage
2235/// specification that uses braces.
2236Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2237                                                    DeclTy *LinkageSpec,
2238                                                    SourceLocation RBraceLoc) {
2239  if (LinkageSpec)
2240    PopDeclContext();
2241  return LinkageSpec;
2242}
2243
2244/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2245/// handler.
2246Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2247{
2248  QualType ExDeclType = GetTypeForDeclarator(D, S);
2249  SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2250
2251  bool Invalid = false;
2252
2253  // Arrays and functions decay.
2254  if (ExDeclType->isArrayType())
2255    ExDeclType = Context.getArrayDecayedType(ExDeclType);
2256  else if (ExDeclType->isFunctionType())
2257    ExDeclType = Context.getPointerType(ExDeclType);
2258
2259  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2260  // The exception-declaration shall not denote a pointer or reference to an
2261  // incomplete type, other than [cv] void*.
2262  QualType BaseType = ExDeclType;
2263  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
2264  unsigned DK = diag::err_catch_incomplete;
2265  if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2266    BaseType = Ptr->getPointeeType();
2267    Mode = 1;
2268    DK = diag::err_catch_incomplete_ptr;
2269  } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2270    BaseType = Ref->getPointeeType();
2271    Mode = 2;
2272    DK = diag::err_catch_incomplete_ref;
2273  }
2274  if ((Mode == 0 || !BaseType->isVoidType()) &&
2275      RequireCompleteType(Begin, BaseType, DK))
2276    Invalid = true;
2277
2278  // FIXME: Need to test for ability to copy-construct and destroy the
2279  // exception variable.
2280  // FIXME: Need to check for abstract classes.
2281
2282  IdentifierInfo *II = D.getIdentifier();
2283  if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
2284    // The scope should be freshly made just for us. There is just no way
2285    // it contains any previous declaration.
2286    assert(!S->isDeclScope(PrevDecl));
2287    if (PrevDecl->isTemplateParameter()) {
2288      // Maybe we will complain about the shadowed template parameter.
2289      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2290
2291    }
2292  }
2293
2294  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
2295                                    II, ExDeclType, VarDecl::None, Begin);
2296  if (D.getInvalidType() || Invalid)
2297    ExDecl->setInvalidDecl();
2298
2299  if (D.getCXXScopeSpec().isSet()) {
2300    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2301      << D.getCXXScopeSpec().getRange();
2302    ExDecl->setInvalidDecl();
2303  }
2304
2305  // Add the exception declaration into this scope.
2306  S->AddDecl(ExDecl);
2307  if (II)
2308    IdResolver.AddDecl(ExDecl);
2309
2310  ProcessDeclAttributes(ExDecl, D);
2311  return ExDecl;
2312}
2313