SemaDeclCXX.cpp revision 1b7f9cbed1b96b58a6e5f7808ebc9345a76a0936
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 "clang/Sema/SemaInternal.h"
15#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/AST/ASTConsumer.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/ASTMutationListener.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/CXXInheritance.h"
25#include "clang/AST/DeclVisitor.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/RecordLayout.h"
28#include "clang/AST/StmtVisitor.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/TypeOrdering.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/ParsedTemplate.h"
33#include "clang/Basic/PartialDiagnostic.h"
34#include "clang/Lex/Preprocessor.h"
35#include "llvm/ADT/SmallString.h"
36#include "llvm/ADT/STLExtras.h"
37#include <map>
38#include <set>
39
40using namespace clang;
41
42//===----------------------------------------------------------------------===//
43// CheckDefaultArgumentVisitor
44//===----------------------------------------------------------------------===//
45
46namespace {
47  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
48  /// the default argument of a parameter to determine whether it
49  /// contains any ill-formed subexpressions. For example, this will
50  /// diagnose the use of local variables or parameters within the
51  /// default argument expression.
52  class CheckDefaultArgumentVisitor
53    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
54    Expr *DefaultArg;
55    Sema *S;
56
57  public:
58    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
59      : DefaultArg(defarg), S(s) {}
60
61    bool VisitExpr(Expr *Node);
62    bool VisitDeclRefExpr(DeclRefExpr *DRE);
63    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
64    bool VisitLambdaExpr(LambdaExpr *Lambda);
65  };
66
67  /// VisitExpr - Visit all of the children of this expression.
68  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
69    bool IsInvalid = false;
70    for (Stmt::child_range I = Node->children(); I; ++I)
71      IsInvalid |= Visit(*I);
72    return IsInvalid;
73  }
74
75  /// VisitDeclRefExpr - Visit a reference to a declaration, to
76  /// determine whether this declaration can be used in the default
77  /// argument expression.
78  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
79    NamedDecl *Decl = DRE->getDecl();
80    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
81      // C++ [dcl.fct.default]p9
82      //   Default arguments are evaluated each time the function is
83      //   called. The order of evaluation of function arguments is
84      //   unspecified. Consequently, parameters of a function shall not
85      //   be used in default argument expressions, even if they are not
86      //   evaluated. Parameters of a function declared before a default
87      //   argument expression are in scope and can hide namespace and
88      //   class member names.
89      return S->Diag(DRE->getLocStart(),
90                     diag::err_param_default_argument_references_param)
91         << Param->getDeclName() << DefaultArg->getSourceRange();
92    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
93      // C++ [dcl.fct.default]p7
94      //   Local variables shall not be used in default argument
95      //   expressions.
96      if (VDecl->isLocalVarDecl())
97        return S->Diag(DRE->getLocStart(),
98                       diag::err_param_default_argument_references_local)
99          << VDecl->getDeclName() << DefaultArg->getSourceRange();
100    }
101
102    return false;
103  }
104
105  /// VisitCXXThisExpr - Visit a C++ "this" expression.
106  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
107    // C++ [dcl.fct.default]p8:
108    //   The keyword this shall not be used in a default argument of a
109    //   member function.
110    return S->Diag(ThisE->getLocStart(),
111                   diag::err_param_default_argument_references_this)
112               << ThisE->getSourceRange();
113  }
114
115  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
116    // C++11 [expr.lambda.prim]p13:
117    //   A lambda-expression appearing in a default argument shall not
118    //   implicitly or explicitly capture any entity.
119    if (Lambda->capture_begin() == Lambda->capture_end())
120      return false;
121
122    return S->Diag(Lambda->getLocStart(),
123                   diag::err_lambda_capture_default_arg);
124  }
125}
126
127void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
128  assert(Context && "ImplicitExceptionSpecification without an ASTContext");
129  // If we have an MSAny or unknown spec already, don't bother.
130  if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
131    return;
132
133  const FunctionProtoType *Proto
134    = Method->getType()->getAs<FunctionProtoType>();
135
136  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
137
138  // If this function can throw any exceptions, make a note of that.
139  if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
140    ClearExceptions();
141    ComputedEST = EST;
142    return;
143  }
144
145  // FIXME: If the call to this decl is using any of its default arguments, we
146  // need to search them for potentially-throwing calls.
147
148  // If this function has a basic noexcept, it doesn't affect the outcome.
149  if (EST == EST_BasicNoexcept)
150    return;
151
152  // If we have a throw-all spec at this point, ignore the function.
153  if (ComputedEST == EST_None)
154    return;
155
156  // If we're still at noexcept(true) and there's a nothrow() callee,
157  // change to that specification.
158  if (EST == EST_DynamicNone) {
159    if (ComputedEST == EST_BasicNoexcept)
160      ComputedEST = EST_DynamicNone;
161    return;
162  }
163
164  // Check out noexcept specs.
165  if (EST == EST_ComputedNoexcept) {
166    FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
167    assert(NR != FunctionProtoType::NR_NoNoexcept &&
168           "Must have noexcept result for EST_ComputedNoexcept.");
169    assert(NR != FunctionProtoType::NR_Dependent &&
170           "Should not generate implicit declarations for dependent cases, "
171           "and don't know how to handle them anyway.");
172
173    // noexcept(false) -> no spec on the new function
174    if (NR == FunctionProtoType::NR_Throw) {
175      ClearExceptions();
176      ComputedEST = EST_None;
177    }
178    // noexcept(true) won't change anything either.
179    return;
180  }
181
182  assert(EST == EST_Dynamic && "EST case not considered earlier.");
183  assert(ComputedEST != EST_None &&
184         "Shouldn't collect exceptions when throw-all is guaranteed.");
185  ComputedEST = EST_Dynamic;
186  // Record the exceptions in this function's exception specification.
187  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
188                                          EEnd = Proto->exception_end();
189       E != EEnd; ++E)
190    if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
191      Exceptions.push_back(*E);
192}
193
194void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
195  if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
196    return;
197
198  // FIXME:
199  //
200  // C++0x [except.spec]p14:
201  //   [An] implicit exception-specification specifies the type-id T if and
202  // only if T is allowed by the exception-specification of a function directly
203  // invoked by f's implicit definition; f shall allow all exceptions if any
204  // function it directly invokes allows all exceptions, and f shall allow no
205  // exceptions if every function it directly invokes allows no exceptions.
206  //
207  // Note in particular that if an implicit exception-specification is generated
208  // for a function containing a throw-expression, that specification can still
209  // be noexcept(true).
210  //
211  // Note also that 'directly invoked' is not defined in the standard, and there
212  // is no indication that we should only consider potentially-evaluated calls.
213  //
214  // Ultimately we should implement the intent of the standard: the exception
215  // specification should be the set of exceptions which can be thrown by the
216  // implicit definition. For now, we assume that any non-nothrow expression can
217  // throw any exception.
218
219  if (E->CanThrow(*Context))
220    ComputedEST = EST_None;
221}
222
223bool
224Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
225                              SourceLocation EqualLoc) {
226  if (RequireCompleteType(Param->getLocation(), Param->getType(),
227                          diag::err_typecheck_decl_incomplete_type)) {
228    Param->setInvalidDecl();
229    return true;
230  }
231
232  // C++ [dcl.fct.default]p5
233  //   A default argument expression is implicitly converted (clause
234  //   4) to the parameter type. The default argument expression has
235  //   the same semantic constraints as the initializer expression in
236  //   a declaration of a variable of the parameter type, using the
237  //   copy-initialization semantics (8.5).
238  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
239                                                                    Param);
240  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
241                                                           EqualLoc);
242  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
243  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
244                                      MultiExprArg(*this, &Arg, 1));
245  if (Result.isInvalid())
246    return true;
247  Arg = Result.takeAs<Expr>();
248
249  CheckImplicitConversions(Arg, EqualLoc);
250  Arg = MaybeCreateExprWithCleanups(Arg);
251
252  // Okay: add the default argument to the parameter
253  Param->setDefaultArg(Arg);
254
255  // We have already instantiated this parameter; provide each of the
256  // instantiations with the uninstantiated default argument.
257  UnparsedDefaultArgInstantiationsMap::iterator InstPos
258    = UnparsedDefaultArgInstantiations.find(Param);
259  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
260    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
261      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
262
263    // We're done tracking this parameter's instantiations.
264    UnparsedDefaultArgInstantiations.erase(InstPos);
265  }
266
267  return false;
268}
269
270/// ActOnParamDefaultArgument - Check whether the default argument
271/// provided for a function parameter is well-formed. If so, attach it
272/// to the parameter declaration.
273void
274Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
275                                Expr *DefaultArg) {
276  if (!param || !DefaultArg)
277    return;
278
279  ParmVarDecl *Param = cast<ParmVarDecl>(param);
280  UnparsedDefaultArgLocs.erase(Param);
281
282  // Default arguments are only permitted in C++
283  if (!getLangOpts().CPlusPlus) {
284    Diag(EqualLoc, diag::err_param_default_argument)
285      << DefaultArg->getSourceRange();
286    Param->setInvalidDecl();
287    return;
288  }
289
290  // Check for unexpanded parameter packs.
291  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
292    Param->setInvalidDecl();
293    return;
294  }
295
296  // Check that the default argument is well-formed
297  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
298  if (DefaultArgChecker.Visit(DefaultArg)) {
299    Param->setInvalidDecl();
300    return;
301  }
302
303  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
304}
305
306/// ActOnParamUnparsedDefaultArgument - We've seen a default
307/// argument for a function parameter, but we can't parse it yet
308/// because we're inside a class definition. Note that this default
309/// argument will be parsed later.
310void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
311                                             SourceLocation EqualLoc,
312                                             SourceLocation ArgLoc) {
313  if (!param)
314    return;
315
316  ParmVarDecl *Param = cast<ParmVarDecl>(param);
317  if (Param)
318    Param->setUnparsedDefaultArg();
319
320  UnparsedDefaultArgLocs[Param] = ArgLoc;
321}
322
323/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
324/// the default argument for the parameter param failed.
325void Sema::ActOnParamDefaultArgumentError(Decl *param) {
326  if (!param)
327    return;
328
329  ParmVarDecl *Param = cast<ParmVarDecl>(param);
330
331  Param->setInvalidDecl();
332
333  UnparsedDefaultArgLocs.erase(Param);
334}
335
336/// CheckExtraCXXDefaultArguments - Check for any extra default
337/// arguments in the declarator, which is not a function declaration
338/// or definition and therefore is not permitted to have default
339/// arguments. This routine should be invoked for every declarator
340/// that is not a function declaration or definition.
341void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
342  // C++ [dcl.fct.default]p3
343  //   A default argument expression shall be specified only in the
344  //   parameter-declaration-clause of a function declaration or in a
345  //   template-parameter (14.1). It shall not be specified for a
346  //   parameter pack. If it is specified in a
347  //   parameter-declaration-clause, it shall not occur within a
348  //   declarator or abstract-declarator of a parameter-declaration.
349  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
350    DeclaratorChunk &chunk = D.getTypeObject(i);
351    if (chunk.Kind == DeclaratorChunk::Function) {
352      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
353        ParmVarDecl *Param =
354          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
355        if (Param->hasUnparsedDefaultArg()) {
356          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
357          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
358            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
359          delete Toks;
360          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
361        } else if (Param->getDefaultArg()) {
362          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
363            << Param->getDefaultArg()->getSourceRange();
364          Param->setDefaultArg(0);
365        }
366      }
367    }
368  }
369}
370
371// MergeCXXFunctionDecl - Merge two declarations of the same C++
372// function, once we already know that they have the same
373// type. Subroutine of MergeFunctionDecl. Returns true if there was an
374// error, false otherwise.
375bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
376  bool Invalid = false;
377
378  // C++ [dcl.fct.default]p4:
379  //   For non-template functions, default arguments can be added in
380  //   later declarations of a function in the same
381  //   scope. Declarations in different scopes have completely
382  //   distinct sets of default arguments. That is, declarations in
383  //   inner scopes do not acquire default arguments from
384  //   declarations in outer scopes, and vice versa. In a given
385  //   function declaration, all parameters subsequent to a
386  //   parameter with a default argument shall have default
387  //   arguments supplied in this or previous declarations. A
388  //   default argument shall not be redefined by a later
389  //   declaration (not even to the same value).
390  //
391  // C++ [dcl.fct.default]p6:
392  //   Except for member functions of class templates, the default arguments
393  //   in a member function definition that appears outside of the class
394  //   definition are added to the set of default arguments provided by the
395  //   member function declaration in the class definition.
396  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
397    ParmVarDecl *OldParam = Old->getParamDecl(p);
398    ParmVarDecl *NewParam = New->getParamDecl(p);
399
400    if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
401
402      unsigned DiagDefaultParamID =
403        diag::err_param_default_argument_redefinition;
404
405      // MSVC accepts that default parameters be redefined for member functions
406      // of template class. The new default parameter's value is ignored.
407      Invalid = true;
408      if (getLangOpts().MicrosoftExt) {
409        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
410        if (MD && MD->getParent()->getDescribedClassTemplate()) {
411          // Merge the old default argument into the new parameter.
412          NewParam->setHasInheritedDefaultArg();
413          if (OldParam->hasUninstantiatedDefaultArg())
414            NewParam->setUninstantiatedDefaultArg(
415                                      OldParam->getUninstantiatedDefaultArg());
416          else
417            NewParam->setDefaultArg(OldParam->getInit());
418          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
419          Invalid = false;
420        }
421      }
422
423      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
424      // hint here. Alternatively, we could walk the type-source information
425      // for NewParam to find the last source location in the type... but it
426      // isn't worth the effort right now. This is the kind of test case that
427      // is hard to get right:
428      //   int f(int);
429      //   void g(int (*fp)(int) = f);
430      //   void g(int (*fp)(int) = &f);
431      Diag(NewParam->getLocation(), DiagDefaultParamID)
432        << NewParam->getDefaultArgRange();
433
434      // Look for the function declaration where the default argument was
435      // actually written, which may be a declaration prior to Old.
436      for (FunctionDecl *Older = Old->getPreviousDecl();
437           Older; Older = Older->getPreviousDecl()) {
438        if (!Older->getParamDecl(p)->hasDefaultArg())
439          break;
440
441        OldParam = Older->getParamDecl(p);
442      }
443
444      Diag(OldParam->getLocation(), diag::note_previous_definition)
445        << OldParam->getDefaultArgRange();
446    } else if (OldParam->hasDefaultArg()) {
447      // Merge the old default argument into the new parameter.
448      // It's important to use getInit() here;  getDefaultArg()
449      // strips off any top-level ExprWithCleanups.
450      NewParam->setHasInheritedDefaultArg();
451      if (OldParam->hasUninstantiatedDefaultArg())
452        NewParam->setUninstantiatedDefaultArg(
453                                      OldParam->getUninstantiatedDefaultArg());
454      else
455        NewParam->setDefaultArg(OldParam->getInit());
456    } else if (NewParam->hasDefaultArg()) {
457      if (New->getDescribedFunctionTemplate()) {
458        // Paragraph 4, quoted above, only applies to non-template functions.
459        Diag(NewParam->getLocation(),
460             diag::err_param_default_argument_template_redecl)
461          << NewParam->getDefaultArgRange();
462        Diag(Old->getLocation(), diag::note_template_prev_declaration)
463          << false;
464      } else if (New->getTemplateSpecializationKind()
465                   != TSK_ImplicitInstantiation &&
466                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
467        // C++ [temp.expr.spec]p21:
468        //   Default function arguments shall not be specified in a declaration
469        //   or a definition for one of the following explicit specializations:
470        //     - the explicit specialization of a function template;
471        //     - the explicit specialization of a member function template;
472        //     - the explicit specialization of a member function of a class
473        //       template where the class template specialization to which the
474        //       member function specialization belongs is implicitly
475        //       instantiated.
476        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
477          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
478          << New->getDeclName()
479          << NewParam->getDefaultArgRange();
480      } else if (New->getDeclContext()->isDependentContext()) {
481        // C++ [dcl.fct.default]p6 (DR217):
482        //   Default arguments for a member function of a class template shall
483        //   be specified on the initial declaration of the member function
484        //   within the class template.
485        //
486        // Reading the tea leaves a bit in DR217 and its reference to DR205
487        // leads me to the conclusion that one cannot add default function
488        // arguments for an out-of-line definition of a member function of a
489        // dependent type.
490        int WhichKind = 2;
491        if (CXXRecordDecl *Record
492              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
493          if (Record->getDescribedClassTemplate())
494            WhichKind = 0;
495          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
496            WhichKind = 1;
497          else
498            WhichKind = 2;
499        }
500
501        Diag(NewParam->getLocation(),
502             diag::err_param_default_argument_member_template_redecl)
503          << WhichKind
504          << NewParam->getDefaultArgRange();
505      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
506        CXXSpecialMember NewSM = getSpecialMember(Ctor),
507                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
508        if (NewSM != OldSM) {
509          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
510            << NewParam->getDefaultArgRange() << NewSM;
511          Diag(Old->getLocation(), diag::note_previous_declaration_special)
512            << OldSM;
513        }
514      }
515    }
516  }
517
518  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
519  // template has a constexpr specifier then all its declarations shall
520  // contain the constexpr specifier.
521  if (New->isConstexpr() != Old->isConstexpr()) {
522    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
523      << New << New->isConstexpr();
524    Diag(Old->getLocation(), diag::note_previous_declaration);
525    Invalid = true;
526  }
527
528  if (CheckEquivalentExceptionSpec(Old, New))
529    Invalid = true;
530
531  return Invalid;
532}
533
534/// \brief Merge the exception specifications of two variable declarations.
535///
536/// This is called when there's a redeclaration of a VarDecl. The function
537/// checks if the redeclaration might have an exception specification and
538/// validates compatibility and merges the specs if necessary.
539void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
540  // Shortcut if exceptions are disabled.
541  if (!getLangOpts().CXXExceptions)
542    return;
543
544  assert(Context.hasSameType(New->getType(), Old->getType()) &&
545         "Should only be called if types are otherwise the same.");
546
547  QualType NewType = New->getType();
548  QualType OldType = Old->getType();
549
550  // We're only interested in pointers and references to functions, as well
551  // as pointers to member functions.
552  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
553    NewType = R->getPointeeType();
554    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
555  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
556    NewType = P->getPointeeType();
557    OldType = OldType->getAs<PointerType>()->getPointeeType();
558  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
559    NewType = M->getPointeeType();
560    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
561  }
562
563  if (!NewType->isFunctionProtoType())
564    return;
565
566  // There's lots of special cases for functions. For function pointers, system
567  // libraries are hopefully not as broken so that we don't need these
568  // workarounds.
569  if (CheckEquivalentExceptionSpec(
570        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
571        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
572    New->setInvalidDecl();
573  }
574}
575
576/// CheckCXXDefaultArguments - Verify that the default arguments for a
577/// function declaration are well-formed according to C++
578/// [dcl.fct.default].
579void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
580  unsigned NumParams = FD->getNumParams();
581  unsigned p;
582
583  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
584                  isa<CXXMethodDecl>(FD) &&
585                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
586
587  // Find first parameter with a default argument
588  for (p = 0; p < NumParams; ++p) {
589    ParmVarDecl *Param = FD->getParamDecl(p);
590    if (Param->hasDefaultArg()) {
591      // C++11 [expr.prim.lambda]p5:
592      //   [...] Default arguments (8.3.6) shall not be specified in the
593      //   parameter-declaration-clause of a lambda-declarator.
594      //
595      // FIXME: Core issue 974 strikes this sentence, we only provide an
596      // extension warning.
597      if (IsLambda)
598        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
599          << Param->getDefaultArgRange();
600      break;
601    }
602  }
603
604  // C++ [dcl.fct.default]p4:
605  //   In a given function declaration, all parameters
606  //   subsequent to a parameter with a default argument shall
607  //   have default arguments supplied in this or previous
608  //   declarations. A default argument shall not be redefined
609  //   by a later declaration (not even to the same value).
610  unsigned LastMissingDefaultArg = 0;
611  for (; p < NumParams; ++p) {
612    ParmVarDecl *Param = FD->getParamDecl(p);
613    if (!Param->hasDefaultArg()) {
614      if (Param->isInvalidDecl())
615        /* We already complained about this parameter. */;
616      else if (Param->getIdentifier())
617        Diag(Param->getLocation(),
618             diag::err_param_default_argument_missing_name)
619          << Param->getIdentifier();
620      else
621        Diag(Param->getLocation(),
622             diag::err_param_default_argument_missing);
623
624      LastMissingDefaultArg = p;
625    }
626  }
627
628  if (LastMissingDefaultArg > 0) {
629    // Some default arguments were missing. Clear out all of the
630    // default arguments up to (and including) the last missing
631    // default argument, so that we leave the function parameters
632    // in a semantically valid state.
633    for (p = 0; p <= LastMissingDefaultArg; ++p) {
634      ParmVarDecl *Param = FD->getParamDecl(p);
635      if (Param->hasDefaultArg()) {
636        Param->setDefaultArg(0);
637      }
638    }
639  }
640}
641
642// CheckConstexprParameterTypes - Check whether a function's parameter types
643// are all literal types. If so, return true. If not, produce a suitable
644// diagnostic and return false.
645static bool CheckConstexprParameterTypes(Sema &SemaRef,
646                                         const FunctionDecl *FD) {
647  unsigned ArgIndex = 0;
648  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
649  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
650       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
651    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
652    SourceLocation ParamLoc = PD->getLocation();
653    if (!(*i)->isDependentType() &&
654        SemaRef.RequireLiteralType(ParamLoc, *i,
655                            SemaRef.PDiag(diag::err_constexpr_non_literal_param)
656                                     << ArgIndex+1 << PD->getSourceRange()
657                                     << isa<CXXConstructorDecl>(FD)))
658      return false;
659  }
660  return true;
661}
662
663// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
664// the requirements of a constexpr function definition or a constexpr
665// constructor definition. If so, return true. If not, produce appropriate
666// diagnostics and return false.
667//
668// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
669bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
670  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
671  if (MD && MD->isInstance()) {
672    // C++11 [dcl.constexpr]p4:
673    //  The definition of a constexpr constructor shall satisfy the following
674    //  constraints:
675    //  - the class shall not have any virtual base classes;
676    const CXXRecordDecl *RD = MD->getParent();
677    if (RD->getNumVBases()) {
678      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
679        << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
680        << RD->getNumVBases();
681      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
682             E = RD->vbases_end(); I != E; ++I)
683        Diag(I->getLocStart(),
684             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
685      return false;
686    }
687  }
688
689  if (!isa<CXXConstructorDecl>(NewFD)) {
690    // C++11 [dcl.constexpr]p3:
691    //  The definition of a constexpr function shall satisfy the following
692    //  constraints:
693    // - it shall not be virtual;
694    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
695    if (Method && Method->isVirtual()) {
696      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
697
698      // If it's not obvious why this function is virtual, find an overridden
699      // function which uses the 'virtual' keyword.
700      const CXXMethodDecl *WrittenVirtual = Method;
701      while (!WrittenVirtual->isVirtualAsWritten())
702        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
703      if (WrittenVirtual != Method)
704        Diag(WrittenVirtual->getLocation(),
705             diag::note_overridden_virtual_function);
706      return false;
707    }
708
709    // - its return type shall be a literal type;
710    QualType RT = NewFD->getResultType();
711    if (!RT->isDependentType() &&
712        RequireLiteralType(NewFD->getLocation(), RT,
713                           PDiag(diag::err_constexpr_non_literal_return)))
714      return false;
715  }
716
717  // - each of its parameter types shall be a literal type;
718  if (!CheckConstexprParameterTypes(*this, NewFD))
719    return false;
720
721  return true;
722}
723
724/// Check the given declaration statement is legal within a constexpr function
725/// body. C++0x [dcl.constexpr]p3,p4.
726///
727/// \return true if the body is OK, false if we have diagnosed a problem.
728static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
729                                   DeclStmt *DS) {
730  // C++0x [dcl.constexpr]p3 and p4:
731  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
732  //  contain only
733  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
734         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
735    switch ((*DclIt)->getKind()) {
736    case Decl::StaticAssert:
737    case Decl::Using:
738    case Decl::UsingShadow:
739    case Decl::UsingDirective:
740    case Decl::UnresolvedUsingTypename:
741      //   - static_assert-declarations
742      //   - using-declarations,
743      //   - using-directives,
744      continue;
745
746    case Decl::Typedef:
747    case Decl::TypeAlias: {
748      //   - typedef declarations and alias-declarations that do not define
749      //     classes or enumerations,
750      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
751      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
752        // Don't allow variably-modified types in constexpr functions.
753        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
754        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
755          << TL.getSourceRange() << TL.getType()
756          << isa<CXXConstructorDecl>(Dcl);
757        return false;
758      }
759      continue;
760    }
761
762    case Decl::Enum:
763    case Decl::CXXRecord:
764      // As an extension, we allow the declaration (but not the definition) of
765      // classes and enumerations in all declarations, not just in typedef and
766      // alias declarations.
767      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
768        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
769          << isa<CXXConstructorDecl>(Dcl);
770        return false;
771      }
772      continue;
773
774    case Decl::Var:
775      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
776        << isa<CXXConstructorDecl>(Dcl);
777      return false;
778
779    default:
780      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
781        << isa<CXXConstructorDecl>(Dcl);
782      return false;
783    }
784  }
785
786  return true;
787}
788
789/// Check that the given field is initialized within a constexpr constructor.
790///
791/// \param Dcl The constexpr constructor being checked.
792/// \param Field The field being checked. This may be a member of an anonymous
793///        struct or union nested within the class being checked.
794/// \param Inits All declarations, including anonymous struct/union members and
795///        indirect members, for which any initialization was provided.
796/// \param Diagnosed Set to true if an error is produced.
797static void CheckConstexprCtorInitializer(Sema &SemaRef,
798                                          const FunctionDecl *Dcl,
799                                          FieldDecl *Field,
800                                          llvm::SmallSet<Decl*, 16> &Inits,
801                                          bool &Diagnosed) {
802  if (Field->isUnnamedBitfield())
803    return;
804
805  if (Field->isAnonymousStructOrUnion() &&
806      Field->getType()->getAsCXXRecordDecl()->isEmpty())
807    return;
808
809  if (!Inits.count(Field)) {
810    if (!Diagnosed) {
811      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
812      Diagnosed = true;
813    }
814    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
815  } else if (Field->isAnonymousStructOrUnion()) {
816    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
817    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
818         I != E; ++I)
819      // If an anonymous union contains an anonymous struct of which any member
820      // is initialized, all members must be initialized.
821      if (!RD->isUnion() || Inits.count(*I))
822        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
823  }
824}
825
826/// Check the body for the given constexpr function declaration only contains
827/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
828///
829/// \return true if the body is OK, false if we have diagnosed a problem.
830bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
831  if (isa<CXXTryStmt>(Body)) {
832    // C++11 [dcl.constexpr]p3:
833    //  The definition of a constexpr function shall satisfy the following
834    //  constraints: [...]
835    // - its function-body shall be = delete, = default, or a
836    //   compound-statement
837    //
838    // C++11 [dcl.constexpr]p4:
839    //  In the definition of a constexpr constructor, [...]
840    // - its function-body shall not be a function-try-block;
841    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
842      << isa<CXXConstructorDecl>(Dcl);
843    return false;
844  }
845
846  // - its function-body shall be [...] a compound-statement that contains only
847  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
848
849  llvm::SmallVector<SourceLocation, 4> ReturnStmts;
850  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
851         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
852    switch ((*BodyIt)->getStmtClass()) {
853    case Stmt::NullStmtClass:
854      //   - null statements,
855      continue;
856
857    case Stmt::DeclStmtClass:
858      //   - static_assert-declarations
859      //   - using-declarations,
860      //   - using-directives,
861      //   - typedef declarations and alias-declarations that do not define
862      //     classes or enumerations,
863      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
864        return false;
865      continue;
866
867    case Stmt::ReturnStmtClass:
868      //   - and exactly one return statement;
869      if (isa<CXXConstructorDecl>(Dcl))
870        break;
871
872      ReturnStmts.push_back((*BodyIt)->getLocStart());
873      continue;
874
875    default:
876      break;
877    }
878
879    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
880      << isa<CXXConstructorDecl>(Dcl);
881    return false;
882  }
883
884  if (const CXXConstructorDecl *Constructor
885        = dyn_cast<CXXConstructorDecl>(Dcl)) {
886    const CXXRecordDecl *RD = Constructor->getParent();
887    // DR1359:
888    // - every non-variant non-static data member and base class sub-object
889    //   shall be initialized;
890    // - if the class is a non-empty union, or for each non-empty anonymous
891    //   union member of a non-union class, exactly one non-static data member
892    //   shall be initialized;
893    if (RD->isUnion()) {
894      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
895        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
896        return false;
897      }
898    } else if (!Constructor->isDependentContext() &&
899               !Constructor->isDelegatingConstructor()) {
900      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
901
902      // Skip detailed checking if we have enough initializers, and we would
903      // allow at most one initializer per member.
904      bool AnyAnonStructUnionMembers = false;
905      unsigned Fields = 0;
906      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
907           E = RD->field_end(); I != E; ++I, ++Fields) {
908        if ((*I)->isAnonymousStructOrUnion()) {
909          AnyAnonStructUnionMembers = true;
910          break;
911        }
912      }
913      if (AnyAnonStructUnionMembers ||
914          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
915        // Check initialization of non-static data members. Base classes are
916        // always initialized so do not need to be checked. Dependent bases
917        // might not have initializers in the member initializer list.
918        llvm::SmallSet<Decl*, 16> Inits;
919        for (CXXConstructorDecl::init_const_iterator
920               I = Constructor->init_begin(), E = Constructor->init_end();
921             I != E; ++I) {
922          if (FieldDecl *FD = (*I)->getMember())
923            Inits.insert(FD);
924          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
925            Inits.insert(ID->chain_begin(), ID->chain_end());
926        }
927
928        bool Diagnosed = false;
929        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
930             E = RD->field_end(); I != E; ++I)
931          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
932        if (Diagnosed)
933          return false;
934      }
935    }
936  } else {
937    if (ReturnStmts.empty()) {
938      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
939      return false;
940    }
941    if (ReturnStmts.size() > 1) {
942      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
943      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
944        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
945      return false;
946    }
947  }
948
949  // C++11 [dcl.constexpr]p5:
950  //   if no function argument values exist such that the function invocation
951  //   substitution would produce a constant expression, the program is
952  //   ill-formed; no diagnostic required.
953  // C++11 [dcl.constexpr]p3:
954  //   - every constructor call and implicit conversion used in initializing the
955  //     return value shall be one of those allowed in a constant expression.
956  // C++11 [dcl.constexpr]p4:
957  //   - every constructor involved in initializing non-static data members and
958  //     base class sub-objects shall be a constexpr constructor.
959  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
960  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
961    Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
962      << isa<CXXConstructorDecl>(Dcl);
963    for (size_t I = 0, N = Diags.size(); I != N; ++I)
964      Diag(Diags[I].first, Diags[I].second);
965    return false;
966  }
967
968  return true;
969}
970
971/// isCurrentClassName - Determine whether the identifier II is the
972/// name of the class type currently being defined. In the case of
973/// nested classes, this will only return true if II is the name of
974/// the innermost class.
975bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
976                              const CXXScopeSpec *SS) {
977  assert(getLangOpts().CPlusPlus && "No class names in C!");
978
979  CXXRecordDecl *CurDecl;
980  if (SS && SS->isSet() && !SS->isInvalid()) {
981    DeclContext *DC = computeDeclContext(*SS, true);
982    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
983  } else
984    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
985
986  if (CurDecl && CurDecl->getIdentifier())
987    return &II == CurDecl->getIdentifier();
988  else
989    return false;
990}
991
992/// \brief Check the validity of a C++ base class specifier.
993///
994/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
995/// and returns NULL otherwise.
996CXXBaseSpecifier *
997Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
998                         SourceRange SpecifierRange,
999                         bool Virtual, AccessSpecifier Access,
1000                         TypeSourceInfo *TInfo,
1001                         SourceLocation EllipsisLoc) {
1002  QualType BaseType = TInfo->getType();
1003
1004  // C++ [class.union]p1:
1005  //   A union shall not have base classes.
1006  if (Class->isUnion()) {
1007    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1008      << SpecifierRange;
1009    return 0;
1010  }
1011
1012  if (EllipsisLoc.isValid() &&
1013      !TInfo->getType()->containsUnexpandedParameterPack()) {
1014    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1015      << TInfo->getTypeLoc().getSourceRange();
1016    EllipsisLoc = SourceLocation();
1017  }
1018
1019  if (BaseType->isDependentType())
1020    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1021                                          Class->getTagKind() == TTK_Class,
1022                                          Access, TInfo, EllipsisLoc);
1023
1024  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1025
1026  // Base specifiers must be record types.
1027  if (!BaseType->isRecordType()) {
1028    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1029    return 0;
1030  }
1031
1032  // C++ [class.union]p1:
1033  //   A union shall not be used as a base class.
1034  if (BaseType->isUnionType()) {
1035    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1036    return 0;
1037  }
1038
1039  // C++ [class.derived]p2:
1040  //   The class-name in a base-specifier shall not be an incompletely
1041  //   defined class.
1042  if (RequireCompleteType(BaseLoc, BaseType,
1043                          PDiag(diag::err_incomplete_base_class)
1044                            << SpecifierRange)) {
1045    Class->setInvalidDecl();
1046    return 0;
1047  }
1048
1049  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1050  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1051  assert(BaseDecl && "Record type has no declaration");
1052  BaseDecl = BaseDecl->getDefinition();
1053  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1054  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1055  assert(CXXBaseDecl && "Base type is not a C++ type");
1056
1057  // C++ [class]p3:
1058  //   If a class is marked final and it appears as a base-type-specifier in
1059  //   base-clause, the program is ill-formed.
1060  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1061    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1062      << CXXBaseDecl->getDeclName();
1063    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1064      << CXXBaseDecl->getDeclName();
1065    return 0;
1066  }
1067
1068  if (BaseDecl->isInvalidDecl())
1069    Class->setInvalidDecl();
1070
1071  // Create the base specifier.
1072  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1073                                        Class->getTagKind() == TTK_Class,
1074                                        Access, TInfo, EllipsisLoc);
1075}
1076
1077/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1078/// one entry in the base class list of a class specifier, for
1079/// example:
1080///    class foo : public bar, virtual private baz {
1081/// 'public bar' and 'virtual private baz' are each base-specifiers.
1082BaseResult
1083Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1084                         bool Virtual, AccessSpecifier Access,
1085                         ParsedType basetype, SourceLocation BaseLoc,
1086                         SourceLocation EllipsisLoc) {
1087  if (!classdecl)
1088    return true;
1089
1090  AdjustDeclIfTemplate(classdecl);
1091  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1092  if (!Class)
1093    return true;
1094
1095  TypeSourceInfo *TInfo = 0;
1096  GetTypeFromParser(basetype, &TInfo);
1097
1098  if (EllipsisLoc.isInvalid() &&
1099      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1100                                      UPPC_BaseType))
1101    return true;
1102
1103  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1104                                                      Virtual, Access, TInfo,
1105                                                      EllipsisLoc))
1106    return BaseSpec;
1107
1108  return true;
1109}
1110
1111/// \brief Performs the actual work of attaching the given base class
1112/// specifiers to a C++ class.
1113bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1114                                unsigned NumBases) {
1115 if (NumBases == 0)
1116    return false;
1117
1118  // Used to keep track of which base types we have already seen, so
1119  // that we can properly diagnose redundant direct base types. Note
1120  // that the key is always the unqualified canonical type of the base
1121  // class.
1122  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1123
1124  // Copy non-redundant base specifiers into permanent storage.
1125  unsigned NumGoodBases = 0;
1126  bool Invalid = false;
1127  for (unsigned idx = 0; idx < NumBases; ++idx) {
1128    QualType NewBaseType
1129      = Context.getCanonicalType(Bases[idx]->getType());
1130    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1131
1132    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1133    if (KnownBase) {
1134      // C++ [class.mi]p3:
1135      //   A class shall not be specified as a direct base class of a
1136      //   derived class more than once.
1137      Diag(Bases[idx]->getLocStart(),
1138           diag::err_duplicate_base_class)
1139        << KnownBase->getType()
1140        << Bases[idx]->getSourceRange();
1141
1142      // Delete the duplicate base class specifier; we're going to
1143      // overwrite its pointer later.
1144      Context.Deallocate(Bases[idx]);
1145
1146      Invalid = true;
1147    } else {
1148      // Okay, add this new base class.
1149      KnownBase = Bases[idx];
1150      Bases[NumGoodBases++] = Bases[idx];
1151      if (const RecordType *Record = NewBaseType->getAs<RecordType>())
1152        if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1153          if (RD->hasAttr<WeakAttr>())
1154            Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1155    }
1156  }
1157
1158  // Attach the remaining base class specifiers to the derived class.
1159  Class->setBases(Bases, NumGoodBases);
1160
1161  // Delete the remaining (good) base class specifiers, since their
1162  // data has been copied into the CXXRecordDecl.
1163  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1164    Context.Deallocate(Bases[idx]);
1165
1166  return Invalid;
1167}
1168
1169/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1170/// class, after checking whether there are any duplicate base
1171/// classes.
1172void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1173                               unsigned NumBases) {
1174  if (!ClassDecl || !Bases || !NumBases)
1175    return;
1176
1177  AdjustDeclIfTemplate(ClassDecl);
1178  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1179                       (CXXBaseSpecifier**)(Bases), NumBases);
1180}
1181
1182static CXXRecordDecl *GetClassForType(QualType T) {
1183  if (const RecordType *RT = T->getAs<RecordType>())
1184    return cast<CXXRecordDecl>(RT->getDecl());
1185  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1186    return ICT->getDecl();
1187  else
1188    return 0;
1189}
1190
1191/// \brief Determine whether the type \p Derived is a C++ class that is
1192/// derived from the type \p Base.
1193bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1194  if (!getLangOpts().CPlusPlus)
1195    return false;
1196
1197  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1198  if (!DerivedRD)
1199    return false;
1200
1201  CXXRecordDecl *BaseRD = GetClassForType(Base);
1202  if (!BaseRD)
1203    return false;
1204
1205  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1206  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1207}
1208
1209/// \brief Determine whether the type \p Derived is a C++ class that is
1210/// derived from the type \p Base.
1211bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1212  if (!getLangOpts().CPlusPlus)
1213    return false;
1214
1215  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1216  if (!DerivedRD)
1217    return false;
1218
1219  CXXRecordDecl *BaseRD = GetClassForType(Base);
1220  if (!BaseRD)
1221    return false;
1222
1223  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1224}
1225
1226void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1227                              CXXCastPath &BasePathArray) {
1228  assert(BasePathArray.empty() && "Base path array must be empty!");
1229  assert(Paths.isRecordingPaths() && "Must record paths!");
1230
1231  const CXXBasePath &Path = Paths.front();
1232
1233  // We first go backward and check if we have a virtual base.
1234  // FIXME: It would be better if CXXBasePath had the base specifier for
1235  // the nearest virtual base.
1236  unsigned Start = 0;
1237  for (unsigned I = Path.size(); I != 0; --I) {
1238    if (Path[I - 1].Base->isVirtual()) {
1239      Start = I - 1;
1240      break;
1241    }
1242  }
1243
1244  // Now add all bases.
1245  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1246    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1247}
1248
1249/// \brief Determine whether the given base path includes a virtual
1250/// base class.
1251bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1252  for (CXXCastPath::const_iterator B = BasePath.begin(),
1253                                BEnd = BasePath.end();
1254       B != BEnd; ++B)
1255    if ((*B)->isVirtual())
1256      return true;
1257
1258  return false;
1259}
1260
1261/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1262/// conversion (where Derived and Base are class types) is
1263/// well-formed, meaning that the conversion is unambiguous (and
1264/// that all of the base classes are accessible). Returns true
1265/// and emits a diagnostic if the code is ill-formed, returns false
1266/// otherwise. Loc is the location where this routine should point to
1267/// if there is an error, and Range is the source range to highlight
1268/// if there is an error.
1269bool
1270Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1271                                   unsigned InaccessibleBaseID,
1272                                   unsigned AmbigiousBaseConvID,
1273                                   SourceLocation Loc, SourceRange Range,
1274                                   DeclarationName Name,
1275                                   CXXCastPath *BasePath) {
1276  // First, determine whether the path from Derived to Base is
1277  // ambiguous. This is slightly more expensive than checking whether
1278  // the Derived to Base conversion exists, because here we need to
1279  // explore multiple paths to determine if there is an ambiguity.
1280  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1281                     /*DetectVirtual=*/false);
1282  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1283  assert(DerivationOkay &&
1284         "Can only be used with a derived-to-base conversion");
1285  (void)DerivationOkay;
1286
1287  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1288    if (InaccessibleBaseID) {
1289      // Check that the base class can be accessed.
1290      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1291                                   InaccessibleBaseID)) {
1292        case AR_inaccessible:
1293          return true;
1294        case AR_accessible:
1295        case AR_dependent:
1296        case AR_delayed:
1297          break;
1298      }
1299    }
1300
1301    // Build a base path if necessary.
1302    if (BasePath)
1303      BuildBasePathArray(Paths, *BasePath);
1304    return false;
1305  }
1306
1307  // We know that the derived-to-base conversion is ambiguous, and
1308  // we're going to produce a diagnostic. Perform the derived-to-base
1309  // search just one more time to compute all of the possible paths so
1310  // that we can print them out. This is more expensive than any of
1311  // the previous derived-to-base checks we've done, but at this point
1312  // performance isn't as much of an issue.
1313  Paths.clear();
1314  Paths.setRecordingPaths(true);
1315  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1316  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1317  (void)StillOkay;
1318
1319  // Build up a textual representation of the ambiguous paths, e.g.,
1320  // D -> B -> A, that will be used to illustrate the ambiguous
1321  // conversions in the diagnostic. We only print one of the paths
1322  // to each base class subobject.
1323  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1324
1325  Diag(Loc, AmbigiousBaseConvID)
1326  << Derived << Base << PathDisplayStr << Range << Name;
1327  return true;
1328}
1329
1330bool
1331Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1332                                   SourceLocation Loc, SourceRange Range,
1333                                   CXXCastPath *BasePath,
1334                                   bool IgnoreAccess) {
1335  return CheckDerivedToBaseConversion(Derived, Base,
1336                                      IgnoreAccess ? 0
1337                                       : diag::err_upcast_to_inaccessible_base,
1338                                      diag::err_ambiguous_derived_to_base_conv,
1339                                      Loc, Range, DeclarationName(),
1340                                      BasePath);
1341}
1342
1343
1344/// @brief Builds a string representing ambiguous paths from a
1345/// specific derived class to different subobjects of the same base
1346/// class.
1347///
1348/// This function builds a string that can be used in error messages
1349/// to show the different paths that one can take through the
1350/// inheritance hierarchy to go from the derived class to different
1351/// subobjects of a base class. The result looks something like this:
1352/// @code
1353/// struct D -> struct B -> struct A
1354/// struct D -> struct C -> struct A
1355/// @endcode
1356std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1357  std::string PathDisplayStr;
1358  std::set<unsigned> DisplayedPaths;
1359  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1360       Path != Paths.end(); ++Path) {
1361    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1362      // We haven't displayed a path to this particular base
1363      // class subobject yet.
1364      PathDisplayStr += "\n    ";
1365      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1366      for (CXXBasePath::const_iterator Element = Path->begin();
1367           Element != Path->end(); ++Element)
1368        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1369    }
1370  }
1371
1372  return PathDisplayStr;
1373}
1374
1375//===----------------------------------------------------------------------===//
1376// C++ class member Handling
1377//===----------------------------------------------------------------------===//
1378
1379/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1380bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1381                                SourceLocation ASLoc,
1382                                SourceLocation ColonLoc,
1383                                AttributeList *Attrs) {
1384  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1385  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1386                                                  ASLoc, ColonLoc);
1387  CurContext->addHiddenDecl(ASDecl);
1388  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1389}
1390
1391/// CheckOverrideControl - Check C++0x override control semantics.
1392void Sema::CheckOverrideControl(const Decl *D) {
1393  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1394  if (!MD || !MD->isVirtual())
1395    return;
1396
1397  if (MD->isDependentContext())
1398    return;
1399
1400  // C++0x [class.virtual]p3:
1401  //   If a virtual function is marked with the virt-specifier override and does
1402  //   not override a member function of a base class,
1403  //   the program is ill-formed.
1404  bool HasOverriddenMethods =
1405    MD->begin_overridden_methods() != MD->end_overridden_methods();
1406  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1407    Diag(MD->getLocation(),
1408                 diag::err_function_marked_override_not_overriding)
1409      << MD->getDeclName();
1410    return;
1411  }
1412}
1413
1414/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1415/// function overrides a virtual member function marked 'final', according to
1416/// C++0x [class.virtual]p3.
1417bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1418                                                  const CXXMethodDecl *Old) {
1419  if (!Old->hasAttr<FinalAttr>())
1420    return false;
1421
1422  Diag(New->getLocation(), diag::err_final_function_overridden)
1423    << New->getDeclName();
1424  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1425  return true;
1426}
1427
1428/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1429/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1430/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1431/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1432/// present but parsing it has been deferred.
1433Decl *
1434Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1435                               MultiTemplateParamsArg TemplateParameterLists,
1436                               Expr *BW, const VirtSpecifiers &VS,
1437                               bool HasDeferredInit) {
1438  const DeclSpec &DS = D.getDeclSpec();
1439  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1440  DeclarationName Name = NameInfo.getName();
1441  SourceLocation Loc = NameInfo.getLoc();
1442
1443  // For anonymous bitfields, the location should point to the type.
1444  if (Loc.isInvalid())
1445    Loc = D.getLocStart();
1446
1447  Expr *BitWidth = static_cast<Expr*>(BW);
1448
1449  assert(isa<CXXRecordDecl>(CurContext));
1450  assert(!DS.isFriendSpecified());
1451
1452  bool isFunc = D.isDeclarationOfFunction();
1453
1454  // C++ 9.2p6: A member shall not be declared to have automatic storage
1455  // duration (auto, register) or with the extern storage-class-specifier.
1456  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1457  // data members and cannot be applied to names declared const or static,
1458  // and cannot be applied to reference members.
1459  switch (DS.getStorageClassSpec()) {
1460    case DeclSpec::SCS_unspecified:
1461    case DeclSpec::SCS_typedef:
1462    case DeclSpec::SCS_static:
1463      // FALL THROUGH.
1464      break;
1465    case DeclSpec::SCS_mutable:
1466      if (isFunc) {
1467        if (DS.getStorageClassSpecLoc().isValid())
1468          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1469        else
1470          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1471
1472        // FIXME: It would be nicer if the keyword was ignored only for this
1473        // declarator. Otherwise we could get follow-up errors.
1474        D.getMutableDeclSpec().ClearStorageClassSpecs();
1475      }
1476      break;
1477    default:
1478      if (DS.getStorageClassSpecLoc().isValid())
1479        Diag(DS.getStorageClassSpecLoc(),
1480             diag::err_storageclass_invalid_for_member);
1481      else
1482        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1483      D.getMutableDeclSpec().ClearStorageClassSpecs();
1484  }
1485
1486  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1487                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1488                      !isFunc);
1489
1490  Decl *Member;
1491  if (isInstField) {
1492    CXXScopeSpec &SS = D.getCXXScopeSpec();
1493
1494    // Data members must have identifiers for names.
1495    if (Name.getNameKind() != DeclarationName::Identifier) {
1496      Diag(Loc, diag::err_bad_variable_name)
1497        << Name;
1498      return 0;
1499    }
1500
1501    IdentifierInfo *II = Name.getAsIdentifierInfo();
1502
1503    // Member field could not be with "template" keyword.
1504    // So TemplateParameterLists should be empty in this case.
1505    if (TemplateParameterLists.size()) {
1506      TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1507      if (TemplateParams->size()) {
1508        // There is no such thing as a member field template.
1509        Diag(D.getIdentifierLoc(), diag::err_template_member)
1510            << II
1511            << SourceRange(TemplateParams->getTemplateLoc(),
1512                TemplateParams->getRAngleLoc());
1513      } else {
1514        // There is an extraneous 'template<>' for this member.
1515        Diag(TemplateParams->getTemplateLoc(),
1516            diag::err_template_member_noparams)
1517            << II
1518            << SourceRange(TemplateParams->getTemplateLoc(),
1519                TemplateParams->getRAngleLoc());
1520      }
1521      return 0;
1522    }
1523
1524    if (SS.isSet() && !SS.isInvalid()) {
1525      // The user provided a superfluous scope specifier inside a class
1526      // definition:
1527      //
1528      // class X {
1529      //   int X::member;
1530      // };
1531      DeclContext *DC = 0;
1532      if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1533        Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1534          << Name << FixItHint::CreateRemoval(SS.getRange());
1535      else
1536        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1537          << Name << SS.getRange();
1538
1539      SS.clear();
1540    }
1541
1542    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1543                         HasDeferredInit, AS);
1544    assert(Member && "HandleField never returns null");
1545  } else {
1546    assert(!HasDeferredInit);
1547
1548    Member = HandleDeclarator(S, D, move(TemplateParameterLists));
1549    if (!Member) {
1550      return 0;
1551    }
1552
1553    // Non-instance-fields can't have a bitfield.
1554    if (BitWidth) {
1555      if (Member->isInvalidDecl()) {
1556        // don't emit another diagnostic.
1557      } else if (isa<VarDecl>(Member)) {
1558        // C++ 9.6p3: A bit-field shall not be a static member.
1559        // "static member 'A' cannot be a bit-field"
1560        Diag(Loc, diag::err_static_not_bitfield)
1561          << Name << BitWidth->getSourceRange();
1562      } else if (isa<TypedefDecl>(Member)) {
1563        // "typedef member 'x' cannot be a bit-field"
1564        Diag(Loc, diag::err_typedef_not_bitfield)
1565          << Name << BitWidth->getSourceRange();
1566      } else {
1567        // A function typedef ("typedef int f(); f a;").
1568        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1569        Diag(Loc, diag::err_not_integral_type_bitfield)
1570          << Name << cast<ValueDecl>(Member)->getType()
1571          << BitWidth->getSourceRange();
1572      }
1573
1574      BitWidth = 0;
1575      Member->setInvalidDecl();
1576    }
1577
1578    Member->setAccess(AS);
1579
1580    // If we have declared a member function template, set the access of the
1581    // templated declaration as well.
1582    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1583      FunTmpl->getTemplatedDecl()->setAccess(AS);
1584  }
1585
1586  if (VS.isOverrideSpecified()) {
1587    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1588    if (!MD || !MD->isVirtual()) {
1589      Diag(Member->getLocStart(),
1590           diag::override_keyword_only_allowed_on_virtual_member_functions)
1591        << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1592    } else
1593      MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1594  }
1595  if (VS.isFinalSpecified()) {
1596    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1597    if (!MD || !MD->isVirtual()) {
1598      Diag(Member->getLocStart(),
1599           diag::override_keyword_only_allowed_on_virtual_member_functions)
1600      << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1601    } else
1602      MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1603  }
1604
1605  if (VS.getLastLocation().isValid()) {
1606    // Update the end location of a method that has a virt-specifiers.
1607    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1608      MD->setRangeEnd(VS.getLastLocation());
1609  }
1610
1611  CheckOverrideControl(Member);
1612
1613  assert((Name || isInstField) && "No identifier for non-field ?");
1614
1615  if (isInstField)
1616    FieldCollector->Add(cast<FieldDecl>(Member));
1617  return Member;
1618}
1619
1620/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1621/// in-class initializer for a non-static C++ class member, and after
1622/// instantiating an in-class initializer in a class template. Such actions
1623/// are deferred until the class is complete.
1624void
1625Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1626                                       Expr *InitExpr) {
1627  FieldDecl *FD = cast<FieldDecl>(D);
1628
1629  if (!InitExpr) {
1630    FD->setInvalidDecl();
1631    FD->removeInClassInitializer();
1632    return;
1633  }
1634
1635  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1636    FD->setInvalidDecl();
1637    FD->removeInClassInitializer();
1638    return;
1639  }
1640
1641  ExprResult Init = InitExpr;
1642  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1643    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1644      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1645        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1646    }
1647    Expr **Inits = &InitExpr;
1648    unsigned NumInits = 1;
1649    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1650    InitializationKind Kind = EqualLoc.isInvalid()
1651        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1652        : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1653    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1654    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1655    if (Init.isInvalid()) {
1656      FD->setInvalidDecl();
1657      return;
1658    }
1659
1660    CheckImplicitConversions(Init.get(), EqualLoc);
1661  }
1662
1663  // C++0x [class.base.init]p7:
1664  //   The initialization of each base and member constitutes a
1665  //   full-expression.
1666  Init = MaybeCreateExprWithCleanups(Init);
1667  if (Init.isInvalid()) {
1668    FD->setInvalidDecl();
1669    return;
1670  }
1671
1672  InitExpr = Init.release();
1673
1674  FD->setInClassInitializer(InitExpr);
1675}
1676
1677/// \brief Find the direct and/or virtual base specifiers that
1678/// correspond to the given base type, for use in base initialization
1679/// within a constructor.
1680static bool FindBaseInitializer(Sema &SemaRef,
1681                                CXXRecordDecl *ClassDecl,
1682                                QualType BaseType,
1683                                const CXXBaseSpecifier *&DirectBaseSpec,
1684                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1685  // First, check for a direct base class.
1686  DirectBaseSpec = 0;
1687  for (CXXRecordDecl::base_class_const_iterator Base
1688         = ClassDecl->bases_begin();
1689       Base != ClassDecl->bases_end(); ++Base) {
1690    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1691      // We found a direct base of this type. That's what we're
1692      // initializing.
1693      DirectBaseSpec = &*Base;
1694      break;
1695    }
1696  }
1697
1698  // Check for a virtual base class.
1699  // FIXME: We might be able to short-circuit this if we know in advance that
1700  // there are no virtual bases.
1701  VirtualBaseSpec = 0;
1702  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1703    // We haven't found a base yet; search the class hierarchy for a
1704    // virtual base class.
1705    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1706                       /*DetectVirtual=*/false);
1707    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1708                              BaseType, Paths)) {
1709      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1710           Path != Paths.end(); ++Path) {
1711        if (Path->back().Base->isVirtual()) {
1712          VirtualBaseSpec = Path->back().Base;
1713          break;
1714        }
1715      }
1716    }
1717  }
1718
1719  return DirectBaseSpec || VirtualBaseSpec;
1720}
1721
1722/// \brief Handle a C++ member initializer using braced-init-list syntax.
1723MemInitResult
1724Sema::ActOnMemInitializer(Decl *ConstructorD,
1725                          Scope *S,
1726                          CXXScopeSpec &SS,
1727                          IdentifierInfo *MemberOrBase,
1728                          ParsedType TemplateTypeTy,
1729                          const DeclSpec &DS,
1730                          SourceLocation IdLoc,
1731                          Expr *InitList,
1732                          SourceLocation EllipsisLoc) {
1733  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1734                             DS, IdLoc, InitList,
1735                             EllipsisLoc);
1736}
1737
1738/// \brief Handle a C++ member initializer using parentheses syntax.
1739MemInitResult
1740Sema::ActOnMemInitializer(Decl *ConstructorD,
1741                          Scope *S,
1742                          CXXScopeSpec &SS,
1743                          IdentifierInfo *MemberOrBase,
1744                          ParsedType TemplateTypeTy,
1745                          const DeclSpec &DS,
1746                          SourceLocation IdLoc,
1747                          SourceLocation LParenLoc,
1748                          Expr **Args, unsigned NumArgs,
1749                          SourceLocation RParenLoc,
1750                          SourceLocation EllipsisLoc) {
1751  Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1752                                           RParenLoc);
1753  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1754                             DS, IdLoc, List, EllipsisLoc);
1755}
1756
1757namespace {
1758
1759// Callback to only accept typo corrections that can be a valid C++ member
1760// intializer: either a non-static field member or a base class.
1761class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1762 public:
1763  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1764      : ClassDecl(ClassDecl) {}
1765
1766  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1767    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1768      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1769        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1770      else
1771        return isa<TypeDecl>(ND);
1772    }
1773    return false;
1774  }
1775
1776 private:
1777  CXXRecordDecl *ClassDecl;
1778};
1779
1780}
1781
1782/// \brief Handle a C++ member initializer.
1783MemInitResult
1784Sema::BuildMemInitializer(Decl *ConstructorD,
1785                          Scope *S,
1786                          CXXScopeSpec &SS,
1787                          IdentifierInfo *MemberOrBase,
1788                          ParsedType TemplateTypeTy,
1789                          const DeclSpec &DS,
1790                          SourceLocation IdLoc,
1791                          Expr *Init,
1792                          SourceLocation EllipsisLoc) {
1793  if (!ConstructorD)
1794    return true;
1795
1796  AdjustDeclIfTemplate(ConstructorD);
1797
1798  CXXConstructorDecl *Constructor
1799    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1800  if (!Constructor) {
1801    // The user wrote a constructor initializer on a function that is
1802    // not a C++ constructor. Ignore the error for now, because we may
1803    // have more member initializers coming; we'll diagnose it just
1804    // once in ActOnMemInitializers.
1805    return true;
1806  }
1807
1808  CXXRecordDecl *ClassDecl = Constructor->getParent();
1809
1810  // C++ [class.base.init]p2:
1811  //   Names in a mem-initializer-id are looked up in the scope of the
1812  //   constructor's class and, if not found in that scope, are looked
1813  //   up in the scope containing the constructor's definition.
1814  //   [Note: if the constructor's class contains a member with the
1815  //   same name as a direct or virtual base class of the class, a
1816  //   mem-initializer-id naming the member or base class and composed
1817  //   of a single identifier refers to the class member. A
1818  //   mem-initializer-id for the hidden base class may be specified
1819  //   using a qualified name. ]
1820  if (!SS.getScopeRep() && !TemplateTypeTy) {
1821    // Look for a member, first.
1822    DeclContext::lookup_result Result
1823      = ClassDecl->lookup(MemberOrBase);
1824    if (Result.first != Result.second) {
1825      ValueDecl *Member;
1826      if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1827          (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
1828        if (EllipsisLoc.isValid())
1829          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1830            << MemberOrBase
1831            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
1832
1833        return BuildMemberInitializer(Member, Init, IdLoc);
1834      }
1835    }
1836  }
1837  // It didn't name a member, so see if it names a class.
1838  QualType BaseType;
1839  TypeSourceInfo *TInfo = 0;
1840
1841  if (TemplateTypeTy) {
1842    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1843  } else if (DS.getTypeSpecType() == TST_decltype) {
1844    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
1845  } else {
1846    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1847    LookupParsedName(R, S, &SS);
1848
1849    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1850    if (!TyD) {
1851      if (R.isAmbiguous()) return true;
1852
1853      // We don't want access-control diagnostics here.
1854      R.suppressDiagnostics();
1855
1856      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1857        bool NotUnknownSpecialization = false;
1858        DeclContext *DC = computeDeclContext(SS, false);
1859        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1860          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1861
1862        if (!NotUnknownSpecialization) {
1863          // When the scope specifier can refer to a member of an unknown
1864          // specialization, we take it as a type name.
1865          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1866                                       SS.getWithLocInContext(Context),
1867                                       *MemberOrBase, IdLoc);
1868          if (BaseType.isNull())
1869            return true;
1870
1871          R.clear();
1872          R.setLookupName(MemberOrBase);
1873        }
1874      }
1875
1876      // If no results were found, try to correct typos.
1877      TypoCorrection Corr;
1878      MemInitializerValidatorCCC Validator(ClassDecl);
1879      if (R.empty() && BaseType.isNull() &&
1880          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1881                              Validator, ClassDecl))) {
1882        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1883        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
1884        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1885          // We have found a non-static data member with a similar
1886          // name to what was typed; complain and initialize that
1887          // member.
1888          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1889            << MemberOrBase << true << CorrectedQuotedStr
1890            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1891          Diag(Member->getLocation(), diag::note_previous_decl)
1892            << CorrectedQuotedStr;
1893
1894          return BuildMemberInitializer(Member, Init, IdLoc);
1895        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1896          const CXXBaseSpecifier *DirectBaseSpec;
1897          const CXXBaseSpecifier *VirtualBaseSpec;
1898          if (FindBaseInitializer(*this, ClassDecl,
1899                                  Context.getTypeDeclType(Type),
1900                                  DirectBaseSpec, VirtualBaseSpec)) {
1901            // We have found a direct or virtual base class with a
1902            // similar name to what was typed; complain and initialize
1903            // that base class.
1904            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1905              << MemberOrBase << false << CorrectedQuotedStr
1906              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1907
1908            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1909                                                             : VirtualBaseSpec;
1910            Diag(BaseSpec->getLocStart(),
1911                 diag::note_base_class_specified_here)
1912              << BaseSpec->getType()
1913              << BaseSpec->getSourceRange();
1914
1915            TyD = Type;
1916          }
1917        }
1918      }
1919
1920      if (!TyD && BaseType.isNull()) {
1921        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1922          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
1923        return true;
1924      }
1925    }
1926
1927    if (BaseType.isNull()) {
1928      BaseType = Context.getTypeDeclType(TyD);
1929      if (SS.isSet()) {
1930        NestedNameSpecifier *Qualifier =
1931          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1932
1933        // FIXME: preserve source range information
1934        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1935      }
1936    }
1937  }
1938
1939  if (!TInfo)
1940    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1941
1942  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
1943}
1944
1945/// Checks a member initializer expression for cases where reference (or
1946/// pointer) members are bound to by-value parameters (or their addresses).
1947static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1948                                               Expr *Init,
1949                                               SourceLocation IdLoc) {
1950  QualType MemberTy = Member->getType();
1951
1952  // We only handle pointers and references currently.
1953  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1954  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1955    return;
1956
1957  const bool IsPointer = MemberTy->isPointerType();
1958  if (IsPointer) {
1959    if (const UnaryOperator *Op
1960          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1961      // The only case we're worried about with pointers requires taking the
1962      // address.
1963      if (Op->getOpcode() != UO_AddrOf)
1964        return;
1965
1966      Init = Op->getSubExpr();
1967    } else {
1968      // We only handle address-of expression initializers for pointers.
1969      return;
1970    }
1971  }
1972
1973  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1974    // Taking the address of a temporary will be diagnosed as a hard error.
1975    if (IsPointer)
1976      return;
1977
1978    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1979      << Member << Init->getSourceRange();
1980  } else if (const DeclRefExpr *DRE
1981               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1982    // We only warn when referring to a non-reference parameter declaration.
1983    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1984    if (!Parameter || Parameter->getType()->isReferenceType())
1985      return;
1986
1987    S.Diag(Init->getExprLoc(),
1988           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1989                     : diag::warn_bind_ref_member_to_parameter)
1990      << Member << Parameter << Init->getSourceRange();
1991  } else {
1992    // Other initializers are fine.
1993    return;
1994  }
1995
1996  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1997    << (unsigned)IsPointer;
1998}
1999
2000/// Checks an initializer expression for use of uninitialized fields, such as
2001/// containing the field that is being initialized. Returns true if there is an
2002/// uninitialized field was used an updates the SourceLocation parameter; false
2003/// otherwise.
2004static bool InitExprContainsUninitializedFields(const Stmt *S,
2005                                                const ValueDecl *LhsField,
2006                                                SourceLocation *L) {
2007  assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2008
2009  if (isa<CallExpr>(S)) {
2010    // Do not descend into function calls or constructors, as the use
2011    // of an uninitialized field may be valid. One would have to inspect
2012    // the contents of the function/ctor to determine if it is safe or not.
2013    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2014    // may be safe, depending on what the function/ctor does.
2015    return false;
2016  }
2017  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2018    const NamedDecl *RhsField = ME->getMemberDecl();
2019
2020    if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2021      // The member expression points to a static data member.
2022      assert(VD->isStaticDataMember() &&
2023             "Member points to non-static data member!");
2024      (void)VD;
2025      return false;
2026    }
2027
2028    if (isa<EnumConstantDecl>(RhsField)) {
2029      // The member expression points to an enum.
2030      return false;
2031    }
2032
2033    if (RhsField == LhsField) {
2034      // Initializing a field with itself. Throw a warning.
2035      // But wait; there are exceptions!
2036      // Exception #1:  The field may not belong to this record.
2037      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
2038      const Expr *base = ME->getBase();
2039      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2040        // Even though the field matches, it does not belong to this record.
2041        return false;
2042      }
2043      // None of the exceptions triggered; return true to indicate an
2044      // uninitialized field was used.
2045      *L = ME->getMemberLoc();
2046      return true;
2047    }
2048  } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
2049    // sizeof/alignof doesn't reference contents, do not warn.
2050    return false;
2051  } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2052    // address-of doesn't reference contents (the pointer may be dereferenced
2053    // in the same expression but it would be rare; and weird).
2054    if (UOE->getOpcode() == UO_AddrOf)
2055      return false;
2056  }
2057  for (Stmt::const_child_range it = S->children(); it; ++it) {
2058    if (!*it) {
2059      // An expression such as 'member(arg ?: "")' may trigger this.
2060      continue;
2061    }
2062    if (InitExprContainsUninitializedFields(*it, LhsField, L))
2063      return true;
2064  }
2065  return false;
2066}
2067
2068MemInitResult
2069Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2070                             SourceLocation IdLoc) {
2071  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2072  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2073  assert((DirectMember || IndirectMember) &&
2074         "Member must be a FieldDecl or IndirectFieldDecl");
2075
2076  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2077    return true;
2078
2079  if (Member->isInvalidDecl())
2080    return true;
2081
2082  // Diagnose value-uses of fields to initialize themselves, e.g.
2083  //   foo(foo)
2084  // where foo is not also a parameter to the constructor.
2085  // TODO: implement -Wuninitialized and fold this into that framework.
2086  Expr **Args;
2087  unsigned NumArgs;
2088  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2089    Args = ParenList->getExprs();
2090    NumArgs = ParenList->getNumExprs();
2091  } else {
2092    InitListExpr *InitList = cast<InitListExpr>(Init);
2093    Args = InitList->getInits();
2094    NumArgs = InitList->getNumInits();
2095  }
2096  for (unsigned i = 0; i < NumArgs; ++i) {
2097    SourceLocation L;
2098    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
2099      // FIXME: Return true in the case when other fields are used before being
2100      // uninitialized. For example, let this field be the i'th field. When
2101      // initializing the i'th field, throw a warning if any of the >= i'th
2102      // fields are used, as they are not yet initialized.
2103      // Right now we are only handling the case where the i'th field uses
2104      // itself in its initializer.
2105      Diag(L, diag::warn_field_is_uninit);
2106    }
2107  }
2108
2109  SourceRange InitRange = Init->getSourceRange();
2110
2111  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2112    // Can't check initialization for a member of dependent type or when
2113    // any of the arguments are type-dependent expressions.
2114    DiscardCleanupsInEvaluationContext();
2115  } else {
2116    bool InitList = false;
2117    if (isa<InitListExpr>(Init)) {
2118      InitList = true;
2119      Args = &Init;
2120      NumArgs = 1;
2121
2122      if (isStdInitializerList(Member->getType(), 0)) {
2123        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2124            << /*at end of ctor*/1 << InitRange;
2125      }
2126    }
2127
2128    // Initialize the member.
2129    InitializedEntity MemberEntity =
2130      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2131                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2132    InitializationKind Kind =
2133      InitList ? InitializationKind::CreateDirectList(IdLoc)
2134               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2135                                                  InitRange.getEnd());
2136
2137    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2138    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2139                                            MultiExprArg(*this, Args, NumArgs),
2140                                            0);
2141    if (MemberInit.isInvalid())
2142      return true;
2143
2144    CheckImplicitConversions(MemberInit.get(),
2145                             InitRange.getBegin());
2146
2147    // C++0x [class.base.init]p7:
2148    //   The initialization of each base and member constitutes a
2149    //   full-expression.
2150    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2151    if (MemberInit.isInvalid())
2152      return true;
2153
2154    // If we are in a dependent context, template instantiation will
2155    // perform this type-checking again. Just save the arguments that we
2156    // received.
2157    // FIXME: This isn't quite ideal, since our ASTs don't capture all
2158    // of the information that we have about the member
2159    // initializer. However, deconstructing the ASTs is a dicey process,
2160    // and this approach is far more likely to get the corner cases right.
2161    if (CurContext->isDependentContext()) {
2162      // The existing Init will do fine.
2163    } else {
2164      Init = MemberInit.get();
2165      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2166    }
2167  }
2168
2169  if (DirectMember) {
2170    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2171                                            InitRange.getBegin(), Init,
2172                                            InitRange.getEnd());
2173  } else {
2174    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2175                                            InitRange.getBegin(), Init,
2176                                            InitRange.getEnd());
2177  }
2178}
2179
2180MemInitResult
2181Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2182                                 CXXRecordDecl *ClassDecl) {
2183  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2184  if (!LangOpts.CPlusPlus0x)
2185    return Diag(NameLoc, diag::err_delegating_ctor)
2186      << TInfo->getTypeLoc().getLocalSourceRange();
2187  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2188
2189  bool InitList = true;
2190  Expr **Args = &Init;
2191  unsigned NumArgs = 1;
2192  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2193    InitList = false;
2194    Args = ParenList->getExprs();
2195    NumArgs = ParenList->getNumExprs();
2196  }
2197
2198  SourceRange InitRange = Init->getSourceRange();
2199  // Initialize the object.
2200  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2201                                     QualType(ClassDecl->getTypeForDecl(), 0));
2202  InitializationKind Kind =
2203    InitList ? InitializationKind::CreateDirectList(NameLoc)
2204             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2205                                                InitRange.getEnd());
2206  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2207  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2208                                              MultiExprArg(*this, Args,NumArgs),
2209                                              0);
2210  if (DelegationInit.isInvalid())
2211    return true;
2212
2213  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2214         "Delegating constructor with no target?");
2215
2216  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2217
2218  // C++0x [class.base.init]p7:
2219  //   The initialization of each base and member constitutes a
2220  //   full-expression.
2221  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2222  if (DelegationInit.isInvalid())
2223    return true;
2224
2225  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2226                                          DelegationInit.takeAs<Expr>(),
2227                                          InitRange.getEnd());
2228}
2229
2230MemInitResult
2231Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2232                           Expr *Init, CXXRecordDecl *ClassDecl,
2233                           SourceLocation EllipsisLoc) {
2234  SourceLocation BaseLoc
2235    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2236
2237  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2238    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2239             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2240
2241  // C++ [class.base.init]p2:
2242  //   [...] Unless the mem-initializer-id names a nonstatic data
2243  //   member of the constructor's class or a direct or virtual base
2244  //   of that class, the mem-initializer is ill-formed. A
2245  //   mem-initializer-list can initialize a base class using any
2246  //   name that denotes that base class type.
2247  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2248
2249  SourceRange InitRange = Init->getSourceRange();
2250  if (EllipsisLoc.isValid()) {
2251    // This is a pack expansion.
2252    if (!BaseType->containsUnexpandedParameterPack())  {
2253      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2254        << SourceRange(BaseLoc, InitRange.getEnd());
2255
2256      EllipsisLoc = SourceLocation();
2257    }
2258  } else {
2259    // Check for any unexpanded parameter packs.
2260    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2261      return true;
2262
2263    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2264      return true;
2265  }
2266
2267  // Check for direct and virtual base classes.
2268  const CXXBaseSpecifier *DirectBaseSpec = 0;
2269  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2270  if (!Dependent) {
2271    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2272                                       BaseType))
2273      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2274
2275    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2276                        VirtualBaseSpec);
2277
2278    // C++ [base.class.init]p2:
2279    // Unless the mem-initializer-id names a nonstatic data member of the
2280    // constructor's class or a direct or virtual base of that class, the
2281    // mem-initializer is ill-formed.
2282    if (!DirectBaseSpec && !VirtualBaseSpec) {
2283      // If the class has any dependent bases, then it's possible that
2284      // one of those types will resolve to the same type as
2285      // BaseType. Therefore, just treat this as a dependent base
2286      // class initialization.  FIXME: Should we try to check the
2287      // initialization anyway? It seems odd.
2288      if (ClassDecl->hasAnyDependentBases())
2289        Dependent = true;
2290      else
2291        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2292          << BaseType << Context.getTypeDeclType(ClassDecl)
2293          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2294    }
2295  }
2296
2297  if (Dependent) {
2298    DiscardCleanupsInEvaluationContext();
2299
2300    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2301                                            /*IsVirtual=*/false,
2302                                            InitRange.getBegin(), Init,
2303                                            InitRange.getEnd(), EllipsisLoc);
2304  }
2305
2306  // C++ [base.class.init]p2:
2307  //   If a mem-initializer-id is ambiguous because it designates both
2308  //   a direct non-virtual base class and an inherited virtual base
2309  //   class, the mem-initializer is ill-formed.
2310  if (DirectBaseSpec && VirtualBaseSpec)
2311    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2312      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2313
2314  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2315  if (!BaseSpec)
2316    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2317
2318  // Initialize the base.
2319  bool InitList = true;
2320  Expr **Args = &Init;
2321  unsigned NumArgs = 1;
2322  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2323    InitList = false;
2324    Args = ParenList->getExprs();
2325    NumArgs = ParenList->getNumExprs();
2326  }
2327
2328  InitializedEntity BaseEntity =
2329    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2330  InitializationKind Kind =
2331    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2332             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2333                                                InitRange.getEnd());
2334  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2335  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2336                                          MultiExprArg(*this, Args, NumArgs),
2337                                          0);
2338  if (BaseInit.isInvalid())
2339    return true;
2340
2341  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2342
2343  // C++0x [class.base.init]p7:
2344  //   The initialization of each base and member constitutes a
2345  //   full-expression.
2346  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2347  if (BaseInit.isInvalid())
2348    return true;
2349
2350  // If we are in a dependent context, template instantiation will
2351  // perform this type-checking again. Just save the arguments that we
2352  // received in a ParenListExpr.
2353  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2354  // of the information that we have about the base
2355  // initializer. However, deconstructing the ASTs is a dicey process,
2356  // and this approach is far more likely to get the corner cases right.
2357  if (CurContext->isDependentContext())
2358    BaseInit = Owned(Init);
2359
2360  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2361                                          BaseSpec->isVirtual(),
2362                                          InitRange.getBegin(),
2363                                          BaseInit.takeAs<Expr>(),
2364                                          InitRange.getEnd(), EllipsisLoc);
2365}
2366
2367// Create a static_cast\<T&&>(expr).
2368static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2369  QualType ExprType = E->getType();
2370  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2371  SourceLocation ExprLoc = E->getLocStart();
2372  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2373      TargetType, ExprLoc);
2374
2375  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2376                                   SourceRange(ExprLoc, ExprLoc),
2377                                   E->getSourceRange()).take();
2378}
2379
2380/// ImplicitInitializerKind - How an implicit base or member initializer should
2381/// initialize its base or member.
2382enum ImplicitInitializerKind {
2383  IIK_Default,
2384  IIK_Copy,
2385  IIK_Move
2386};
2387
2388static bool
2389BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2390                             ImplicitInitializerKind ImplicitInitKind,
2391                             CXXBaseSpecifier *BaseSpec,
2392                             bool IsInheritedVirtualBase,
2393                             CXXCtorInitializer *&CXXBaseInit) {
2394  InitializedEntity InitEntity
2395    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2396                                        IsInheritedVirtualBase);
2397
2398  ExprResult BaseInit;
2399
2400  switch (ImplicitInitKind) {
2401  case IIK_Default: {
2402    InitializationKind InitKind
2403      = InitializationKind::CreateDefault(Constructor->getLocation());
2404    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2405    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2406                               MultiExprArg(SemaRef, 0, 0));
2407    break;
2408  }
2409
2410  case IIK_Move:
2411  case IIK_Copy: {
2412    bool Moving = ImplicitInitKind == IIK_Move;
2413    ParmVarDecl *Param = Constructor->getParamDecl(0);
2414    QualType ParamType = Param->getType().getNonReferenceType();
2415
2416    Expr *CopyCtorArg =
2417      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2418                          SourceLocation(), Param, false,
2419                          Constructor->getLocation(), ParamType,
2420                          VK_LValue, 0);
2421
2422    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2423
2424    // Cast to the base class to avoid ambiguities.
2425    QualType ArgTy =
2426      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2427                                       ParamType.getQualifiers());
2428
2429    if (Moving) {
2430      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2431    }
2432
2433    CXXCastPath BasePath;
2434    BasePath.push_back(BaseSpec);
2435    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2436                                            CK_UncheckedDerivedToBase,
2437                                            Moving ? VK_XValue : VK_LValue,
2438                                            &BasePath).take();
2439
2440    InitializationKind InitKind
2441      = InitializationKind::CreateDirect(Constructor->getLocation(),
2442                                         SourceLocation(), SourceLocation());
2443    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2444                                   &CopyCtorArg, 1);
2445    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2446                               MultiExprArg(&CopyCtorArg, 1));
2447    break;
2448  }
2449  }
2450
2451  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2452  if (BaseInit.isInvalid())
2453    return true;
2454
2455  CXXBaseInit =
2456    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2457               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2458                                                        SourceLocation()),
2459                                             BaseSpec->isVirtual(),
2460                                             SourceLocation(),
2461                                             BaseInit.takeAs<Expr>(),
2462                                             SourceLocation(),
2463                                             SourceLocation());
2464
2465  return false;
2466}
2467
2468static bool RefersToRValueRef(Expr *MemRef) {
2469  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2470  return Referenced->getType()->isRValueReferenceType();
2471}
2472
2473static bool
2474BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2475                               ImplicitInitializerKind ImplicitInitKind,
2476                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2477                               CXXCtorInitializer *&CXXMemberInit) {
2478  if (Field->isInvalidDecl())
2479    return true;
2480
2481  SourceLocation Loc = Constructor->getLocation();
2482
2483  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2484    bool Moving = ImplicitInitKind == IIK_Move;
2485    ParmVarDecl *Param = Constructor->getParamDecl(0);
2486    QualType ParamType = Param->getType().getNonReferenceType();
2487
2488    // Suppress copying zero-width bitfields.
2489    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2490      return false;
2491
2492    Expr *MemberExprBase =
2493      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2494                          SourceLocation(), Param, false,
2495                          Loc, ParamType, VK_LValue, 0);
2496
2497    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2498
2499    if (Moving) {
2500      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2501    }
2502
2503    // Build a reference to this field within the parameter.
2504    CXXScopeSpec SS;
2505    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2506                              Sema::LookupMemberName);
2507    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2508                                  : cast<ValueDecl>(Field), AS_public);
2509    MemberLookup.resolveKind();
2510    ExprResult CtorArg
2511      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2512                                         ParamType, Loc,
2513                                         /*IsArrow=*/false,
2514                                         SS,
2515                                         /*TemplateKWLoc=*/SourceLocation(),
2516                                         /*FirstQualifierInScope=*/0,
2517                                         MemberLookup,
2518                                         /*TemplateArgs=*/0);
2519    if (CtorArg.isInvalid())
2520      return true;
2521
2522    // C++11 [class.copy]p15:
2523    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2524    //     with static_cast<T&&>(x.m);
2525    if (RefersToRValueRef(CtorArg.get())) {
2526      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2527    }
2528
2529    // When the field we are copying is an array, create index variables for
2530    // each dimension of the array. We use these index variables to subscript
2531    // the source array, and other clients (e.g., CodeGen) will perform the
2532    // necessary iteration with these index variables.
2533    SmallVector<VarDecl *, 4> IndexVariables;
2534    QualType BaseType = Field->getType();
2535    QualType SizeType = SemaRef.Context.getSizeType();
2536    bool InitializingArray = false;
2537    while (const ConstantArrayType *Array
2538                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2539      InitializingArray = true;
2540      // Create the iteration variable for this array index.
2541      IdentifierInfo *IterationVarName = 0;
2542      {
2543        SmallString<8> Str;
2544        llvm::raw_svector_ostream OS(Str);
2545        OS << "__i" << IndexVariables.size();
2546        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2547      }
2548      VarDecl *IterationVar
2549        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2550                          IterationVarName, SizeType,
2551                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2552                          SC_None, SC_None);
2553      IndexVariables.push_back(IterationVar);
2554
2555      // Create a reference to the iteration variable.
2556      ExprResult IterationVarRef
2557        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2558      assert(!IterationVarRef.isInvalid() &&
2559             "Reference to invented variable cannot fail!");
2560      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2561      assert(!IterationVarRef.isInvalid() &&
2562             "Conversion of invented variable cannot fail!");
2563
2564      // Subscript the array with this iteration variable.
2565      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2566                                                        IterationVarRef.take(),
2567                                                        Loc);
2568      if (CtorArg.isInvalid())
2569        return true;
2570
2571      BaseType = Array->getElementType();
2572    }
2573
2574    // The array subscript expression is an lvalue, which is wrong for moving.
2575    if (Moving && InitializingArray)
2576      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2577
2578    // Construct the entity that we will be initializing. For an array, this
2579    // will be first element in the array, which may require several levels
2580    // of array-subscript entities.
2581    SmallVector<InitializedEntity, 4> Entities;
2582    Entities.reserve(1 + IndexVariables.size());
2583    if (Indirect)
2584      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2585    else
2586      Entities.push_back(InitializedEntity::InitializeMember(Field));
2587    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2588      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2589                                                              0,
2590                                                              Entities.back()));
2591
2592    // Direct-initialize to use the copy constructor.
2593    InitializationKind InitKind =
2594      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2595
2596    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2597    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2598                                   &CtorArgE, 1);
2599
2600    ExprResult MemberInit
2601      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2602                        MultiExprArg(&CtorArgE, 1));
2603    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2604    if (MemberInit.isInvalid())
2605      return true;
2606
2607    if (Indirect) {
2608      assert(IndexVariables.size() == 0 &&
2609             "Indirect field improperly initialized");
2610      CXXMemberInit
2611        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2612                                                   Loc, Loc,
2613                                                   MemberInit.takeAs<Expr>(),
2614                                                   Loc);
2615    } else
2616      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2617                                                 Loc, MemberInit.takeAs<Expr>(),
2618                                                 Loc,
2619                                                 IndexVariables.data(),
2620                                                 IndexVariables.size());
2621    return false;
2622  }
2623
2624  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2625
2626  QualType FieldBaseElementType =
2627    SemaRef.Context.getBaseElementType(Field->getType());
2628
2629  if (FieldBaseElementType->isRecordType()) {
2630    InitializedEntity InitEntity
2631      = Indirect? InitializedEntity::InitializeMember(Indirect)
2632                : InitializedEntity::InitializeMember(Field);
2633    InitializationKind InitKind =
2634      InitializationKind::CreateDefault(Loc);
2635
2636    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2637    ExprResult MemberInit =
2638      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2639
2640    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2641    if (MemberInit.isInvalid())
2642      return true;
2643
2644    if (Indirect)
2645      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2646                                                               Indirect, Loc,
2647                                                               Loc,
2648                                                               MemberInit.get(),
2649                                                               Loc);
2650    else
2651      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2652                                                               Field, Loc, Loc,
2653                                                               MemberInit.get(),
2654                                                               Loc);
2655    return false;
2656  }
2657
2658  if (!Field->getParent()->isUnion()) {
2659    if (FieldBaseElementType->isReferenceType()) {
2660      SemaRef.Diag(Constructor->getLocation(),
2661                   diag::err_uninitialized_member_in_ctor)
2662      << (int)Constructor->isImplicit()
2663      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2664      << 0 << Field->getDeclName();
2665      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2666      return true;
2667    }
2668
2669    if (FieldBaseElementType.isConstQualified()) {
2670      SemaRef.Diag(Constructor->getLocation(),
2671                   diag::err_uninitialized_member_in_ctor)
2672      << (int)Constructor->isImplicit()
2673      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2674      << 1 << Field->getDeclName();
2675      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2676      return true;
2677    }
2678  }
2679
2680  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2681      FieldBaseElementType->isObjCRetainableType() &&
2682      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2683      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2684    // Instant objects:
2685    //   Default-initialize Objective-C pointers to NULL.
2686    CXXMemberInit
2687      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2688                                                 Loc, Loc,
2689                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2690                                                 Loc);
2691    return false;
2692  }
2693
2694  // Nothing to initialize.
2695  CXXMemberInit = 0;
2696  return false;
2697}
2698
2699namespace {
2700struct BaseAndFieldInfo {
2701  Sema &S;
2702  CXXConstructorDecl *Ctor;
2703  bool AnyErrorsInInits;
2704  ImplicitInitializerKind IIK;
2705  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2706  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2707
2708  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2709    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2710    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2711    if (Generated && Ctor->isCopyConstructor())
2712      IIK = IIK_Copy;
2713    else if (Generated && Ctor->isMoveConstructor())
2714      IIK = IIK_Move;
2715    else
2716      IIK = IIK_Default;
2717  }
2718
2719  bool isImplicitCopyOrMove() const {
2720    switch (IIK) {
2721    case IIK_Copy:
2722    case IIK_Move:
2723      return true;
2724
2725    case IIK_Default:
2726      return false;
2727    }
2728
2729    llvm_unreachable("Invalid ImplicitInitializerKind!");
2730  }
2731};
2732}
2733
2734/// \brief Determine whether the given indirect field declaration is somewhere
2735/// within an anonymous union.
2736static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2737  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2738                                      CEnd = F->chain_end();
2739       C != CEnd; ++C)
2740    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2741      if (Record->isUnion())
2742        return true;
2743
2744  return false;
2745}
2746
2747/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2748/// array type.
2749static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2750  if (T->isIncompleteArrayType())
2751    return true;
2752
2753  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2754    if (!ArrayT->getSize())
2755      return true;
2756
2757    T = ArrayT->getElementType();
2758  }
2759
2760  return false;
2761}
2762
2763static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2764                                    FieldDecl *Field,
2765                                    IndirectFieldDecl *Indirect = 0) {
2766
2767  // Overwhelmingly common case: we have a direct initializer for this field.
2768  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2769    Info.AllToInit.push_back(Init);
2770    return false;
2771  }
2772
2773  // C++0x [class.base.init]p8: if the entity is a non-static data member that
2774  // has a brace-or-equal-initializer, the entity is initialized as specified
2775  // in [dcl.init].
2776  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
2777    CXXCtorInitializer *Init;
2778    if (Indirect)
2779      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2780                                                      SourceLocation(),
2781                                                      SourceLocation(), 0,
2782                                                      SourceLocation());
2783    else
2784      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2785                                                      SourceLocation(),
2786                                                      SourceLocation(), 0,
2787                                                      SourceLocation());
2788    Info.AllToInit.push_back(Init);
2789    return false;
2790  }
2791
2792  // Don't build an implicit initializer for union members if none was
2793  // explicitly specified.
2794  if (Field->getParent()->isUnion() ||
2795      (Indirect && isWithinAnonymousUnion(Indirect)))
2796    return false;
2797
2798  // Don't initialize incomplete or zero-length arrays.
2799  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2800    return false;
2801
2802  // Don't try to build an implicit initializer if there were semantic
2803  // errors in any of the initializers (and therefore we might be
2804  // missing some that the user actually wrote).
2805  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2806    return false;
2807
2808  CXXCtorInitializer *Init = 0;
2809  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2810                                     Indirect, Init))
2811    return true;
2812
2813  if (Init)
2814    Info.AllToInit.push_back(Init);
2815
2816  return false;
2817}
2818
2819bool
2820Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2821                               CXXCtorInitializer *Initializer) {
2822  assert(Initializer->isDelegatingInitializer());
2823  Constructor->setNumCtorInitializers(1);
2824  CXXCtorInitializer **initializer =
2825    new (Context) CXXCtorInitializer*[1];
2826  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2827  Constructor->setCtorInitializers(initializer);
2828
2829  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2830    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
2831    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2832  }
2833
2834  DelegatingCtorDecls.push_back(Constructor);
2835
2836  return false;
2837}
2838
2839bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2840                               CXXCtorInitializer **Initializers,
2841                               unsigned NumInitializers,
2842                               bool AnyErrors) {
2843  if (Constructor->isDependentContext()) {
2844    // Just store the initializers as written, they will be checked during
2845    // instantiation.
2846    if (NumInitializers > 0) {
2847      Constructor->setNumCtorInitializers(NumInitializers);
2848      CXXCtorInitializer **baseOrMemberInitializers =
2849        new (Context) CXXCtorInitializer*[NumInitializers];
2850      memcpy(baseOrMemberInitializers, Initializers,
2851             NumInitializers * sizeof(CXXCtorInitializer*));
2852      Constructor->setCtorInitializers(baseOrMemberInitializers);
2853    }
2854
2855    return false;
2856  }
2857
2858  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2859
2860  // We need to build the initializer AST according to order of construction
2861  // and not what user specified in the Initializers list.
2862  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2863  if (!ClassDecl)
2864    return true;
2865
2866  bool HadError = false;
2867
2868  for (unsigned i = 0; i < NumInitializers; i++) {
2869    CXXCtorInitializer *Member = Initializers[i];
2870
2871    if (Member->isBaseInitializer())
2872      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2873    else
2874      Info.AllBaseFields[Member->getAnyMember()] = Member;
2875  }
2876
2877  // Keep track of the direct virtual bases.
2878  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2879  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2880       E = ClassDecl->bases_end(); I != E; ++I) {
2881    if (I->isVirtual())
2882      DirectVBases.insert(I);
2883  }
2884
2885  // Push virtual bases before others.
2886  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2887       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2888
2889    if (CXXCtorInitializer *Value
2890        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2891      Info.AllToInit.push_back(Value);
2892    } else if (!AnyErrors) {
2893      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2894      CXXCtorInitializer *CXXBaseInit;
2895      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2896                                       VBase, IsInheritedVirtualBase,
2897                                       CXXBaseInit)) {
2898        HadError = true;
2899        continue;
2900      }
2901
2902      Info.AllToInit.push_back(CXXBaseInit);
2903    }
2904  }
2905
2906  // Non-virtual bases.
2907  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2908       E = ClassDecl->bases_end(); Base != E; ++Base) {
2909    // Virtuals are in the virtual base list and already constructed.
2910    if (Base->isVirtual())
2911      continue;
2912
2913    if (CXXCtorInitializer *Value
2914          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2915      Info.AllToInit.push_back(Value);
2916    } else if (!AnyErrors) {
2917      CXXCtorInitializer *CXXBaseInit;
2918      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2919                                       Base, /*IsInheritedVirtualBase=*/false,
2920                                       CXXBaseInit)) {
2921        HadError = true;
2922        continue;
2923      }
2924
2925      Info.AllToInit.push_back(CXXBaseInit);
2926    }
2927  }
2928
2929  // Fields.
2930  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2931                               MemEnd = ClassDecl->decls_end();
2932       Mem != MemEnd; ++Mem) {
2933    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2934      // C++ [class.bit]p2:
2935      //   A declaration for a bit-field that omits the identifier declares an
2936      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
2937      //   initialized.
2938      if (F->isUnnamedBitfield())
2939        continue;
2940
2941      // If we're not generating the implicit copy/move constructor, then we'll
2942      // handle anonymous struct/union fields based on their individual
2943      // indirect fields.
2944      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2945        continue;
2946
2947      if (CollectFieldInitializer(*this, Info, F))
2948        HadError = true;
2949      continue;
2950    }
2951
2952    // Beyond this point, we only consider default initialization.
2953    if (Info.IIK != IIK_Default)
2954      continue;
2955
2956    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2957      if (F->getType()->isIncompleteArrayType()) {
2958        assert(ClassDecl->hasFlexibleArrayMember() &&
2959               "Incomplete array type is not valid");
2960        continue;
2961      }
2962
2963      // Initialize each field of an anonymous struct individually.
2964      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2965        HadError = true;
2966
2967      continue;
2968    }
2969  }
2970
2971  NumInitializers = Info.AllToInit.size();
2972  if (NumInitializers > 0) {
2973    Constructor->setNumCtorInitializers(NumInitializers);
2974    CXXCtorInitializer **baseOrMemberInitializers =
2975      new (Context) CXXCtorInitializer*[NumInitializers];
2976    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2977           NumInitializers * sizeof(CXXCtorInitializer*));
2978    Constructor->setCtorInitializers(baseOrMemberInitializers);
2979
2980    // Constructors implicitly reference the base and member
2981    // destructors.
2982    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2983                                           Constructor->getParent());
2984  }
2985
2986  return HadError;
2987}
2988
2989static void *GetKeyForTopLevelField(FieldDecl *Field) {
2990  // For anonymous unions, use the class declaration as the key.
2991  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2992    if (RT->getDecl()->isAnonymousStructOrUnion())
2993      return static_cast<void *>(RT->getDecl());
2994  }
2995  return static_cast<void *>(Field);
2996}
2997
2998static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2999  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3000}
3001
3002static void *GetKeyForMember(ASTContext &Context,
3003                             CXXCtorInitializer *Member) {
3004  if (!Member->isAnyMemberInitializer())
3005    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3006
3007  // For fields injected into the class via declaration of an anonymous union,
3008  // use its anonymous union class declaration as the unique key.
3009  FieldDecl *Field = Member->getAnyMember();
3010
3011  // If the field is a member of an anonymous struct or union, our key
3012  // is the anonymous record decl that's a direct child of the class.
3013  RecordDecl *RD = Field->getParent();
3014  if (RD->isAnonymousStructOrUnion()) {
3015    while (true) {
3016      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3017      if (Parent->isAnonymousStructOrUnion())
3018        RD = Parent;
3019      else
3020        break;
3021    }
3022
3023    return static_cast<void *>(RD);
3024  }
3025
3026  return static_cast<void *>(Field);
3027}
3028
3029static void
3030DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3031                                  const CXXConstructorDecl *Constructor,
3032                                  CXXCtorInitializer **Inits,
3033                                  unsigned NumInits) {
3034  if (Constructor->getDeclContext()->isDependentContext())
3035    return;
3036
3037  // Don't check initializers order unless the warning is enabled at the
3038  // location of at least one initializer.
3039  bool ShouldCheckOrder = false;
3040  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3041    CXXCtorInitializer *Init = Inits[InitIndex];
3042    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3043                                         Init->getSourceLocation())
3044          != DiagnosticsEngine::Ignored) {
3045      ShouldCheckOrder = true;
3046      break;
3047    }
3048  }
3049  if (!ShouldCheckOrder)
3050    return;
3051
3052  // Build the list of bases and members in the order that they'll
3053  // actually be initialized.  The explicit initializers should be in
3054  // this same order but may be missing things.
3055  SmallVector<const void*, 32> IdealInitKeys;
3056
3057  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3058
3059  // 1. Virtual bases.
3060  for (CXXRecordDecl::base_class_const_iterator VBase =
3061       ClassDecl->vbases_begin(),
3062       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3063    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3064
3065  // 2. Non-virtual bases.
3066  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3067       E = ClassDecl->bases_end(); Base != E; ++Base) {
3068    if (Base->isVirtual())
3069      continue;
3070    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3071  }
3072
3073  // 3. Direct fields.
3074  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3075       E = ClassDecl->field_end(); Field != E; ++Field) {
3076    if (Field->isUnnamedBitfield())
3077      continue;
3078
3079    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3080  }
3081
3082  unsigned NumIdealInits = IdealInitKeys.size();
3083  unsigned IdealIndex = 0;
3084
3085  CXXCtorInitializer *PrevInit = 0;
3086  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3087    CXXCtorInitializer *Init = Inits[InitIndex];
3088    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3089
3090    // Scan forward to try to find this initializer in the idealized
3091    // initializers list.
3092    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3093      if (InitKey == IdealInitKeys[IdealIndex])
3094        break;
3095
3096    // If we didn't find this initializer, it must be because we
3097    // scanned past it on a previous iteration.  That can only
3098    // happen if we're out of order;  emit a warning.
3099    if (IdealIndex == NumIdealInits && PrevInit) {
3100      Sema::SemaDiagnosticBuilder D =
3101        SemaRef.Diag(PrevInit->getSourceLocation(),
3102                     diag::warn_initializer_out_of_order);
3103
3104      if (PrevInit->isAnyMemberInitializer())
3105        D << 0 << PrevInit->getAnyMember()->getDeclName();
3106      else
3107        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3108
3109      if (Init->isAnyMemberInitializer())
3110        D << 0 << Init->getAnyMember()->getDeclName();
3111      else
3112        D << 1 << Init->getTypeSourceInfo()->getType();
3113
3114      // Move back to the initializer's location in the ideal list.
3115      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3116        if (InitKey == IdealInitKeys[IdealIndex])
3117          break;
3118
3119      assert(IdealIndex != NumIdealInits &&
3120             "initializer not found in initializer list");
3121    }
3122
3123    PrevInit = Init;
3124  }
3125}
3126
3127namespace {
3128bool CheckRedundantInit(Sema &S,
3129                        CXXCtorInitializer *Init,
3130                        CXXCtorInitializer *&PrevInit) {
3131  if (!PrevInit) {
3132    PrevInit = Init;
3133    return false;
3134  }
3135
3136  if (FieldDecl *Field = Init->getMember())
3137    S.Diag(Init->getSourceLocation(),
3138           diag::err_multiple_mem_initialization)
3139      << Field->getDeclName()
3140      << Init->getSourceRange();
3141  else {
3142    const Type *BaseClass = Init->getBaseClass();
3143    assert(BaseClass && "neither field nor base");
3144    S.Diag(Init->getSourceLocation(),
3145           diag::err_multiple_base_initialization)
3146      << QualType(BaseClass, 0)
3147      << Init->getSourceRange();
3148  }
3149  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3150    << 0 << PrevInit->getSourceRange();
3151
3152  return true;
3153}
3154
3155typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3156typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3157
3158bool CheckRedundantUnionInit(Sema &S,
3159                             CXXCtorInitializer *Init,
3160                             RedundantUnionMap &Unions) {
3161  FieldDecl *Field = Init->getAnyMember();
3162  RecordDecl *Parent = Field->getParent();
3163  NamedDecl *Child = Field;
3164
3165  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3166    if (Parent->isUnion()) {
3167      UnionEntry &En = Unions[Parent];
3168      if (En.first && En.first != Child) {
3169        S.Diag(Init->getSourceLocation(),
3170               diag::err_multiple_mem_union_initialization)
3171          << Field->getDeclName()
3172          << Init->getSourceRange();
3173        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3174          << 0 << En.second->getSourceRange();
3175        return true;
3176      }
3177      if (!En.first) {
3178        En.first = Child;
3179        En.second = Init;
3180      }
3181      if (!Parent->isAnonymousStructOrUnion())
3182        return false;
3183    }
3184
3185    Child = Parent;
3186    Parent = cast<RecordDecl>(Parent->getDeclContext());
3187  }
3188
3189  return false;
3190}
3191}
3192
3193/// ActOnMemInitializers - Handle the member initializers for a constructor.
3194void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3195                                SourceLocation ColonLoc,
3196                                CXXCtorInitializer **meminits,
3197                                unsigned NumMemInits,
3198                                bool AnyErrors) {
3199  if (!ConstructorDecl)
3200    return;
3201
3202  AdjustDeclIfTemplate(ConstructorDecl);
3203
3204  CXXConstructorDecl *Constructor
3205    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3206
3207  if (!Constructor) {
3208    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3209    return;
3210  }
3211
3212  CXXCtorInitializer **MemInits =
3213    reinterpret_cast<CXXCtorInitializer **>(meminits);
3214
3215  // Mapping for the duplicate initializers check.
3216  // For member initializers, this is keyed with a FieldDecl*.
3217  // For base initializers, this is keyed with a Type*.
3218  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3219
3220  // Mapping for the inconsistent anonymous-union initializers check.
3221  RedundantUnionMap MemberUnions;
3222
3223  bool HadError = false;
3224  for (unsigned i = 0; i < NumMemInits; i++) {
3225    CXXCtorInitializer *Init = MemInits[i];
3226
3227    // Set the source order index.
3228    Init->setSourceOrder(i);
3229
3230    if (Init->isAnyMemberInitializer()) {
3231      FieldDecl *Field = Init->getAnyMember();
3232      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3233          CheckRedundantUnionInit(*this, Init, MemberUnions))
3234        HadError = true;
3235    } else if (Init->isBaseInitializer()) {
3236      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3237      if (CheckRedundantInit(*this, Init, Members[Key]))
3238        HadError = true;
3239    } else {
3240      assert(Init->isDelegatingInitializer());
3241      // This must be the only initializer
3242      if (i != 0 || NumMemInits > 1) {
3243        Diag(MemInits[0]->getSourceLocation(),
3244             diag::err_delegating_initializer_alone)
3245          << MemInits[0]->getSourceRange();
3246        HadError = true;
3247        // We will treat this as being the only initializer.
3248      }
3249      SetDelegatingInitializer(Constructor, MemInits[i]);
3250      // Return immediately as the initializer is set.
3251      return;
3252    }
3253  }
3254
3255  if (HadError)
3256    return;
3257
3258  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3259
3260  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3261}
3262
3263void
3264Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3265                                             CXXRecordDecl *ClassDecl) {
3266  // Ignore dependent contexts. Also ignore unions, since their members never
3267  // have destructors implicitly called.
3268  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3269    return;
3270
3271  // FIXME: all the access-control diagnostics are positioned on the
3272  // field/base declaration.  That's probably good; that said, the
3273  // user might reasonably want to know why the destructor is being
3274  // emitted, and we currently don't say.
3275
3276  // Non-static data members.
3277  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3278       E = ClassDecl->field_end(); I != E; ++I) {
3279    FieldDecl *Field = *I;
3280    if (Field->isInvalidDecl())
3281      continue;
3282
3283    // Don't destroy incomplete or zero-length arrays.
3284    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3285      continue;
3286
3287    QualType FieldType = Context.getBaseElementType(Field->getType());
3288
3289    const RecordType* RT = FieldType->getAs<RecordType>();
3290    if (!RT)
3291      continue;
3292
3293    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3294    if (FieldClassDecl->isInvalidDecl())
3295      continue;
3296    if (FieldClassDecl->hasIrrelevantDestructor())
3297      continue;
3298    // The destructor for an implicit anonymous union member is never invoked.
3299    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3300      continue;
3301
3302    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3303    assert(Dtor && "No dtor found for FieldClassDecl!");
3304    CheckDestructorAccess(Field->getLocation(), Dtor,
3305                          PDiag(diag::err_access_dtor_field)
3306                            << Field->getDeclName()
3307                            << FieldType);
3308
3309    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3310    DiagnoseUseOfDecl(Dtor, Location);
3311  }
3312
3313  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3314
3315  // Bases.
3316  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3317       E = ClassDecl->bases_end(); Base != E; ++Base) {
3318    // Bases are always records in a well-formed non-dependent class.
3319    const RecordType *RT = Base->getType()->getAs<RecordType>();
3320
3321    // Remember direct virtual bases.
3322    if (Base->isVirtual())
3323      DirectVirtualBases.insert(RT);
3324
3325    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3326    // If our base class is invalid, we probably can't get its dtor anyway.
3327    if (BaseClassDecl->isInvalidDecl())
3328      continue;
3329    if (BaseClassDecl->hasIrrelevantDestructor())
3330      continue;
3331
3332    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3333    assert(Dtor && "No dtor found for BaseClassDecl!");
3334
3335    // FIXME: caret should be on the start of the class name
3336    CheckDestructorAccess(Base->getLocStart(), Dtor,
3337                          PDiag(diag::err_access_dtor_base)
3338                            << Base->getType()
3339                            << Base->getSourceRange());
3340
3341    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3342    DiagnoseUseOfDecl(Dtor, Location);
3343  }
3344
3345  // Virtual bases.
3346  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3347       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3348
3349    // Bases are always records in a well-formed non-dependent class.
3350    const RecordType *RT = VBase->getType()->getAs<RecordType>();
3351
3352    // Ignore direct virtual bases.
3353    if (DirectVirtualBases.count(RT))
3354      continue;
3355
3356    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3357    // If our base class is invalid, we probably can't get its dtor anyway.
3358    if (BaseClassDecl->isInvalidDecl())
3359      continue;
3360    if (BaseClassDecl->hasIrrelevantDestructor())
3361      continue;
3362
3363    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3364    assert(Dtor && "No dtor found for BaseClassDecl!");
3365    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3366                          PDiag(diag::err_access_dtor_vbase)
3367                            << VBase->getType());
3368
3369    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3370    DiagnoseUseOfDecl(Dtor, Location);
3371  }
3372}
3373
3374void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3375  if (!CDtorDecl)
3376    return;
3377
3378  if (CXXConstructorDecl *Constructor
3379      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3380    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3381}
3382
3383bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3384                                  unsigned DiagID, AbstractDiagSelID SelID) {
3385  if (SelID == -1)
3386    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
3387  else
3388    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
3389}
3390
3391bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3392                                  const PartialDiagnostic &PD) {
3393  if (!getLangOpts().CPlusPlus)
3394    return false;
3395
3396  if (const ArrayType *AT = Context.getAsArrayType(T))
3397    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3398
3399  if (const PointerType *PT = T->getAs<PointerType>()) {
3400    // Find the innermost pointer type.
3401    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3402      PT = T;
3403
3404    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3405      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3406  }
3407
3408  const RecordType *RT = T->getAs<RecordType>();
3409  if (!RT)
3410    return false;
3411
3412  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3413
3414  // We can't answer whether something is abstract until it has a
3415  // definition.  If it's currently being defined, we'll walk back
3416  // over all the declarations when we have a full definition.
3417  const CXXRecordDecl *Def = RD->getDefinition();
3418  if (!Def || Def->isBeingDefined())
3419    return false;
3420
3421  if (!RD->isAbstract())
3422    return false;
3423
3424  Diag(Loc, PD) << RD->getDeclName();
3425  DiagnoseAbstractType(RD);
3426
3427  return true;
3428}
3429
3430void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3431  // Check if we've already emitted the list of pure virtual functions
3432  // for this class.
3433  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3434    return;
3435
3436  CXXFinalOverriderMap FinalOverriders;
3437  RD->getFinalOverriders(FinalOverriders);
3438
3439  // Keep a set of seen pure methods so we won't diagnose the same method
3440  // more than once.
3441  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3442
3443  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3444                                   MEnd = FinalOverriders.end();
3445       M != MEnd;
3446       ++M) {
3447    for (OverridingMethods::iterator SO = M->second.begin(),
3448                                  SOEnd = M->second.end();
3449         SO != SOEnd; ++SO) {
3450      // C++ [class.abstract]p4:
3451      //   A class is abstract if it contains or inherits at least one
3452      //   pure virtual function for which the final overrider is pure
3453      //   virtual.
3454
3455      //
3456      if (SO->second.size() != 1)
3457        continue;
3458
3459      if (!SO->second.front().Method->isPure())
3460        continue;
3461
3462      if (!SeenPureMethods.insert(SO->second.front().Method))
3463        continue;
3464
3465      Diag(SO->second.front().Method->getLocation(),
3466           diag::note_pure_virtual_function)
3467        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3468    }
3469  }
3470
3471  if (!PureVirtualClassDiagSet)
3472    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3473  PureVirtualClassDiagSet->insert(RD);
3474}
3475
3476namespace {
3477struct AbstractUsageInfo {
3478  Sema &S;
3479  CXXRecordDecl *Record;
3480  CanQualType AbstractType;
3481  bool Invalid;
3482
3483  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3484    : S(S), Record(Record),
3485      AbstractType(S.Context.getCanonicalType(
3486                   S.Context.getTypeDeclType(Record))),
3487      Invalid(false) {}
3488
3489  void DiagnoseAbstractType() {
3490    if (Invalid) return;
3491    S.DiagnoseAbstractType(Record);
3492    Invalid = true;
3493  }
3494
3495  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3496};
3497
3498struct CheckAbstractUsage {
3499  AbstractUsageInfo &Info;
3500  const NamedDecl *Ctx;
3501
3502  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3503    : Info(Info), Ctx(Ctx) {}
3504
3505  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3506    switch (TL.getTypeLocClass()) {
3507#define ABSTRACT_TYPELOC(CLASS, PARENT)
3508#define TYPELOC(CLASS, PARENT) \
3509    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3510#include "clang/AST/TypeLocNodes.def"
3511    }
3512  }
3513
3514  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3515    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3516    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3517      if (!TL.getArg(I))
3518        continue;
3519
3520      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3521      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3522    }
3523  }
3524
3525  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3526    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3527  }
3528
3529  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3530    // Visit the type parameters from a permissive context.
3531    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3532      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3533      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3534        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3535          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3536      // TODO: other template argument types?
3537    }
3538  }
3539
3540  // Visit pointee types from a permissive context.
3541#define CheckPolymorphic(Type) \
3542  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3543    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3544  }
3545  CheckPolymorphic(PointerTypeLoc)
3546  CheckPolymorphic(ReferenceTypeLoc)
3547  CheckPolymorphic(MemberPointerTypeLoc)
3548  CheckPolymorphic(BlockPointerTypeLoc)
3549  CheckPolymorphic(AtomicTypeLoc)
3550
3551  /// Handle all the types we haven't given a more specific
3552  /// implementation for above.
3553  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3554    // Every other kind of type that we haven't called out already
3555    // that has an inner type is either (1) sugar or (2) contains that
3556    // inner type in some way as a subobject.
3557    if (TypeLoc Next = TL.getNextTypeLoc())
3558      return Visit(Next, Sel);
3559
3560    // If there's no inner type and we're in a permissive context,
3561    // don't diagnose.
3562    if (Sel == Sema::AbstractNone) return;
3563
3564    // Check whether the type matches the abstract type.
3565    QualType T = TL.getType();
3566    if (T->isArrayType()) {
3567      Sel = Sema::AbstractArrayType;
3568      T = Info.S.Context.getBaseElementType(T);
3569    }
3570    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3571    if (CT != Info.AbstractType) return;
3572
3573    // It matched; do some magic.
3574    if (Sel == Sema::AbstractArrayType) {
3575      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3576        << T << TL.getSourceRange();
3577    } else {
3578      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3579        << Sel << T << TL.getSourceRange();
3580    }
3581    Info.DiagnoseAbstractType();
3582  }
3583};
3584
3585void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3586                                  Sema::AbstractDiagSelID Sel) {
3587  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3588}
3589
3590}
3591
3592/// Check for invalid uses of an abstract type in a method declaration.
3593static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3594                                    CXXMethodDecl *MD) {
3595  // No need to do the check on definitions, which require that
3596  // the return/param types be complete.
3597  if (MD->doesThisDeclarationHaveABody())
3598    return;
3599
3600  // For safety's sake, just ignore it if we don't have type source
3601  // information.  This should never happen for non-implicit methods,
3602  // but...
3603  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3604    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3605}
3606
3607/// Check for invalid uses of an abstract type within a class definition.
3608static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3609                                    CXXRecordDecl *RD) {
3610  for (CXXRecordDecl::decl_iterator
3611         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3612    Decl *D = *I;
3613    if (D->isImplicit()) continue;
3614
3615    // Methods and method templates.
3616    if (isa<CXXMethodDecl>(D)) {
3617      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3618    } else if (isa<FunctionTemplateDecl>(D)) {
3619      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3620      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3621
3622    // Fields and static variables.
3623    } else if (isa<FieldDecl>(D)) {
3624      FieldDecl *FD = cast<FieldDecl>(D);
3625      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3626        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3627    } else if (isa<VarDecl>(D)) {
3628      VarDecl *VD = cast<VarDecl>(D);
3629      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3630        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3631
3632    // Nested classes and class templates.
3633    } else if (isa<CXXRecordDecl>(D)) {
3634      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3635    } else if (isa<ClassTemplateDecl>(D)) {
3636      CheckAbstractClassUsage(Info,
3637                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3638    }
3639  }
3640}
3641
3642/// \brief Perform semantic checks on a class definition that has been
3643/// completing, introducing implicitly-declared members, checking for
3644/// abstract types, etc.
3645void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3646  if (!Record)
3647    return;
3648
3649  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3650    AbstractUsageInfo Info(*this, Record);
3651    CheckAbstractClassUsage(Info, Record);
3652  }
3653
3654  // If this is not an aggregate type and has no user-declared constructor,
3655  // complain about any non-static data members of reference or const scalar
3656  // type, since they will never get initializers.
3657  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3658      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3659      !Record->isLambda()) {
3660    bool Complained = false;
3661    for (RecordDecl::field_iterator F = Record->field_begin(),
3662                                 FEnd = Record->field_end();
3663         F != FEnd; ++F) {
3664      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3665        continue;
3666
3667      if (F->getType()->isReferenceType() ||
3668          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3669        if (!Complained) {
3670          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3671            << Record->getTagKind() << Record;
3672          Complained = true;
3673        }
3674
3675        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3676          << F->getType()->isReferenceType()
3677          << F->getDeclName();
3678      }
3679    }
3680  }
3681
3682  if (Record->isDynamicClass() && !Record->isDependentType())
3683    DynamicClasses.push_back(Record);
3684
3685  if (Record->getIdentifier()) {
3686    // C++ [class.mem]p13:
3687    //   If T is the name of a class, then each of the following shall have a
3688    //   name different from T:
3689    //     - every member of every anonymous union that is a member of class T.
3690    //
3691    // C++ [class.mem]p14:
3692    //   In addition, if class T has a user-declared constructor (12.1), every
3693    //   non-static data member of class T shall have a name different from T.
3694    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3695         R.first != R.second; ++R.first) {
3696      NamedDecl *D = *R.first;
3697      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3698          isa<IndirectFieldDecl>(D)) {
3699        Diag(D->getLocation(), diag::err_member_name_of_class)
3700          << D->getDeclName();
3701        break;
3702      }
3703    }
3704  }
3705
3706  // Warn if the class has virtual methods but non-virtual public destructor.
3707  if (Record->isPolymorphic() && !Record->isDependentType()) {
3708    CXXDestructorDecl *dtor = Record->getDestructor();
3709    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3710      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3711           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3712  }
3713
3714  // See if a method overloads virtual methods in a base
3715  /// class without overriding any.
3716  if (!Record->isDependentType()) {
3717    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3718                                     MEnd = Record->method_end();
3719         M != MEnd; ++M) {
3720      if (!(*M)->isStatic())
3721        DiagnoseHiddenVirtualMethods(Record, *M);
3722    }
3723  }
3724
3725  // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3726  // function that is not a constructor declares that member function to be
3727  // const. [...] The class of which that function is a member shall be
3728  // a literal type.
3729  //
3730  // If the class has virtual bases, any constexpr members will already have
3731  // been diagnosed by the checks performed on the member declaration, so
3732  // suppress this (less useful) diagnostic.
3733  if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3734      !Record->isLiteral() && !Record->getNumVBases()) {
3735    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3736                                     MEnd = Record->method_end();
3737         M != MEnd; ++M) {
3738      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3739        switch (Record->getTemplateSpecializationKind()) {
3740        case TSK_ImplicitInstantiation:
3741        case TSK_ExplicitInstantiationDeclaration:
3742        case TSK_ExplicitInstantiationDefinition:
3743          // If a template instantiates to a non-literal type, but its members
3744          // instantiate to constexpr functions, the template is technically
3745          // ill-formed, but we allow it for sanity.
3746          continue;
3747
3748        case TSK_Undeclared:
3749        case TSK_ExplicitSpecialization:
3750          RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3751                             PDiag(diag::err_constexpr_method_non_literal));
3752          break;
3753        }
3754
3755        // Only produce one error per class.
3756        break;
3757      }
3758    }
3759  }
3760
3761  // Declare inherited constructors. We do this eagerly here because:
3762  // - The standard requires an eager diagnostic for conflicting inherited
3763  //   constructors from different classes.
3764  // - The lazy declaration of the other implicit constructors is so as to not
3765  //   waste space and performance on classes that are not meant to be
3766  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3767  //   have inherited constructors.
3768  DeclareInheritedConstructors(Record);
3769
3770  if (!Record->isDependentType())
3771    CheckExplicitlyDefaultedMethods(Record);
3772}
3773
3774void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3775  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3776                                      ME = Record->method_end();
3777       MI != ME; ++MI) {
3778    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3779      switch (getSpecialMember(*MI)) {
3780      case CXXDefaultConstructor:
3781        CheckExplicitlyDefaultedDefaultConstructor(
3782                                                  cast<CXXConstructorDecl>(*MI));
3783        break;
3784
3785      case CXXDestructor:
3786        CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3787        break;
3788
3789      case CXXCopyConstructor:
3790        CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3791        break;
3792
3793      case CXXCopyAssignment:
3794        CheckExplicitlyDefaultedCopyAssignment(*MI);
3795        break;
3796
3797      case CXXMoveConstructor:
3798        CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
3799        break;
3800
3801      case CXXMoveAssignment:
3802        CheckExplicitlyDefaultedMoveAssignment(*MI);
3803        break;
3804
3805      case CXXInvalid:
3806        llvm_unreachable("non-special member explicitly defaulted!");
3807      }
3808    }
3809  }
3810
3811}
3812
3813void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3814  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3815
3816  // Whether this was the first-declared instance of the constructor.
3817  // This affects whether we implicitly add an exception spec (and, eventually,
3818  // constexpr). It is also ill-formed to explicitly default a constructor such
3819  // that it would be deleted. (C++0x [decl.fct.def.default])
3820  bool First = CD == CD->getCanonicalDecl();
3821
3822  bool HadError = false;
3823  if (CD->getNumParams() != 0) {
3824    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3825      << CD->getSourceRange();
3826    HadError = true;
3827  }
3828
3829  ImplicitExceptionSpecification Spec
3830    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3831  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3832  if (EPI.ExceptionSpecType == EST_Delayed) {
3833    // Exception specification depends on some deferred part of the class. We'll
3834    // try again when the class's definition has been fully processed.
3835    return;
3836  }
3837  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3838                          *ExceptionType = Context.getFunctionType(
3839                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3840
3841  // C++11 [dcl.fct.def.default]p2:
3842  //   An explicitly-defaulted function may be declared constexpr only if it
3843  //   would have been implicitly declared as constexpr,
3844  // Do not apply this rule to templates, since core issue 1358 makes such
3845  // functions always instantiate to constexpr functions.
3846  if (CD->isConstexpr() &&
3847      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
3848    if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3849      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3850        << CXXDefaultConstructor;
3851      HadError = true;
3852    }
3853  }
3854  //   and may have an explicit exception-specification only if it is compatible
3855  //   with the exception-specification on the implicit declaration.
3856  if (CtorType->hasExceptionSpec()) {
3857    if (CheckEquivalentExceptionSpec(
3858          PDiag(diag::err_incorrect_defaulted_exception_spec)
3859            << CXXDefaultConstructor,
3860          PDiag(),
3861          ExceptionType, SourceLocation(),
3862          CtorType, CD->getLocation())) {
3863      HadError = true;
3864    }
3865  }
3866
3867  //   If a function is explicitly defaulted on its first declaration,
3868  if (First) {
3869    //  -- it is implicitly considered to be constexpr if the implicit
3870    //     definition would be,
3871    CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3872
3873    //  -- it is implicitly considered to have the same
3874    //     exception-specification as if it had been implicitly declared
3875    //
3876    // FIXME: a compatible, but different, explicit exception specification
3877    // will be silently overridden. We should issue a warning if this happens.
3878    EPI.ExtInfo = CtorType->getExtInfo();
3879
3880    // Such a function is also trivial if the implicitly-declared function
3881    // would have been.
3882    CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
3883  }
3884
3885  if (HadError) {
3886    CD->setInvalidDecl();
3887    return;
3888  }
3889
3890  if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
3891    if (First) {
3892      CD->setDeletedAsWritten();
3893    } else {
3894      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3895        << CXXDefaultConstructor;
3896      CD->setInvalidDecl();
3897    }
3898  }
3899}
3900
3901void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3902  assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3903
3904  // Whether this was the first-declared instance of the constructor.
3905  bool First = CD == CD->getCanonicalDecl();
3906
3907  bool HadError = false;
3908  if (CD->getNumParams() != 1) {
3909    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3910      << CD->getSourceRange();
3911    HadError = true;
3912  }
3913
3914  ImplicitExceptionSpecification Spec(Context);
3915  bool Const;
3916  llvm::tie(Spec, Const) =
3917    ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3918
3919  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3920  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3921                          *ExceptionType = Context.getFunctionType(
3922                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3923
3924  // Check for parameter type matching.
3925  // This is a copy ctor so we know it's a cv-qualified reference to T.
3926  QualType ArgType = CtorType->getArgType(0);
3927  if (ArgType->getPointeeType().isVolatileQualified()) {
3928    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3929    HadError = true;
3930  }
3931  if (ArgType->getPointeeType().isConstQualified() && !Const) {
3932    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3933    HadError = true;
3934  }
3935
3936  // C++11 [dcl.fct.def.default]p2:
3937  //   An explicitly-defaulted function may be declared constexpr only if it
3938  //   would have been implicitly declared as constexpr,
3939  // Do not apply this rule to templates, since core issue 1358 makes such
3940  // functions always instantiate to constexpr functions.
3941  if (CD->isConstexpr() &&
3942      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
3943    if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3944      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3945        << CXXCopyConstructor;
3946      HadError = true;
3947    }
3948  }
3949  //   and may have an explicit exception-specification only if it is compatible
3950  //   with the exception-specification on the implicit declaration.
3951  if (CtorType->hasExceptionSpec()) {
3952    if (CheckEquivalentExceptionSpec(
3953          PDiag(diag::err_incorrect_defaulted_exception_spec)
3954            << CXXCopyConstructor,
3955          PDiag(),
3956          ExceptionType, SourceLocation(),
3957          CtorType, CD->getLocation())) {
3958      HadError = true;
3959    }
3960  }
3961
3962  //   If a function is explicitly defaulted on its first declaration,
3963  if (First) {
3964    //  -- it is implicitly considered to be constexpr if the implicit
3965    //     definition would be,
3966    CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3967
3968    //  -- it is implicitly considered to have the same
3969    //     exception-specification as if it had been implicitly declared, and
3970    //
3971    // FIXME: a compatible, but different, explicit exception specification
3972    // will be silently overridden. We should issue a warning if this happens.
3973    EPI.ExtInfo = CtorType->getExtInfo();
3974
3975    //  -- [...] it shall have the same parameter type as if it had been
3976    //     implicitly declared.
3977    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3978
3979    // Such a function is also trivial if the implicitly-declared function
3980    // would have been.
3981    CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
3982  }
3983
3984  if (HadError) {
3985    CD->setInvalidDecl();
3986    return;
3987  }
3988
3989  if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
3990    if (First) {
3991      CD->setDeletedAsWritten();
3992    } else {
3993      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3994        << CXXCopyConstructor;
3995      CD->setInvalidDecl();
3996    }
3997  }
3998}
3999
4000void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4001  assert(MD->isExplicitlyDefaulted());
4002
4003  // Whether this was the first-declared instance of the operator
4004  bool First = MD == MD->getCanonicalDecl();
4005
4006  bool HadError = false;
4007  if (MD->getNumParams() != 1) {
4008    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4009      << MD->getSourceRange();
4010    HadError = true;
4011  }
4012
4013  QualType ReturnType =
4014    MD->getType()->getAs<FunctionType>()->getResultType();
4015  if (!ReturnType->isLValueReferenceType() ||
4016      !Context.hasSameType(
4017        Context.getCanonicalType(ReturnType->getPointeeType()),
4018        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4019    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4020    HadError = true;
4021  }
4022
4023  ImplicitExceptionSpecification Spec(Context);
4024  bool Const;
4025  llvm::tie(Spec, Const) =
4026    ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4027
4028  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4029  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4030                          *ExceptionType = Context.getFunctionType(
4031                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4032
4033  QualType ArgType = OperType->getArgType(0);
4034  if (!ArgType->isLValueReferenceType()) {
4035    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4036    HadError = true;
4037  } else {
4038    if (ArgType->getPointeeType().isVolatileQualified()) {
4039      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4040      HadError = true;
4041    }
4042    if (ArgType->getPointeeType().isConstQualified() && !Const) {
4043      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4044      HadError = true;
4045    }
4046  }
4047
4048  if (OperType->getTypeQuals()) {
4049    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4050    HadError = true;
4051  }
4052
4053  if (OperType->hasExceptionSpec()) {
4054    if (CheckEquivalentExceptionSpec(
4055          PDiag(diag::err_incorrect_defaulted_exception_spec)
4056            << CXXCopyAssignment,
4057          PDiag(),
4058          ExceptionType, SourceLocation(),
4059          OperType, MD->getLocation())) {
4060      HadError = true;
4061    }
4062  }
4063  if (First) {
4064    // We set the declaration to have the computed exception spec here.
4065    // We duplicate the one parameter type.
4066    EPI.RefQualifier = OperType->getRefQualifier();
4067    EPI.ExtInfo = OperType->getExtInfo();
4068    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4069
4070    // Such a function is also trivial if the implicitly-declared function
4071    // would have been.
4072    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
4073  }
4074
4075  if (HadError) {
4076    MD->setInvalidDecl();
4077    return;
4078  }
4079
4080  if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
4081    if (First) {
4082      MD->setDeletedAsWritten();
4083    } else {
4084      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4085        << CXXCopyAssignment;
4086      MD->setInvalidDecl();
4087    }
4088  }
4089}
4090
4091void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4092  assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4093
4094  // Whether this was the first-declared instance of the constructor.
4095  bool First = CD == CD->getCanonicalDecl();
4096
4097  bool HadError = false;
4098  if (CD->getNumParams() != 1) {
4099    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4100      << CD->getSourceRange();
4101    HadError = true;
4102  }
4103
4104  ImplicitExceptionSpecification Spec(
4105      ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4106
4107  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4108  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4109                          *ExceptionType = Context.getFunctionType(
4110                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4111
4112  // Check for parameter type matching.
4113  // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4114  QualType ArgType = CtorType->getArgType(0);
4115  if (ArgType->getPointeeType().isVolatileQualified()) {
4116    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4117    HadError = true;
4118  }
4119  if (ArgType->getPointeeType().isConstQualified()) {
4120    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4121    HadError = true;
4122  }
4123
4124  // C++11 [dcl.fct.def.default]p2:
4125  //   An explicitly-defaulted function may be declared constexpr only if it
4126  //   would have been implicitly declared as constexpr,
4127  // Do not apply this rule to templates, since core issue 1358 makes such
4128  // functions always instantiate to constexpr functions.
4129  if (CD->isConstexpr() &&
4130      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4131    if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4132      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4133        << CXXMoveConstructor;
4134      HadError = true;
4135    }
4136  }
4137  //   and may have an explicit exception-specification only if it is compatible
4138  //   with the exception-specification on the implicit declaration.
4139  if (CtorType->hasExceptionSpec()) {
4140    if (CheckEquivalentExceptionSpec(
4141          PDiag(diag::err_incorrect_defaulted_exception_spec)
4142            << CXXMoveConstructor,
4143          PDiag(),
4144          ExceptionType, SourceLocation(),
4145          CtorType, CD->getLocation())) {
4146      HadError = true;
4147    }
4148  }
4149
4150  //   If a function is explicitly defaulted on its first declaration,
4151  if (First) {
4152    //  -- it is implicitly considered to be constexpr if the implicit
4153    //     definition would be,
4154    CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4155
4156    //  -- it is implicitly considered to have the same
4157    //     exception-specification as if it had been implicitly declared, and
4158    //
4159    // FIXME: a compatible, but different, explicit exception specification
4160    // will be silently overridden. We should issue a warning if this happens.
4161    EPI.ExtInfo = CtorType->getExtInfo();
4162
4163    //  -- [...] it shall have the same parameter type as if it had been
4164    //     implicitly declared.
4165    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4166
4167    // Such a function is also trivial if the implicitly-declared function
4168    // would have been.
4169    CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
4170  }
4171
4172  if (HadError) {
4173    CD->setInvalidDecl();
4174    return;
4175  }
4176
4177  if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
4178    if (First) {
4179      CD->setDeletedAsWritten();
4180    } else {
4181      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4182        << CXXMoveConstructor;
4183      CD->setInvalidDecl();
4184    }
4185  }
4186}
4187
4188void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4189  assert(MD->isExplicitlyDefaulted());
4190
4191  // Whether this was the first-declared instance of the operator
4192  bool First = MD == MD->getCanonicalDecl();
4193
4194  bool HadError = false;
4195  if (MD->getNumParams() != 1) {
4196    Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4197      << MD->getSourceRange();
4198    HadError = true;
4199  }
4200
4201  QualType ReturnType =
4202    MD->getType()->getAs<FunctionType>()->getResultType();
4203  if (!ReturnType->isLValueReferenceType() ||
4204      !Context.hasSameType(
4205        Context.getCanonicalType(ReturnType->getPointeeType()),
4206        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4207    Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4208    HadError = true;
4209  }
4210
4211  ImplicitExceptionSpecification Spec(
4212      ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4213
4214  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4215  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4216                          *ExceptionType = Context.getFunctionType(
4217                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4218
4219  QualType ArgType = OperType->getArgType(0);
4220  if (!ArgType->isRValueReferenceType()) {
4221    Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4222    HadError = true;
4223  } else {
4224    if (ArgType->getPointeeType().isVolatileQualified()) {
4225      Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4226      HadError = true;
4227    }
4228    if (ArgType->getPointeeType().isConstQualified()) {
4229      Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4230      HadError = true;
4231    }
4232  }
4233
4234  if (OperType->getTypeQuals()) {
4235    Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4236    HadError = true;
4237  }
4238
4239  if (OperType->hasExceptionSpec()) {
4240    if (CheckEquivalentExceptionSpec(
4241          PDiag(diag::err_incorrect_defaulted_exception_spec)
4242            << CXXMoveAssignment,
4243          PDiag(),
4244          ExceptionType, SourceLocation(),
4245          OperType, MD->getLocation())) {
4246      HadError = true;
4247    }
4248  }
4249  if (First) {
4250    // We set the declaration to have the computed exception spec here.
4251    // We duplicate the one parameter type.
4252    EPI.RefQualifier = OperType->getRefQualifier();
4253    EPI.ExtInfo = OperType->getExtInfo();
4254    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4255
4256    // Such a function is also trivial if the implicitly-declared function
4257    // would have been.
4258    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
4259  }
4260
4261  if (HadError) {
4262    MD->setInvalidDecl();
4263    return;
4264  }
4265
4266  if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
4267    if (First) {
4268      MD->setDeletedAsWritten();
4269    } else {
4270      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4271        << CXXMoveAssignment;
4272      MD->setInvalidDecl();
4273    }
4274  }
4275}
4276
4277void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4278  assert(DD->isExplicitlyDefaulted());
4279
4280  // Whether this was the first-declared instance of the destructor.
4281  bool First = DD == DD->getCanonicalDecl();
4282
4283  ImplicitExceptionSpecification Spec
4284    = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4285  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4286  const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4287                          *ExceptionType = Context.getFunctionType(
4288                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4289
4290  if (DtorType->hasExceptionSpec()) {
4291    if (CheckEquivalentExceptionSpec(
4292          PDiag(diag::err_incorrect_defaulted_exception_spec)
4293            << CXXDestructor,
4294          PDiag(),
4295          ExceptionType, SourceLocation(),
4296          DtorType, DD->getLocation())) {
4297      DD->setInvalidDecl();
4298      return;
4299    }
4300  }
4301  if (First) {
4302    // We set the declaration to have the computed exception spec here.
4303    // There are no parameters.
4304    EPI.ExtInfo = DtorType->getExtInfo();
4305    DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4306
4307    // Such a function is also trivial if the implicitly-declared function
4308    // would have been.
4309    DD->setTrivial(DD->getParent()->hasTrivialDestructor());
4310  }
4311
4312  if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
4313    if (First) {
4314      DD->setDeletedAsWritten();
4315    } else {
4316      Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
4317        << CXXDestructor;
4318      DD->setInvalidDecl();
4319    }
4320  }
4321}
4322
4323namespace {
4324struct SpecialMemberDeletionInfo {
4325  Sema &S;
4326  CXXMethodDecl *MD;
4327  Sema::CXXSpecialMember CSM;
4328
4329  // Properties of the special member, computed for convenience.
4330  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4331  SourceLocation Loc;
4332
4333  bool AllFieldsAreConst;
4334
4335  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4336                            Sema::CXXSpecialMember CSM)
4337    : S(S), MD(MD), CSM(CSM),
4338      IsConstructor(false), IsAssignment(false), IsMove(false),
4339      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4340      AllFieldsAreConst(true) {
4341    switch (CSM) {
4342      case Sema::CXXDefaultConstructor:
4343      case Sema::CXXCopyConstructor:
4344        IsConstructor = true;
4345        break;
4346      case Sema::CXXMoveConstructor:
4347        IsConstructor = true;
4348        IsMove = true;
4349        break;
4350      case Sema::CXXCopyAssignment:
4351        IsAssignment = true;
4352        break;
4353      case Sema::CXXMoveAssignment:
4354        IsAssignment = true;
4355        IsMove = true;
4356        break;
4357      case Sema::CXXDestructor:
4358        break;
4359      case Sema::CXXInvalid:
4360        llvm_unreachable("invalid special member kind");
4361    }
4362
4363    if (MD->getNumParams()) {
4364      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4365      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4366    }
4367  }
4368
4369  bool inUnion() const { return MD->getParent()->isUnion(); }
4370
4371  /// Look up the corresponding special member in the given class.
4372  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4373    unsigned TQ = MD->getTypeQualifiers();
4374    return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4375                                 MD->getRefQualifier() == RQ_RValue,
4376                                 TQ & Qualifiers::Const,
4377                                 TQ & Qualifiers::Volatile);
4378  }
4379
4380  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, FieldDecl *Field);
4381
4382  bool shouldDeleteForBase(CXXRecordDecl *BaseDecl, bool IsVirtualBase);
4383  bool shouldDeleteForField(FieldDecl *FD);
4384  bool shouldDeleteForAllConstMembers();
4385};
4386}
4387
4388/// Check whether we should delete a special member function due to having a
4389/// direct or virtual base class or static data member of class type M.
4390bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4391    CXXRecordDecl *Class, FieldDecl *Field) {
4392  // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
4393  // -- any direct or virtual base class [...] has a type with a destructor
4394  //    that is deleted or inaccessible
4395  if (!IsAssignment) {
4396    CXXDestructorDecl *Dtor = S.LookupDestructor(Class);
4397    if (Dtor->isDeleted())
4398      return true;
4399    if (S.CheckDestructorAccess(Loc, Dtor, S.PDiag()) != Sema::AR_accessible)
4400      return true;
4401
4402    // C++11 [class.dtor]p5:
4403    // -- X is a union-like class that has a variant member with a non-trivial
4404    //    destructor
4405    if (CSM == Sema::CXXDestructor && Field && Field->getParent()->isUnion() &&
4406        !Dtor->isTrivial())
4407      return true;
4408  }
4409
4410  // C++11 [class.ctor]p5:
4411  // -- any direct or virtual base class [...] has class type M [...] and
4412  //    either M has no default constructor or overload resolution as applied
4413  //    to M's default constructor results in an ambiguity or in a function
4414  //    that is deleted or inaccessible
4415  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4416  // -- a direct or virtual base class B that cannot be copied/moved because
4417  //    overload resolution, as applied to B's corresponding special member,
4418  //    results in an ambiguity or a function that is deleted or inaccessible
4419  //    from the defaulted special member
4420  // FIXME: in-class initializers should be handled here
4421  if (CSM != Sema::CXXDestructor) {
4422    Sema::SpecialMemberOverloadResult *SMOR = lookupIn(Class);
4423    if (!SMOR->hasSuccess())
4424      return true;
4425
4426    CXXMethodDecl *Member = SMOR->getMethod();
4427    // A member of a union must have a trivial corresponding special member.
4428    if (Field && Field->getParent()->isUnion() && !Member->isTrivial())
4429      return true;
4430
4431    if (IsConstructor) {
4432      CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Member);
4433      if (S.CheckConstructorAccess(Loc, Ctor, Ctor->getAccess(), S.PDiag())
4434            != Sema::AR_accessible)
4435        return true;
4436
4437      // -- for the move constructor, a [...] direct or virtual base class with
4438      //    a type that does not have a move constructor and is not trivially
4439      //    copyable.
4440      if (IsMove && !Ctor->isMoveConstructor() && !Class->isTriviallyCopyable())
4441        return true;
4442    } else {
4443      assert(IsAssignment && "unexpected kind of special member");
4444      if (S.CheckDirectMemberAccess(Loc, Member, S.PDiag())
4445            != Sema::AR_accessible)
4446        return true;
4447
4448      // -- for the move assignment operator, a direct base class with a type
4449      //    that does not have a move assignment operator and is not trivially
4450      //    copyable.
4451      if (IsMove && !Member->isMoveAssignmentOperator() &&
4452          !Class->isTriviallyCopyable())
4453        return true;
4454    }
4455  }
4456
4457  return false;
4458}
4459
4460/// Check whether we should delete a special member function due to the class
4461/// having a particular direct or virtual base class.
4462bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXRecordDecl *BaseDecl,
4463                                                    bool IsVirtualBase) {
4464  // C++11 [class.copy]p23:
4465  // -- for the move assignment operator, any direct or indirect virtual
4466  //    base class.
4467  if (CSM == Sema::CXXMoveAssignment && IsVirtualBase)
4468    return true;
4469
4470  if (shouldDeleteForClassSubobject(BaseDecl, 0))
4471    return true;
4472
4473  return false;
4474}
4475
4476/// Check whether we should delete a special member function due to the class
4477/// having a particular non-static data member.
4478bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4479  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4480  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4481
4482  if (CSM == Sema::CXXDefaultConstructor) {
4483    // For a default constructor, all references must be initialized in-class
4484    // and, if a union, it must have a non-const member.
4485    if (FieldType->isReferenceType() && !FD->hasInClassInitializer())
4486      return true;
4487
4488    if (inUnion() && !FieldType.isConstQualified())
4489      AllFieldsAreConst = false;
4490
4491    // C++11 [class.ctor]p5: any non-variant non-static data member of
4492    // const-qualified type (or array thereof) with no
4493    // brace-or-equal-initializer does not have a user-provided default
4494    // constructor.
4495    if (!inUnion() && FieldType.isConstQualified() &&
4496        !FD->hasInClassInitializer() &&
4497        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor()))
4498      return true;
4499  } else if (CSM == Sema::CXXCopyConstructor) {
4500    // For a copy constructor, data members must not be of rvalue reference
4501    // type.
4502    if (FieldType->isRValueReferenceType())
4503      return true;
4504  } else if (IsAssignment) {
4505    // For an assignment operator, data members must not be of reference type.
4506    if (FieldType->isReferenceType())
4507      return true;
4508  }
4509
4510  if (FieldRecord) {
4511    // Some additional restrictions exist on the variant members.
4512    if (!inUnion() && FieldRecord->isUnion() &&
4513        FieldRecord->isAnonymousStructOrUnion()) {
4514      bool AllVariantFieldsAreConst = true;
4515
4516      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4517                                         UE = FieldRecord->field_end();
4518           UI != UE; ++UI) {
4519        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4520
4521        if (!UnionFieldType.isConstQualified())
4522          AllVariantFieldsAreConst = false;
4523
4524        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4525        if (UnionFieldRecord &&
4526            shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4527          return true;
4528      }
4529
4530      // At least one member in each anonymous union must be non-const
4531      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4532          FieldRecord->field_begin() != FieldRecord->field_end())
4533        return true;
4534
4535      // Don't try to initialize the anonymous union
4536      // This is technically non-conformant, but sanity demands it.
4537      return false;
4538    }
4539
4540    // When checking a constructor, the field's destructor must be accessible
4541    // and not deleted.
4542    if (IsConstructor) {
4543      CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4544      if (FieldDtor->isDeleted())
4545        return true;
4546      if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4547          Sema::AR_accessible)
4548        return true;
4549    }
4550
4551    // Check that the corresponding member of the field is accessible,
4552    // unique, and non-deleted. We don't do this if it has an explicit
4553    // initialization when default-constructing.
4554    if (!(CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())) {
4555      Sema::SpecialMemberOverloadResult *SMOR = lookupIn(FieldRecord);
4556      if (!SMOR->hasSuccess())
4557        return true;
4558
4559      CXXMethodDecl *FieldMember = SMOR->getMethod();
4560
4561      // We need the corresponding member of a union to be trivial so that
4562      // we can safely process all members simultaneously.
4563      if (inUnion() && !FieldMember->isTrivial())
4564        return true;
4565
4566      if (IsConstructor) {
4567        CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4568        if (S.CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4569                                     S.PDiag()) != Sema::AR_accessible)
4570        return true;
4571
4572        // For a move operation, the corresponding operation must actually
4573        // be a move operation (and not a copy selected by overload
4574        // resolution) unless we are working on a trivially copyable class.
4575        if (IsMove && !FieldCtor->isMoveConstructor() &&
4576            !FieldRecord->isTriviallyCopyable())
4577          return true;
4578      } else if (CSM == Sema::CXXDestructor) {
4579        CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4580        if (FieldDtor->isDeleted())
4581          return true;
4582        if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4583            Sema::AR_accessible)
4584          return true;
4585      } else {
4586        assert(IsAssignment && "unexpected kind of special member");
4587        if (S.CheckDirectMemberAccess(Loc, FieldMember, S.PDiag())
4588              != Sema::AR_accessible)
4589          return true;
4590
4591        // -- for the move assignment operator, a non-static data member with a
4592        //    type that does not have a move assignment operator and is not
4593        //    trivially copyable.
4594        if (IsMove && !FieldMember->isMoveAssignmentOperator() &&
4595            !FieldRecord->isTriviallyCopyable())
4596          return true;
4597      }
4598    }
4599  } else if (IsAssignment && FieldType.isConstQualified()) {
4600    // C++11 [class.copy]p23:
4601    // -- a non-static data member of const non-class type (or array thereof)
4602    return true;
4603  }
4604
4605  return false;
4606}
4607
4608/// C++11 [class.ctor] p5:
4609///   A defaulted default constructor for a class X is defined as deleted if
4610/// X is a union and all of its variant members are of const-qualified type.
4611bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4612  // This is a silly definition, because it gives an empty union a deleted
4613  // default constructor. Don't do that.
4614  return CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4615    (MD->getParent()->field_begin() != MD->getParent()->field_end());
4616}
4617
4618/// Determine whether a defaulted special member function should be defined as
4619/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4620/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4621bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4622  assert(!MD->isInvalidDecl());
4623  CXXRecordDecl *RD = MD->getParent();
4624  assert(!RD->isDependentType() && "do deletion after instantiation");
4625  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4626    return false;
4627
4628  // FIXME: Provide the ability to diagnose why a special member was deleted.
4629
4630  // C++11 [expr.lambda.prim]p19:
4631  //   The closure type associated with a lambda-expression has a
4632  //   deleted (8.4.3) default constructor and a deleted copy
4633  //   assignment operator.
4634  if (RD->isLambda() &&
4635      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment))
4636    return true;
4637
4638  // C++11 [class.dtor]p5:
4639  // -- for a virtual destructor, lookup of the non-array deallocation function
4640  //    results in an ambiguity or in a function that is deleted or inaccessible
4641  if (CSM == Sema::CXXDestructor && MD->isVirtual()) {
4642    FunctionDecl *OperatorDelete = 0;
4643    DeclarationName Name =
4644      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4645    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4646                                 OperatorDelete, false))
4647      return true;
4648  }
4649
4650  // For an anonymous struct or union, the copy and assignment special members
4651  // will never be used, so skip the check. For an anonymous union declared at
4652  // namespace scope, the constructor and destructor are used.
4653  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4654      RD->isAnonymousStructOrUnion())
4655    return false;
4656
4657  // Do access control from the special member function
4658  ContextRAII MethodContext(*this, MD);
4659
4660  SpecialMemberDeletionInfo SMI(*this, MD, CSM);
4661
4662  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4663                                          BE = RD->bases_end(); BI != BE; ++BI)
4664    if (!BI->isVirtual() &&
4665        SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), false))
4666      return true;
4667
4668  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4669                                          BE = RD->vbases_end(); BI != BE; ++BI)
4670    if (SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), true))
4671      return true;
4672
4673  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4674                                     FE = RD->field_end(); FI != FE; ++FI)
4675    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4676        SMI.shouldDeleteForField(*FI))
4677      return true;
4678
4679  if (SMI.shouldDeleteForAllConstMembers())
4680    return true;
4681
4682  return false;
4683}
4684
4685/// \brief Data used with FindHiddenVirtualMethod
4686namespace {
4687  struct FindHiddenVirtualMethodData {
4688    Sema *S;
4689    CXXMethodDecl *Method;
4690    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4691    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4692  };
4693}
4694
4695/// \brief Member lookup function that determines whether a given C++
4696/// method overloads virtual methods in a base class without overriding any,
4697/// to be used with CXXRecordDecl::lookupInBases().
4698static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4699                                    CXXBasePath &Path,
4700                                    void *UserData) {
4701  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4702
4703  FindHiddenVirtualMethodData &Data
4704    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4705
4706  DeclarationName Name = Data.Method->getDeclName();
4707  assert(Name.getNameKind() == DeclarationName::Identifier);
4708
4709  bool foundSameNameMethod = false;
4710  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4711  for (Path.Decls = BaseRecord->lookup(Name);
4712       Path.Decls.first != Path.Decls.second;
4713       ++Path.Decls.first) {
4714    NamedDecl *D = *Path.Decls.first;
4715    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4716      MD = MD->getCanonicalDecl();
4717      foundSameNameMethod = true;
4718      // Interested only in hidden virtual methods.
4719      if (!MD->isVirtual())
4720        continue;
4721      // If the method we are checking overrides a method from its base
4722      // don't warn about the other overloaded methods.
4723      if (!Data.S->IsOverload(Data.Method, MD, false))
4724        return true;
4725      // Collect the overload only if its hidden.
4726      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4727        overloadedMethods.push_back(MD);
4728    }
4729  }
4730
4731  if (foundSameNameMethod)
4732    Data.OverloadedMethods.append(overloadedMethods.begin(),
4733                                   overloadedMethods.end());
4734  return foundSameNameMethod;
4735}
4736
4737/// \brief See if a method overloads virtual methods in a base class without
4738/// overriding any.
4739void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4740  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4741                               MD->getLocation()) == DiagnosticsEngine::Ignored)
4742    return;
4743  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4744    return;
4745
4746  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4747                     /*bool RecordPaths=*/false,
4748                     /*bool DetectVirtual=*/false);
4749  FindHiddenVirtualMethodData Data;
4750  Data.Method = MD;
4751  Data.S = this;
4752
4753  // Keep the base methods that were overriden or introduced in the subclass
4754  // by 'using' in a set. A base method not in this set is hidden.
4755  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4756       res.first != res.second; ++res.first) {
4757    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4758      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4759                                          E = MD->end_overridden_methods();
4760           I != E; ++I)
4761        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4762    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4763      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4764        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4765  }
4766
4767  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4768      !Data.OverloadedMethods.empty()) {
4769    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4770      << MD << (Data.OverloadedMethods.size() > 1);
4771
4772    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4773      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4774      Diag(overloadedMD->getLocation(),
4775           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4776    }
4777  }
4778}
4779
4780void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4781                                             Decl *TagDecl,
4782                                             SourceLocation LBrac,
4783                                             SourceLocation RBrac,
4784                                             AttributeList *AttrList) {
4785  if (!TagDecl)
4786    return;
4787
4788  AdjustDeclIfTemplate(TagDecl);
4789
4790  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4791              // strict aliasing violation!
4792              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4793              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4794
4795  CheckCompletedCXXClass(
4796                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4797}
4798
4799/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4800/// special functions, such as the default constructor, copy
4801/// constructor, or destructor, to the given C++ class (C++
4802/// [special]p1).  This routine can only be executed just before the
4803/// definition of the class is complete.
4804void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4805  if (!ClassDecl->hasUserDeclaredConstructor())
4806    ++ASTContext::NumImplicitDefaultConstructors;
4807
4808  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4809    ++ASTContext::NumImplicitCopyConstructors;
4810
4811  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4812    ++ASTContext::NumImplicitMoveConstructors;
4813
4814  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4815    ++ASTContext::NumImplicitCopyAssignmentOperators;
4816
4817    // If we have a dynamic class, then the copy assignment operator may be
4818    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4819    // it shows up in the right place in the vtable and that we diagnose
4820    // problems with the implicit exception specification.
4821    if (ClassDecl->isDynamicClass())
4822      DeclareImplicitCopyAssignment(ClassDecl);
4823  }
4824
4825  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
4826    ++ASTContext::NumImplicitMoveAssignmentOperators;
4827
4828    // Likewise for the move assignment operator.
4829    if (ClassDecl->isDynamicClass())
4830      DeclareImplicitMoveAssignment(ClassDecl);
4831  }
4832
4833  if (!ClassDecl->hasUserDeclaredDestructor()) {
4834    ++ASTContext::NumImplicitDestructors;
4835
4836    // If we have a dynamic class, then the destructor may be virtual, so we
4837    // have to declare the destructor immediately. This ensures that, e.g., it
4838    // shows up in the right place in the vtable and that we diagnose problems
4839    // with the implicit exception specification.
4840    if (ClassDecl->isDynamicClass())
4841      DeclareImplicitDestructor(ClassDecl);
4842  }
4843}
4844
4845void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4846  if (!D)
4847    return;
4848
4849  int NumParamList = D->getNumTemplateParameterLists();
4850  for (int i = 0; i < NumParamList; i++) {
4851    TemplateParameterList* Params = D->getTemplateParameterList(i);
4852    for (TemplateParameterList::iterator Param = Params->begin(),
4853                                      ParamEnd = Params->end();
4854          Param != ParamEnd; ++Param) {
4855      NamedDecl *Named = cast<NamedDecl>(*Param);
4856      if (Named->getDeclName()) {
4857        S->AddDecl(Named);
4858        IdResolver.AddDecl(Named);
4859      }
4860    }
4861  }
4862}
4863
4864void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4865  if (!D)
4866    return;
4867
4868  TemplateParameterList *Params = 0;
4869  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4870    Params = Template->getTemplateParameters();
4871  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4872           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4873    Params = PartialSpec->getTemplateParameters();
4874  else
4875    return;
4876
4877  for (TemplateParameterList::iterator Param = Params->begin(),
4878                                    ParamEnd = Params->end();
4879       Param != ParamEnd; ++Param) {
4880    NamedDecl *Named = cast<NamedDecl>(*Param);
4881    if (Named->getDeclName()) {
4882      S->AddDecl(Named);
4883      IdResolver.AddDecl(Named);
4884    }
4885  }
4886}
4887
4888void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4889  if (!RecordD) return;
4890  AdjustDeclIfTemplate(RecordD);
4891  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4892  PushDeclContext(S, Record);
4893}
4894
4895void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4896  if (!RecordD) return;
4897  PopDeclContext();
4898}
4899
4900/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4901/// parsing a top-level (non-nested) C++ class, and we are now
4902/// parsing those parts of the given Method declaration that could
4903/// not be parsed earlier (C++ [class.mem]p2), such as default
4904/// arguments. This action should enter the scope of the given
4905/// Method declaration as if we had just parsed the qualified method
4906/// name. However, it should not bring the parameters into scope;
4907/// that will be performed by ActOnDelayedCXXMethodParameter.
4908void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4909}
4910
4911/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4912/// C++ method declaration. We're (re-)introducing the given
4913/// function parameter into scope for use in parsing later parts of
4914/// the method declaration. For example, we could see an
4915/// ActOnParamDefaultArgument event for this parameter.
4916void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4917  if (!ParamD)
4918    return;
4919
4920  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4921
4922  // If this parameter has an unparsed default argument, clear it out
4923  // to make way for the parsed default argument.
4924  if (Param->hasUnparsedDefaultArg())
4925    Param->setDefaultArg(0);
4926
4927  S->AddDecl(Param);
4928  if (Param->getDeclName())
4929    IdResolver.AddDecl(Param);
4930}
4931
4932/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4933/// processing the delayed method declaration for Method. The method
4934/// declaration is now considered finished. There may be a separate
4935/// ActOnStartOfFunctionDef action later (not necessarily
4936/// immediately!) for this method, if it was also defined inside the
4937/// class body.
4938void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4939  if (!MethodD)
4940    return;
4941
4942  AdjustDeclIfTemplate(MethodD);
4943
4944  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4945
4946  // Now that we have our default arguments, check the constructor
4947  // again. It could produce additional diagnostics or affect whether
4948  // the class has implicitly-declared destructors, among other
4949  // things.
4950  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4951    CheckConstructor(Constructor);
4952
4953  // Check the default arguments, which we may have added.
4954  if (!Method->isInvalidDecl())
4955    CheckCXXDefaultArguments(Method);
4956}
4957
4958/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4959/// the well-formedness of the constructor declarator @p D with type @p
4960/// R. If there are any errors in the declarator, this routine will
4961/// emit diagnostics and set the invalid bit to true.  In any case, the type
4962/// will be updated to reflect a well-formed type for the constructor and
4963/// returned.
4964QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4965                                          StorageClass &SC) {
4966  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4967
4968  // C++ [class.ctor]p3:
4969  //   A constructor shall not be virtual (10.3) or static (9.4). A
4970  //   constructor can be invoked for a const, volatile or const
4971  //   volatile object. A constructor shall not be declared const,
4972  //   volatile, or const volatile (9.3.2).
4973  if (isVirtual) {
4974    if (!D.isInvalidType())
4975      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4976        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4977        << SourceRange(D.getIdentifierLoc());
4978    D.setInvalidType();
4979  }
4980  if (SC == SC_Static) {
4981    if (!D.isInvalidType())
4982      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4983        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4984        << SourceRange(D.getIdentifierLoc());
4985    D.setInvalidType();
4986    SC = SC_None;
4987  }
4988
4989  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4990  if (FTI.TypeQuals != 0) {
4991    if (FTI.TypeQuals & Qualifiers::Const)
4992      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4993        << "const" << SourceRange(D.getIdentifierLoc());
4994    if (FTI.TypeQuals & Qualifiers::Volatile)
4995      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4996        << "volatile" << SourceRange(D.getIdentifierLoc());
4997    if (FTI.TypeQuals & Qualifiers::Restrict)
4998      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4999        << "restrict" << SourceRange(D.getIdentifierLoc());
5000    D.setInvalidType();
5001  }
5002
5003  // C++0x [class.ctor]p4:
5004  //   A constructor shall not be declared with a ref-qualifier.
5005  if (FTI.hasRefQualifier()) {
5006    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5007      << FTI.RefQualifierIsLValueRef
5008      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5009    D.setInvalidType();
5010  }
5011
5012  // Rebuild the function type "R" without any type qualifiers (in
5013  // case any of the errors above fired) and with "void" as the
5014  // return type, since constructors don't have return types.
5015  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5016  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5017    return R;
5018
5019  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5020  EPI.TypeQuals = 0;
5021  EPI.RefQualifier = RQ_None;
5022
5023  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5024                                 Proto->getNumArgs(), EPI);
5025}
5026
5027/// CheckConstructor - Checks a fully-formed constructor for
5028/// well-formedness, issuing any diagnostics required. Returns true if
5029/// the constructor declarator is invalid.
5030void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5031  CXXRecordDecl *ClassDecl
5032    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5033  if (!ClassDecl)
5034    return Constructor->setInvalidDecl();
5035
5036  // C++ [class.copy]p3:
5037  //   A declaration of a constructor for a class X is ill-formed if
5038  //   its first parameter is of type (optionally cv-qualified) X and
5039  //   either there are no other parameters or else all other
5040  //   parameters have default arguments.
5041  if (!Constructor->isInvalidDecl() &&
5042      ((Constructor->getNumParams() == 1) ||
5043       (Constructor->getNumParams() > 1 &&
5044        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5045      Constructor->getTemplateSpecializationKind()
5046                                              != TSK_ImplicitInstantiation) {
5047    QualType ParamType = Constructor->getParamDecl(0)->getType();
5048    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5049    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5050      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5051      const char *ConstRef
5052        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5053                                                        : " const &";
5054      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5055        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5056
5057      // FIXME: Rather that making the constructor invalid, we should endeavor
5058      // to fix the type.
5059      Constructor->setInvalidDecl();
5060    }
5061  }
5062}
5063
5064/// CheckDestructor - Checks a fully-formed destructor definition for
5065/// well-formedness, issuing any diagnostics required.  Returns true
5066/// on error.
5067bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5068  CXXRecordDecl *RD = Destructor->getParent();
5069
5070  if (Destructor->isVirtual()) {
5071    SourceLocation Loc;
5072
5073    if (!Destructor->isImplicit())
5074      Loc = Destructor->getLocation();
5075    else
5076      Loc = RD->getLocation();
5077
5078    // If we have a virtual destructor, look up the deallocation function
5079    FunctionDecl *OperatorDelete = 0;
5080    DeclarationName Name =
5081    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5082    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5083      return true;
5084
5085    MarkFunctionReferenced(Loc, OperatorDelete);
5086
5087    Destructor->setOperatorDelete(OperatorDelete);
5088  }
5089
5090  return false;
5091}
5092
5093static inline bool
5094FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5095  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5096          FTI.ArgInfo[0].Param &&
5097          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5098}
5099
5100/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5101/// the well-formednes of the destructor declarator @p D with type @p
5102/// R. If there are any errors in the declarator, this routine will
5103/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5104/// will be updated to reflect a well-formed type for the destructor and
5105/// returned.
5106QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5107                                         StorageClass& SC) {
5108  // C++ [class.dtor]p1:
5109  //   [...] A typedef-name that names a class is a class-name
5110  //   (7.1.3); however, a typedef-name that names a class shall not
5111  //   be used as the identifier in the declarator for a destructor
5112  //   declaration.
5113  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5114  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5115    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5116      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5117  else if (const TemplateSpecializationType *TST =
5118             DeclaratorType->getAs<TemplateSpecializationType>())
5119    if (TST->isTypeAlias())
5120      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5121        << DeclaratorType << 1;
5122
5123  // C++ [class.dtor]p2:
5124  //   A destructor is used to destroy objects of its class type. A
5125  //   destructor takes no parameters, and no return type can be
5126  //   specified for it (not even void). The address of a destructor
5127  //   shall not be taken. A destructor shall not be static. A
5128  //   destructor can be invoked for a const, volatile or const
5129  //   volatile object. A destructor shall not be declared const,
5130  //   volatile or const volatile (9.3.2).
5131  if (SC == SC_Static) {
5132    if (!D.isInvalidType())
5133      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5134        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5135        << SourceRange(D.getIdentifierLoc())
5136        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5137
5138    SC = SC_None;
5139  }
5140  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5141    // Destructors don't have return types, but the parser will
5142    // happily parse something like:
5143    //
5144    //   class X {
5145    //     float ~X();
5146    //   };
5147    //
5148    // The return type will be eliminated later.
5149    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5150      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5151      << SourceRange(D.getIdentifierLoc());
5152  }
5153
5154  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5155  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5156    if (FTI.TypeQuals & Qualifiers::Const)
5157      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5158        << "const" << SourceRange(D.getIdentifierLoc());
5159    if (FTI.TypeQuals & Qualifiers::Volatile)
5160      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5161        << "volatile" << SourceRange(D.getIdentifierLoc());
5162    if (FTI.TypeQuals & Qualifiers::Restrict)
5163      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5164        << "restrict" << SourceRange(D.getIdentifierLoc());
5165    D.setInvalidType();
5166  }
5167
5168  // C++0x [class.dtor]p2:
5169  //   A destructor shall not be declared with a ref-qualifier.
5170  if (FTI.hasRefQualifier()) {
5171    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5172      << FTI.RefQualifierIsLValueRef
5173      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5174    D.setInvalidType();
5175  }
5176
5177  // Make sure we don't have any parameters.
5178  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5179    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5180
5181    // Delete the parameters.
5182    FTI.freeArgs();
5183    D.setInvalidType();
5184  }
5185
5186  // Make sure the destructor isn't variadic.
5187  if (FTI.isVariadic) {
5188    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5189    D.setInvalidType();
5190  }
5191
5192  // Rebuild the function type "R" without any type qualifiers or
5193  // parameters (in case any of the errors above fired) and with
5194  // "void" as the return type, since destructors don't have return
5195  // types.
5196  if (!D.isInvalidType())
5197    return R;
5198
5199  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5200  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5201  EPI.Variadic = false;
5202  EPI.TypeQuals = 0;
5203  EPI.RefQualifier = RQ_None;
5204  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5205}
5206
5207/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5208/// well-formednes of the conversion function declarator @p D with
5209/// type @p R. If there are any errors in the declarator, this routine
5210/// will emit diagnostics and return true. Otherwise, it will return
5211/// false. Either way, the type @p R will be updated to reflect a
5212/// well-formed type for the conversion operator.
5213void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5214                                     StorageClass& SC) {
5215  // C++ [class.conv.fct]p1:
5216  //   Neither parameter types nor return type can be specified. The
5217  //   type of a conversion function (8.3.5) is "function taking no
5218  //   parameter returning conversion-type-id."
5219  if (SC == SC_Static) {
5220    if (!D.isInvalidType())
5221      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5222        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5223        << SourceRange(D.getIdentifierLoc());
5224    D.setInvalidType();
5225    SC = SC_None;
5226  }
5227
5228  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5229
5230  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5231    // Conversion functions don't have return types, but the parser will
5232    // happily parse something like:
5233    //
5234    //   class X {
5235    //     float operator bool();
5236    //   };
5237    //
5238    // The return type will be changed later anyway.
5239    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5240      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5241      << SourceRange(D.getIdentifierLoc());
5242    D.setInvalidType();
5243  }
5244
5245  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5246
5247  // Make sure we don't have any parameters.
5248  if (Proto->getNumArgs() > 0) {
5249    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5250
5251    // Delete the parameters.
5252    D.getFunctionTypeInfo().freeArgs();
5253    D.setInvalidType();
5254  } else if (Proto->isVariadic()) {
5255    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5256    D.setInvalidType();
5257  }
5258
5259  // Diagnose "&operator bool()" and other such nonsense.  This
5260  // is actually a gcc extension which we don't support.
5261  if (Proto->getResultType() != ConvType) {
5262    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5263      << Proto->getResultType();
5264    D.setInvalidType();
5265    ConvType = Proto->getResultType();
5266  }
5267
5268  // C++ [class.conv.fct]p4:
5269  //   The conversion-type-id shall not represent a function type nor
5270  //   an array type.
5271  if (ConvType->isArrayType()) {
5272    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5273    ConvType = Context.getPointerType(ConvType);
5274    D.setInvalidType();
5275  } else if (ConvType->isFunctionType()) {
5276    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5277    ConvType = Context.getPointerType(ConvType);
5278    D.setInvalidType();
5279  }
5280
5281  // Rebuild the function type "R" without any parameters (in case any
5282  // of the errors above fired) and with the conversion type as the
5283  // return type.
5284  if (D.isInvalidType())
5285    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5286
5287  // C++0x explicit conversion operators.
5288  if (D.getDeclSpec().isExplicitSpecified())
5289    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5290         getLangOpts().CPlusPlus0x ?
5291           diag::warn_cxx98_compat_explicit_conversion_functions :
5292           diag::ext_explicit_conversion_functions)
5293      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5294}
5295
5296/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5297/// the declaration of the given C++ conversion function. This routine
5298/// is responsible for recording the conversion function in the C++
5299/// class, if possible.
5300Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5301  assert(Conversion && "Expected to receive a conversion function declaration");
5302
5303  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5304
5305  // Make sure we aren't redeclaring the conversion function.
5306  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5307
5308  // C++ [class.conv.fct]p1:
5309  //   [...] A conversion function is never used to convert a
5310  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5311  //   same object type (or a reference to it), to a (possibly
5312  //   cv-qualified) base class of that type (or a reference to it),
5313  //   or to (possibly cv-qualified) void.
5314  // FIXME: Suppress this warning if the conversion function ends up being a
5315  // virtual function that overrides a virtual function in a base class.
5316  QualType ClassType
5317    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5318  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5319    ConvType = ConvTypeRef->getPointeeType();
5320  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5321      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5322    /* Suppress diagnostics for instantiations. */;
5323  else if (ConvType->isRecordType()) {
5324    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5325    if (ConvType == ClassType)
5326      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5327        << ClassType;
5328    else if (IsDerivedFrom(ClassType, ConvType))
5329      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5330        <<  ClassType << ConvType;
5331  } else if (ConvType->isVoidType()) {
5332    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5333      << ClassType << ConvType;
5334  }
5335
5336  if (FunctionTemplateDecl *ConversionTemplate
5337                                = Conversion->getDescribedFunctionTemplate())
5338    return ConversionTemplate;
5339
5340  return Conversion;
5341}
5342
5343//===----------------------------------------------------------------------===//
5344// Namespace Handling
5345//===----------------------------------------------------------------------===//
5346
5347
5348
5349/// ActOnStartNamespaceDef - This is called at the start of a namespace
5350/// definition.
5351Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5352                                   SourceLocation InlineLoc,
5353                                   SourceLocation NamespaceLoc,
5354                                   SourceLocation IdentLoc,
5355                                   IdentifierInfo *II,
5356                                   SourceLocation LBrace,
5357                                   AttributeList *AttrList) {
5358  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5359  // For anonymous namespace, take the location of the left brace.
5360  SourceLocation Loc = II ? IdentLoc : LBrace;
5361  bool IsInline = InlineLoc.isValid();
5362  bool IsInvalid = false;
5363  bool IsStd = false;
5364  bool AddToKnown = false;
5365  Scope *DeclRegionScope = NamespcScope->getParent();
5366
5367  NamespaceDecl *PrevNS = 0;
5368  if (II) {
5369    // C++ [namespace.def]p2:
5370    //   The identifier in an original-namespace-definition shall not
5371    //   have been previously defined in the declarative region in
5372    //   which the original-namespace-definition appears. The
5373    //   identifier in an original-namespace-definition is the name of
5374    //   the namespace. Subsequently in that declarative region, it is
5375    //   treated as an original-namespace-name.
5376    //
5377    // Since namespace names are unique in their scope, and we don't
5378    // look through using directives, just look for any ordinary names.
5379
5380    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5381    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5382    Decl::IDNS_Namespace;
5383    NamedDecl *PrevDecl = 0;
5384    for (DeclContext::lookup_result R
5385         = CurContext->getRedeclContext()->lookup(II);
5386         R.first != R.second; ++R.first) {
5387      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5388        PrevDecl = *R.first;
5389        break;
5390      }
5391    }
5392
5393    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5394
5395    if (PrevNS) {
5396      // This is an extended namespace definition.
5397      if (IsInline != PrevNS->isInline()) {
5398        // inline-ness must match
5399        if (PrevNS->isInline()) {
5400          // The user probably just forgot the 'inline', so suggest that it
5401          // be added back.
5402          Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5403            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5404        } else {
5405          Diag(Loc, diag::err_inline_namespace_mismatch)
5406            << IsInline;
5407        }
5408        Diag(PrevNS->getLocation(), diag::note_previous_definition);
5409
5410        IsInline = PrevNS->isInline();
5411      }
5412    } else if (PrevDecl) {
5413      // This is an invalid name redefinition.
5414      Diag(Loc, diag::err_redefinition_different_kind)
5415        << II;
5416      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5417      IsInvalid = true;
5418      // Continue on to push Namespc as current DeclContext and return it.
5419    } else if (II->isStr("std") &&
5420               CurContext->getRedeclContext()->isTranslationUnit()) {
5421      // This is the first "real" definition of the namespace "std", so update
5422      // our cache of the "std" namespace to point at this definition.
5423      PrevNS = getStdNamespace();
5424      IsStd = true;
5425      AddToKnown = !IsInline;
5426    } else {
5427      // We've seen this namespace for the first time.
5428      AddToKnown = !IsInline;
5429    }
5430  } else {
5431    // Anonymous namespaces.
5432
5433    // Determine whether the parent already has an anonymous namespace.
5434    DeclContext *Parent = CurContext->getRedeclContext();
5435    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5436      PrevNS = TU->getAnonymousNamespace();
5437    } else {
5438      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5439      PrevNS = ND->getAnonymousNamespace();
5440    }
5441
5442    if (PrevNS && IsInline != PrevNS->isInline()) {
5443      // inline-ness must match
5444      Diag(Loc, diag::err_inline_namespace_mismatch)
5445        << IsInline;
5446      Diag(PrevNS->getLocation(), diag::note_previous_definition);
5447
5448      // Recover by ignoring the new namespace's inline status.
5449      IsInline = PrevNS->isInline();
5450    }
5451  }
5452
5453  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5454                                                 StartLoc, Loc, II, PrevNS);
5455  if (IsInvalid)
5456    Namespc->setInvalidDecl();
5457
5458  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5459
5460  // FIXME: Should we be merging attributes?
5461  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5462    PushNamespaceVisibilityAttr(Attr, Loc);
5463
5464  if (IsStd)
5465    StdNamespace = Namespc;
5466  if (AddToKnown)
5467    KnownNamespaces[Namespc] = false;
5468
5469  if (II) {
5470    PushOnScopeChains(Namespc, DeclRegionScope);
5471  } else {
5472    // Link the anonymous namespace into its parent.
5473    DeclContext *Parent = CurContext->getRedeclContext();
5474    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5475      TU->setAnonymousNamespace(Namespc);
5476    } else {
5477      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5478    }
5479
5480    CurContext->addDecl(Namespc);
5481
5482    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5483    //   behaves as if it were replaced by
5484    //     namespace unique { /* empty body */ }
5485    //     using namespace unique;
5486    //     namespace unique { namespace-body }
5487    //   where all occurrences of 'unique' in a translation unit are
5488    //   replaced by the same identifier and this identifier differs
5489    //   from all other identifiers in the entire program.
5490
5491    // We just create the namespace with an empty name and then add an
5492    // implicit using declaration, just like the standard suggests.
5493    //
5494    // CodeGen enforces the "universally unique" aspect by giving all
5495    // declarations semantically contained within an anonymous
5496    // namespace internal linkage.
5497
5498    if (!PrevNS) {
5499      UsingDirectiveDecl* UD
5500        = UsingDirectiveDecl::Create(Context, CurContext,
5501                                     /* 'using' */ LBrace,
5502                                     /* 'namespace' */ SourceLocation(),
5503                                     /* qualifier */ NestedNameSpecifierLoc(),
5504                                     /* identifier */ SourceLocation(),
5505                                     Namespc,
5506                                     /* Ancestor */ CurContext);
5507      UD->setImplicit();
5508      CurContext->addDecl(UD);
5509    }
5510  }
5511
5512  // Although we could have an invalid decl (i.e. the namespace name is a
5513  // redefinition), push it as current DeclContext and try to continue parsing.
5514  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5515  // for the namespace has the declarations that showed up in that particular
5516  // namespace definition.
5517  PushDeclContext(NamespcScope, Namespc);
5518  return Namespc;
5519}
5520
5521/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5522/// is a namespace alias, returns the namespace it points to.
5523static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5524  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5525    return AD->getNamespace();
5526  return dyn_cast_or_null<NamespaceDecl>(D);
5527}
5528
5529/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5530/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5531void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5532  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5533  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5534  Namespc->setRBraceLoc(RBrace);
5535  PopDeclContext();
5536  if (Namespc->hasAttr<VisibilityAttr>())
5537    PopPragmaVisibility(true, RBrace);
5538}
5539
5540CXXRecordDecl *Sema::getStdBadAlloc() const {
5541  return cast_or_null<CXXRecordDecl>(
5542                                  StdBadAlloc.get(Context.getExternalSource()));
5543}
5544
5545NamespaceDecl *Sema::getStdNamespace() const {
5546  return cast_or_null<NamespaceDecl>(
5547                                 StdNamespace.get(Context.getExternalSource()));
5548}
5549
5550/// \brief Retrieve the special "std" namespace, which may require us to
5551/// implicitly define the namespace.
5552NamespaceDecl *Sema::getOrCreateStdNamespace() {
5553  if (!StdNamespace) {
5554    // The "std" namespace has not yet been defined, so build one implicitly.
5555    StdNamespace = NamespaceDecl::Create(Context,
5556                                         Context.getTranslationUnitDecl(),
5557                                         /*Inline=*/false,
5558                                         SourceLocation(), SourceLocation(),
5559                                         &PP.getIdentifierTable().get("std"),
5560                                         /*PrevDecl=*/0);
5561    getStdNamespace()->setImplicit(true);
5562  }
5563
5564  return getStdNamespace();
5565}
5566
5567bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5568  assert(getLangOpts().CPlusPlus &&
5569         "Looking for std::initializer_list outside of C++.");
5570
5571  // We're looking for implicit instantiations of
5572  // template <typename E> class std::initializer_list.
5573
5574  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5575    return false;
5576
5577  ClassTemplateDecl *Template = 0;
5578  const TemplateArgument *Arguments = 0;
5579
5580  if (const RecordType *RT = Ty->getAs<RecordType>()) {
5581
5582    ClassTemplateSpecializationDecl *Specialization =
5583        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5584    if (!Specialization)
5585      return false;
5586
5587    Template = Specialization->getSpecializedTemplate();
5588    Arguments = Specialization->getTemplateArgs().data();
5589  } else if (const TemplateSpecializationType *TST =
5590                 Ty->getAs<TemplateSpecializationType>()) {
5591    Template = dyn_cast_or_null<ClassTemplateDecl>(
5592        TST->getTemplateName().getAsTemplateDecl());
5593    Arguments = TST->getArgs();
5594  }
5595  if (!Template)
5596    return false;
5597
5598  if (!StdInitializerList) {
5599    // Haven't recognized std::initializer_list yet, maybe this is it.
5600    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5601    if (TemplateClass->getIdentifier() !=
5602            &PP.getIdentifierTable().get("initializer_list") ||
5603        !getStdNamespace()->InEnclosingNamespaceSetOf(
5604            TemplateClass->getDeclContext()))
5605      return false;
5606    // This is a template called std::initializer_list, but is it the right
5607    // template?
5608    TemplateParameterList *Params = Template->getTemplateParameters();
5609    if (Params->getMinRequiredArguments() != 1)
5610      return false;
5611    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5612      return false;
5613
5614    // It's the right template.
5615    StdInitializerList = Template;
5616  }
5617
5618  if (Template != StdInitializerList)
5619    return false;
5620
5621  // This is an instance of std::initializer_list. Find the argument type.
5622  if (Element)
5623    *Element = Arguments[0].getAsType();
5624  return true;
5625}
5626
5627static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5628  NamespaceDecl *Std = S.getStdNamespace();
5629  if (!Std) {
5630    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5631    return 0;
5632  }
5633
5634  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5635                      Loc, Sema::LookupOrdinaryName);
5636  if (!S.LookupQualifiedName(Result, Std)) {
5637    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5638    return 0;
5639  }
5640  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5641  if (!Template) {
5642    Result.suppressDiagnostics();
5643    // We found something weird. Complain about the first thing we found.
5644    NamedDecl *Found = *Result.begin();
5645    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5646    return 0;
5647  }
5648
5649  // We found some template called std::initializer_list. Now verify that it's
5650  // correct.
5651  TemplateParameterList *Params = Template->getTemplateParameters();
5652  if (Params->getMinRequiredArguments() != 1 ||
5653      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5654    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5655    return 0;
5656  }
5657
5658  return Template;
5659}
5660
5661QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5662  if (!StdInitializerList) {
5663    StdInitializerList = LookupStdInitializerList(*this, Loc);
5664    if (!StdInitializerList)
5665      return QualType();
5666  }
5667
5668  TemplateArgumentListInfo Args(Loc, Loc);
5669  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5670                                       Context.getTrivialTypeSourceInfo(Element,
5671                                                                        Loc)));
5672  return Context.getCanonicalType(
5673      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5674}
5675
5676bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5677  // C++ [dcl.init.list]p2:
5678  //   A constructor is an initializer-list constructor if its first parameter
5679  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5680  //   std::initializer_list<E> for some type E, and either there are no other
5681  //   parameters or else all other parameters have default arguments.
5682  if (Ctor->getNumParams() < 1 ||
5683      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5684    return false;
5685
5686  QualType ArgType = Ctor->getParamDecl(0)->getType();
5687  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5688    ArgType = RT->getPointeeType().getUnqualifiedType();
5689
5690  return isStdInitializerList(ArgType, 0);
5691}
5692
5693/// \brief Determine whether a using statement is in a context where it will be
5694/// apply in all contexts.
5695static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5696  switch (CurContext->getDeclKind()) {
5697    case Decl::TranslationUnit:
5698      return true;
5699    case Decl::LinkageSpec:
5700      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5701    default:
5702      return false;
5703  }
5704}
5705
5706namespace {
5707
5708// Callback to only accept typo corrections that are namespaces.
5709class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5710 public:
5711  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5712    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5713      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5714    }
5715    return false;
5716  }
5717};
5718
5719}
5720
5721static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5722                                       CXXScopeSpec &SS,
5723                                       SourceLocation IdentLoc,
5724                                       IdentifierInfo *Ident) {
5725  NamespaceValidatorCCC Validator;
5726  R.clear();
5727  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5728                                               R.getLookupKind(), Sc, &SS,
5729                                               Validator)) {
5730    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5731    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5732    if (DeclContext *DC = S.computeDeclContext(SS, false))
5733      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5734        << Ident << DC << CorrectedQuotedStr << SS.getRange()
5735        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5736    else
5737      S.Diag(IdentLoc, diag::err_using_directive_suggest)
5738        << Ident << CorrectedQuotedStr
5739        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5740
5741    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5742         diag::note_namespace_defined_here) << CorrectedQuotedStr;
5743
5744    Ident = Corrected.getCorrectionAsIdentifierInfo();
5745    R.addDecl(Corrected.getCorrectionDecl());
5746    return true;
5747  }
5748  return false;
5749}
5750
5751Decl *Sema::ActOnUsingDirective(Scope *S,
5752                                          SourceLocation UsingLoc,
5753                                          SourceLocation NamespcLoc,
5754                                          CXXScopeSpec &SS,
5755                                          SourceLocation IdentLoc,
5756                                          IdentifierInfo *NamespcName,
5757                                          AttributeList *AttrList) {
5758  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5759  assert(NamespcName && "Invalid NamespcName.");
5760  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5761
5762  // This can only happen along a recovery path.
5763  while (S->getFlags() & Scope::TemplateParamScope)
5764    S = S->getParent();
5765  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5766
5767  UsingDirectiveDecl *UDir = 0;
5768  NestedNameSpecifier *Qualifier = 0;
5769  if (SS.isSet())
5770    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5771
5772  // Lookup namespace name.
5773  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5774  LookupParsedName(R, S, &SS);
5775  if (R.isAmbiguous())
5776    return 0;
5777
5778  if (R.empty()) {
5779    R.clear();
5780    // Allow "using namespace std;" or "using namespace ::std;" even if
5781    // "std" hasn't been defined yet, for GCC compatibility.
5782    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5783        NamespcName->isStr("std")) {
5784      Diag(IdentLoc, diag::ext_using_undefined_std);
5785      R.addDecl(getOrCreateStdNamespace());
5786      R.resolveKind();
5787    }
5788    // Otherwise, attempt typo correction.
5789    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5790  }
5791
5792  if (!R.empty()) {
5793    NamedDecl *Named = R.getFoundDecl();
5794    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5795        && "expected namespace decl");
5796    // C++ [namespace.udir]p1:
5797    //   A using-directive specifies that the names in the nominated
5798    //   namespace can be used in the scope in which the
5799    //   using-directive appears after the using-directive. During
5800    //   unqualified name lookup (3.4.1), the names appear as if they
5801    //   were declared in the nearest enclosing namespace which
5802    //   contains both the using-directive and the nominated
5803    //   namespace. [Note: in this context, "contains" means "contains
5804    //   directly or indirectly". ]
5805
5806    // Find enclosing context containing both using-directive and
5807    // nominated namespace.
5808    NamespaceDecl *NS = getNamespaceDecl(Named);
5809    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5810    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5811      CommonAncestor = CommonAncestor->getParent();
5812
5813    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5814                                      SS.getWithLocInContext(Context),
5815                                      IdentLoc, Named, CommonAncestor);
5816
5817    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5818        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5819      Diag(IdentLoc, diag::warn_using_directive_in_header);
5820    }
5821
5822    PushUsingDirective(S, UDir);
5823  } else {
5824    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5825  }
5826
5827  // FIXME: We ignore attributes for now.
5828  return UDir;
5829}
5830
5831void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5832  // If the scope has an associated entity and the using directive is at
5833  // namespace or translation unit scope, add the UsingDirectiveDecl into
5834  // its lookup structure so qualified name lookup can find it.
5835  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5836  if (Ctx && !Ctx->isFunctionOrMethod())
5837    Ctx->addDecl(UDir);
5838  else
5839    // Otherwise, it is at block sope. The using-directives will affect lookup
5840    // only to the end of the scope.
5841    S->PushUsingDirective(UDir);
5842}
5843
5844
5845Decl *Sema::ActOnUsingDeclaration(Scope *S,
5846                                  AccessSpecifier AS,
5847                                  bool HasUsingKeyword,
5848                                  SourceLocation UsingLoc,
5849                                  CXXScopeSpec &SS,
5850                                  UnqualifiedId &Name,
5851                                  AttributeList *AttrList,
5852                                  bool IsTypeName,
5853                                  SourceLocation TypenameLoc) {
5854  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5855
5856  switch (Name.getKind()) {
5857  case UnqualifiedId::IK_ImplicitSelfParam:
5858  case UnqualifiedId::IK_Identifier:
5859  case UnqualifiedId::IK_OperatorFunctionId:
5860  case UnqualifiedId::IK_LiteralOperatorId:
5861  case UnqualifiedId::IK_ConversionFunctionId:
5862    break;
5863
5864  case UnqualifiedId::IK_ConstructorName:
5865  case UnqualifiedId::IK_ConstructorTemplateId:
5866    // C++0x inherited constructors.
5867    Diag(Name.getLocStart(),
5868         getLangOpts().CPlusPlus0x ?
5869           diag::warn_cxx98_compat_using_decl_constructor :
5870           diag::err_using_decl_constructor)
5871      << SS.getRange();
5872
5873    if (getLangOpts().CPlusPlus0x) break;
5874
5875    return 0;
5876
5877  case UnqualifiedId::IK_DestructorName:
5878    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5879      << SS.getRange();
5880    return 0;
5881
5882  case UnqualifiedId::IK_TemplateId:
5883    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5884      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5885    return 0;
5886  }
5887
5888  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5889  DeclarationName TargetName = TargetNameInfo.getName();
5890  if (!TargetName)
5891    return 0;
5892
5893  // Warn about using declarations.
5894  // TODO: store that the declaration was written without 'using' and
5895  // talk about access decls instead of using decls in the
5896  // diagnostics.
5897  if (!HasUsingKeyword) {
5898    UsingLoc = Name.getLocStart();
5899
5900    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5901      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5902  }
5903
5904  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5905      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5906    return 0;
5907
5908  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5909                                        TargetNameInfo, AttrList,
5910                                        /* IsInstantiation */ false,
5911                                        IsTypeName, TypenameLoc);
5912  if (UD)
5913    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5914
5915  return UD;
5916}
5917
5918/// \brief Determine whether a using declaration considers the given
5919/// declarations as "equivalent", e.g., if they are redeclarations of
5920/// the same entity or are both typedefs of the same type.
5921static bool
5922IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5923                         bool &SuppressRedeclaration) {
5924  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5925    SuppressRedeclaration = false;
5926    return true;
5927  }
5928
5929  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5930    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5931      SuppressRedeclaration = true;
5932      return Context.hasSameType(TD1->getUnderlyingType(),
5933                                 TD2->getUnderlyingType());
5934    }
5935
5936  return false;
5937}
5938
5939
5940/// Determines whether to create a using shadow decl for a particular
5941/// decl, given the set of decls existing prior to this using lookup.
5942bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5943                                const LookupResult &Previous) {
5944  // Diagnose finding a decl which is not from a base class of the
5945  // current class.  We do this now because there are cases where this
5946  // function will silently decide not to build a shadow decl, which
5947  // will pre-empt further diagnostics.
5948  //
5949  // We don't need to do this in C++0x because we do the check once on
5950  // the qualifier.
5951  //
5952  // FIXME: diagnose the following if we care enough:
5953  //   struct A { int foo; };
5954  //   struct B : A { using A::foo; };
5955  //   template <class T> struct C : A {};
5956  //   template <class T> struct D : C<T> { using B::foo; } // <---
5957  // This is invalid (during instantiation) in C++03 because B::foo
5958  // resolves to the using decl in B, which is not a base class of D<T>.
5959  // We can't diagnose it immediately because C<T> is an unknown
5960  // specialization.  The UsingShadowDecl in D<T> then points directly
5961  // to A::foo, which will look well-formed when we instantiate.
5962  // The right solution is to not collapse the shadow-decl chain.
5963  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
5964    DeclContext *OrigDC = Orig->getDeclContext();
5965
5966    // Handle enums and anonymous structs.
5967    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5968    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5969    while (OrigRec->isAnonymousStructOrUnion())
5970      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5971
5972    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5973      if (OrigDC == CurContext) {
5974        Diag(Using->getLocation(),
5975             diag::err_using_decl_nested_name_specifier_is_current_class)
5976          << Using->getQualifierLoc().getSourceRange();
5977        Diag(Orig->getLocation(), diag::note_using_decl_target);
5978        return true;
5979      }
5980
5981      Diag(Using->getQualifierLoc().getBeginLoc(),
5982           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5983        << Using->getQualifier()
5984        << cast<CXXRecordDecl>(CurContext)
5985        << Using->getQualifierLoc().getSourceRange();
5986      Diag(Orig->getLocation(), diag::note_using_decl_target);
5987      return true;
5988    }
5989  }
5990
5991  if (Previous.empty()) return false;
5992
5993  NamedDecl *Target = Orig;
5994  if (isa<UsingShadowDecl>(Target))
5995    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5996
5997  // If the target happens to be one of the previous declarations, we
5998  // don't have a conflict.
5999  //
6000  // FIXME: but we might be increasing its access, in which case we
6001  // should redeclare it.
6002  NamedDecl *NonTag = 0, *Tag = 0;
6003  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6004         I != E; ++I) {
6005    NamedDecl *D = (*I)->getUnderlyingDecl();
6006    bool Result;
6007    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6008      return Result;
6009
6010    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6011  }
6012
6013  if (Target->isFunctionOrFunctionTemplate()) {
6014    FunctionDecl *FD;
6015    if (isa<FunctionTemplateDecl>(Target))
6016      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6017    else
6018      FD = cast<FunctionDecl>(Target);
6019
6020    NamedDecl *OldDecl = 0;
6021    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6022    case Ovl_Overload:
6023      return false;
6024
6025    case Ovl_NonFunction:
6026      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6027      break;
6028
6029    // We found a decl with the exact signature.
6030    case Ovl_Match:
6031      // If we're in a record, we want to hide the target, so we
6032      // return true (without a diagnostic) to tell the caller not to
6033      // build a shadow decl.
6034      if (CurContext->isRecord())
6035        return true;
6036
6037      // If we're not in a record, this is an error.
6038      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6039      break;
6040    }
6041
6042    Diag(Target->getLocation(), diag::note_using_decl_target);
6043    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6044    return true;
6045  }
6046
6047  // Target is not a function.
6048
6049  if (isa<TagDecl>(Target)) {
6050    // No conflict between a tag and a non-tag.
6051    if (!Tag) return false;
6052
6053    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6054    Diag(Target->getLocation(), diag::note_using_decl_target);
6055    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6056    return true;
6057  }
6058
6059  // No conflict between a tag and a non-tag.
6060  if (!NonTag) return false;
6061
6062  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6063  Diag(Target->getLocation(), diag::note_using_decl_target);
6064  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6065  return true;
6066}
6067
6068/// Builds a shadow declaration corresponding to a 'using' declaration.
6069UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6070                                            UsingDecl *UD,
6071                                            NamedDecl *Orig) {
6072
6073  // If we resolved to another shadow declaration, just coalesce them.
6074  NamedDecl *Target = Orig;
6075  if (isa<UsingShadowDecl>(Target)) {
6076    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6077    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6078  }
6079
6080  UsingShadowDecl *Shadow
6081    = UsingShadowDecl::Create(Context, CurContext,
6082                              UD->getLocation(), UD, Target);
6083  UD->addShadowDecl(Shadow);
6084
6085  Shadow->setAccess(UD->getAccess());
6086  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6087    Shadow->setInvalidDecl();
6088
6089  if (S)
6090    PushOnScopeChains(Shadow, S);
6091  else
6092    CurContext->addDecl(Shadow);
6093
6094
6095  return Shadow;
6096}
6097
6098/// Hides a using shadow declaration.  This is required by the current
6099/// using-decl implementation when a resolvable using declaration in a
6100/// class is followed by a declaration which would hide or override
6101/// one or more of the using decl's targets; for example:
6102///
6103///   struct Base { void foo(int); };
6104///   struct Derived : Base {
6105///     using Base::foo;
6106///     void foo(int);
6107///   };
6108///
6109/// The governing language is C++03 [namespace.udecl]p12:
6110///
6111///   When a using-declaration brings names from a base class into a
6112///   derived class scope, member functions in the derived class
6113///   override and/or hide member functions with the same name and
6114///   parameter types in a base class (rather than conflicting).
6115///
6116/// There are two ways to implement this:
6117///   (1) optimistically create shadow decls when they're not hidden
6118///       by existing declarations, or
6119///   (2) don't create any shadow decls (or at least don't make them
6120///       visible) until we've fully parsed/instantiated the class.
6121/// The problem with (1) is that we might have to retroactively remove
6122/// a shadow decl, which requires several O(n) operations because the
6123/// decl structures are (very reasonably) not designed for removal.
6124/// (2) avoids this but is very fiddly and phase-dependent.
6125void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6126  if (Shadow->getDeclName().getNameKind() ==
6127        DeclarationName::CXXConversionFunctionName)
6128    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6129
6130  // Remove it from the DeclContext...
6131  Shadow->getDeclContext()->removeDecl(Shadow);
6132
6133  // ...and the scope, if applicable...
6134  if (S) {
6135    S->RemoveDecl(Shadow);
6136    IdResolver.RemoveDecl(Shadow);
6137  }
6138
6139  // ...and the using decl.
6140  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6141
6142  // TODO: complain somehow if Shadow was used.  It shouldn't
6143  // be possible for this to happen, because...?
6144}
6145
6146/// Builds a using declaration.
6147///
6148/// \param IsInstantiation - Whether this call arises from an
6149///   instantiation of an unresolved using declaration.  We treat
6150///   the lookup differently for these declarations.
6151NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6152                                       SourceLocation UsingLoc,
6153                                       CXXScopeSpec &SS,
6154                                       const DeclarationNameInfo &NameInfo,
6155                                       AttributeList *AttrList,
6156                                       bool IsInstantiation,
6157                                       bool IsTypeName,
6158                                       SourceLocation TypenameLoc) {
6159  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6160  SourceLocation IdentLoc = NameInfo.getLoc();
6161  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6162
6163  // FIXME: We ignore attributes for now.
6164
6165  if (SS.isEmpty()) {
6166    Diag(IdentLoc, diag::err_using_requires_qualname);
6167    return 0;
6168  }
6169
6170  // Do the redeclaration lookup in the current scope.
6171  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6172                        ForRedeclaration);
6173  Previous.setHideTags(false);
6174  if (S) {
6175    LookupName(Previous, S);
6176
6177    // It is really dumb that we have to do this.
6178    LookupResult::Filter F = Previous.makeFilter();
6179    while (F.hasNext()) {
6180      NamedDecl *D = F.next();
6181      if (!isDeclInScope(D, CurContext, S))
6182        F.erase();
6183    }
6184    F.done();
6185  } else {
6186    assert(IsInstantiation && "no scope in non-instantiation");
6187    assert(CurContext->isRecord() && "scope not record in instantiation");
6188    LookupQualifiedName(Previous, CurContext);
6189  }
6190
6191  // Check for invalid redeclarations.
6192  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6193    return 0;
6194
6195  // Check for bad qualifiers.
6196  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6197    return 0;
6198
6199  DeclContext *LookupContext = computeDeclContext(SS);
6200  NamedDecl *D;
6201  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6202  if (!LookupContext) {
6203    if (IsTypeName) {
6204      // FIXME: not all declaration name kinds are legal here
6205      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6206                                              UsingLoc, TypenameLoc,
6207                                              QualifierLoc,
6208                                              IdentLoc, NameInfo.getName());
6209    } else {
6210      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6211                                           QualifierLoc, NameInfo);
6212    }
6213  } else {
6214    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6215                          NameInfo, IsTypeName);
6216  }
6217  D->setAccess(AS);
6218  CurContext->addDecl(D);
6219
6220  if (!LookupContext) return D;
6221  UsingDecl *UD = cast<UsingDecl>(D);
6222
6223  if (RequireCompleteDeclContext(SS, LookupContext)) {
6224    UD->setInvalidDecl();
6225    return UD;
6226  }
6227
6228  // Constructor inheriting using decls get special treatment.
6229  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6230    if (CheckInheritedConstructorUsingDecl(UD))
6231      UD->setInvalidDecl();
6232    return UD;
6233  }
6234
6235  // Otherwise, look up the target name.
6236
6237  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6238
6239  // Unlike most lookups, we don't always want to hide tag
6240  // declarations: tag names are visible through the using declaration
6241  // even if hidden by ordinary names, *except* in a dependent context
6242  // where it's important for the sanity of two-phase lookup.
6243  if (!IsInstantiation)
6244    R.setHideTags(false);
6245
6246  LookupQualifiedName(R, LookupContext);
6247
6248  if (R.empty()) {
6249    Diag(IdentLoc, diag::err_no_member)
6250      << NameInfo.getName() << LookupContext << SS.getRange();
6251    UD->setInvalidDecl();
6252    return UD;
6253  }
6254
6255  if (R.isAmbiguous()) {
6256    UD->setInvalidDecl();
6257    return UD;
6258  }
6259
6260  if (IsTypeName) {
6261    // If we asked for a typename and got a non-type decl, error out.
6262    if (!R.getAsSingle<TypeDecl>()) {
6263      Diag(IdentLoc, diag::err_using_typename_non_type);
6264      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6265        Diag((*I)->getUnderlyingDecl()->getLocation(),
6266             diag::note_using_decl_target);
6267      UD->setInvalidDecl();
6268      return UD;
6269    }
6270  } else {
6271    // If we asked for a non-typename and we got a type, error out,
6272    // but only if this is an instantiation of an unresolved using
6273    // decl.  Otherwise just silently find the type name.
6274    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6275      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6276      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6277      UD->setInvalidDecl();
6278      return UD;
6279    }
6280  }
6281
6282  // C++0x N2914 [namespace.udecl]p6:
6283  // A using-declaration shall not name a namespace.
6284  if (R.getAsSingle<NamespaceDecl>()) {
6285    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6286      << SS.getRange();
6287    UD->setInvalidDecl();
6288    return UD;
6289  }
6290
6291  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6292    if (!CheckUsingShadowDecl(UD, *I, Previous))
6293      BuildUsingShadowDecl(S, UD, *I);
6294  }
6295
6296  return UD;
6297}
6298
6299/// Additional checks for a using declaration referring to a constructor name.
6300bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6301  if (UD->isTypeName()) {
6302    // FIXME: Cannot specify typename when specifying constructor
6303    return true;
6304  }
6305
6306  const Type *SourceType = UD->getQualifier()->getAsType();
6307  assert(SourceType &&
6308         "Using decl naming constructor doesn't have type in scope spec.");
6309  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6310
6311  // Check whether the named type is a direct base class.
6312  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6313  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6314  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6315       BaseIt != BaseE; ++BaseIt) {
6316    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6317    if (CanonicalSourceType == BaseType)
6318      break;
6319  }
6320
6321  if (BaseIt == BaseE) {
6322    // Did not find SourceType in the bases.
6323    Diag(UD->getUsingLocation(),
6324         diag::err_using_decl_constructor_not_in_direct_base)
6325      << UD->getNameInfo().getSourceRange()
6326      << QualType(SourceType, 0) << TargetClass;
6327    return true;
6328  }
6329
6330  BaseIt->setInheritConstructors();
6331
6332  return false;
6333}
6334
6335/// Checks that the given using declaration is not an invalid
6336/// redeclaration.  Note that this is checking only for the using decl
6337/// itself, not for any ill-formedness among the UsingShadowDecls.
6338bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6339                                       bool isTypeName,
6340                                       const CXXScopeSpec &SS,
6341                                       SourceLocation NameLoc,
6342                                       const LookupResult &Prev) {
6343  // C++03 [namespace.udecl]p8:
6344  // C++0x [namespace.udecl]p10:
6345  //   A using-declaration is a declaration and can therefore be used
6346  //   repeatedly where (and only where) multiple declarations are
6347  //   allowed.
6348  //
6349  // That's in non-member contexts.
6350  if (!CurContext->getRedeclContext()->isRecord())
6351    return false;
6352
6353  NestedNameSpecifier *Qual
6354    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6355
6356  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6357    NamedDecl *D = *I;
6358
6359    bool DTypename;
6360    NestedNameSpecifier *DQual;
6361    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6362      DTypename = UD->isTypeName();
6363      DQual = UD->getQualifier();
6364    } else if (UnresolvedUsingValueDecl *UD
6365                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6366      DTypename = false;
6367      DQual = UD->getQualifier();
6368    } else if (UnresolvedUsingTypenameDecl *UD
6369                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6370      DTypename = true;
6371      DQual = UD->getQualifier();
6372    } else continue;
6373
6374    // using decls differ if one says 'typename' and the other doesn't.
6375    // FIXME: non-dependent using decls?
6376    if (isTypeName != DTypename) continue;
6377
6378    // using decls differ if they name different scopes (but note that
6379    // template instantiation can cause this check to trigger when it
6380    // didn't before instantiation).
6381    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6382        Context.getCanonicalNestedNameSpecifier(DQual))
6383      continue;
6384
6385    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6386    Diag(D->getLocation(), diag::note_using_decl) << 1;
6387    return true;
6388  }
6389
6390  return false;
6391}
6392
6393
6394/// Checks that the given nested-name qualifier used in a using decl
6395/// in the current context is appropriately related to the current
6396/// scope.  If an error is found, diagnoses it and returns true.
6397bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6398                                   const CXXScopeSpec &SS,
6399                                   SourceLocation NameLoc) {
6400  DeclContext *NamedContext = computeDeclContext(SS);
6401
6402  if (!CurContext->isRecord()) {
6403    // C++03 [namespace.udecl]p3:
6404    // C++0x [namespace.udecl]p8:
6405    //   A using-declaration for a class member shall be a member-declaration.
6406
6407    // If we weren't able to compute a valid scope, it must be a
6408    // dependent class scope.
6409    if (!NamedContext || NamedContext->isRecord()) {
6410      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6411        << SS.getRange();
6412      return true;
6413    }
6414
6415    // Otherwise, everything is known to be fine.
6416    return false;
6417  }
6418
6419  // The current scope is a record.
6420
6421  // If the named context is dependent, we can't decide much.
6422  if (!NamedContext) {
6423    // FIXME: in C++0x, we can diagnose if we can prove that the
6424    // nested-name-specifier does not refer to a base class, which is
6425    // still possible in some cases.
6426
6427    // Otherwise we have to conservatively report that things might be
6428    // okay.
6429    return false;
6430  }
6431
6432  if (!NamedContext->isRecord()) {
6433    // Ideally this would point at the last name in the specifier,
6434    // but we don't have that level of source info.
6435    Diag(SS.getRange().getBegin(),
6436         diag::err_using_decl_nested_name_specifier_is_not_class)
6437      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6438    return true;
6439  }
6440
6441  if (!NamedContext->isDependentContext() &&
6442      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6443    return true;
6444
6445  if (getLangOpts().CPlusPlus0x) {
6446    // C++0x [namespace.udecl]p3:
6447    //   In a using-declaration used as a member-declaration, the
6448    //   nested-name-specifier shall name a base class of the class
6449    //   being defined.
6450
6451    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6452                                 cast<CXXRecordDecl>(NamedContext))) {
6453      if (CurContext == NamedContext) {
6454        Diag(NameLoc,
6455             diag::err_using_decl_nested_name_specifier_is_current_class)
6456          << SS.getRange();
6457        return true;
6458      }
6459
6460      Diag(SS.getRange().getBegin(),
6461           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6462        << (NestedNameSpecifier*) SS.getScopeRep()
6463        << cast<CXXRecordDecl>(CurContext)
6464        << SS.getRange();
6465      return true;
6466    }
6467
6468    return false;
6469  }
6470
6471  // C++03 [namespace.udecl]p4:
6472  //   A using-declaration used as a member-declaration shall refer
6473  //   to a member of a base class of the class being defined [etc.].
6474
6475  // Salient point: SS doesn't have to name a base class as long as
6476  // lookup only finds members from base classes.  Therefore we can
6477  // diagnose here only if we can prove that that can't happen,
6478  // i.e. if the class hierarchies provably don't intersect.
6479
6480  // TODO: it would be nice if "definitely valid" results were cached
6481  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6482  // need to be repeated.
6483
6484  struct UserData {
6485    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6486
6487    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6488      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6489      Data->Bases.insert(Base);
6490      return true;
6491    }
6492
6493    bool hasDependentBases(const CXXRecordDecl *Class) {
6494      return !Class->forallBases(collect, this);
6495    }
6496
6497    /// Returns true if the base is dependent or is one of the
6498    /// accumulated base classes.
6499    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6500      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6501      return !Data->Bases.count(Base);
6502    }
6503
6504    bool mightShareBases(const CXXRecordDecl *Class) {
6505      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6506    }
6507  };
6508
6509  UserData Data;
6510
6511  // Returns false if we find a dependent base.
6512  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6513    return false;
6514
6515  // Returns false if the class has a dependent base or if it or one
6516  // of its bases is present in the base set of the current context.
6517  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6518    return false;
6519
6520  Diag(SS.getRange().getBegin(),
6521       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6522    << (NestedNameSpecifier*) SS.getScopeRep()
6523    << cast<CXXRecordDecl>(CurContext)
6524    << SS.getRange();
6525
6526  return true;
6527}
6528
6529Decl *Sema::ActOnAliasDeclaration(Scope *S,
6530                                  AccessSpecifier AS,
6531                                  MultiTemplateParamsArg TemplateParamLists,
6532                                  SourceLocation UsingLoc,
6533                                  UnqualifiedId &Name,
6534                                  TypeResult Type) {
6535  // Skip up to the relevant declaration scope.
6536  while (S->getFlags() & Scope::TemplateParamScope)
6537    S = S->getParent();
6538  assert((S->getFlags() & Scope::DeclScope) &&
6539         "got alias-declaration outside of declaration scope");
6540
6541  if (Type.isInvalid())
6542    return 0;
6543
6544  bool Invalid = false;
6545  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6546  TypeSourceInfo *TInfo = 0;
6547  GetTypeFromParser(Type.get(), &TInfo);
6548
6549  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6550    return 0;
6551
6552  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6553                                      UPPC_DeclarationType)) {
6554    Invalid = true;
6555    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6556                                             TInfo->getTypeLoc().getBeginLoc());
6557  }
6558
6559  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6560  LookupName(Previous, S);
6561
6562  // Warn about shadowing the name of a template parameter.
6563  if (Previous.isSingleResult() &&
6564      Previous.getFoundDecl()->isTemplateParameter()) {
6565    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6566    Previous.clear();
6567  }
6568
6569  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6570         "name in alias declaration must be an identifier");
6571  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6572                                               Name.StartLocation,
6573                                               Name.Identifier, TInfo);
6574
6575  NewTD->setAccess(AS);
6576
6577  if (Invalid)
6578    NewTD->setInvalidDecl();
6579
6580  CheckTypedefForVariablyModifiedType(S, NewTD);
6581  Invalid |= NewTD->isInvalidDecl();
6582
6583  bool Redeclaration = false;
6584
6585  NamedDecl *NewND;
6586  if (TemplateParamLists.size()) {
6587    TypeAliasTemplateDecl *OldDecl = 0;
6588    TemplateParameterList *OldTemplateParams = 0;
6589
6590    if (TemplateParamLists.size() != 1) {
6591      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6592        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6593         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6594    }
6595    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6596
6597    // Only consider previous declarations in the same scope.
6598    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6599                         /*ExplicitInstantiationOrSpecialization*/false);
6600    if (!Previous.empty()) {
6601      Redeclaration = true;
6602
6603      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6604      if (!OldDecl && !Invalid) {
6605        Diag(UsingLoc, diag::err_redefinition_different_kind)
6606          << Name.Identifier;
6607
6608        NamedDecl *OldD = Previous.getRepresentativeDecl();
6609        if (OldD->getLocation().isValid())
6610          Diag(OldD->getLocation(), diag::note_previous_definition);
6611
6612        Invalid = true;
6613      }
6614
6615      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6616        if (TemplateParameterListsAreEqual(TemplateParams,
6617                                           OldDecl->getTemplateParameters(),
6618                                           /*Complain=*/true,
6619                                           TPL_TemplateMatch))
6620          OldTemplateParams = OldDecl->getTemplateParameters();
6621        else
6622          Invalid = true;
6623
6624        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6625        if (!Invalid &&
6626            !Context.hasSameType(OldTD->getUnderlyingType(),
6627                                 NewTD->getUnderlyingType())) {
6628          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6629          // but we can't reasonably accept it.
6630          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6631            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6632          if (OldTD->getLocation().isValid())
6633            Diag(OldTD->getLocation(), diag::note_previous_definition);
6634          Invalid = true;
6635        }
6636      }
6637    }
6638
6639    // Merge any previous default template arguments into our parameters,
6640    // and check the parameter list.
6641    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6642                                   TPC_TypeAliasTemplate))
6643      return 0;
6644
6645    TypeAliasTemplateDecl *NewDecl =
6646      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6647                                    Name.Identifier, TemplateParams,
6648                                    NewTD);
6649
6650    NewDecl->setAccess(AS);
6651
6652    if (Invalid)
6653      NewDecl->setInvalidDecl();
6654    else if (OldDecl)
6655      NewDecl->setPreviousDeclaration(OldDecl);
6656
6657    NewND = NewDecl;
6658  } else {
6659    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6660    NewND = NewTD;
6661  }
6662
6663  if (!Redeclaration)
6664    PushOnScopeChains(NewND, S);
6665
6666  return NewND;
6667}
6668
6669Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6670                                             SourceLocation NamespaceLoc,
6671                                             SourceLocation AliasLoc,
6672                                             IdentifierInfo *Alias,
6673                                             CXXScopeSpec &SS,
6674                                             SourceLocation IdentLoc,
6675                                             IdentifierInfo *Ident) {
6676
6677  // Lookup the namespace name.
6678  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6679  LookupParsedName(R, S, &SS);
6680
6681  // Check if we have a previous declaration with the same name.
6682  NamedDecl *PrevDecl
6683    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6684                       ForRedeclaration);
6685  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6686    PrevDecl = 0;
6687
6688  if (PrevDecl) {
6689    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6690      // We already have an alias with the same name that points to the same
6691      // namespace, so don't create a new one.
6692      // FIXME: At some point, we'll want to create the (redundant)
6693      // declaration to maintain better source information.
6694      if (!R.isAmbiguous() && !R.empty() &&
6695          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6696        return 0;
6697    }
6698
6699    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6700      diag::err_redefinition_different_kind;
6701    Diag(AliasLoc, DiagID) << Alias;
6702    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6703    return 0;
6704  }
6705
6706  if (R.isAmbiguous())
6707    return 0;
6708
6709  if (R.empty()) {
6710    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6711      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
6712      return 0;
6713    }
6714  }
6715
6716  NamespaceAliasDecl *AliasDecl =
6717    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6718                               Alias, SS.getWithLocInContext(Context),
6719                               IdentLoc, R.getFoundDecl());
6720
6721  PushOnScopeChains(AliasDecl, S);
6722  return AliasDecl;
6723}
6724
6725namespace {
6726  /// \brief Scoped object used to handle the state changes required in Sema
6727  /// to implicitly define the body of a C++ member function;
6728  class ImplicitlyDefinedFunctionScope {
6729    Sema &S;
6730    Sema::ContextRAII SavedContext;
6731
6732  public:
6733    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6734      : S(S), SavedContext(S, Method)
6735    {
6736      S.PushFunctionScope();
6737      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6738    }
6739
6740    ~ImplicitlyDefinedFunctionScope() {
6741      S.PopExpressionEvaluationContext();
6742      S.PopFunctionScopeInfo();
6743    }
6744  };
6745}
6746
6747Sema::ImplicitExceptionSpecification
6748Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6749  // C++ [except.spec]p14:
6750  //   An implicitly declared special member function (Clause 12) shall have an
6751  //   exception-specification. [...]
6752  ImplicitExceptionSpecification ExceptSpec(Context);
6753  if (ClassDecl->isInvalidDecl())
6754    return ExceptSpec;
6755
6756  // Direct base-class constructors.
6757  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6758                                       BEnd = ClassDecl->bases_end();
6759       B != BEnd; ++B) {
6760    if (B->isVirtual()) // Handled below.
6761      continue;
6762
6763    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6764      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6765      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6766      // If this is a deleted function, add it anyway. This might be conformant
6767      // with the standard. This might not. I'm not sure. It might not matter.
6768      if (Constructor)
6769        ExceptSpec.CalledDecl(Constructor);
6770    }
6771  }
6772
6773  // Virtual base-class constructors.
6774  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6775                                       BEnd = ClassDecl->vbases_end();
6776       B != BEnd; ++B) {
6777    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6778      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6779      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6780      // If this is a deleted function, add it anyway. This might be conformant
6781      // with the standard. This might not. I'm not sure. It might not matter.
6782      if (Constructor)
6783        ExceptSpec.CalledDecl(Constructor);
6784    }
6785  }
6786
6787  // Field constructors.
6788  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6789                               FEnd = ClassDecl->field_end();
6790       F != FEnd; ++F) {
6791    if (F->hasInClassInitializer()) {
6792      if (Expr *E = F->getInClassInitializer())
6793        ExceptSpec.CalledExpr(E);
6794      else if (!F->isInvalidDecl())
6795        ExceptSpec.SetDelayed();
6796    } else if (const RecordType *RecordTy
6797              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6798      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6799      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6800      // If this is a deleted function, add it anyway. This might be conformant
6801      // with the standard. This might not. I'm not sure. It might not matter.
6802      // In particular, the problem is that this function never gets called. It
6803      // might just be ill-formed because this function attempts to refer to
6804      // a deleted function here.
6805      if (Constructor)
6806        ExceptSpec.CalledDecl(Constructor);
6807    }
6808  }
6809
6810  return ExceptSpec;
6811}
6812
6813CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6814                                                     CXXRecordDecl *ClassDecl) {
6815  // C++ [class.ctor]p5:
6816  //   A default constructor for a class X is a constructor of class X
6817  //   that can be called without an argument. If there is no
6818  //   user-declared constructor for class X, a default constructor is
6819  //   implicitly declared. An implicitly-declared default constructor
6820  //   is an inline public member of its class.
6821  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6822         "Should not build implicit default constructor!");
6823
6824  ImplicitExceptionSpecification Spec =
6825    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6826  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6827
6828  // Create the actual constructor declaration.
6829  CanQualType ClassType
6830    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6831  SourceLocation ClassLoc = ClassDecl->getLocation();
6832  DeclarationName Name
6833    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6834  DeclarationNameInfo NameInfo(Name, ClassLoc);
6835  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6836      Context, ClassDecl, ClassLoc, NameInfo,
6837      Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6838      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6839      /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
6840        getLangOpts().CPlusPlus0x);
6841  DefaultCon->setAccess(AS_public);
6842  DefaultCon->setDefaulted();
6843  DefaultCon->setImplicit();
6844  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6845
6846  // Note that we have declared this constructor.
6847  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6848
6849  if (Scope *S = getScopeForContext(ClassDecl))
6850    PushOnScopeChains(DefaultCon, S, false);
6851  ClassDecl->addDecl(DefaultCon);
6852
6853  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6854    DefaultCon->setDeletedAsWritten();
6855
6856  return DefaultCon;
6857}
6858
6859void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6860                                            CXXConstructorDecl *Constructor) {
6861  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6862          !Constructor->doesThisDeclarationHaveABody() &&
6863          !Constructor->isDeleted()) &&
6864    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6865
6866  CXXRecordDecl *ClassDecl = Constructor->getParent();
6867  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6868
6869  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6870  DiagnosticErrorTrap Trap(Diags);
6871  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6872      Trap.hasErrorOccurred()) {
6873    Diag(CurrentLocation, diag::note_member_synthesized_at)
6874      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6875    Constructor->setInvalidDecl();
6876    return;
6877  }
6878
6879  SourceLocation Loc = Constructor->getLocation();
6880  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6881
6882  Constructor->setUsed();
6883  MarkVTableUsed(CurrentLocation, ClassDecl);
6884
6885  if (ASTMutationListener *L = getASTMutationListener()) {
6886    L->CompletedImplicitDefinition(Constructor);
6887  }
6888}
6889
6890/// Get any existing defaulted default constructor for the given class. Do not
6891/// implicitly define one if it does not exist.
6892static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6893                                                             CXXRecordDecl *D) {
6894  ASTContext &Context = Self.Context;
6895  QualType ClassType = Context.getTypeDeclType(D);
6896  DeclarationName ConstructorName
6897    = Context.DeclarationNames.getCXXConstructorName(
6898                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6899
6900  DeclContext::lookup_const_iterator Con, ConEnd;
6901  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6902       Con != ConEnd; ++Con) {
6903    // A function template cannot be defaulted.
6904    if (isa<FunctionTemplateDecl>(*Con))
6905      continue;
6906
6907    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6908    if (Constructor->isDefaultConstructor())
6909      return Constructor->isDefaulted() ? Constructor : 0;
6910  }
6911  return 0;
6912}
6913
6914void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6915  if (!D) return;
6916  AdjustDeclIfTemplate(D);
6917
6918  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6919  CXXConstructorDecl *CtorDecl
6920    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6921
6922  if (!CtorDecl) return;
6923
6924  // Compute the exception specification for the default constructor.
6925  const FunctionProtoType *CtorTy =
6926    CtorDecl->getType()->castAs<FunctionProtoType>();
6927  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6928    ImplicitExceptionSpecification Spec =
6929      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6930    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6931    assert(EPI.ExceptionSpecType != EST_Delayed);
6932
6933    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6934  }
6935
6936  // If the default constructor is explicitly defaulted, checking the exception
6937  // specification is deferred until now.
6938  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6939      !ClassDecl->isDependentType())
6940    CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6941}
6942
6943void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6944  // We start with an initial pass over the base classes to collect those that
6945  // inherit constructors from. If there are none, we can forgo all further
6946  // processing.
6947  typedef SmallVector<const RecordType *, 4> BasesVector;
6948  BasesVector BasesToInheritFrom;
6949  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6950                                          BaseE = ClassDecl->bases_end();
6951         BaseIt != BaseE; ++BaseIt) {
6952    if (BaseIt->getInheritConstructors()) {
6953      QualType Base = BaseIt->getType();
6954      if (Base->isDependentType()) {
6955        // If we inherit constructors from anything that is dependent, just
6956        // abort processing altogether. We'll get another chance for the
6957        // instantiations.
6958        return;
6959      }
6960      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6961    }
6962  }
6963  if (BasesToInheritFrom.empty())
6964    return;
6965
6966  // Now collect the constructors that we already have in the current class.
6967  // Those take precedence over inherited constructors.
6968  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6969  //   unless there is a user-declared constructor with the same signature in
6970  //   the class where the using-declaration appears.
6971  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6972  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6973                                    CtorE = ClassDecl->ctor_end();
6974       CtorIt != CtorE; ++CtorIt) {
6975    ExistingConstructors.insert(
6976        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6977  }
6978
6979  Scope *S = getScopeForContext(ClassDecl);
6980  DeclarationName CreatedCtorName =
6981      Context.DeclarationNames.getCXXConstructorName(
6982          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6983
6984  // Now comes the true work.
6985  // First, we keep a map from constructor types to the base that introduced
6986  // them. Needed for finding conflicting constructors. We also keep the
6987  // actually inserted declarations in there, for pretty diagnostics.
6988  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6989  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6990  ConstructorToSourceMap InheritedConstructors;
6991  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6992                             BaseE = BasesToInheritFrom.end();
6993       BaseIt != BaseE; ++BaseIt) {
6994    const RecordType *Base = *BaseIt;
6995    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6996    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6997    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6998                                      CtorE = BaseDecl->ctor_end();
6999         CtorIt != CtorE; ++CtorIt) {
7000      // Find the using declaration for inheriting this base's constructors.
7001      DeclarationName Name =
7002          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7003      UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7004          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7005      SourceLocation UsingLoc = UD ? UD->getLocation() :
7006                                     ClassDecl->getLocation();
7007
7008      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7009      //   from the class X named in the using-declaration consists of actual
7010      //   constructors and notional constructors that result from the
7011      //   transformation of defaulted parameters as follows:
7012      //   - all non-template default constructors of X, and
7013      //   - for each non-template constructor of X that has at least one
7014      //     parameter with a default argument, the set of constructors that
7015      //     results from omitting any ellipsis parameter specification and
7016      //     successively omitting parameters with a default argument from the
7017      //     end of the parameter-type-list.
7018      CXXConstructorDecl *BaseCtor = *CtorIt;
7019      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7020      const FunctionProtoType *BaseCtorType =
7021          BaseCtor->getType()->getAs<FunctionProtoType>();
7022
7023      for (unsigned params = BaseCtor->getMinRequiredArguments(),
7024                    maxParams = BaseCtor->getNumParams();
7025           params <= maxParams; ++params) {
7026        // Skip default constructors. They're never inherited.
7027        if (params == 0)
7028          continue;
7029        // Skip copy and move constructors for the same reason.
7030        if (CanBeCopyOrMove && params == 1)
7031          continue;
7032
7033        // Build up a function type for this particular constructor.
7034        // FIXME: The working paper does not consider that the exception spec
7035        // for the inheriting constructor might be larger than that of the
7036        // source. This code doesn't yet, either. When it does, this code will
7037        // need to be delayed until after exception specifications and in-class
7038        // member initializers are attached.
7039        const Type *NewCtorType;
7040        if (params == maxParams)
7041          NewCtorType = BaseCtorType;
7042        else {
7043          SmallVector<QualType, 16> Args;
7044          for (unsigned i = 0; i < params; ++i) {
7045            Args.push_back(BaseCtorType->getArgType(i));
7046          }
7047          FunctionProtoType::ExtProtoInfo ExtInfo =
7048              BaseCtorType->getExtProtoInfo();
7049          ExtInfo.Variadic = false;
7050          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7051                                                Args.data(), params, ExtInfo)
7052                       .getTypePtr();
7053        }
7054        const Type *CanonicalNewCtorType =
7055            Context.getCanonicalType(NewCtorType);
7056
7057        // Now that we have the type, first check if the class already has a
7058        // constructor with this signature.
7059        if (ExistingConstructors.count(CanonicalNewCtorType))
7060          continue;
7061
7062        // Then we check if we have already declared an inherited constructor
7063        // with this signature.
7064        std::pair<ConstructorToSourceMap::iterator, bool> result =
7065            InheritedConstructors.insert(std::make_pair(
7066                CanonicalNewCtorType,
7067                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7068        if (!result.second) {
7069          // Already in the map. If it came from a different class, that's an
7070          // error. Not if it's from the same.
7071          CanQualType PreviousBase = result.first->second.first;
7072          if (CanonicalBase != PreviousBase) {
7073            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7074            const CXXConstructorDecl *PrevBaseCtor =
7075                PrevCtor->getInheritedConstructor();
7076            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7077
7078            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7079            Diag(BaseCtor->getLocation(),
7080                 diag::note_using_decl_constructor_conflict_current_ctor);
7081            Diag(PrevBaseCtor->getLocation(),
7082                 diag::note_using_decl_constructor_conflict_previous_ctor);
7083            Diag(PrevCtor->getLocation(),
7084                 diag::note_using_decl_constructor_conflict_previous_using);
7085          }
7086          continue;
7087        }
7088
7089        // OK, we're there, now add the constructor.
7090        // C++0x [class.inhctor]p8: [...] that would be performed by a
7091        //   user-written inline constructor [...]
7092        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7093        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7094            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7095            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7096            /*ImplicitlyDeclared=*/true,
7097            // FIXME: Due to a defect in the standard, we treat inherited
7098            // constructors as constexpr even if that makes them ill-formed.
7099            /*Constexpr=*/BaseCtor->isConstexpr());
7100        NewCtor->setAccess(BaseCtor->getAccess());
7101
7102        // Build up the parameter decls and add them.
7103        SmallVector<ParmVarDecl *, 16> ParamDecls;
7104        for (unsigned i = 0; i < params; ++i) {
7105          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7106                                                   UsingLoc, UsingLoc,
7107                                                   /*IdentifierInfo=*/0,
7108                                                   BaseCtorType->getArgType(i),
7109                                                   /*TInfo=*/0, SC_None,
7110                                                   SC_None, /*DefaultArg=*/0));
7111        }
7112        NewCtor->setParams(ParamDecls);
7113        NewCtor->setInheritedConstructor(BaseCtor);
7114
7115        PushOnScopeChains(NewCtor, S, false);
7116        ClassDecl->addDecl(NewCtor);
7117        result.first->second.second = NewCtor;
7118      }
7119    }
7120  }
7121}
7122
7123Sema::ImplicitExceptionSpecification
7124Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
7125  // C++ [except.spec]p14:
7126  //   An implicitly declared special member function (Clause 12) shall have
7127  //   an exception-specification.
7128  ImplicitExceptionSpecification ExceptSpec(Context);
7129  if (ClassDecl->isInvalidDecl())
7130    return ExceptSpec;
7131
7132  // Direct base-class destructors.
7133  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7134                                       BEnd = ClassDecl->bases_end();
7135       B != BEnd; ++B) {
7136    if (B->isVirtual()) // Handled below.
7137      continue;
7138
7139    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7140      ExceptSpec.CalledDecl(
7141                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7142  }
7143
7144  // Virtual base-class destructors.
7145  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7146                                       BEnd = ClassDecl->vbases_end();
7147       B != BEnd; ++B) {
7148    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7149      ExceptSpec.CalledDecl(
7150                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7151  }
7152
7153  // Field destructors.
7154  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7155                               FEnd = ClassDecl->field_end();
7156       F != FEnd; ++F) {
7157    if (const RecordType *RecordTy
7158        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7159      ExceptSpec.CalledDecl(
7160                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7161  }
7162
7163  return ExceptSpec;
7164}
7165
7166CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7167  // C++ [class.dtor]p2:
7168  //   If a class has no user-declared destructor, a destructor is
7169  //   declared implicitly. An implicitly-declared destructor is an
7170  //   inline public member of its class.
7171
7172  ImplicitExceptionSpecification Spec =
7173      ComputeDefaultedDtorExceptionSpec(ClassDecl);
7174  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7175
7176  // Create the actual destructor declaration.
7177  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
7178
7179  CanQualType ClassType
7180    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7181  SourceLocation ClassLoc = ClassDecl->getLocation();
7182  DeclarationName Name
7183    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7184  DeclarationNameInfo NameInfo(Name, ClassLoc);
7185  CXXDestructorDecl *Destructor
7186      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7187                                  /*isInline=*/true,
7188                                  /*isImplicitlyDeclared=*/true);
7189  Destructor->setAccess(AS_public);
7190  Destructor->setDefaulted();
7191  Destructor->setImplicit();
7192  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7193
7194  // Note that we have declared this destructor.
7195  ++ASTContext::NumImplicitDestructorsDeclared;
7196
7197  // Introduce this destructor into its scope.
7198  if (Scope *S = getScopeForContext(ClassDecl))
7199    PushOnScopeChains(Destructor, S, false);
7200  ClassDecl->addDecl(Destructor);
7201
7202  // This could be uniqued if it ever proves significant.
7203  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
7204
7205  AddOverriddenMethods(ClassDecl, Destructor);
7206
7207  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7208    Destructor->setDeletedAsWritten();
7209
7210  return Destructor;
7211}
7212
7213void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7214                                    CXXDestructorDecl *Destructor) {
7215  assert((Destructor->isDefaulted() &&
7216          !Destructor->doesThisDeclarationHaveABody() &&
7217          !Destructor->isDeleted()) &&
7218         "DefineImplicitDestructor - call it for implicit default dtor");
7219  CXXRecordDecl *ClassDecl = Destructor->getParent();
7220  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7221
7222  if (Destructor->isInvalidDecl())
7223    return;
7224
7225  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7226
7227  DiagnosticErrorTrap Trap(Diags);
7228  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7229                                         Destructor->getParent());
7230
7231  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7232    Diag(CurrentLocation, diag::note_member_synthesized_at)
7233      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7234
7235    Destructor->setInvalidDecl();
7236    return;
7237  }
7238
7239  SourceLocation Loc = Destructor->getLocation();
7240  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7241  Destructor->setImplicitlyDefined(true);
7242  Destructor->setUsed();
7243  MarkVTableUsed(CurrentLocation, ClassDecl);
7244
7245  if (ASTMutationListener *L = getASTMutationListener()) {
7246    L->CompletedImplicitDefinition(Destructor);
7247  }
7248}
7249
7250void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7251                                         CXXDestructorDecl *destructor) {
7252  // C++11 [class.dtor]p3:
7253  //   A declaration of a destructor that does not have an exception-
7254  //   specification is implicitly considered to have the same exception-
7255  //   specification as an implicit declaration.
7256  const FunctionProtoType *dtorType = destructor->getType()->
7257                                        getAs<FunctionProtoType>();
7258  if (dtorType->hasExceptionSpec())
7259    return;
7260
7261  ImplicitExceptionSpecification exceptSpec =
7262      ComputeDefaultedDtorExceptionSpec(classDecl);
7263
7264  // Replace the destructor's type, building off the existing one. Fortunately,
7265  // the only thing of interest in the destructor type is its extended info.
7266  // The return and arguments are fixed.
7267  FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
7268  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7269  epi.NumExceptions = exceptSpec.size();
7270  epi.Exceptions = exceptSpec.data();
7271  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7272
7273  destructor->setType(ty);
7274
7275  // FIXME: If the destructor has a body that could throw, and the newly created
7276  // spec doesn't allow exceptions, we should emit a warning, because this
7277  // change in behavior can break conforming C++03 programs at runtime.
7278  // However, we don't have a body yet, so it needs to be done somewhere else.
7279}
7280
7281/// \brief Builds a statement that copies/moves the given entity from \p From to
7282/// \c To.
7283///
7284/// This routine is used to copy/move the members of a class with an
7285/// implicitly-declared copy/move assignment operator. When the entities being
7286/// copied are arrays, this routine builds for loops to copy them.
7287///
7288/// \param S The Sema object used for type-checking.
7289///
7290/// \param Loc The location where the implicit copy/move is being generated.
7291///
7292/// \param T The type of the expressions being copied/moved. Both expressions
7293/// must have this type.
7294///
7295/// \param To The expression we are copying/moving to.
7296///
7297/// \param From The expression we are copying/moving from.
7298///
7299/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7300/// Otherwise, it's a non-static member subobject.
7301///
7302/// \param Copying Whether we're copying or moving.
7303///
7304/// \param Depth Internal parameter recording the depth of the recursion.
7305///
7306/// \returns A statement or a loop that copies the expressions.
7307static StmtResult
7308BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7309                      Expr *To, Expr *From,
7310                      bool CopyingBaseSubobject, bool Copying,
7311                      unsigned Depth = 0) {
7312  // C++0x [class.copy]p28:
7313  //   Each subobject is assigned in the manner appropriate to its type:
7314  //
7315  //     - if the subobject is of class type, as if by a call to operator= with
7316  //       the subobject as the object expression and the corresponding
7317  //       subobject of x as a single function argument (as if by explicit
7318  //       qualification; that is, ignoring any possible virtual overriding
7319  //       functions in more derived classes);
7320  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7321    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7322
7323    // Look for operator=.
7324    DeclarationName Name
7325      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7326    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7327    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7328
7329    // Filter out any result that isn't a copy/move-assignment operator.
7330    LookupResult::Filter F = OpLookup.makeFilter();
7331    while (F.hasNext()) {
7332      NamedDecl *D = F.next();
7333      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7334        if (Copying ? Method->isCopyAssignmentOperator() :
7335                      Method->isMoveAssignmentOperator())
7336          continue;
7337
7338      F.erase();
7339    }
7340    F.done();
7341
7342    // Suppress the protected check (C++ [class.protected]) for each of the
7343    // assignment operators we found. This strange dance is required when
7344    // we're assigning via a base classes's copy-assignment operator. To
7345    // ensure that we're getting the right base class subobject (without
7346    // ambiguities), we need to cast "this" to that subobject type; to
7347    // ensure that we don't go through the virtual call mechanism, we need
7348    // to qualify the operator= name with the base class (see below). However,
7349    // this means that if the base class has a protected copy assignment
7350    // operator, the protected member access check will fail. So, we
7351    // rewrite "protected" access to "public" access in this case, since we
7352    // know by construction that we're calling from a derived class.
7353    if (CopyingBaseSubobject) {
7354      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7355           L != LEnd; ++L) {
7356        if (L.getAccess() == AS_protected)
7357          L.setAccess(AS_public);
7358      }
7359    }
7360
7361    // Create the nested-name-specifier that will be used to qualify the
7362    // reference to operator=; this is required to suppress the virtual
7363    // call mechanism.
7364    CXXScopeSpec SS;
7365    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7366    SS.MakeTrivial(S.Context,
7367                   NestedNameSpecifier::Create(S.Context, 0, false,
7368                                               CanonicalT),
7369                   Loc);
7370
7371    // Create the reference to operator=.
7372    ExprResult OpEqualRef
7373      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7374                                   /*TemplateKWLoc=*/SourceLocation(),
7375                                   /*FirstQualifierInScope=*/0,
7376                                   OpLookup,
7377                                   /*TemplateArgs=*/0,
7378                                   /*SuppressQualifierCheck=*/true);
7379    if (OpEqualRef.isInvalid())
7380      return StmtError();
7381
7382    // Build the call to the assignment operator.
7383
7384    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7385                                                  OpEqualRef.takeAs<Expr>(),
7386                                                  Loc, &From, 1, Loc);
7387    if (Call.isInvalid())
7388      return StmtError();
7389
7390    return S.Owned(Call.takeAs<Stmt>());
7391  }
7392
7393  //     - if the subobject is of scalar type, the built-in assignment
7394  //       operator is used.
7395  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7396  if (!ArrayTy) {
7397    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7398    if (Assignment.isInvalid())
7399      return StmtError();
7400
7401    return S.Owned(Assignment.takeAs<Stmt>());
7402  }
7403
7404  //     - if the subobject is an array, each element is assigned, in the
7405  //       manner appropriate to the element type;
7406
7407  // Construct a loop over the array bounds, e.g.,
7408  //
7409  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7410  //
7411  // that will copy each of the array elements.
7412  QualType SizeType = S.Context.getSizeType();
7413
7414  // Create the iteration variable.
7415  IdentifierInfo *IterationVarName = 0;
7416  {
7417    SmallString<8> Str;
7418    llvm::raw_svector_ostream OS(Str);
7419    OS << "__i" << Depth;
7420    IterationVarName = &S.Context.Idents.get(OS.str());
7421  }
7422  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7423                                          IterationVarName, SizeType,
7424                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7425                                          SC_None, SC_None);
7426
7427  // Initialize the iteration variable to zero.
7428  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7429  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7430
7431  // Create a reference to the iteration variable; we'll use this several
7432  // times throughout.
7433  Expr *IterationVarRef
7434    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7435  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7436  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7437  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7438
7439  // Create the DeclStmt that holds the iteration variable.
7440  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7441
7442  // Create the comparison against the array bound.
7443  llvm::APInt Upper
7444    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7445  Expr *Comparison
7446    = new (S.Context) BinaryOperator(IterationVarRefRVal,
7447                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7448                                     BO_NE, S.Context.BoolTy,
7449                                     VK_RValue, OK_Ordinary, Loc);
7450
7451  // Create the pre-increment of the iteration variable.
7452  Expr *Increment
7453    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7454                                    VK_LValue, OK_Ordinary, Loc);
7455
7456  // Subscript the "from" and "to" expressions with the iteration variable.
7457  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7458                                                         IterationVarRefRVal,
7459                                                         Loc));
7460  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7461                                                       IterationVarRefRVal,
7462                                                       Loc));
7463  if (!Copying) // Cast to rvalue
7464    From = CastForMoving(S, From);
7465
7466  // Build the copy/move for an individual element of the array.
7467  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7468                                          To, From, CopyingBaseSubobject,
7469                                          Copying, Depth + 1);
7470  if (Copy.isInvalid())
7471    return StmtError();
7472
7473  // Construct the loop that copies all elements of this array.
7474  return S.ActOnForStmt(Loc, Loc, InitStmt,
7475                        S.MakeFullExpr(Comparison),
7476                        0, S.MakeFullExpr(Increment),
7477                        Loc, Copy.take());
7478}
7479
7480std::pair<Sema::ImplicitExceptionSpecification, bool>
7481Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7482                                                   CXXRecordDecl *ClassDecl) {
7483  if (ClassDecl->isInvalidDecl())
7484    return std::make_pair(ImplicitExceptionSpecification(Context), false);
7485
7486  // C++ [class.copy]p10:
7487  //   If the class definition does not explicitly declare a copy
7488  //   assignment operator, one is declared implicitly.
7489  //   The implicitly-defined copy assignment operator for a class X
7490  //   will have the form
7491  //
7492  //       X& X::operator=(const X&)
7493  //
7494  //   if
7495  bool HasConstCopyAssignment = true;
7496
7497  //       -- each direct base class B of X has a copy assignment operator
7498  //          whose parameter is of type const B&, const volatile B& or B,
7499  //          and
7500  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7501                                       BaseEnd = ClassDecl->bases_end();
7502       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7503    // We'll handle this below
7504    if (LangOpts.CPlusPlus0x && Base->isVirtual())
7505      continue;
7506
7507    assert(!Base->getType()->isDependentType() &&
7508           "Cannot generate implicit members for class with dependent bases.");
7509    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7510    LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7511                            &HasConstCopyAssignment);
7512  }
7513
7514  // In C++11, the above citation has "or virtual" added
7515  if (LangOpts.CPlusPlus0x) {
7516    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7517                                         BaseEnd = ClassDecl->vbases_end();
7518         HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7519      assert(!Base->getType()->isDependentType() &&
7520             "Cannot generate implicit members for class with dependent bases.");
7521      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7522      LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7523                              &HasConstCopyAssignment);
7524    }
7525  }
7526
7527  //       -- for all the nonstatic data members of X that are of a class
7528  //          type M (or array thereof), each such class type has a copy
7529  //          assignment operator whose parameter is of type const M&,
7530  //          const volatile M& or M.
7531  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7532                                  FieldEnd = ClassDecl->field_end();
7533       HasConstCopyAssignment && Field != FieldEnd;
7534       ++Field) {
7535    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7536    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7537      LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7538                              &HasConstCopyAssignment);
7539    }
7540  }
7541
7542  //   Otherwise, the implicitly declared copy assignment operator will
7543  //   have the form
7544  //
7545  //       X& X::operator=(X&)
7546
7547  // C++ [except.spec]p14:
7548  //   An implicitly declared special member function (Clause 12) shall have an
7549  //   exception-specification. [...]
7550
7551  // It is unspecified whether or not an implicit copy assignment operator
7552  // attempts to deduplicate calls to assignment operators of virtual bases are
7553  // made. As such, this exception specification is effectively unspecified.
7554  // Based on a similar decision made for constness in C++0x, we're erring on
7555  // the side of assuming such calls to be made regardless of whether they
7556  // actually happen.
7557  ImplicitExceptionSpecification ExceptSpec(Context);
7558  unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
7559  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7560                                       BaseEnd = ClassDecl->bases_end();
7561       Base != BaseEnd; ++Base) {
7562    if (Base->isVirtual())
7563      continue;
7564
7565    CXXRecordDecl *BaseClassDecl
7566      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7567    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7568                                                            ArgQuals, false, 0))
7569      ExceptSpec.CalledDecl(CopyAssign);
7570  }
7571
7572  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7573                                       BaseEnd = ClassDecl->vbases_end();
7574       Base != BaseEnd; ++Base) {
7575    CXXRecordDecl *BaseClassDecl
7576      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7577    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7578                                                            ArgQuals, false, 0))
7579      ExceptSpec.CalledDecl(CopyAssign);
7580  }
7581
7582  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7583                                  FieldEnd = ClassDecl->field_end();
7584       Field != FieldEnd;
7585       ++Field) {
7586    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7587    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7588      if (CXXMethodDecl *CopyAssign =
7589          LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7590        ExceptSpec.CalledDecl(CopyAssign);
7591    }
7592  }
7593
7594  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7595}
7596
7597CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7598  // Note: The following rules are largely analoguous to the copy
7599  // constructor rules. Note that virtual bases are not taken into account
7600  // for determining the argument type of the operator. Note also that
7601  // operators taking an object instead of a reference are allowed.
7602
7603  ImplicitExceptionSpecification Spec(Context);
7604  bool Const;
7605  llvm::tie(Spec, Const) =
7606    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7607
7608  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7609  QualType RetType = Context.getLValueReferenceType(ArgType);
7610  if (Const)
7611    ArgType = ArgType.withConst();
7612  ArgType = Context.getLValueReferenceType(ArgType);
7613
7614  //   An implicitly-declared copy assignment operator is an inline public
7615  //   member of its class.
7616  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7617  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7618  SourceLocation ClassLoc = ClassDecl->getLocation();
7619  DeclarationNameInfo NameInfo(Name, ClassLoc);
7620  CXXMethodDecl *CopyAssignment
7621    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7622                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7623                            /*TInfo=*/0, /*isStatic=*/false,
7624                            /*StorageClassAsWritten=*/SC_None,
7625                            /*isInline=*/true, /*isConstexpr=*/false,
7626                            SourceLocation());
7627  CopyAssignment->setAccess(AS_public);
7628  CopyAssignment->setDefaulted();
7629  CopyAssignment->setImplicit();
7630  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7631
7632  // Add the parameter to the operator.
7633  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7634                                               ClassLoc, ClassLoc, /*Id=*/0,
7635                                               ArgType, /*TInfo=*/0,
7636                                               SC_None,
7637                                               SC_None, 0);
7638  CopyAssignment->setParams(FromParam);
7639
7640  // Note that we have added this copy-assignment operator.
7641  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7642
7643  if (Scope *S = getScopeForContext(ClassDecl))
7644    PushOnScopeChains(CopyAssignment, S, false);
7645  ClassDecl->addDecl(CopyAssignment);
7646
7647  // C++0x [class.copy]p19:
7648  //   ....  If the class definition does not explicitly declare a copy
7649  //   assignment operator, there is no user-declared move constructor, and
7650  //   there is no user-declared move assignment operator, a copy assignment
7651  //   operator is implicitly declared as defaulted.
7652  if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
7653          !getLangOpts().MicrosoftMode) ||
7654      ClassDecl->hasUserDeclaredMoveAssignment() ||
7655      ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7656    CopyAssignment->setDeletedAsWritten();
7657
7658  AddOverriddenMethods(ClassDecl, CopyAssignment);
7659  return CopyAssignment;
7660}
7661
7662void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7663                                        CXXMethodDecl *CopyAssignOperator) {
7664  assert((CopyAssignOperator->isDefaulted() &&
7665          CopyAssignOperator->isOverloadedOperator() &&
7666          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7667          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7668          !CopyAssignOperator->isDeleted()) &&
7669         "DefineImplicitCopyAssignment called for wrong function");
7670
7671  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7672
7673  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7674    CopyAssignOperator->setInvalidDecl();
7675    return;
7676  }
7677
7678  CopyAssignOperator->setUsed();
7679
7680  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7681  DiagnosticErrorTrap Trap(Diags);
7682
7683  // C++0x [class.copy]p30:
7684  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7685  //   for a non-union class X performs memberwise copy assignment of its
7686  //   subobjects. The direct base classes of X are assigned first, in the
7687  //   order of their declaration in the base-specifier-list, and then the
7688  //   immediate non-static data members of X are assigned, in the order in
7689  //   which they were declared in the class definition.
7690
7691  // The statements that form the synthesized function body.
7692  ASTOwningVector<Stmt*> Statements(*this);
7693
7694  // The parameter for the "other" object, which we are copying from.
7695  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7696  Qualifiers OtherQuals = Other->getType().getQualifiers();
7697  QualType OtherRefType = Other->getType();
7698  if (const LValueReferenceType *OtherRef
7699                                = OtherRefType->getAs<LValueReferenceType>()) {
7700    OtherRefType = OtherRef->getPointeeType();
7701    OtherQuals = OtherRefType.getQualifiers();
7702  }
7703
7704  // Our location for everything implicitly-generated.
7705  SourceLocation Loc = CopyAssignOperator->getLocation();
7706
7707  // Construct a reference to the "other" object. We'll be using this
7708  // throughout the generated ASTs.
7709  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7710  assert(OtherRef && "Reference to parameter cannot fail!");
7711
7712  // Construct the "this" pointer. We'll be using this throughout the generated
7713  // ASTs.
7714  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7715  assert(This && "Reference to this cannot fail!");
7716
7717  // Assign base classes.
7718  bool Invalid = false;
7719  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7720       E = ClassDecl->bases_end(); Base != E; ++Base) {
7721    // Form the assignment:
7722    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7723    QualType BaseType = Base->getType().getUnqualifiedType();
7724    if (!BaseType->isRecordType()) {
7725      Invalid = true;
7726      continue;
7727    }
7728
7729    CXXCastPath BasePath;
7730    BasePath.push_back(Base);
7731
7732    // Construct the "from" expression, which is an implicit cast to the
7733    // appropriately-qualified base type.
7734    Expr *From = OtherRef;
7735    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7736                             CK_UncheckedDerivedToBase,
7737                             VK_LValue, &BasePath).take();
7738
7739    // Dereference "this".
7740    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7741
7742    // Implicitly cast "this" to the appropriately-qualified base type.
7743    To = ImpCastExprToType(To.take(),
7744                           Context.getCVRQualifiedType(BaseType,
7745                                     CopyAssignOperator->getTypeQualifiers()),
7746                           CK_UncheckedDerivedToBase,
7747                           VK_LValue, &BasePath);
7748
7749    // Build the copy.
7750    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7751                                            To.get(), From,
7752                                            /*CopyingBaseSubobject=*/true,
7753                                            /*Copying=*/true);
7754    if (Copy.isInvalid()) {
7755      Diag(CurrentLocation, diag::note_member_synthesized_at)
7756        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7757      CopyAssignOperator->setInvalidDecl();
7758      return;
7759    }
7760
7761    // Success! Record the copy.
7762    Statements.push_back(Copy.takeAs<Expr>());
7763  }
7764
7765  // \brief Reference to the __builtin_memcpy function.
7766  Expr *BuiltinMemCpyRef = 0;
7767  // \brief Reference to the __builtin_objc_memmove_collectable function.
7768  Expr *CollectableMemCpyRef = 0;
7769
7770  // Assign non-static members.
7771  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7772                                  FieldEnd = ClassDecl->field_end();
7773       Field != FieldEnd; ++Field) {
7774    if (Field->isUnnamedBitfield())
7775      continue;
7776
7777    // Check for members of reference type; we can't copy those.
7778    if (Field->getType()->isReferenceType()) {
7779      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7780        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7781      Diag(Field->getLocation(), diag::note_declared_at);
7782      Diag(CurrentLocation, diag::note_member_synthesized_at)
7783        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7784      Invalid = true;
7785      continue;
7786    }
7787
7788    // Check for members of const-qualified, non-class type.
7789    QualType BaseType = Context.getBaseElementType(Field->getType());
7790    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7791      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7792        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7793      Diag(Field->getLocation(), diag::note_declared_at);
7794      Diag(CurrentLocation, diag::note_member_synthesized_at)
7795        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7796      Invalid = true;
7797      continue;
7798    }
7799
7800    // Suppress assigning zero-width bitfields.
7801    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7802      continue;
7803
7804    QualType FieldType = Field->getType().getNonReferenceType();
7805    if (FieldType->isIncompleteArrayType()) {
7806      assert(ClassDecl->hasFlexibleArrayMember() &&
7807             "Incomplete array type is not valid");
7808      continue;
7809    }
7810
7811    // Build references to the field in the object we're copying from and to.
7812    CXXScopeSpec SS; // Intentionally empty
7813    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7814                              LookupMemberName);
7815    MemberLookup.addDecl(*Field);
7816    MemberLookup.resolveKind();
7817    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7818                                               Loc, /*IsArrow=*/false,
7819                                               SS, SourceLocation(), 0,
7820                                               MemberLookup, 0);
7821    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7822                                             Loc, /*IsArrow=*/true,
7823                                             SS, SourceLocation(), 0,
7824                                             MemberLookup, 0);
7825    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7826    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7827
7828    // If the field should be copied with __builtin_memcpy rather than via
7829    // explicit assignments, do so. This optimization only applies for arrays
7830    // of scalars and arrays of class type with trivial copy-assignment
7831    // operators.
7832    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7833        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7834      // Compute the size of the memory buffer to be copied.
7835      QualType SizeType = Context.getSizeType();
7836      llvm::APInt Size(Context.getTypeSize(SizeType),
7837                       Context.getTypeSizeInChars(BaseType).getQuantity());
7838      for (const ConstantArrayType *Array
7839              = Context.getAsConstantArrayType(FieldType);
7840           Array;
7841           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7842        llvm::APInt ArraySize
7843          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7844        Size *= ArraySize;
7845      }
7846
7847      // Take the address of the field references for "from" and "to".
7848      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7849      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7850
7851      bool NeedsCollectableMemCpy =
7852          (BaseType->isRecordType() &&
7853           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7854
7855      if (NeedsCollectableMemCpy) {
7856        if (!CollectableMemCpyRef) {
7857          // Create a reference to the __builtin_objc_memmove_collectable function.
7858          LookupResult R(*this,
7859                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7860                         Loc, LookupOrdinaryName);
7861          LookupName(R, TUScope, true);
7862
7863          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7864          if (!CollectableMemCpy) {
7865            // Something went horribly wrong earlier, and we will have
7866            // complained about it.
7867            Invalid = true;
7868            continue;
7869          }
7870
7871          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7872                                                  CollectableMemCpy->getType(),
7873                                                  VK_LValue, Loc, 0).take();
7874          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7875        }
7876      }
7877      // Create a reference to the __builtin_memcpy builtin function.
7878      else if (!BuiltinMemCpyRef) {
7879        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7880                       LookupOrdinaryName);
7881        LookupName(R, TUScope, true);
7882
7883        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7884        if (!BuiltinMemCpy) {
7885          // Something went horribly wrong earlier, and we will have complained
7886          // about it.
7887          Invalid = true;
7888          continue;
7889        }
7890
7891        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7892                                            BuiltinMemCpy->getType(),
7893                                            VK_LValue, Loc, 0).take();
7894        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7895      }
7896
7897      ASTOwningVector<Expr*> CallArgs(*this);
7898      CallArgs.push_back(To.takeAs<Expr>());
7899      CallArgs.push_back(From.takeAs<Expr>());
7900      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7901      ExprResult Call = ExprError();
7902      if (NeedsCollectableMemCpy)
7903        Call = ActOnCallExpr(/*Scope=*/0,
7904                             CollectableMemCpyRef,
7905                             Loc, move_arg(CallArgs),
7906                             Loc);
7907      else
7908        Call = ActOnCallExpr(/*Scope=*/0,
7909                             BuiltinMemCpyRef,
7910                             Loc, move_arg(CallArgs),
7911                             Loc);
7912
7913      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7914      Statements.push_back(Call.takeAs<Expr>());
7915      continue;
7916    }
7917
7918    // Build the copy of this field.
7919    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7920                                            To.get(), From.get(),
7921                                            /*CopyingBaseSubobject=*/false,
7922                                            /*Copying=*/true);
7923    if (Copy.isInvalid()) {
7924      Diag(CurrentLocation, diag::note_member_synthesized_at)
7925        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7926      CopyAssignOperator->setInvalidDecl();
7927      return;
7928    }
7929
7930    // Success! Record the copy.
7931    Statements.push_back(Copy.takeAs<Stmt>());
7932  }
7933
7934  if (!Invalid) {
7935    // Add a "return *this;"
7936    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7937
7938    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7939    if (Return.isInvalid())
7940      Invalid = true;
7941    else {
7942      Statements.push_back(Return.takeAs<Stmt>());
7943
7944      if (Trap.hasErrorOccurred()) {
7945        Diag(CurrentLocation, diag::note_member_synthesized_at)
7946          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7947        Invalid = true;
7948      }
7949    }
7950  }
7951
7952  if (Invalid) {
7953    CopyAssignOperator->setInvalidDecl();
7954    return;
7955  }
7956
7957  StmtResult Body;
7958  {
7959    CompoundScopeRAII CompoundScope(*this);
7960    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7961                             /*isStmtExpr=*/false);
7962    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7963  }
7964  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7965
7966  if (ASTMutationListener *L = getASTMutationListener()) {
7967    L->CompletedImplicitDefinition(CopyAssignOperator);
7968  }
7969}
7970
7971Sema::ImplicitExceptionSpecification
7972Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7973  ImplicitExceptionSpecification ExceptSpec(Context);
7974
7975  if (ClassDecl->isInvalidDecl())
7976    return ExceptSpec;
7977
7978  // C++0x [except.spec]p14:
7979  //   An implicitly declared special member function (Clause 12) shall have an
7980  //   exception-specification. [...]
7981
7982  // It is unspecified whether or not an implicit move assignment operator
7983  // attempts to deduplicate calls to assignment operators of virtual bases are
7984  // made. As such, this exception specification is effectively unspecified.
7985  // Based on a similar decision made for constness in C++0x, we're erring on
7986  // the side of assuming such calls to be made regardless of whether they
7987  // actually happen.
7988  // Note that a move constructor is not implicitly declared when there are
7989  // virtual bases, but it can still be user-declared and explicitly defaulted.
7990  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7991                                       BaseEnd = ClassDecl->bases_end();
7992       Base != BaseEnd; ++Base) {
7993    if (Base->isVirtual())
7994      continue;
7995
7996    CXXRecordDecl *BaseClassDecl
7997      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7998    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7999                                                           false, 0))
8000      ExceptSpec.CalledDecl(MoveAssign);
8001  }
8002
8003  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8004                                       BaseEnd = ClassDecl->vbases_end();
8005       Base != BaseEnd; ++Base) {
8006    CXXRecordDecl *BaseClassDecl
8007      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8008    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8009                                                           false, 0))
8010      ExceptSpec.CalledDecl(MoveAssign);
8011  }
8012
8013  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8014                                  FieldEnd = ClassDecl->field_end();
8015       Field != FieldEnd;
8016       ++Field) {
8017    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8018    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8019      if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8020                                                             false, 0))
8021        ExceptSpec.CalledDecl(MoveAssign);
8022    }
8023  }
8024
8025  return ExceptSpec;
8026}
8027
8028CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8029  // Note: The following rules are largely analoguous to the move
8030  // constructor rules.
8031
8032  ImplicitExceptionSpecification Spec(
8033      ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8034
8035  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8036  QualType RetType = Context.getLValueReferenceType(ArgType);
8037  ArgType = Context.getRValueReferenceType(ArgType);
8038
8039  //   An implicitly-declared move assignment operator is an inline public
8040  //   member of its class.
8041  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8042  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8043  SourceLocation ClassLoc = ClassDecl->getLocation();
8044  DeclarationNameInfo NameInfo(Name, ClassLoc);
8045  CXXMethodDecl *MoveAssignment
8046    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8047                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
8048                            /*TInfo=*/0, /*isStatic=*/false,
8049                            /*StorageClassAsWritten=*/SC_None,
8050                            /*isInline=*/true,
8051                            /*isConstexpr=*/false,
8052                            SourceLocation());
8053  MoveAssignment->setAccess(AS_public);
8054  MoveAssignment->setDefaulted();
8055  MoveAssignment->setImplicit();
8056  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8057
8058  // Add the parameter to the operator.
8059  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8060                                               ClassLoc, ClassLoc, /*Id=*/0,
8061                                               ArgType, /*TInfo=*/0,
8062                                               SC_None,
8063                                               SC_None, 0);
8064  MoveAssignment->setParams(FromParam);
8065
8066  // Note that we have added this copy-assignment operator.
8067  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8068
8069  // C++0x [class.copy]p9:
8070  //   If the definition of a class X does not explicitly declare a move
8071  //   assignment operator, one will be implicitly declared as defaulted if and
8072  //   only if:
8073  //   [...]
8074  //   - the move assignment operator would not be implicitly defined as
8075  //     deleted.
8076  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8077    // Cache this result so that we don't try to generate this over and over
8078    // on every lookup, leaking memory and wasting time.
8079    ClassDecl->setFailedImplicitMoveAssignment();
8080    return 0;
8081  }
8082
8083  if (Scope *S = getScopeForContext(ClassDecl))
8084    PushOnScopeChains(MoveAssignment, S, false);
8085  ClassDecl->addDecl(MoveAssignment);
8086
8087  AddOverriddenMethods(ClassDecl, MoveAssignment);
8088  return MoveAssignment;
8089}
8090
8091void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8092                                        CXXMethodDecl *MoveAssignOperator) {
8093  assert((MoveAssignOperator->isDefaulted() &&
8094          MoveAssignOperator->isOverloadedOperator() &&
8095          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8096          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8097          !MoveAssignOperator->isDeleted()) &&
8098         "DefineImplicitMoveAssignment called for wrong function");
8099
8100  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8101
8102  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8103    MoveAssignOperator->setInvalidDecl();
8104    return;
8105  }
8106
8107  MoveAssignOperator->setUsed();
8108
8109  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8110  DiagnosticErrorTrap Trap(Diags);
8111
8112  // C++0x [class.copy]p28:
8113  //   The implicitly-defined or move assignment operator for a non-union class
8114  //   X performs memberwise move assignment of its subobjects. The direct base
8115  //   classes of X are assigned first, in the order of their declaration in the
8116  //   base-specifier-list, and then the immediate non-static data members of X
8117  //   are assigned, in the order in which they were declared in the class
8118  //   definition.
8119
8120  // The statements that form the synthesized function body.
8121  ASTOwningVector<Stmt*> Statements(*this);
8122
8123  // The parameter for the "other" object, which we are move from.
8124  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8125  QualType OtherRefType = Other->getType()->
8126      getAs<RValueReferenceType>()->getPointeeType();
8127  assert(OtherRefType.getQualifiers() == 0 &&
8128         "Bad argument type of defaulted move assignment");
8129
8130  // Our location for everything implicitly-generated.
8131  SourceLocation Loc = MoveAssignOperator->getLocation();
8132
8133  // Construct a reference to the "other" object. We'll be using this
8134  // throughout the generated ASTs.
8135  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8136  assert(OtherRef && "Reference to parameter cannot fail!");
8137  // Cast to rvalue.
8138  OtherRef = CastForMoving(*this, OtherRef);
8139
8140  // Construct the "this" pointer. We'll be using this throughout the generated
8141  // ASTs.
8142  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8143  assert(This && "Reference to this cannot fail!");
8144
8145  // Assign base classes.
8146  bool Invalid = false;
8147  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8148       E = ClassDecl->bases_end(); Base != E; ++Base) {
8149    // Form the assignment:
8150    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8151    QualType BaseType = Base->getType().getUnqualifiedType();
8152    if (!BaseType->isRecordType()) {
8153      Invalid = true;
8154      continue;
8155    }
8156
8157    CXXCastPath BasePath;
8158    BasePath.push_back(Base);
8159
8160    // Construct the "from" expression, which is an implicit cast to the
8161    // appropriately-qualified base type.
8162    Expr *From = OtherRef;
8163    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8164                             VK_XValue, &BasePath).take();
8165
8166    // Dereference "this".
8167    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8168
8169    // Implicitly cast "this" to the appropriately-qualified base type.
8170    To = ImpCastExprToType(To.take(),
8171                           Context.getCVRQualifiedType(BaseType,
8172                                     MoveAssignOperator->getTypeQualifiers()),
8173                           CK_UncheckedDerivedToBase,
8174                           VK_LValue, &BasePath);
8175
8176    // Build the move.
8177    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8178                                            To.get(), From,
8179                                            /*CopyingBaseSubobject=*/true,
8180                                            /*Copying=*/false);
8181    if (Move.isInvalid()) {
8182      Diag(CurrentLocation, diag::note_member_synthesized_at)
8183        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8184      MoveAssignOperator->setInvalidDecl();
8185      return;
8186    }
8187
8188    // Success! Record the move.
8189    Statements.push_back(Move.takeAs<Expr>());
8190  }
8191
8192  // \brief Reference to the __builtin_memcpy function.
8193  Expr *BuiltinMemCpyRef = 0;
8194  // \brief Reference to the __builtin_objc_memmove_collectable function.
8195  Expr *CollectableMemCpyRef = 0;
8196
8197  // Assign non-static members.
8198  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8199                                  FieldEnd = ClassDecl->field_end();
8200       Field != FieldEnd; ++Field) {
8201    if (Field->isUnnamedBitfield())
8202      continue;
8203
8204    // Check for members of reference type; we can't move those.
8205    if (Field->getType()->isReferenceType()) {
8206      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8207        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8208      Diag(Field->getLocation(), diag::note_declared_at);
8209      Diag(CurrentLocation, diag::note_member_synthesized_at)
8210        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8211      Invalid = true;
8212      continue;
8213    }
8214
8215    // Check for members of const-qualified, non-class type.
8216    QualType BaseType = Context.getBaseElementType(Field->getType());
8217    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8218      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8219        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8220      Diag(Field->getLocation(), diag::note_declared_at);
8221      Diag(CurrentLocation, diag::note_member_synthesized_at)
8222        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8223      Invalid = true;
8224      continue;
8225    }
8226
8227    // Suppress assigning zero-width bitfields.
8228    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8229      continue;
8230
8231    QualType FieldType = Field->getType().getNonReferenceType();
8232    if (FieldType->isIncompleteArrayType()) {
8233      assert(ClassDecl->hasFlexibleArrayMember() &&
8234             "Incomplete array type is not valid");
8235      continue;
8236    }
8237
8238    // Build references to the field in the object we're copying from and to.
8239    CXXScopeSpec SS; // Intentionally empty
8240    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8241                              LookupMemberName);
8242    MemberLookup.addDecl(*Field);
8243    MemberLookup.resolveKind();
8244    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8245                                               Loc, /*IsArrow=*/false,
8246                                               SS, SourceLocation(), 0,
8247                                               MemberLookup, 0);
8248    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8249                                             Loc, /*IsArrow=*/true,
8250                                             SS, SourceLocation(), 0,
8251                                             MemberLookup, 0);
8252    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8253    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8254
8255    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8256        "Member reference with rvalue base must be rvalue except for reference "
8257        "members, which aren't allowed for move assignment.");
8258
8259    // If the field should be copied with __builtin_memcpy rather than via
8260    // explicit assignments, do so. This optimization only applies for arrays
8261    // of scalars and arrays of class type with trivial move-assignment
8262    // operators.
8263    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8264        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8265      // Compute the size of the memory buffer to be copied.
8266      QualType SizeType = Context.getSizeType();
8267      llvm::APInt Size(Context.getTypeSize(SizeType),
8268                       Context.getTypeSizeInChars(BaseType).getQuantity());
8269      for (const ConstantArrayType *Array
8270              = Context.getAsConstantArrayType(FieldType);
8271           Array;
8272           Array = Context.getAsConstantArrayType(Array->getElementType())) {
8273        llvm::APInt ArraySize
8274          = Array->getSize().zextOrTrunc(Size.getBitWidth());
8275        Size *= ArraySize;
8276      }
8277
8278      // Take the address of the field references for "from" and "to". We
8279      // directly construct UnaryOperators here because semantic analysis
8280      // does not permit us to take the address of an xvalue.
8281      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8282                             Context.getPointerType(From.get()->getType()),
8283                             VK_RValue, OK_Ordinary, Loc);
8284      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8285                           Context.getPointerType(To.get()->getType()),
8286                           VK_RValue, OK_Ordinary, Loc);
8287
8288      bool NeedsCollectableMemCpy =
8289          (BaseType->isRecordType() &&
8290           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8291
8292      if (NeedsCollectableMemCpy) {
8293        if (!CollectableMemCpyRef) {
8294          // Create a reference to the __builtin_objc_memmove_collectable function.
8295          LookupResult R(*this,
8296                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
8297                         Loc, LookupOrdinaryName);
8298          LookupName(R, TUScope, true);
8299
8300          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8301          if (!CollectableMemCpy) {
8302            // Something went horribly wrong earlier, and we will have
8303            // complained about it.
8304            Invalid = true;
8305            continue;
8306          }
8307
8308          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8309                                                  CollectableMemCpy->getType(),
8310                                                  VK_LValue, Loc, 0).take();
8311          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8312        }
8313      }
8314      // Create a reference to the __builtin_memcpy builtin function.
8315      else if (!BuiltinMemCpyRef) {
8316        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8317                       LookupOrdinaryName);
8318        LookupName(R, TUScope, true);
8319
8320        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8321        if (!BuiltinMemCpy) {
8322          // Something went horribly wrong earlier, and we will have complained
8323          // about it.
8324          Invalid = true;
8325          continue;
8326        }
8327
8328        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8329                                            BuiltinMemCpy->getType(),
8330                                            VK_LValue, Loc, 0).take();
8331        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8332      }
8333
8334      ASTOwningVector<Expr*> CallArgs(*this);
8335      CallArgs.push_back(To.takeAs<Expr>());
8336      CallArgs.push_back(From.takeAs<Expr>());
8337      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8338      ExprResult Call = ExprError();
8339      if (NeedsCollectableMemCpy)
8340        Call = ActOnCallExpr(/*Scope=*/0,
8341                             CollectableMemCpyRef,
8342                             Loc, move_arg(CallArgs),
8343                             Loc);
8344      else
8345        Call = ActOnCallExpr(/*Scope=*/0,
8346                             BuiltinMemCpyRef,
8347                             Loc, move_arg(CallArgs),
8348                             Loc);
8349
8350      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8351      Statements.push_back(Call.takeAs<Expr>());
8352      continue;
8353    }
8354
8355    // Build the move of this field.
8356    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8357                                            To.get(), From.get(),
8358                                            /*CopyingBaseSubobject=*/false,
8359                                            /*Copying=*/false);
8360    if (Move.isInvalid()) {
8361      Diag(CurrentLocation, diag::note_member_synthesized_at)
8362        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8363      MoveAssignOperator->setInvalidDecl();
8364      return;
8365    }
8366
8367    // Success! Record the copy.
8368    Statements.push_back(Move.takeAs<Stmt>());
8369  }
8370
8371  if (!Invalid) {
8372    // Add a "return *this;"
8373    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8374
8375    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8376    if (Return.isInvalid())
8377      Invalid = true;
8378    else {
8379      Statements.push_back(Return.takeAs<Stmt>());
8380
8381      if (Trap.hasErrorOccurred()) {
8382        Diag(CurrentLocation, diag::note_member_synthesized_at)
8383          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8384        Invalid = true;
8385      }
8386    }
8387  }
8388
8389  if (Invalid) {
8390    MoveAssignOperator->setInvalidDecl();
8391    return;
8392  }
8393
8394  StmtResult Body;
8395  {
8396    CompoundScopeRAII CompoundScope(*this);
8397    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8398                             /*isStmtExpr=*/false);
8399    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8400  }
8401  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8402
8403  if (ASTMutationListener *L = getASTMutationListener()) {
8404    L->CompletedImplicitDefinition(MoveAssignOperator);
8405  }
8406}
8407
8408std::pair<Sema::ImplicitExceptionSpecification, bool>
8409Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
8410  if (ClassDecl->isInvalidDecl())
8411    return std::make_pair(ImplicitExceptionSpecification(Context), false);
8412
8413  // C++ [class.copy]p5:
8414  //   The implicitly-declared copy constructor for a class X will
8415  //   have the form
8416  //
8417  //       X::X(const X&)
8418  //
8419  //   if
8420  // FIXME: It ought to be possible to store this on the record.
8421  bool HasConstCopyConstructor = true;
8422
8423  //     -- each direct or virtual base class B of X has a copy
8424  //        constructor whose first parameter is of type const B& or
8425  //        const volatile B&, and
8426  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8427                                       BaseEnd = ClassDecl->bases_end();
8428       HasConstCopyConstructor && Base != BaseEnd;
8429       ++Base) {
8430    // Virtual bases are handled below.
8431    if (Base->isVirtual())
8432      continue;
8433
8434    CXXRecordDecl *BaseClassDecl
8435      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8436    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8437                             &HasConstCopyConstructor);
8438  }
8439
8440  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8441                                       BaseEnd = ClassDecl->vbases_end();
8442       HasConstCopyConstructor && Base != BaseEnd;
8443       ++Base) {
8444    CXXRecordDecl *BaseClassDecl
8445      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8446    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8447                             &HasConstCopyConstructor);
8448  }
8449
8450  //     -- for all the nonstatic data members of X that are of a
8451  //        class type M (or array thereof), each such class type
8452  //        has a copy constructor whose first parameter is of type
8453  //        const M& or const volatile M&.
8454  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8455                                  FieldEnd = ClassDecl->field_end();
8456       HasConstCopyConstructor && Field != FieldEnd;
8457       ++Field) {
8458    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8459    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8460      LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8461                               &HasConstCopyConstructor);
8462    }
8463  }
8464  //   Otherwise, the implicitly declared copy constructor will have
8465  //   the form
8466  //
8467  //       X::X(X&)
8468
8469  // C++ [except.spec]p14:
8470  //   An implicitly declared special member function (Clause 12) shall have an
8471  //   exception-specification. [...]
8472  ImplicitExceptionSpecification ExceptSpec(Context);
8473  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8474  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8475                                       BaseEnd = ClassDecl->bases_end();
8476       Base != BaseEnd;
8477       ++Base) {
8478    // Virtual bases are handled below.
8479    if (Base->isVirtual())
8480      continue;
8481
8482    CXXRecordDecl *BaseClassDecl
8483      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8484    if (CXXConstructorDecl *CopyConstructor =
8485          LookupCopyingConstructor(BaseClassDecl, Quals))
8486      ExceptSpec.CalledDecl(CopyConstructor);
8487  }
8488  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8489                                       BaseEnd = ClassDecl->vbases_end();
8490       Base != BaseEnd;
8491       ++Base) {
8492    CXXRecordDecl *BaseClassDecl
8493      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8494    if (CXXConstructorDecl *CopyConstructor =
8495          LookupCopyingConstructor(BaseClassDecl, Quals))
8496      ExceptSpec.CalledDecl(CopyConstructor);
8497  }
8498  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8499                                  FieldEnd = ClassDecl->field_end();
8500       Field != FieldEnd;
8501       ++Field) {
8502    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8503    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8504      if (CXXConstructorDecl *CopyConstructor =
8505        LookupCopyingConstructor(FieldClassDecl, Quals))
8506      ExceptSpec.CalledDecl(CopyConstructor);
8507    }
8508  }
8509
8510  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8511}
8512
8513CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8514                                                    CXXRecordDecl *ClassDecl) {
8515  // C++ [class.copy]p4:
8516  //   If the class definition does not explicitly declare a copy
8517  //   constructor, one is declared implicitly.
8518
8519  ImplicitExceptionSpecification Spec(Context);
8520  bool Const;
8521  llvm::tie(Spec, Const) =
8522    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8523
8524  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8525  QualType ArgType = ClassType;
8526  if (Const)
8527    ArgType = ArgType.withConst();
8528  ArgType = Context.getLValueReferenceType(ArgType);
8529
8530  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8531
8532  DeclarationName Name
8533    = Context.DeclarationNames.getCXXConstructorName(
8534                                           Context.getCanonicalType(ClassType));
8535  SourceLocation ClassLoc = ClassDecl->getLocation();
8536  DeclarationNameInfo NameInfo(Name, ClassLoc);
8537
8538  //   An implicitly-declared copy constructor is an inline public
8539  //   member of its class.
8540  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8541      Context, ClassDecl, ClassLoc, NameInfo,
8542      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8543      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8544      /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8545        getLangOpts().CPlusPlus0x);
8546  CopyConstructor->setAccess(AS_public);
8547  CopyConstructor->setDefaulted();
8548  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8549
8550  // Note that we have declared this constructor.
8551  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8552
8553  // Add the parameter to the constructor.
8554  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8555                                               ClassLoc, ClassLoc,
8556                                               /*IdentifierInfo=*/0,
8557                                               ArgType, /*TInfo=*/0,
8558                                               SC_None,
8559                                               SC_None, 0);
8560  CopyConstructor->setParams(FromParam);
8561
8562  if (Scope *S = getScopeForContext(ClassDecl))
8563    PushOnScopeChains(CopyConstructor, S, false);
8564  ClassDecl->addDecl(CopyConstructor);
8565
8566  // C++11 [class.copy]p8:
8567  //   ... If the class definition does not explicitly declare a copy
8568  //   constructor, there is no user-declared move constructor, and there is no
8569  //   user-declared move assignment operator, a copy constructor is implicitly
8570  //   declared as defaulted.
8571  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8572      (ClassDecl->hasUserDeclaredMoveAssignment() &&
8573          !getLangOpts().MicrosoftMode) ||
8574      ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8575    CopyConstructor->setDeletedAsWritten();
8576
8577  return CopyConstructor;
8578}
8579
8580void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8581                                   CXXConstructorDecl *CopyConstructor) {
8582  assert((CopyConstructor->isDefaulted() &&
8583          CopyConstructor->isCopyConstructor() &&
8584          !CopyConstructor->doesThisDeclarationHaveABody() &&
8585          !CopyConstructor->isDeleted()) &&
8586         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8587
8588  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8589  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8590
8591  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8592  DiagnosticErrorTrap Trap(Diags);
8593
8594  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8595      Trap.hasErrorOccurred()) {
8596    Diag(CurrentLocation, diag::note_member_synthesized_at)
8597      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8598    CopyConstructor->setInvalidDecl();
8599  }  else {
8600    Sema::CompoundScopeRAII CompoundScope(*this);
8601    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8602                                               CopyConstructor->getLocation(),
8603                                               MultiStmtArg(*this, 0, 0),
8604                                               /*isStmtExpr=*/false)
8605                                                              .takeAs<Stmt>());
8606    CopyConstructor->setImplicitlyDefined(true);
8607  }
8608
8609  CopyConstructor->setUsed();
8610  if (ASTMutationListener *L = getASTMutationListener()) {
8611    L->CompletedImplicitDefinition(CopyConstructor);
8612  }
8613}
8614
8615Sema::ImplicitExceptionSpecification
8616Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8617  // C++ [except.spec]p14:
8618  //   An implicitly declared special member function (Clause 12) shall have an
8619  //   exception-specification. [...]
8620  ImplicitExceptionSpecification ExceptSpec(Context);
8621  if (ClassDecl->isInvalidDecl())
8622    return ExceptSpec;
8623
8624  // Direct base-class constructors.
8625  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8626                                       BEnd = ClassDecl->bases_end();
8627       B != BEnd; ++B) {
8628    if (B->isVirtual()) // Handled below.
8629      continue;
8630
8631    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8632      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8633      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8634      // If this is a deleted function, add it anyway. This might be conformant
8635      // with the standard. This might not. I'm not sure. It might not matter.
8636      if (Constructor)
8637        ExceptSpec.CalledDecl(Constructor);
8638    }
8639  }
8640
8641  // Virtual base-class constructors.
8642  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8643                                       BEnd = ClassDecl->vbases_end();
8644       B != BEnd; ++B) {
8645    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8646      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8647      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8648      // If this is a deleted function, add it anyway. This might be conformant
8649      // with the standard. This might not. I'm not sure. It might not matter.
8650      if (Constructor)
8651        ExceptSpec.CalledDecl(Constructor);
8652    }
8653  }
8654
8655  // Field constructors.
8656  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8657                               FEnd = ClassDecl->field_end();
8658       F != FEnd; ++F) {
8659    if (const RecordType *RecordTy
8660              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8661      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8662      CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8663      // If this is a deleted function, add it anyway. This might be conformant
8664      // with the standard. This might not. I'm not sure. It might not matter.
8665      // In particular, the problem is that this function never gets called. It
8666      // might just be ill-formed because this function attempts to refer to
8667      // a deleted function here.
8668      if (Constructor)
8669        ExceptSpec.CalledDecl(Constructor);
8670    }
8671  }
8672
8673  return ExceptSpec;
8674}
8675
8676CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8677                                                    CXXRecordDecl *ClassDecl) {
8678  ImplicitExceptionSpecification Spec(
8679      ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8680
8681  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8682  QualType ArgType = Context.getRValueReferenceType(ClassType);
8683
8684  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8685
8686  DeclarationName Name
8687    = Context.DeclarationNames.getCXXConstructorName(
8688                                           Context.getCanonicalType(ClassType));
8689  SourceLocation ClassLoc = ClassDecl->getLocation();
8690  DeclarationNameInfo NameInfo(Name, ClassLoc);
8691
8692  // C++0x [class.copy]p11:
8693  //   An implicitly-declared copy/move constructor is an inline public
8694  //   member of its class.
8695  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8696      Context, ClassDecl, ClassLoc, NameInfo,
8697      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8698      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8699      /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8700        getLangOpts().CPlusPlus0x);
8701  MoveConstructor->setAccess(AS_public);
8702  MoveConstructor->setDefaulted();
8703  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8704
8705  // Add the parameter to the constructor.
8706  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8707                                               ClassLoc, ClassLoc,
8708                                               /*IdentifierInfo=*/0,
8709                                               ArgType, /*TInfo=*/0,
8710                                               SC_None,
8711                                               SC_None, 0);
8712  MoveConstructor->setParams(FromParam);
8713
8714  // C++0x [class.copy]p9:
8715  //   If the definition of a class X does not explicitly declare a move
8716  //   constructor, one will be implicitly declared as defaulted if and only if:
8717  //   [...]
8718  //   - the move constructor would not be implicitly defined as deleted.
8719  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8720    // Cache this result so that we don't try to generate this over and over
8721    // on every lookup, leaking memory and wasting time.
8722    ClassDecl->setFailedImplicitMoveConstructor();
8723    return 0;
8724  }
8725
8726  // Note that we have declared this constructor.
8727  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8728
8729  if (Scope *S = getScopeForContext(ClassDecl))
8730    PushOnScopeChains(MoveConstructor, S, false);
8731  ClassDecl->addDecl(MoveConstructor);
8732
8733  return MoveConstructor;
8734}
8735
8736void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8737                                   CXXConstructorDecl *MoveConstructor) {
8738  assert((MoveConstructor->isDefaulted() &&
8739          MoveConstructor->isMoveConstructor() &&
8740          !MoveConstructor->doesThisDeclarationHaveABody() &&
8741          !MoveConstructor->isDeleted()) &&
8742         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8743
8744  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8745  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8746
8747  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8748  DiagnosticErrorTrap Trap(Diags);
8749
8750  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8751      Trap.hasErrorOccurred()) {
8752    Diag(CurrentLocation, diag::note_member_synthesized_at)
8753      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8754    MoveConstructor->setInvalidDecl();
8755  }  else {
8756    Sema::CompoundScopeRAII CompoundScope(*this);
8757    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8758                                               MoveConstructor->getLocation(),
8759                                               MultiStmtArg(*this, 0, 0),
8760                                               /*isStmtExpr=*/false)
8761                                                              .takeAs<Stmt>());
8762    MoveConstructor->setImplicitlyDefined(true);
8763  }
8764
8765  MoveConstructor->setUsed();
8766
8767  if (ASTMutationListener *L = getASTMutationListener()) {
8768    L->CompletedImplicitDefinition(MoveConstructor);
8769  }
8770}
8771
8772bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8773  return FD->isDeleted() &&
8774         (FD->isDefaulted() || FD->isImplicit()) &&
8775         isa<CXXMethodDecl>(FD);
8776}
8777
8778/// \brief Mark the call operator of the given lambda closure type as "used".
8779static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8780  CXXMethodDecl *CallOperator
8781    = cast<CXXMethodDecl>(
8782        *Lambda->lookup(
8783          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
8784  CallOperator->setReferenced();
8785  CallOperator->setUsed();
8786}
8787
8788void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8789       SourceLocation CurrentLocation,
8790       CXXConversionDecl *Conv)
8791{
8792  CXXRecordDecl *Lambda = Conv->getParent();
8793
8794  // Make sure that the lambda call operator is marked used.
8795  markLambdaCallOperatorUsed(*this, Lambda);
8796
8797  Conv->setUsed();
8798
8799  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8800  DiagnosticErrorTrap Trap(Diags);
8801
8802  // Return the address of the __invoke function.
8803  DeclarationName InvokeName = &Context.Idents.get("__invoke");
8804  CXXMethodDecl *Invoke
8805    = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8806  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8807                                       VK_LValue, Conv->getLocation()).take();
8808  assert(FunctionRef && "Can't refer to __invoke function?");
8809  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8810  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8811                                           Conv->getLocation(),
8812                                           Conv->getLocation()));
8813
8814  // Fill in the __invoke function with a dummy implementation. IR generation
8815  // will fill in the actual details.
8816  Invoke->setUsed();
8817  Invoke->setReferenced();
8818  Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8819                                             Conv->getLocation()));
8820
8821  if (ASTMutationListener *L = getASTMutationListener()) {
8822    L->CompletedImplicitDefinition(Conv);
8823    L->CompletedImplicitDefinition(Invoke);
8824  }
8825}
8826
8827void Sema::DefineImplicitLambdaToBlockPointerConversion(
8828       SourceLocation CurrentLocation,
8829       CXXConversionDecl *Conv)
8830{
8831  Conv->setUsed();
8832
8833  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8834  DiagnosticErrorTrap Trap(Diags);
8835
8836  // Copy-initialize the lambda object as needed to capture it.
8837  Expr *This = ActOnCXXThis(CurrentLocation).take();
8838  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
8839
8840  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8841                                                        Conv->getLocation(),
8842                                                        Conv, DerefThis);
8843
8844  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8845  // behavior.  Note that only the general conversion function does this
8846  // (since it's unusable otherwise); in the case where we inline the
8847  // block literal, it has block literal lifetime semantics.
8848  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
8849    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8850                                          CK_CopyAndAutoreleaseBlockObject,
8851                                          BuildBlock.get(), 0, VK_RValue);
8852
8853  if (BuildBlock.isInvalid()) {
8854    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8855    Conv->setInvalidDecl();
8856    return;
8857  }
8858
8859  // Create the return statement that returns the block from the conversion
8860  // function.
8861  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
8862  if (Return.isInvalid()) {
8863    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8864    Conv->setInvalidDecl();
8865    return;
8866  }
8867
8868  // Set the body of the conversion function.
8869  Stmt *ReturnS = Return.take();
8870  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8871                                           Conv->getLocation(),
8872                                           Conv->getLocation()));
8873
8874  // We're done; notify the mutation listener, if any.
8875  if (ASTMutationListener *L = getASTMutationListener()) {
8876    L->CompletedImplicitDefinition(Conv);
8877  }
8878}
8879
8880/// \brief Determine whether the given list arguments contains exactly one
8881/// "real" (non-default) argument.
8882static bool hasOneRealArgument(MultiExprArg Args) {
8883  switch (Args.size()) {
8884  case 0:
8885    return false;
8886
8887  default:
8888    if (!Args.get()[1]->isDefaultArgument())
8889      return false;
8890
8891    // fall through
8892  case 1:
8893    return !Args.get()[0]->isDefaultArgument();
8894  }
8895
8896  return false;
8897}
8898
8899ExprResult
8900Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8901                            CXXConstructorDecl *Constructor,
8902                            MultiExprArg ExprArgs,
8903                            bool HadMultipleCandidates,
8904                            bool RequiresZeroInit,
8905                            unsigned ConstructKind,
8906                            SourceRange ParenRange) {
8907  bool Elidable = false;
8908
8909  // C++0x [class.copy]p34:
8910  //   When certain criteria are met, an implementation is allowed to
8911  //   omit the copy/move construction of a class object, even if the
8912  //   copy/move constructor and/or destructor for the object have
8913  //   side effects. [...]
8914  //     - when a temporary class object that has not been bound to a
8915  //       reference (12.2) would be copied/moved to a class object
8916  //       with the same cv-unqualified type, the copy/move operation
8917  //       can be omitted by constructing the temporary object
8918  //       directly into the target of the omitted copy/move
8919  if (ConstructKind == CXXConstructExpr::CK_Complete &&
8920      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
8921    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
8922    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
8923  }
8924
8925  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
8926                               Elidable, move(ExprArgs), HadMultipleCandidates,
8927                               RequiresZeroInit, ConstructKind, ParenRange);
8928}
8929
8930/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8931/// including handling of its default argument expressions.
8932ExprResult
8933Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8934                            CXXConstructorDecl *Constructor, bool Elidable,
8935                            MultiExprArg ExprArgs,
8936                            bool HadMultipleCandidates,
8937                            bool RequiresZeroInit,
8938                            unsigned ConstructKind,
8939                            SourceRange ParenRange) {
8940  unsigned NumExprs = ExprArgs.size();
8941  Expr **Exprs = (Expr **)ExprArgs.release();
8942
8943  for (specific_attr_iterator<NonNullAttr>
8944           i = Constructor->specific_attr_begin<NonNullAttr>(),
8945           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8946    const NonNullAttr *NonNull = *i;
8947    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8948  }
8949
8950  MarkFunctionReferenced(ConstructLoc, Constructor);
8951  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
8952                                        Constructor, Elidable, Exprs, NumExprs,
8953                                        HadMultipleCandidates, /*FIXME*/false,
8954                                        RequiresZeroInit,
8955              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8956                                        ParenRange));
8957}
8958
8959bool Sema::InitializeVarWithConstructor(VarDecl *VD,
8960                                        CXXConstructorDecl *Constructor,
8961                                        MultiExprArg Exprs,
8962                                        bool HadMultipleCandidates) {
8963  // FIXME: Provide the correct paren SourceRange when available.
8964  ExprResult TempResult =
8965    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
8966                          move(Exprs), HadMultipleCandidates, false,
8967                          CXXConstructExpr::CK_Complete, SourceRange());
8968  if (TempResult.isInvalid())
8969    return true;
8970
8971  Expr *Temp = TempResult.takeAs<Expr>();
8972  CheckImplicitConversions(Temp, VD->getLocation());
8973  MarkFunctionReferenced(VD->getLocation(), Constructor);
8974  Temp = MaybeCreateExprWithCleanups(Temp);
8975  VD->setInit(Temp);
8976
8977  return false;
8978}
8979
8980void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
8981  if (VD->isInvalidDecl()) return;
8982
8983  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
8984  if (ClassDecl->isInvalidDecl()) return;
8985  if (ClassDecl->hasIrrelevantDestructor()) return;
8986  if (ClassDecl->isDependentContext()) return;
8987
8988  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8989  MarkFunctionReferenced(VD->getLocation(), Destructor);
8990  CheckDestructorAccess(VD->getLocation(), Destructor,
8991                        PDiag(diag::err_access_dtor_var)
8992                        << VD->getDeclName()
8993                        << VD->getType());
8994  DiagnoseUseOfDecl(Destructor, VD->getLocation());
8995
8996  if (!VD->hasGlobalStorage()) return;
8997
8998  // Emit warning for non-trivial dtor in global scope (a real global,
8999  // class-static, function-static).
9000  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9001
9002  // TODO: this should be re-enabled for static locals by !CXAAtExit
9003  if (!VD->isStaticLocal())
9004    Diag(VD->getLocation(), diag::warn_global_destructor);
9005}
9006
9007/// \brief Given a constructor and the set of arguments provided for the
9008/// constructor, convert the arguments and add any required default arguments
9009/// to form a proper call to this constructor.
9010///
9011/// \returns true if an error occurred, false otherwise.
9012bool
9013Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9014                              MultiExprArg ArgsPtr,
9015                              SourceLocation Loc,
9016                              ASTOwningVector<Expr*> &ConvertedArgs,
9017                              bool AllowExplicit) {
9018  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9019  unsigned NumArgs = ArgsPtr.size();
9020  Expr **Args = (Expr **)ArgsPtr.get();
9021
9022  const FunctionProtoType *Proto
9023    = Constructor->getType()->getAs<FunctionProtoType>();
9024  assert(Proto && "Constructor without a prototype?");
9025  unsigned NumArgsInProto = Proto->getNumArgs();
9026
9027  // If too few arguments are available, we'll fill in the rest with defaults.
9028  if (NumArgs < NumArgsInProto)
9029    ConvertedArgs.reserve(NumArgsInProto);
9030  else
9031    ConvertedArgs.reserve(NumArgs);
9032
9033  VariadicCallType CallType =
9034    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9035  SmallVector<Expr *, 8> AllArgs;
9036  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9037                                        Proto, 0, Args, NumArgs, AllArgs,
9038                                        CallType, AllowExplicit);
9039  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9040
9041  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9042
9043  // FIXME: Missing call to CheckFunctionCall or equivalent
9044
9045  return Invalid;
9046}
9047
9048static inline bool
9049CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9050                                       const FunctionDecl *FnDecl) {
9051  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9052  if (isa<NamespaceDecl>(DC)) {
9053    return SemaRef.Diag(FnDecl->getLocation(),
9054                        diag::err_operator_new_delete_declared_in_namespace)
9055      << FnDecl->getDeclName();
9056  }
9057
9058  if (isa<TranslationUnitDecl>(DC) &&
9059      FnDecl->getStorageClass() == SC_Static) {
9060    return SemaRef.Diag(FnDecl->getLocation(),
9061                        diag::err_operator_new_delete_declared_static)
9062      << FnDecl->getDeclName();
9063  }
9064
9065  return false;
9066}
9067
9068static inline bool
9069CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9070                            CanQualType ExpectedResultType,
9071                            CanQualType ExpectedFirstParamType,
9072                            unsigned DependentParamTypeDiag,
9073                            unsigned InvalidParamTypeDiag) {
9074  QualType ResultType =
9075    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9076
9077  // Check that the result type is not dependent.
9078  if (ResultType->isDependentType())
9079    return SemaRef.Diag(FnDecl->getLocation(),
9080                        diag::err_operator_new_delete_dependent_result_type)
9081    << FnDecl->getDeclName() << ExpectedResultType;
9082
9083  // Check that the result type is what we expect.
9084  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9085    return SemaRef.Diag(FnDecl->getLocation(),
9086                        diag::err_operator_new_delete_invalid_result_type)
9087    << FnDecl->getDeclName() << ExpectedResultType;
9088
9089  // A function template must have at least 2 parameters.
9090  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9091    return SemaRef.Diag(FnDecl->getLocation(),
9092                      diag::err_operator_new_delete_template_too_few_parameters)
9093        << FnDecl->getDeclName();
9094
9095  // The function decl must have at least 1 parameter.
9096  if (FnDecl->getNumParams() == 0)
9097    return SemaRef.Diag(FnDecl->getLocation(),
9098                        diag::err_operator_new_delete_too_few_parameters)
9099      << FnDecl->getDeclName();
9100
9101  // Check the the first parameter type is not dependent.
9102  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9103  if (FirstParamType->isDependentType())
9104    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9105      << FnDecl->getDeclName() << ExpectedFirstParamType;
9106
9107  // Check that the first parameter type is what we expect.
9108  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9109      ExpectedFirstParamType)
9110    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9111    << FnDecl->getDeclName() << ExpectedFirstParamType;
9112
9113  return false;
9114}
9115
9116static bool
9117CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9118  // C++ [basic.stc.dynamic.allocation]p1:
9119  //   A program is ill-formed if an allocation function is declared in a
9120  //   namespace scope other than global scope or declared static in global
9121  //   scope.
9122  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9123    return true;
9124
9125  CanQualType SizeTy =
9126    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9127
9128  // C++ [basic.stc.dynamic.allocation]p1:
9129  //  The return type shall be void*. The first parameter shall have type
9130  //  std::size_t.
9131  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9132                                  SizeTy,
9133                                  diag::err_operator_new_dependent_param_type,
9134                                  diag::err_operator_new_param_type))
9135    return true;
9136
9137  // C++ [basic.stc.dynamic.allocation]p1:
9138  //  The first parameter shall not have an associated default argument.
9139  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9140    return SemaRef.Diag(FnDecl->getLocation(),
9141                        diag::err_operator_new_default_arg)
9142      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9143
9144  return false;
9145}
9146
9147static bool
9148CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9149  // C++ [basic.stc.dynamic.deallocation]p1:
9150  //   A program is ill-formed if deallocation functions are declared in a
9151  //   namespace scope other than global scope or declared static in global
9152  //   scope.
9153  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9154    return true;
9155
9156  // C++ [basic.stc.dynamic.deallocation]p2:
9157  //   Each deallocation function shall return void and its first parameter
9158  //   shall be void*.
9159  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9160                                  SemaRef.Context.VoidPtrTy,
9161                                 diag::err_operator_delete_dependent_param_type,
9162                                 diag::err_operator_delete_param_type))
9163    return true;
9164
9165  return false;
9166}
9167
9168/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9169/// of this overloaded operator is well-formed. If so, returns false;
9170/// otherwise, emits appropriate diagnostics and returns true.
9171bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9172  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9173         "Expected an overloaded operator declaration");
9174
9175  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9176
9177  // C++ [over.oper]p5:
9178  //   The allocation and deallocation functions, operator new,
9179  //   operator new[], operator delete and operator delete[], are
9180  //   described completely in 3.7.3. The attributes and restrictions
9181  //   found in the rest of this subclause do not apply to them unless
9182  //   explicitly stated in 3.7.3.
9183  if (Op == OO_Delete || Op == OO_Array_Delete)
9184    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9185
9186  if (Op == OO_New || Op == OO_Array_New)
9187    return CheckOperatorNewDeclaration(*this, FnDecl);
9188
9189  // C++ [over.oper]p6:
9190  //   An operator function shall either be a non-static member
9191  //   function or be a non-member function and have at least one
9192  //   parameter whose type is a class, a reference to a class, an
9193  //   enumeration, or a reference to an enumeration.
9194  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9195    if (MethodDecl->isStatic())
9196      return Diag(FnDecl->getLocation(),
9197                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9198  } else {
9199    bool ClassOrEnumParam = false;
9200    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9201                                   ParamEnd = FnDecl->param_end();
9202         Param != ParamEnd; ++Param) {
9203      QualType ParamType = (*Param)->getType().getNonReferenceType();
9204      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9205          ParamType->isEnumeralType()) {
9206        ClassOrEnumParam = true;
9207        break;
9208      }
9209    }
9210
9211    if (!ClassOrEnumParam)
9212      return Diag(FnDecl->getLocation(),
9213                  diag::err_operator_overload_needs_class_or_enum)
9214        << FnDecl->getDeclName();
9215  }
9216
9217  // C++ [over.oper]p8:
9218  //   An operator function cannot have default arguments (8.3.6),
9219  //   except where explicitly stated below.
9220  //
9221  // Only the function-call operator allows default arguments
9222  // (C++ [over.call]p1).
9223  if (Op != OO_Call) {
9224    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9225         Param != FnDecl->param_end(); ++Param) {
9226      if ((*Param)->hasDefaultArg())
9227        return Diag((*Param)->getLocation(),
9228                    diag::err_operator_overload_default_arg)
9229          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9230    }
9231  }
9232
9233  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9234    { false, false, false }
9235#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9236    , { Unary, Binary, MemberOnly }
9237#include "clang/Basic/OperatorKinds.def"
9238  };
9239
9240  bool CanBeUnaryOperator = OperatorUses[Op][0];
9241  bool CanBeBinaryOperator = OperatorUses[Op][1];
9242  bool MustBeMemberOperator = OperatorUses[Op][2];
9243
9244  // C++ [over.oper]p8:
9245  //   [...] Operator functions cannot have more or fewer parameters
9246  //   than the number required for the corresponding operator, as
9247  //   described in the rest of this subclause.
9248  unsigned NumParams = FnDecl->getNumParams()
9249                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9250  if (Op != OO_Call &&
9251      ((NumParams == 1 && !CanBeUnaryOperator) ||
9252       (NumParams == 2 && !CanBeBinaryOperator) ||
9253       (NumParams < 1) || (NumParams > 2))) {
9254    // We have the wrong number of parameters.
9255    unsigned ErrorKind;
9256    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9257      ErrorKind = 2;  // 2 -> unary or binary.
9258    } else if (CanBeUnaryOperator) {
9259      ErrorKind = 0;  // 0 -> unary
9260    } else {
9261      assert(CanBeBinaryOperator &&
9262             "All non-call overloaded operators are unary or binary!");
9263      ErrorKind = 1;  // 1 -> binary
9264    }
9265
9266    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9267      << FnDecl->getDeclName() << NumParams << ErrorKind;
9268  }
9269
9270  // Overloaded operators other than operator() cannot be variadic.
9271  if (Op != OO_Call &&
9272      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9273    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9274      << FnDecl->getDeclName();
9275  }
9276
9277  // Some operators must be non-static member functions.
9278  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9279    return Diag(FnDecl->getLocation(),
9280                diag::err_operator_overload_must_be_member)
9281      << FnDecl->getDeclName();
9282  }
9283
9284  // C++ [over.inc]p1:
9285  //   The user-defined function called operator++ implements the
9286  //   prefix and postfix ++ operator. If this function is a member
9287  //   function with no parameters, or a non-member function with one
9288  //   parameter of class or enumeration type, it defines the prefix
9289  //   increment operator ++ for objects of that type. If the function
9290  //   is a member function with one parameter (which shall be of type
9291  //   int) or a non-member function with two parameters (the second
9292  //   of which shall be of type int), it defines the postfix
9293  //   increment operator ++ for objects of that type.
9294  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9295    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9296    bool ParamIsInt = false;
9297    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9298      ParamIsInt = BT->getKind() == BuiltinType::Int;
9299
9300    if (!ParamIsInt)
9301      return Diag(LastParam->getLocation(),
9302                  diag::err_operator_overload_post_incdec_must_be_int)
9303        << LastParam->getType() << (Op == OO_MinusMinus);
9304  }
9305
9306  return false;
9307}
9308
9309/// CheckLiteralOperatorDeclaration - Check whether the declaration
9310/// of this literal operator function is well-formed. If so, returns
9311/// false; otherwise, emits appropriate diagnostics and returns true.
9312bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9313  if (isa<CXXMethodDecl>(FnDecl)) {
9314    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9315      << FnDecl->getDeclName();
9316    return true;
9317  }
9318
9319  if (FnDecl->isExternC()) {
9320    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9321    return true;
9322  }
9323
9324  bool Valid = false;
9325
9326  // This might be the definition of a literal operator template.
9327  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9328  // This might be a specialization of a literal operator template.
9329  if (!TpDecl)
9330    TpDecl = FnDecl->getPrimaryTemplate();
9331
9332  // template <char...> type operator "" name() is the only valid template
9333  // signature, and the only valid signature with no parameters.
9334  if (TpDecl) {
9335    if (FnDecl->param_size() == 0) {
9336      // Must have only one template parameter
9337      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9338      if (Params->size() == 1) {
9339        NonTypeTemplateParmDecl *PmDecl =
9340          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9341
9342        // The template parameter must be a char parameter pack.
9343        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9344            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9345          Valid = true;
9346      }
9347    }
9348  } else if (FnDecl->param_size()) {
9349    // Check the first parameter
9350    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9351
9352    QualType T = (*Param)->getType().getUnqualifiedType();
9353
9354    // unsigned long long int, long double, and any character type are allowed
9355    // as the only parameters.
9356    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9357        Context.hasSameType(T, Context.LongDoubleTy) ||
9358        Context.hasSameType(T, Context.CharTy) ||
9359        Context.hasSameType(T, Context.WCharTy) ||
9360        Context.hasSameType(T, Context.Char16Ty) ||
9361        Context.hasSameType(T, Context.Char32Ty)) {
9362      if (++Param == FnDecl->param_end())
9363        Valid = true;
9364      goto FinishedParams;
9365    }
9366
9367    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9368    const PointerType *PT = T->getAs<PointerType>();
9369    if (!PT)
9370      goto FinishedParams;
9371    T = PT->getPointeeType();
9372    if (!T.isConstQualified() || T.isVolatileQualified())
9373      goto FinishedParams;
9374    T = T.getUnqualifiedType();
9375
9376    // Move on to the second parameter;
9377    ++Param;
9378
9379    // If there is no second parameter, the first must be a const char *
9380    if (Param == FnDecl->param_end()) {
9381      if (Context.hasSameType(T, Context.CharTy))
9382        Valid = true;
9383      goto FinishedParams;
9384    }
9385
9386    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9387    // are allowed as the first parameter to a two-parameter function
9388    if (!(Context.hasSameType(T, Context.CharTy) ||
9389          Context.hasSameType(T, Context.WCharTy) ||
9390          Context.hasSameType(T, Context.Char16Ty) ||
9391          Context.hasSameType(T, Context.Char32Ty)))
9392      goto FinishedParams;
9393
9394    // The second and final parameter must be an std::size_t
9395    T = (*Param)->getType().getUnqualifiedType();
9396    if (Context.hasSameType(T, Context.getSizeType()) &&
9397        ++Param == FnDecl->param_end())
9398      Valid = true;
9399  }
9400
9401  // FIXME: This diagnostic is absolutely terrible.
9402FinishedParams:
9403  if (!Valid) {
9404    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9405      << FnDecl->getDeclName();
9406    return true;
9407  }
9408
9409  // A parameter-declaration-clause containing a default argument is not
9410  // equivalent to any of the permitted forms.
9411  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9412                                    ParamEnd = FnDecl->param_end();
9413       Param != ParamEnd; ++Param) {
9414    if ((*Param)->hasDefaultArg()) {
9415      Diag((*Param)->getDefaultArgRange().getBegin(),
9416           diag::err_literal_operator_default_argument)
9417        << (*Param)->getDefaultArgRange();
9418      break;
9419    }
9420  }
9421
9422  StringRef LiteralName
9423    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9424  if (LiteralName[0] != '_') {
9425    // C++11 [usrlit.suffix]p1:
9426    //   Literal suffix identifiers that do not start with an underscore
9427    //   are reserved for future standardization.
9428    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9429  }
9430
9431  return false;
9432}
9433
9434/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9435/// linkage specification, including the language and (if present)
9436/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9437/// the location of the language string literal, which is provided
9438/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9439/// the '{' brace. Otherwise, this linkage specification does not
9440/// have any braces.
9441Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9442                                           SourceLocation LangLoc,
9443                                           StringRef Lang,
9444                                           SourceLocation LBraceLoc) {
9445  LinkageSpecDecl::LanguageIDs Language;
9446  if (Lang == "\"C\"")
9447    Language = LinkageSpecDecl::lang_c;
9448  else if (Lang == "\"C++\"")
9449    Language = LinkageSpecDecl::lang_cxx;
9450  else {
9451    Diag(LangLoc, diag::err_bad_language);
9452    return 0;
9453  }
9454
9455  // FIXME: Add all the various semantics of linkage specifications
9456
9457  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9458                                               ExternLoc, LangLoc, Language);
9459  CurContext->addDecl(D);
9460  PushDeclContext(S, D);
9461  return D;
9462}
9463
9464/// ActOnFinishLinkageSpecification - Complete the definition of
9465/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9466/// valid, it's the position of the closing '}' brace in a linkage
9467/// specification that uses braces.
9468Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9469                                            Decl *LinkageSpec,
9470                                            SourceLocation RBraceLoc) {
9471  if (LinkageSpec) {
9472    if (RBraceLoc.isValid()) {
9473      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9474      LSDecl->setRBraceLoc(RBraceLoc);
9475    }
9476    PopDeclContext();
9477  }
9478  return LinkageSpec;
9479}
9480
9481/// \brief Perform semantic analysis for the variable declaration that
9482/// occurs within a C++ catch clause, returning the newly-created
9483/// variable.
9484VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9485                                         TypeSourceInfo *TInfo,
9486                                         SourceLocation StartLoc,
9487                                         SourceLocation Loc,
9488                                         IdentifierInfo *Name) {
9489  bool Invalid = false;
9490  QualType ExDeclType = TInfo->getType();
9491
9492  // Arrays and functions decay.
9493  if (ExDeclType->isArrayType())
9494    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9495  else if (ExDeclType->isFunctionType())
9496    ExDeclType = Context.getPointerType(ExDeclType);
9497
9498  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9499  // The exception-declaration shall not denote a pointer or reference to an
9500  // incomplete type, other than [cv] void*.
9501  // N2844 forbids rvalue references.
9502  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9503    Diag(Loc, diag::err_catch_rvalue_ref);
9504    Invalid = true;
9505  }
9506
9507  QualType BaseType = ExDeclType;
9508  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9509  unsigned DK = diag::err_catch_incomplete;
9510  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9511    BaseType = Ptr->getPointeeType();
9512    Mode = 1;
9513    DK = diag::err_catch_incomplete_ptr;
9514  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9515    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9516    BaseType = Ref->getPointeeType();
9517    Mode = 2;
9518    DK = diag::err_catch_incomplete_ref;
9519  }
9520  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9521      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9522    Invalid = true;
9523
9524  if (!Invalid && !ExDeclType->isDependentType() &&
9525      RequireNonAbstractType(Loc, ExDeclType,
9526                             diag::err_abstract_type_in_decl,
9527                             AbstractVariableType))
9528    Invalid = true;
9529
9530  // Only the non-fragile NeXT runtime currently supports C++ catches
9531  // of ObjC types, and no runtime supports catching ObjC types by value.
9532  if (!Invalid && getLangOpts().ObjC1) {
9533    QualType T = ExDeclType;
9534    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9535      T = RT->getPointeeType();
9536
9537    if (T->isObjCObjectType()) {
9538      Diag(Loc, diag::err_objc_object_catch);
9539      Invalid = true;
9540    } else if (T->isObjCObjectPointerType()) {
9541      if (!getLangOpts().ObjCNonFragileABI)
9542        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9543    }
9544  }
9545
9546  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9547                                    ExDeclType, TInfo, SC_None, SC_None);
9548  ExDecl->setExceptionVariable(true);
9549
9550  // In ARC, infer 'retaining' for variables of retainable type.
9551  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9552    Invalid = true;
9553
9554  if (!Invalid && !ExDeclType->isDependentType()) {
9555    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9556      // C++ [except.handle]p16:
9557      //   The object declared in an exception-declaration or, if the
9558      //   exception-declaration does not specify a name, a temporary (12.2) is
9559      //   copy-initialized (8.5) from the exception object. [...]
9560      //   The object is destroyed when the handler exits, after the destruction
9561      //   of any automatic objects initialized within the handler.
9562      //
9563      // We just pretend to initialize the object with itself, then make sure
9564      // it can be destroyed later.
9565      QualType initType = ExDeclType;
9566
9567      InitializedEntity entity =
9568        InitializedEntity::InitializeVariable(ExDecl);
9569      InitializationKind initKind =
9570        InitializationKind::CreateCopy(Loc, SourceLocation());
9571
9572      Expr *opaqueValue =
9573        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9574      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9575      ExprResult result = sequence.Perform(*this, entity, initKind,
9576                                           MultiExprArg(&opaqueValue, 1));
9577      if (result.isInvalid())
9578        Invalid = true;
9579      else {
9580        // If the constructor used was non-trivial, set this as the
9581        // "initializer".
9582        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9583        if (!construct->getConstructor()->isTrivial()) {
9584          Expr *init = MaybeCreateExprWithCleanups(construct);
9585          ExDecl->setInit(init);
9586        }
9587
9588        // And make sure it's destructable.
9589        FinalizeVarWithDestructor(ExDecl, recordType);
9590      }
9591    }
9592  }
9593
9594  if (Invalid)
9595    ExDecl->setInvalidDecl();
9596
9597  return ExDecl;
9598}
9599
9600/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9601/// handler.
9602Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9603  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9604  bool Invalid = D.isInvalidType();
9605
9606  // Check for unexpanded parameter packs.
9607  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9608                                               UPPC_ExceptionType)) {
9609    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9610                                             D.getIdentifierLoc());
9611    Invalid = true;
9612  }
9613
9614  IdentifierInfo *II = D.getIdentifier();
9615  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9616                                             LookupOrdinaryName,
9617                                             ForRedeclaration)) {
9618    // The scope should be freshly made just for us. There is just no way
9619    // it contains any previous declaration.
9620    assert(!S->isDeclScope(PrevDecl));
9621    if (PrevDecl->isTemplateParameter()) {
9622      // Maybe we will complain about the shadowed template parameter.
9623      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9624      PrevDecl = 0;
9625    }
9626  }
9627
9628  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9629    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9630      << D.getCXXScopeSpec().getRange();
9631    Invalid = true;
9632  }
9633
9634  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9635                                              D.getLocStart(),
9636                                              D.getIdentifierLoc(),
9637                                              D.getIdentifier());
9638  if (Invalid)
9639    ExDecl->setInvalidDecl();
9640
9641  // Add the exception declaration into this scope.
9642  if (II)
9643    PushOnScopeChains(ExDecl, S);
9644  else
9645    CurContext->addDecl(ExDecl);
9646
9647  ProcessDeclAttributes(S, ExDecl, D);
9648  return ExDecl;
9649}
9650
9651Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9652                                         Expr *AssertExpr,
9653                                         Expr *AssertMessageExpr_,
9654                                         SourceLocation RParenLoc) {
9655  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
9656
9657  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9658    // In a static_assert-declaration, the constant-expression shall be a
9659    // constant expression that can be contextually converted to bool.
9660    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9661    if (Converted.isInvalid())
9662      return 0;
9663
9664    llvm::APSInt Cond;
9665    if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9666          PDiag(diag::err_static_assert_expression_is_not_constant),
9667          /*AllowFold=*/false).isInvalid())
9668      return 0;
9669
9670    if (!Cond) {
9671      llvm::SmallString<256> MsgBuffer;
9672      llvm::raw_svector_ostream Msg(MsgBuffer);
9673      AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
9674      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9675        << Msg.str() << AssertExpr->getSourceRange();
9676    }
9677  }
9678
9679  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9680    return 0;
9681
9682  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9683                                        AssertExpr, AssertMessage, RParenLoc);
9684
9685  CurContext->addDecl(Decl);
9686  return Decl;
9687}
9688
9689/// \brief Perform semantic analysis of the given friend type declaration.
9690///
9691/// \returns A friend declaration that.
9692FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9693                                      SourceLocation FriendLoc,
9694                                      TypeSourceInfo *TSInfo) {
9695  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9696
9697  QualType T = TSInfo->getType();
9698  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9699
9700  // C++03 [class.friend]p2:
9701  //   An elaborated-type-specifier shall be used in a friend declaration
9702  //   for a class.*
9703  //
9704  //   * The class-key of the elaborated-type-specifier is required.
9705  if (!ActiveTemplateInstantiations.empty()) {
9706    // Do not complain about the form of friend template types during
9707    // template instantiation; we will already have complained when the
9708    // template was declared.
9709  } else if (!T->isElaboratedTypeSpecifier()) {
9710    // If we evaluated the type to a record type, suggest putting
9711    // a tag in front.
9712    if (const RecordType *RT = T->getAs<RecordType>()) {
9713      RecordDecl *RD = RT->getDecl();
9714
9715      std::string InsertionText = std::string(" ") + RD->getKindName();
9716
9717      Diag(TypeRange.getBegin(),
9718           getLangOpts().CPlusPlus0x ?
9719             diag::warn_cxx98_compat_unelaborated_friend_type :
9720             diag::ext_unelaborated_friend_type)
9721        << (unsigned) RD->getTagKind()
9722        << T
9723        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9724                                      InsertionText);
9725    } else {
9726      Diag(FriendLoc,
9727           getLangOpts().CPlusPlus0x ?
9728             diag::warn_cxx98_compat_nonclass_type_friend :
9729             diag::ext_nonclass_type_friend)
9730        << T
9731        << SourceRange(FriendLoc, TypeRange.getEnd());
9732    }
9733  } else if (T->getAs<EnumType>()) {
9734    Diag(FriendLoc,
9735         getLangOpts().CPlusPlus0x ?
9736           diag::warn_cxx98_compat_enum_friend :
9737           diag::ext_enum_friend)
9738      << T
9739      << SourceRange(FriendLoc, TypeRange.getEnd());
9740  }
9741
9742  // C++0x [class.friend]p3:
9743  //   If the type specifier in a friend declaration designates a (possibly
9744  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9745  //   the friend declaration is ignored.
9746
9747  // FIXME: C++0x has some syntactic restrictions on friend type declarations
9748  // in [class.friend]p3 that we do not implement.
9749
9750  return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
9751}
9752
9753/// Handle a friend tag declaration where the scope specifier was
9754/// templated.
9755Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9756                                    unsigned TagSpec, SourceLocation TagLoc,
9757                                    CXXScopeSpec &SS,
9758                                    IdentifierInfo *Name, SourceLocation NameLoc,
9759                                    AttributeList *Attr,
9760                                    MultiTemplateParamsArg TempParamLists) {
9761  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9762
9763  bool isExplicitSpecialization = false;
9764  bool Invalid = false;
9765
9766  if (TemplateParameterList *TemplateParams
9767        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9768                                                  TempParamLists.get(),
9769                                                  TempParamLists.size(),
9770                                                  /*friend*/ true,
9771                                                  isExplicitSpecialization,
9772                                                  Invalid)) {
9773    if (TemplateParams->size() > 0) {
9774      // This is a declaration of a class template.
9775      if (Invalid)
9776        return 0;
9777
9778      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9779                                SS, Name, NameLoc, Attr,
9780                                TemplateParams, AS_public,
9781                                /*ModulePrivateLoc=*/SourceLocation(),
9782                                TempParamLists.size() - 1,
9783                   (TemplateParameterList**) TempParamLists.release()).take();
9784    } else {
9785      // The "template<>" header is extraneous.
9786      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9787        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9788      isExplicitSpecialization = true;
9789    }
9790  }
9791
9792  if (Invalid) return 0;
9793
9794  bool isAllExplicitSpecializations = true;
9795  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9796    if (TempParamLists.get()[I]->size()) {
9797      isAllExplicitSpecializations = false;
9798      break;
9799    }
9800  }
9801
9802  // FIXME: don't ignore attributes.
9803
9804  // If it's explicit specializations all the way down, just forget
9805  // about the template header and build an appropriate non-templated
9806  // friend.  TODO: for source fidelity, remember the headers.
9807  if (isAllExplicitSpecializations) {
9808    if (SS.isEmpty()) {
9809      bool Owned = false;
9810      bool IsDependent = false;
9811      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9812                      Attr, AS_public,
9813                      /*ModulePrivateLoc=*/SourceLocation(),
9814                      MultiTemplateParamsArg(), Owned, IsDependent,
9815                      /*ScopedEnumKWLoc=*/SourceLocation(),
9816                      /*ScopedEnumUsesClassTag=*/false,
9817                      /*UnderlyingType=*/TypeResult());
9818    }
9819
9820    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9821    ElaboratedTypeKeyword Keyword
9822      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9823    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9824                                   *Name, NameLoc);
9825    if (T.isNull())
9826      return 0;
9827
9828    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9829    if (isa<DependentNameType>(T)) {
9830      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9831      TL.setElaboratedKeywordLoc(TagLoc);
9832      TL.setQualifierLoc(QualifierLoc);
9833      TL.setNameLoc(NameLoc);
9834    } else {
9835      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9836      TL.setElaboratedKeywordLoc(TagLoc);
9837      TL.setQualifierLoc(QualifierLoc);
9838      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9839    }
9840
9841    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9842                                            TSI, FriendLoc);
9843    Friend->setAccess(AS_public);
9844    CurContext->addDecl(Friend);
9845    return Friend;
9846  }
9847
9848  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9849
9850
9851
9852  // Handle the case of a templated-scope friend class.  e.g.
9853  //   template <class T> class A<T>::B;
9854  // FIXME: we don't support these right now.
9855  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9856  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9857  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9858  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9859  TL.setElaboratedKeywordLoc(TagLoc);
9860  TL.setQualifierLoc(SS.getWithLocInContext(Context));
9861  TL.setNameLoc(NameLoc);
9862
9863  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9864                                          TSI, FriendLoc);
9865  Friend->setAccess(AS_public);
9866  Friend->setUnsupportedFriend(true);
9867  CurContext->addDecl(Friend);
9868  return Friend;
9869}
9870
9871
9872/// Handle a friend type declaration.  This works in tandem with
9873/// ActOnTag.
9874///
9875/// Notes on friend class templates:
9876///
9877/// We generally treat friend class declarations as if they were
9878/// declaring a class.  So, for example, the elaborated type specifier
9879/// in a friend declaration is required to obey the restrictions of a
9880/// class-head (i.e. no typedefs in the scope chain), template
9881/// parameters are required to match up with simple template-ids, &c.
9882/// However, unlike when declaring a template specialization, it's
9883/// okay to refer to a template specialization without an empty
9884/// template parameter declaration, e.g.
9885///   friend class A<T>::B<unsigned>;
9886/// We permit this as a special case; if there are any template
9887/// parameters present at all, require proper matching, i.e.
9888///   template <> template <class T> friend class A<int>::B;
9889Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
9890                                MultiTemplateParamsArg TempParams) {
9891  SourceLocation Loc = DS.getLocStart();
9892
9893  assert(DS.isFriendSpecified());
9894  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9895
9896  // Try to convert the decl specifier to a type.  This works for
9897  // friend templates because ActOnTag never produces a ClassTemplateDecl
9898  // for a TUK_Friend.
9899  Declarator TheDeclarator(DS, Declarator::MemberContext);
9900  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9901  QualType T = TSI->getType();
9902  if (TheDeclarator.isInvalidType())
9903    return 0;
9904
9905  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9906    return 0;
9907
9908  // This is definitely an error in C++98.  It's probably meant to
9909  // be forbidden in C++0x, too, but the specification is just
9910  // poorly written.
9911  //
9912  // The problem is with declarations like the following:
9913  //   template <T> friend A<T>::foo;
9914  // where deciding whether a class C is a friend or not now hinges
9915  // on whether there exists an instantiation of A that causes
9916  // 'foo' to equal C.  There are restrictions on class-heads
9917  // (which we declare (by fiat) elaborated friend declarations to
9918  // be) that makes this tractable.
9919  //
9920  // FIXME: handle "template <> friend class A<T>;", which
9921  // is possibly well-formed?  Who even knows?
9922  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
9923    Diag(Loc, diag::err_tagless_friend_type_template)
9924      << DS.getSourceRange();
9925    return 0;
9926  }
9927
9928  // C++98 [class.friend]p1: A friend of a class is a function
9929  //   or class that is not a member of the class . . .
9930  // This is fixed in DR77, which just barely didn't make the C++03
9931  // deadline.  It's also a very silly restriction that seriously
9932  // affects inner classes and which nobody else seems to implement;
9933  // thus we never diagnose it, not even in -pedantic.
9934  //
9935  // But note that we could warn about it: it's always useless to
9936  // friend one of your own members (it's not, however, worthless to
9937  // friend a member of an arbitrary specialization of your template).
9938
9939  Decl *D;
9940  if (unsigned NumTempParamLists = TempParams.size())
9941    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
9942                                   NumTempParamLists,
9943                                   TempParams.release(),
9944                                   TSI,
9945                                   DS.getFriendSpecLoc());
9946  else
9947    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
9948
9949  if (!D)
9950    return 0;
9951
9952  D->setAccess(AS_public);
9953  CurContext->addDecl(D);
9954
9955  return D;
9956}
9957
9958Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
9959                                    MultiTemplateParamsArg TemplateParams) {
9960  const DeclSpec &DS = D.getDeclSpec();
9961
9962  assert(DS.isFriendSpecified());
9963  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9964
9965  SourceLocation Loc = D.getIdentifierLoc();
9966  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9967
9968  // C++ [class.friend]p1
9969  //   A friend of a class is a function or class....
9970  // Note that this sees through typedefs, which is intended.
9971  // It *doesn't* see through dependent types, which is correct
9972  // according to [temp.arg.type]p3:
9973  //   If a declaration acquires a function type through a
9974  //   type dependent on a template-parameter and this causes
9975  //   a declaration that does not use the syntactic form of a
9976  //   function declarator to have a function type, the program
9977  //   is ill-formed.
9978  if (!TInfo->getType()->isFunctionType()) {
9979    Diag(Loc, diag::err_unexpected_friend);
9980
9981    // It might be worthwhile to try to recover by creating an
9982    // appropriate declaration.
9983    return 0;
9984  }
9985
9986  // C++ [namespace.memdef]p3
9987  //  - If a friend declaration in a non-local class first declares a
9988  //    class or function, the friend class or function is a member
9989  //    of the innermost enclosing namespace.
9990  //  - The name of the friend is not found by simple name lookup
9991  //    until a matching declaration is provided in that namespace
9992  //    scope (either before or after the class declaration granting
9993  //    friendship).
9994  //  - If a friend function is called, its name may be found by the
9995  //    name lookup that considers functions from namespaces and
9996  //    classes associated with the types of the function arguments.
9997  //  - When looking for a prior declaration of a class or a function
9998  //    declared as a friend, scopes outside the innermost enclosing
9999  //    namespace scope are not considered.
10000
10001  CXXScopeSpec &SS = D.getCXXScopeSpec();
10002  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10003  DeclarationName Name = NameInfo.getName();
10004  assert(Name);
10005
10006  // Check for unexpanded parameter packs.
10007  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10008      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10009      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10010    return 0;
10011
10012  // The context we found the declaration in, or in which we should
10013  // create the declaration.
10014  DeclContext *DC;
10015  Scope *DCScope = S;
10016  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10017                        ForRedeclaration);
10018
10019  // FIXME: there are different rules in local classes
10020
10021  // There are four cases here.
10022  //   - There's no scope specifier, in which case we just go to the
10023  //     appropriate scope and look for a function or function template
10024  //     there as appropriate.
10025  // Recover from invalid scope qualifiers as if they just weren't there.
10026  if (SS.isInvalid() || !SS.isSet()) {
10027    // C++0x [namespace.memdef]p3:
10028    //   If the name in a friend declaration is neither qualified nor
10029    //   a template-id and the declaration is a function or an
10030    //   elaborated-type-specifier, the lookup to determine whether
10031    //   the entity has been previously declared shall not consider
10032    //   any scopes outside the innermost enclosing namespace.
10033    // C++0x [class.friend]p11:
10034    //   If a friend declaration appears in a local class and the name
10035    //   specified is an unqualified name, a prior declaration is
10036    //   looked up without considering scopes that are outside the
10037    //   innermost enclosing non-class scope. For a friend function
10038    //   declaration, if there is no prior declaration, the program is
10039    //   ill-formed.
10040    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10041    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10042
10043    // Find the appropriate context according to the above.
10044    DC = CurContext;
10045    while (true) {
10046      // Skip class contexts.  If someone can cite chapter and verse
10047      // for this behavior, that would be nice --- it's what GCC and
10048      // EDG do, and it seems like a reasonable intent, but the spec
10049      // really only says that checks for unqualified existing
10050      // declarations should stop at the nearest enclosing namespace,
10051      // not that they should only consider the nearest enclosing
10052      // namespace.
10053      while (DC->isRecord())
10054        DC = DC->getParent();
10055
10056      LookupQualifiedName(Previous, DC);
10057
10058      // TODO: decide what we think about using declarations.
10059      if (isLocal || !Previous.empty())
10060        break;
10061
10062      if (isTemplateId) {
10063        if (isa<TranslationUnitDecl>(DC)) break;
10064      } else {
10065        if (DC->isFileContext()) break;
10066      }
10067      DC = DC->getParent();
10068    }
10069
10070    // C++ [class.friend]p1: A friend of a class is a function or
10071    //   class that is not a member of the class . . .
10072    // C++11 changes this for both friend types and functions.
10073    // Most C++ 98 compilers do seem to give an error here, so
10074    // we do, too.
10075    if (!Previous.empty() && DC->Equals(CurContext))
10076      Diag(DS.getFriendSpecLoc(),
10077           getLangOpts().CPlusPlus0x ?
10078             diag::warn_cxx98_compat_friend_is_member :
10079             diag::err_friend_is_member);
10080
10081    DCScope = getScopeForDeclContext(S, DC);
10082
10083    // C++ [class.friend]p6:
10084    //   A function can be defined in a friend declaration of a class if and
10085    //   only if the class is a non-local class (9.8), the function name is
10086    //   unqualified, and the function has namespace scope.
10087    if (isLocal && D.isFunctionDefinition()) {
10088      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10089    }
10090
10091  //   - There's a non-dependent scope specifier, in which case we
10092  //     compute it and do a previous lookup there for a function
10093  //     or function template.
10094  } else if (!SS.getScopeRep()->isDependent()) {
10095    DC = computeDeclContext(SS);
10096    if (!DC) return 0;
10097
10098    if (RequireCompleteDeclContext(SS, DC)) return 0;
10099
10100    LookupQualifiedName(Previous, DC);
10101
10102    // Ignore things found implicitly in the wrong scope.
10103    // TODO: better diagnostics for this case.  Suggesting the right
10104    // qualified scope would be nice...
10105    LookupResult::Filter F = Previous.makeFilter();
10106    while (F.hasNext()) {
10107      NamedDecl *D = F.next();
10108      if (!DC->InEnclosingNamespaceSetOf(
10109              D->getDeclContext()->getRedeclContext()))
10110        F.erase();
10111    }
10112    F.done();
10113
10114    if (Previous.empty()) {
10115      D.setInvalidType();
10116      Diag(Loc, diag::err_qualified_friend_not_found)
10117          << Name << TInfo->getType();
10118      return 0;
10119    }
10120
10121    // C++ [class.friend]p1: A friend of a class is a function or
10122    //   class that is not a member of the class . . .
10123    if (DC->Equals(CurContext))
10124      Diag(DS.getFriendSpecLoc(),
10125           getLangOpts().CPlusPlus0x ?
10126             diag::warn_cxx98_compat_friend_is_member :
10127             diag::err_friend_is_member);
10128
10129    if (D.isFunctionDefinition()) {
10130      // C++ [class.friend]p6:
10131      //   A function can be defined in a friend declaration of a class if and
10132      //   only if the class is a non-local class (9.8), the function name is
10133      //   unqualified, and the function has namespace scope.
10134      SemaDiagnosticBuilder DB
10135        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10136
10137      DB << SS.getScopeRep();
10138      if (DC->isFileContext())
10139        DB << FixItHint::CreateRemoval(SS.getRange());
10140      SS.clear();
10141    }
10142
10143  //   - There's a scope specifier that does not match any template
10144  //     parameter lists, in which case we use some arbitrary context,
10145  //     create a method or method template, and wait for instantiation.
10146  //   - There's a scope specifier that does match some template
10147  //     parameter lists, which we don't handle right now.
10148  } else {
10149    if (D.isFunctionDefinition()) {
10150      // C++ [class.friend]p6:
10151      //   A function can be defined in a friend declaration of a class if and
10152      //   only if the class is a non-local class (9.8), the function name is
10153      //   unqualified, and the function has namespace scope.
10154      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10155        << SS.getScopeRep();
10156    }
10157
10158    DC = CurContext;
10159    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10160  }
10161
10162  if (!DC->isRecord()) {
10163    // This implies that it has to be an operator or function.
10164    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10165        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10166        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10167      Diag(Loc, diag::err_introducing_special_friend) <<
10168        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10169         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10170      return 0;
10171    }
10172  }
10173
10174  // FIXME: This is an egregious hack to cope with cases where the scope stack
10175  // does not contain the declaration context, i.e., in an out-of-line
10176  // definition of a class.
10177  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10178  if (!DCScope) {
10179    FakeDCScope.setEntity(DC);
10180    DCScope = &FakeDCScope;
10181  }
10182
10183  bool AddToScope = true;
10184  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10185                                          move(TemplateParams), AddToScope);
10186  if (!ND) return 0;
10187
10188  assert(ND->getDeclContext() == DC);
10189  assert(ND->getLexicalDeclContext() == CurContext);
10190
10191  // Add the function declaration to the appropriate lookup tables,
10192  // adjusting the redeclarations list as necessary.  We don't
10193  // want to do this yet if the friending class is dependent.
10194  //
10195  // Also update the scope-based lookup if the target context's
10196  // lookup context is in lexical scope.
10197  if (!CurContext->isDependentContext()) {
10198    DC = DC->getRedeclContext();
10199    DC->makeDeclVisibleInContext(ND);
10200    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10201      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10202  }
10203
10204  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10205                                       D.getIdentifierLoc(), ND,
10206                                       DS.getFriendSpecLoc());
10207  FrD->setAccess(AS_public);
10208  CurContext->addDecl(FrD);
10209
10210  if (ND->isInvalidDecl())
10211    FrD->setInvalidDecl();
10212  else {
10213    FunctionDecl *FD;
10214    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10215      FD = FTD->getTemplatedDecl();
10216    else
10217      FD = cast<FunctionDecl>(ND);
10218
10219    // Mark templated-scope function declarations as unsupported.
10220    if (FD->getNumTemplateParameterLists())
10221      FrD->setUnsupportedFriend(true);
10222  }
10223
10224  return ND;
10225}
10226
10227void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10228  AdjustDeclIfTemplate(Dcl);
10229
10230  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10231  if (!Fn) {
10232    Diag(DelLoc, diag::err_deleted_non_function);
10233    return;
10234  }
10235  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10236    Diag(DelLoc, diag::err_deleted_decl_not_first);
10237    Diag(Prev->getLocation(), diag::note_previous_declaration);
10238    // If the declaration wasn't the first, we delete the function anyway for
10239    // recovery.
10240  }
10241  Fn->setDeletedAsWritten();
10242
10243  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10244  if (!MD)
10245    return;
10246
10247  // A deleted special member function is trivial if the corresponding
10248  // implicitly-declared function would have been.
10249  switch (getSpecialMember(MD)) {
10250  case CXXInvalid:
10251    break;
10252  case CXXDefaultConstructor:
10253    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10254    break;
10255  case CXXCopyConstructor:
10256    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10257    break;
10258  case CXXMoveConstructor:
10259    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10260    break;
10261  case CXXCopyAssignment:
10262    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10263    break;
10264  case CXXMoveAssignment:
10265    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10266    break;
10267  case CXXDestructor:
10268    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10269    break;
10270  }
10271}
10272
10273void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10274  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10275
10276  if (MD) {
10277    if (MD->getParent()->isDependentType()) {
10278      MD->setDefaulted();
10279      MD->setExplicitlyDefaulted();
10280      return;
10281    }
10282
10283    CXXSpecialMember Member = getSpecialMember(MD);
10284    if (Member == CXXInvalid) {
10285      Diag(DefaultLoc, diag::err_default_special_members);
10286      return;
10287    }
10288
10289    MD->setDefaulted();
10290    MD->setExplicitlyDefaulted();
10291
10292    // If this definition appears within the record, do the checking when
10293    // the record is complete.
10294    const FunctionDecl *Primary = MD;
10295    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10296      // Find the uninstantiated declaration that actually had the '= default'
10297      // on it.
10298      MD->getTemplateInstantiationPattern()->isDefined(Primary);
10299
10300    if (Primary == Primary->getCanonicalDecl())
10301      return;
10302
10303    switch (Member) {
10304    case CXXDefaultConstructor: {
10305      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10306      CheckExplicitlyDefaultedDefaultConstructor(CD);
10307      if (!CD->isInvalidDecl())
10308        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10309      break;
10310    }
10311
10312    case CXXCopyConstructor: {
10313      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10314      CheckExplicitlyDefaultedCopyConstructor(CD);
10315      if (!CD->isInvalidDecl())
10316        DefineImplicitCopyConstructor(DefaultLoc, CD);
10317      break;
10318    }
10319
10320    case CXXCopyAssignment: {
10321      CheckExplicitlyDefaultedCopyAssignment(MD);
10322      if (!MD->isInvalidDecl())
10323        DefineImplicitCopyAssignment(DefaultLoc, MD);
10324      break;
10325    }
10326
10327    case CXXDestructor: {
10328      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10329      CheckExplicitlyDefaultedDestructor(DD);
10330      if (!DD->isInvalidDecl())
10331        DefineImplicitDestructor(DefaultLoc, DD);
10332      break;
10333    }
10334
10335    case CXXMoveConstructor: {
10336      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10337      CheckExplicitlyDefaultedMoveConstructor(CD);
10338      if (!CD->isInvalidDecl())
10339        DefineImplicitMoveConstructor(DefaultLoc, CD);
10340      break;
10341    }
10342
10343    case CXXMoveAssignment: {
10344      CheckExplicitlyDefaultedMoveAssignment(MD);
10345      if (!MD->isInvalidDecl())
10346        DefineImplicitMoveAssignment(DefaultLoc, MD);
10347      break;
10348    }
10349
10350    case CXXInvalid:
10351      llvm_unreachable("Invalid special member.");
10352    }
10353  } else {
10354    Diag(DefaultLoc, diag::err_default_special_members);
10355  }
10356}
10357
10358static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10359  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10360    Stmt *SubStmt = *CI;
10361    if (!SubStmt)
10362      continue;
10363    if (isa<ReturnStmt>(SubStmt))
10364      Self.Diag(SubStmt->getLocStart(),
10365           diag::err_return_in_constructor_handler);
10366    if (!isa<Expr>(SubStmt))
10367      SearchForReturnInStmt(Self, SubStmt);
10368  }
10369}
10370
10371void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10372  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10373    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10374    SearchForReturnInStmt(*this, Handler);
10375  }
10376}
10377
10378bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10379                                             const CXXMethodDecl *Old) {
10380  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10381  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10382
10383  if (Context.hasSameType(NewTy, OldTy) ||
10384      NewTy->isDependentType() || OldTy->isDependentType())
10385    return false;
10386
10387  // Check if the return types are covariant
10388  QualType NewClassTy, OldClassTy;
10389
10390  /// Both types must be pointers or references to classes.
10391  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10392    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10393      NewClassTy = NewPT->getPointeeType();
10394      OldClassTy = OldPT->getPointeeType();
10395    }
10396  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10397    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10398      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10399        NewClassTy = NewRT->getPointeeType();
10400        OldClassTy = OldRT->getPointeeType();
10401      }
10402    }
10403  }
10404
10405  // The return types aren't either both pointers or references to a class type.
10406  if (NewClassTy.isNull()) {
10407    Diag(New->getLocation(),
10408         diag::err_different_return_type_for_overriding_virtual_function)
10409      << New->getDeclName() << NewTy << OldTy;
10410    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10411
10412    return true;
10413  }
10414
10415  // C++ [class.virtual]p6:
10416  //   If the return type of D::f differs from the return type of B::f, the
10417  //   class type in the return type of D::f shall be complete at the point of
10418  //   declaration of D::f or shall be the class type D.
10419  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10420    if (!RT->isBeingDefined() &&
10421        RequireCompleteType(New->getLocation(), NewClassTy,
10422                            PDiag(diag::err_covariant_return_incomplete)
10423                              << New->getDeclName()))
10424    return true;
10425  }
10426
10427  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10428    // Check if the new class derives from the old class.
10429    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10430      Diag(New->getLocation(),
10431           diag::err_covariant_return_not_derived)
10432      << New->getDeclName() << NewTy << OldTy;
10433      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10434      return true;
10435    }
10436
10437    // Check if we the conversion from derived to base is valid.
10438    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10439                    diag::err_covariant_return_inaccessible_base,
10440                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10441                    // FIXME: Should this point to the return type?
10442                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10443      // FIXME: this note won't trigger for delayed access control
10444      // diagnostics, and it's impossible to get an undelayed error
10445      // here from access control during the original parse because
10446      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10447      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10448      return true;
10449    }
10450  }
10451
10452  // The qualifiers of the return types must be the same.
10453  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10454    Diag(New->getLocation(),
10455         diag::err_covariant_return_type_different_qualifications)
10456    << New->getDeclName() << NewTy << OldTy;
10457    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10458    return true;
10459  };
10460
10461
10462  // The new class type must have the same or less qualifiers as the old type.
10463  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10464    Diag(New->getLocation(),
10465         diag::err_covariant_return_type_class_type_more_qualified)
10466    << New->getDeclName() << NewTy << OldTy;
10467    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10468    return true;
10469  };
10470
10471  return false;
10472}
10473
10474/// \brief Mark the given method pure.
10475///
10476/// \param Method the method to be marked pure.
10477///
10478/// \param InitRange the source range that covers the "0" initializer.
10479bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10480  SourceLocation EndLoc = InitRange.getEnd();
10481  if (EndLoc.isValid())
10482    Method->setRangeEnd(EndLoc);
10483
10484  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10485    Method->setPure();
10486    return false;
10487  }
10488
10489  if (!Method->isInvalidDecl())
10490    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10491      << Method->getDeclName() << InitRange;
10492  return true;
10493}
10494
10495/// \brief Determine whether the given declaration is a static data member.
10496static bool isStaticDataMember(Decl *D) {
10497  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10498  if (!Var)
10499    return false;
10500
10501  return Var->isStaticDataMember();
10502}
10503/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10504/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10505/// is a fresh scope pushed for just this purpose.
10506///
10507/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10508/// static data member of class X, names should be looked up in the scope of
10509/// class X.
10510void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10511  // If there is no declaration, there was an error parsing it.
10512  if (D == 0 || D->isInvalidDecl()) return;
10513
10514  // We should only get called for declarations with scope specifiers, like:
10515  //   int foo::bar;
10516  assert(D->isOutOfLine());
10517  EnterDeclaratorContext(S, D->getDeclContext());
10518
10519  // If we are parsing the initializer for a static data member, push a
10520  // new expression evaluation context that is associated with this static
10521  // data member.
10522  if (isStaticDataMember(D))
10523    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10524}
10525
10526/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10527/// initializer for the out-of-line declaration 'D'.
10528void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10529  // If there is no declaration, there was an error parsing it.
10530  if (D == 0 || D->isInvalidDecl()) return;
10531
10532  if (isStaticDataMember(D))
10533    PopExpressionEvaluationContext();
10534
10535  assert(D->isOutOfLine());
10536  ExitDeclaratorContext(S);
10537}
10538
10539/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10540/// C++ if/switch/while/for statement.
10541/// e.g: "if (int x = f()) {...}"
10542DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10543  // C++ 6.4p2:
10544  // The declarator shall not specify a function or an array.
10545  // The type-specifier-seq shall not contain typedef and shall not declare a
10546  // new class or enumeration.
10547  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10548         "Parser allowed 'typedef' as storage class of condition decl.");
10549
10550  Decl *Dcl = ActOnDeclarator(S, D);
10551  if (!Dcl)
10552    return true;
10553
10554  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10555    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10556      << D.getSourceRange();
10557    return true;
10558  }
10559
10560  return Dcl;
10561}
10562
10563void Sema::LoadExternalVTableUses() {
10564  if (!ExternalSource)
10565    return;
10566
10567  SmallVector<ExternalVTableUse, 4> VTables;
10568  ExternalSource->ReadUsedVTables(VTables);
10569  SmallVector<VTableUse, 4> NewUses;
10570  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10571    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10572      = VTablesUsed.find(VTables[I].Record);
10573    // Even if a definition wasn't required before, it may be required now.
10574    if (Pos != VTablesUsed.end()) {
10575      if (!Pos->second && VTables[I].DefinitionRequired)
10576        Pos->second = true;
10577      continue;
10578    }
10579
10580    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10581    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10582  }
10583
10584  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10585}
10586
10587void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10588                          bool DefinitionRequired) {
10589  // Ignore any vtable uses in unevaluated operands or for classes that do
10590  // not have a vtable.
10591  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10592      CurContext->isDependentContext() ||
10593      ExprEvalContexts.back().Context == Unevaluated)
10594    return;
10595
10596  // Try to insert this class into the map.
10597  LoadExternalVTableUses();
10598  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10599  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10600    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10601  if (!Pos.second) {
10602    // If we already had an entry, check to see if we are promoting this vtable
10603    // to required a definition. If so, we need to reappend to the VTableUses
10604    // list, since we may have already processed the first entry.
10605    if (DefinitionRequired && !Pos.first->second) {
10606      Pos.first->second = true;
10607    } else {
10608      // Otherwise, we can early exit.
10609      return;
10610    }
10611  }
10612
10613  // Local classes need to have their virtual members marked
10614  // immediately. For all other classes, we mark their virtual members
10615  // at the end of the translation unit.
10616  if (Class->isLocalClass())
10617    MarkVirtualMembersReferenced(Loc, Class);
10618  else
10619    VTableUses.push_back(std::make_pair(Class, Loc));
10620}
10621
10622bool Sema::DefineUsedVTables() {
10623  LoadExternalVTableUses();
10624  if (VTableUses.empty())
10625    return false;
10626
10627  // Note: The VTableUses vector could grow as a result of marking
10628  // the members of a class as "used", so we check the size each
10629  // time through the loop and prefer indices (with are stable) to
10630  // iterators (which are not).
10631  bool DefinedAnything = false;
10632  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10633    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10634    if (!Class)
10635      continue;
10636
10637    SourceLocation Loc = VTableUses[I].second;
10638
10639    // If this class has a key function, but that key function is
10640    // defined in another translation unit, we don't need to emit the
10641    // vtable even though we're using it.
10642    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10643    if (KeyFunction && !KeyFunction->hasBody()) {
10644      switch (KeyFunction->getTemplateSpecializationKind()) {
10645      case TSK_Undeclared:
10646      case TSK_ExplicitSpecialization:
10647      case TSK_ExplicitInstantiationDeclaration:
10648        // The key function is in another translation unit.
10649        continue;
10650
10651      case TSK_ExplicitInstantiationDefinition:
10652      case TSK_ImplicitInstantiation:
10653        // We will be instantiating the key function.
10654        break;
10655      }
10656    } else if (!KeyFunction) {
10657      // If we have a class with no key function that is the subject
10658      // of an explicit instantiation declaration, suppress the
10659      // vtable; it will live with the explicit instantiation
10660      // definition.
10661      bool IsExplicitInstantiationDeclaration
10662        = Class->getTemplateSpecializationKind()
10663                                      == TSK_ExplicitInstantiationDeclaration;
10664      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10665                                 REnd = Class->redecls_end();
10666           R != REnd; ++R) {
10667        TemplateSpecializationKind TSK
10668          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10669        if (TSK == TSK_ExplicitInstantiationDeclaration)
10670          IsExplicitInstantiationDeclaration = true;
10671        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10672          IsExplicitInstantiationDeclaration = false;
10673          break;
10674        }
10675      }
10676
10677      if (IsExplicitInstantiationDeclaration)
10678        continue;
10679    }
10680
10681    // Mark all of the virtual members of this class as referenced, so
10682    // that we can build a vtable. Then, tell the AST consumer that a
10683    // vtable for this class is required.
10684    DefinedAnything = true;
10685    MarkVirtualMembersReferenced(Loc, Class);
10686    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10687    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10688
10689    // Optionally warn if we're emitting a weak vtable.
10690    if (Class->getLinkage() == ExternalLinkage &&
10691        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10692      const FunctionDecl *KeyFunctionDef = 0;
10693      if (!KeyFunction ||
10694          (KeyFunction->hasBody(KeyFunctionDef) &&
10695           KeyFunctionDef->isInlined()))
10696        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10697             TSK_ExplicitInstantiationDefinition
10698             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10699          << Class;
10700    }
10701  }
10702  VTableUses.clear();
10703
10704  return DefinedAnything;
10705}
10706
10707void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10708                                        const CXXRecordDecl *RD) {
10709  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10710       e = RD->method_end(); i != e; ++i) {
10711    CXXMethodDecl *MD = *i;
10712
10713    // C++ [basic.def.odr]p2:
10714    //   [...] A virtual member function is used if it is not pure. [...]
10715    if (MD->isVirtual() && !MD->isPure())
10716      MarkFunctionReferenced(Loc, MD);
10717  }
10718
10719  // Only classes that have virtual bases need a VTT.
10720  if (RD->getNumVBases() == 0)
10721    return;
10722
10723  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10724           e = RD->bases_end(); i != e; ++i) {
10725    const CXXRecordDecl *Base =
10726        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10727    if (Base->getNumVBases() == 0)
10728      continue;
10729    MarkVirtualMembersReferenced(Loc, Base);
10730  }
10731}
10732
10733/// SetIvarInitializers - This routine builds initialization ASTs for the
10734/// Objective-C implementation whose ivars need be initialized.
10735void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10736  if (!getLangOpts().CPlusPlus)
10737    return;
10738  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10739    SmallVector<ObjCIvarDecl*, 8> ivars;
10740    CollectIvarsToConstructOrDestruct(OID, ivars);
10741    if (ivars.empty())
10742      return;
10743    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10744    for (unsigned i = 0; i < ivars.size(); i++) {
10745      FieldDecl *Field = ivars[i];
10746      if (Field->isInvalidDecl())
10747        continue;
10748
10749      CXXCtorInitializer *Member;
10750      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10751      InitializationKind InitKind =
10752        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10753
10754      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10755      ExprResult MemberInit =
10756        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10757      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10758      // Note, MemberInit could actually come back empty if no initialization
10759      // is required (e.g., because it would call a trivial default constructor)
10760      if (!MemberInit.get() || MemberInit.isInvalid())
10761        continue;
10762
10763      Member =
10764        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10765                                         SourceLocation(),
10766                                         MemberInit.takeAs<Expr>(),
10767                                         SourceLocation());
10768      AllToInit.push_back(Member);
10769
10770      // Be sure that the destructor is accessible and is marked as referenced.
10771      if (const RecordType *RecordTy
10772                  = Context.getBaseElementType(Field->getType())
10773                                                        ->getAs<RecordType>()) {
10774                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10775        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10776          MarkFunctionReferenced(Field->getLocation(), Destructor);
10777          CheckDestructorAccess(Field->getLocation(), Destructor,
10778                            PDiag(diag::err_access_dtor_ivar)
10779                              << Context.getBaseElementType(Field->getType()));
10780        }
10781      }
10782    }
10783    ObjCImplementation->setIvarInitializers(Context,
10784                                            AllToInit.data(), AllToInit.size());
10785  }
10786}
10787
10788static
10789void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10790                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10791                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10792                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10793                           Sema &S) {
10794  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10795                                                   CE = Current.end();
10796  if (Ctor->isInvalidDecl())
10797    return;
10798
10799  const FunctionDecl *FNTarget = 0;
10800  CXXConstructorDecl *Target;
10801
10802  // We ignore the result here since if we don't have a body, Target will be
10803  // null below.
10804  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10805  Target
10806= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10807
10808  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10809                     // Avoid dereferencing a null pointer here.
10810                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10811
10812  if (!Current.insert(Canonical))
10813    return;
10814
10815  // We know that beyond here, we aren't chaining into a cycle.
10816  if (!Target || !Target->isDelegatingConstructor() ||
10817      Target->isInvalidDecl() || Valid.count(TCanonical)) {
10818    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10819      Valid.insert(*CI);
10820    Current.clear();
10821  // We've hit a cycle.
10822  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10823             Current.count(TCanonical)) {
10824    // If we haven't diagnosed this cycle yet, do so now.
10825    if (!Invalid.count(TCanonical)) {
10826      S.Diag((*Ctor->init_begin())->getSourceLocation(),
10827             diag::warn_delegating_ctor_cycle)
10828        << Ctor;
10829
10830      // Don't add a note for a function delegating directo to itself.
10831      if (TCanonical != Canonical)
10832        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10833
10834      CXXConstructorDecl *C = Target;
10835      while (C->getCanonicalDecl() != Canonical) {
10836        (void)C->getTargetConstructor()->hasBody(FNTarget);
10837        assert(FNTarget && "Ctor cycle through bodiless function");
10838
10839        C
10840       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10841        S.Diag(C->getLocation(), diag::note_which_delegates_to);
10842      }
10843    }
10844
10845    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10846      Invalid.insert(*CI);
10847    Current.clear();
10848  } else {
10849    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10850  }
10851}
10852
10853
10854void Sema::CheckDelegatingCtorCycles() {
10855  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10856
10857  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10858                                                   CE = Current.end();
10859
10860  for (DelegatingCtorDeclsType::iterator
10861         I = DelegatingCtorDecls.begin(ExternalSource),
10862         E = DelegatingCtorDecls.end();
10863       I != E; ++I) {
10864   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
10865  }
10866
10867  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10868    (*CI)->setInvalidDecl();
10869}
10870
10871/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10872Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10873  // Implicitly declared functions (e.g. copy constructors) are
10874  // __host__ __device__
10875  if (D->isImplicit())
10876    return CFT_HostDevice;
10877
10878  if (D->hasAttr<CUDAGlobalAttr>())
10879    return CFT_Global;
10880
10881  if (D->hasAttr<CUDADeviceAttr>()) {
10882    if (D->hasAttr<CUDAHostAttr>())
10883      return CFT_HostDevice;
10884    else
10885      return CFT_Device;
10886  }
10887
10888  return CFT_Host;
10889}
10890
10891bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10892                           CUDAFunctionTarget CalleeTarget) {
10893  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10894  // Callable from the device only."
10895  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10896    return true;
10897
10898  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10899  // Callable from the host only."
10900  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10901  // Callable from the host only."
10902  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10903      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10904    return true;
10905
10906  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10907    return true;
10908
10909  return false;
10910}
10911