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