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