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