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