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