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