SemaDeclCXX.cpp revision 7c3e615f01e8f9f587315800fdaf2305ed824568
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/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclVisitor.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/StmtVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/CXXFieldCollector.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/ParsedTemplate.h"
36#include "clang/Sema/Scope.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallString.h"
40#include <map>
41#include <set>
42
43using namespace clang;
44
45//===----------------------------------------------------------------------===//
46// CheckDefaultArgumentVisitor
47//===----------------------------------------------------------------------===//
48
49namespace {
50  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
51  /// the default argument of a parameter to determine whether it
52  /// contains any ill-formed subexpressions. For example, this will
53  /// diagnose the use of local variables or parameters within the
54  /// default argument expression.
55  class CheckDefaultArgumentVisitor
56    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57    Expr *DefaultArg;
58    Sema *S;
59
60  public:
61    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
62      : DefaultArg(defarg), S(s) {}
63
64    bool VisitExpr(Expr *Node);
65    bool VisitDeclRefExpr(DeclRefExpr *DRE);
66    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
67    bool VisitLambdaExpr(LambdaExpr *Lambda);
68    bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
69  };
70
71  /// VisitExpr - Visit all of the children of this expression.
72  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
73    bool IsInvalid = false;
74    for (Stmt::child_range I = Node->children(); I; ++I)
75      IsInvalid |= Visit(*I);
76    return IsInvalid;
77  }
78
79  /// VisitDeclRefExpr - Visit a reference to a declaration, to
80  /// determine whether this declaration can be used in the default
81  /// argument expression.
82  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
83    NamedDecl *Decl = DRE->getDecl();
84    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
85      // C++ [dcl.fct.default]p9
86      //   Default arguments are evaluated each time the function is
87      //   called. The order of evaluation of function arguments is
88      //   unspecified. Consequently, parameters of a function shall not
89      //   be used in default argument expressions, even if they are not
90      //   evaluated. Parameters of a function declared before a default
91      //   argument expression are in scope and can hide namespace and
92      //   class member names.
93      return S->Diag(DRE->getLocStart(),
94                     diag::err_param_default_argument_references_param)
95         << Param->getDeclName() << DefaultArg->getSourceRange();
96    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
97      // C++ [dcl.fct.default]p7
98      //   Local variables shall not be used in default argument
99      //   expressions.
100      if (VDecl->isLocalVarDecl())
101        return S->Diag(DRE->getLocStart(),
102                       diag::err_param_default_argument_references_local)
103          << VDecl->getDeclName() << DefaultArg->getSourceRange();
104    }
105
106    return false;
107  }
108
109  /// VisitCXXThisExpr - Visit a C++ "this" expression.
110  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
111    // C++ [dcl.fct.default]p8:
112    //   The keyword this shall not be used in a default argument of a
113    //   member function.
114    return S->Diag(ThisE->getLocStart(),
115                   diag::err_param_default_argument_references_this)
116               << ThisE->getSourceRange();
117  }
118
119  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
120    bool Invalid = false;
121    for (PseudoObjectExpr::semantics_iterator
122           i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
123      Expr *E = *i;
124
125      // Look through bindings.
126      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
127        E = OVE->getSourceExpr();
128        assert(E && "pseudo-object binding without source expression?");
129      }
130
131      Invalid |= Visit(E);
132    }
133    return Invalid;
134  }
135
136  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
137    // C++11 [expr.lambda.prim]p13:
138    //   A lambda-expression appearing in a default argument shall not
139    //   implicitly or explicitly capture any entity.
140    if (Lambda->capture_begin() == Lambda->capture_end())
141      return false;
142
143    return S->Diag(Lambda->getLocStart(),
144                   diag::err_lambda_capture_default_arg);
145  }
146}
147
148void
149Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
150                                                 const CXXMethodDecl *Method) {
151  // If we have an MSAny spec already, don't bother.
152  if (!Method || ComputedEST == EST_MSAny)
153    return;
154
155  const FunctionProtoType *Proto
156    = Method->getType()->getAs<FunctionProtoType>();
157  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
158  if (!Proto)
159    return;
160
161  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
162
163  // If this function can throw any exceptions, make a note of that.
164  if (EST == EST_MSAny || EST == EST_None) {
165    ClearExceptions();
166    ComputedEST = EST;
167    return;
168  }
169
170  // FIXME: If the call to this decl is using any of its default arguments, we
171  // need to search them for potentially-throwing calls.
172
173  // If this function has a basic noexcept, it doesn't affect the outcome.
174  if (EST == EST_BasicNoexcept)
175    return;
176
177  // If we have a throw-all spec at this point, ignore the function.
178  if (ComputedEST == EST_None)
179    return;
180
181  // If we're still at noexcept(true) and there's a nothrow() callee,
182  // change to that specification.
183  if (EST == EST_DynamicNone) {
184    if (ComputedEST == EST_BasicNoexcept)
185      ComputedEST = EST_DynamicNone;
186    return;
187  }
188
189  // Check out noexcept specs.
190  if (EST == EST_ComputedNoexcept) {
191    FunctionProtoType::NoexceptResult NR =
192        Proto->getNoexceptSpec(Self->Context);
193    assert(NR != FunctionProtoType::NR_NoNoexcept &&
194           "Must have noexcept result for EST_ComputedNoexcept.");
195    assert(NR != FunctionProtoType::NR_Dependent &&
196           "Should not generate implicit declarations for dependent cases, "
197           "and don't know how to handle them anyway.");
198
199    // noexcept(false) -> no spec on the new function
200    if (NR == FunctionProtoType::NR_Throw) {
201      ClearExceptions();
202      ComputedEST = EST_None;
203    }
204    // noexcept(true) won't change anything either.
205    return;
206  }
207
208  assert(EST == EST_Dynamic && "EST case not considered earlier.");
209  assert(ComputedEST != EST_None &&
210         "Shouldn't collect exceptions when throw-all is guaranteed.");
211  ComputedEST = EST_Dynamic;
212  // Record the exceptions in this function's exception specification.
213  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
214                                          EEnd = Proto->exception_end();
215       E != EEnd; ++E)
216    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
217      Exceptions.push_back(*E);
218}
219
220void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
221  if (!E || ComputedEST == EST_MSAny)
222    return;
223
224  // FIXME:
225  //
226  // C++0x [except.spec]p14:
227  //   [An] implicit exception-specification specifies the type-id T if and
228  // only if T is allowed by the exception-specification of a function directly
229  // invoked by f's implicit definition; f shall allow all exceptions if any
230  // function it directly invokes allows all exceptions, and f shall allow no
231  // exceptions if every function it directly invokes allows no exceptions.
232  //
233  // Note in particular that if an implicit exception-specification is generated
234  // for a function containing a throw-expression, that specification can still
235  // be noexcept(true).
236  //
237  // Note also that 'directly invoked' is not defined in the standard, and there
238  // is no indication that we should only consider potentially-evaluated calls.
239  //
240  // Ultimately we should implement the intent of the standard: the exception
241  // specification should be the set of exceptions which can be thrown by the
242  // implicit definition. For now, we assume that any non-nothrow expression can
243  // throw any exception.
244
245  if (Self->canThrow(E))
246    ComputedEST = EST_None;
247}
248
249bool
250Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
251                              SourceLocation EqualLoc) {
252  if (RequireCompleteType(Param->getLocation(), Param->getType(),
253                          diag::err_typecheck_decl_incomplete_type)) {
254    Param->setInvalidDecl();
255    return true;
256  }
257
258  // C++ [dcl.fct.default]p5
259  //   A default argument expression is implicitly converted (clause
260  //   4) to the parameter type. The default argument expression has
261  //   the same semantic constraints as the initializer expression in
262  //   a declaration of a variable of the parameter type, using the
263  //   copy-initialization semantics (8.5).
264  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265                                                                    Param);
266  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267                                                           EqualLoc);
268  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
269  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
270  if (Result.isInvalid())
271    return true;
272  Arg = Result.takeAs<Expr>();
273
274  CheckCompletedExpr(Arg, EqualLoc);
275  Arg = MaybeCreateExprWithCleanups(Arg);
276
277  // Okay: add the default argument to the parameter
278  Param->setDefaultArg(Arg);
279
280  // We have already instantiated this parameter; provide each of the
281  // instantiations with the uninstantiated default argument.
282  UnparsedDefaultArgInstantiationsMap::iterator InstPos
283    = UnparsedDefaultArgInstantiations.find(Param);
284  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
285    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
286      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287
288    // We're done tracking this parameter's instantiations.
289    UnparsedDefaultArgInstantiations.erase(InstPos);
290  }
291
292  return false;
293}
294
295/// ActOnParamDefaultArgument - Check whether the default argument
296/// provided for a function parameter is well-formed. If so, attach it
297/// to the parameter declaration.
298void
299Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300                                Expr *DefaultArg) {
301  if (!param || !DefaultArg)
302    return;
303
304  ParmVarDecl *Param = cast<ParmVarDecl>(param);
305  UnparsedDefaultArgLocs.erase(Param);
306
307  // Default arguments are only permitted in C++
308  if (!getLangOpts().CPlusPlus) {
309    Diag(EqualLoc, diag::err_param_default_argument)
310      << DefaultArg->getSourceRange();
311    Param->setInvalidDecl();
312    return;
313  }
314
315  // Check for unexpanded parameter packs.
316  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
317    Param->setInvalidDecl();
318    return;
319  }
320
321  // Check that the default argument is well-formed
322  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
323  if (DefaultArgChecker.Visit(DefaultArg)) {
324    Param->setInvalidDecl();
325    return;
326  }
327
328  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
329}
330
331/// ActOnParamUnparsedDefaultArgument - We've seen a default
332/// argument for a function parameter, but we can't parse it yet
333/// because we're inside a class definition. Note that this default
334/// argument will be parsed later.
335void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
336                                             SourceLocation EqualLoc,
337                                             SourceLocation ArgLoc) {
338  if (!param)
339    return;
340
341  ParmVarDecl *Param = cast<ParmVarDecl>(param);
342  if (Param)
343    Param->setUnparsedDefaultArg();
344
345  UnparsedDefaultArgLocs[Param] = ArgLoc;
346}
347
348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
351  if (!param)
352    return;
353
354  ParmVarDecl *Param = cast<ParmVarDecl>(param);
355
356  Param->setInvalidDecl();
357
358  UnparsedDefaultArgLocs.erase(Param);
359}
360
361/// CheckExtraCXXDefaultArguments - Check for any extra default
362/// arguments in the declarator, which is not a function declaration
363/// or definition and therefore is not permitted to have default
364/// arguments. This routine should be invoked for every declarator
365/// that is not a function declaration or definition.
366void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
367  // C++ [dcl.fct.default]p3
368  //   A default argument expression shall be specified only in the
369  //   parameter-declaration-clause of a function declaration or in a
370  //   template-parameter (14.1). It shall not be specified for a
371  //   parameter pack. If it is specified in a
372  //   parameter-declaration-clause, it shall not occur within a
373  //   declarator or abstract-declarator of a parameter-declaration.
374  bool MightBeFunction = D.isFunctionDeclarationContext();
375  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
376    DeclaratorChunk &chunk = D.getTypeObject(i);
377    if (chunk.Kind == DeclaratorChunk::Function) {
378      if (MightBeFunction) {
379        // This is a function declaration. It can have default arguments, but
380        // keep looking in case its return type is a function type with default
381        // arguments.
382        MightBeFunction = false;
383        continue;
384      }
385      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
386        ParmVarDecl *Param =
387          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
388        if (Param->hasUnparsedDefaultArg()) {
389          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
390          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
391            << SourceRange((*Toks)[1].getLocation(),
392                           Toks->back().getLocation());
393          delete Toks;
394          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
395        } else if (Param->getDefaultArg()) {
396          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
397            << Param->getDefaultArg()->getSourceRange();
398          Param->setDefaultArg(0);
399        }
400      }
401    } else if (chunk.Kind != DeclaratorChunk::Paren) {
402      MightBeFunction = false;
403    }
404  }
405}
406
407/// MergeCXXFunctionDecl - Merge two declarations of the same C++
408/// function, once we already know that they have the same
409/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
410/// error, false otherwise.
411bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
412                                Scope *S) {
413  bool Invalid = false;
414
415  // C++ [dcl.fct.default]p4:
416  //   For non-template functions, default arguments can be added in
417  //   later declarations of a function in the same
418  //   scope. Declarations in different scopes have completely
419  //   distinct sets of default arguments. That is, declarations in
420  //   inner scopes do not acquire default arguments from
421  //   declarations in outer scopes, and vice versa. In a given
422  //   function declaration, all parameters subsequent to a
423  //   parameter with a default argument shall have default
424  //   arguments supplied in this or previous declarations. A
425  //   default argument shall not be redefined by a later
426  //   declaration (not even to the same value).
427  //
428  // C++ [dcl.fct.default]p6:
429  //   Except for member functions of class templates, the default arguments
430  //   in a member function definition that appears outside of the class
431  //   definition are added to the set of default arguments provided by the
432  //   member function declaration in the class definition.
433  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
434    ParmVarDecl *OldParam = Old->getParamDecl(p);
435    ParmVarDecl *NewParam = New->getParamDecl(p);
436
437    bool OldParamHasDfl = OldParam->hasDefaultArg();
438    bool NewParamHasDfl = NewParam->hasDefaultArg();
439
440    NamedDecl *ND = Old;
441    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
442      // Ignore default parameters of old decl if they are not in
443      // the same scope.
444      OldParamHasDfl = false;
445
446    if (OldParamHasDfl && NewParamHasDfl) {
447
448      unsigned DiagDefaultParamID =
449        diag::err_param_default_argument_redefinition;
450
451      // MSVC accepts that default parameters be redefined for member functions
452      // of template class. The new default parameter's value is ignored.
453      Invalid = true;
454      if (getLangOpts().MicrosoftExt) {
455        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
456        if (MD && MD->getParent()->getDescribedClassTemplate()) {
457          // Merge the old default argument into the new parameter.
458          NewParam->setHasInheritedDefaultArg();
459          if (OldParam->hasUninstantiatedDefaultArg())
460            NewParam->setUninstantiatedDefaultArg(
461                                      OldParam->getUninstantiatedDefaultArg());
462          else
463            NewParam->setDefaultArg(OldParam->getInit());
464          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
465          Invalid = false;
466        }
467      }
468
469      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
470      // hint here. Alternatively, we could walk the type-source information
471      // for NewParam to find the last source location in the type... but it
472      // isn't worth the effort right now. This is the kind of test case that
473      // is hard to get right:
474      //   int f(int);
475      //   void g(int (*fp)(int) = f);
476      //   void g(int (*fp)(int) = &f);
477      Diag(NewParam->getLocation(), DiagDefaultParamID)
478        << NewParam->getDefaultArgRange();
479
480      // Look for the function declaration where the default argument was
481      // actually written, which may be a declaration prior to Old.
482      for (FunctionDecl *Older = Old->getPreviousDecl();
483           Older; Older = Older->getPreviousDecl()) {
484        if (!Older->getParamDecl(p)->hasDefaultArg())
485          break;
486
487        OldParam = Older->getParamDecl(p);
488      }
489
490      Diag(OldParam->getLocation(), diag::note_previous_definition)
491        << OldParam->getDefaultArgRange();
492    } else if (OldParamHasDfl) {
493      // Merge the old default argument into the new parameter.
494      // It's important to use getInit() here;  getDefaultArg()
495      // strips off any top-level ExprWithCleanups.
496      NewParam->setHasInheritedDefaultArg();
497      if (OldParam->hasUninstantiatedDefaultArg())
498        NewParam->setUninstantiatedDefaultArg(
499                                      OldParam->getUninstantiatedDefaultArg());
500      else
501        NewParam->setDefaultArg(OldParam->getInit());
502    } else if (NewParamHasDfl) {
503      if (New->getDescribedFunctionTemplate()) {
504        // Paragraph 4, quoted above, only applies to non-template functions.
505        Diag(NewParam->getLocation(),
506             diag::err_param_default_argument_template_redecl)
507          << NewParam->getDefaultArgRange();
508        Diag(Old->getLocation(), diag::note_template_prev_declaration)
509          << false;
510      } else if (New->getTemplateSpecializationKind()
511                   != TSK_ImplicitInstantiation &&
512                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
513        // C++ [temp.expr.spec]p21:
514        //   Default function arguments shall not be specified in a declaration
515        //   or a definition for one of the following explicit specializations:
516        //     - the explicit specialization of a function template;
517        //     - the explicit specialization of a member function template;
518        //     - the explicit specialization of a member function of a class
519        //       template where the class template specialization to which the
520        //       member function specialization belongs is implicitly
521        //       instantiated.
522        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
523          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
524          << New->getDeclName()
525          << NewParam->getDefaultArgRange();
526      } else if (New->getDeclContext()->isDependentContext()) {
527        // C++ [dcl.fct.default]p6 (DR217):
528        //   Default arguments for a member function of a class template shall
529        //   be specified on the initial declaration of the member function
530        //   within the class template.
531        //
532        // Reading the tea leaves a bit in DR217 and its reference to DR205
533        // leads me to the conclusion that one cannot add default function
534        // arguments for an out-of-line definition of a member function of a
535        // dependent type.
536        int WhichKind = 2;
537        if (CXXRecordDecl *Record
538              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
539          if (Record->getDescribedClassTemplate())
540            WhichKind = 0;
541          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
542            WhichKind = 1;
543          else
544            WhichKind = 2;
545        }
546
547        Diag(NewParam->getLocation(),
548             diag::err_param_default_argument_member_template_redecl)
549          << WhichKind
550          << NewParam->getDefaultArgRange();
551      }
552    }
553  }
554
555  // DR1344: If a default argument is added outside a class definition and that
556  // default argument makes the function a special member function, the program
557  // is ill-formed. This can only happen for constructors.
558  if (isa<CXXConstructorDecl>(New) &&
559      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
560    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
561                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
562    if (NewSM != OldSM) {
563      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
564      assert(NewParam->hasDefaultArg());
565      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
566        << NewParam->getDefaultArgRange() << NewSM;
567      Diag(Old->getLocation(), diag::note_previous_declaration);
568    }
569  }
570
571  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
572  // template has a constexpr specifier then all its declarations shall
573  // contain the constexpr specifier.
574  if (New->isConstexpr() != Old->isConstexpr()) {
575    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
576      << New << New->isConstexpr();
577    Diag(Old->getLocation(), diag::note_previous_declaration);
578    Invalid = true;
579  }
580
581  if (CheckEquivalentExceptionSpec(Old, New))
582    Invalid = true;
583
584  return Invalid;
585}
586
587/// \brief Merge the exception specifications of two variable declarations.
588///
589/// This is called when there's a redeclaration of a VarDecl. The function
590/// checks if the redeclaration might have an exception specification and
591/// validates compatibility and merges the specs if necessary.
592void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
593  // Shortcut if exceptions are disabled.
594  if (!getLangOpts().CXXExceptions)
595    return;
596
597  assert(Context.hasSameType(New->getType(), Old->getType()) &&
598         "Should only be called if types are otherwise the same.");
599
600  QualType NewType = New->getType();
601  QualType OldType = Old->getType();
602
603  // We're only interested in pointers and references to functions, as well
604  // as pointers to member functions.
605  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
606    NewType = R->getPointeeType();
607    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
608  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
609    NewType = P->getPointeeType();
610    OldType = OldType->getAs<PointerType>()->getPointeeType();
611  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
612    NewType = M->getPointeeType();
613    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
614  }
615
616  if (!NewType->isFunctionProtoType())
617    return;
618
619  // There's lots of special cases for functions. For function pointers, system
620  // libraries are hopefully not as broken so that we don't need these
621  // workarounds.
622  if (CheckEquivalentExceptionSpec(
623        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
624        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
625    New->setInvalidDecl();
626  }
627}
628
629/// CheckCXXDefaultArguments - Verify that the default arguments for a
630/// function declaration are well-formed according to C++
631/// [dcl.fct.default].
632void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
633  unsigned NumParams = FD->getNumParams();
634  unsigned p;
635
636  // Find first parameter with a default argument
637  for (p = 0; p < NumParams; ++p) {
638    ParmVarDecl *Param = FD->getParamDecl(p);
639    if (Param->hasDefaultArg())
640      break;
641  }
642
643  // C++ [dcl.fct.default]p4:
644  //   In a given function declaration, all parameters
645  //   subsequent to a parameter with a default argument shall
646  //   have default arguments supplied in this or previous
647  //   declarations. A default argument shall not be redefined
648  //   by a later declaration (not even to the same value).
649  unsigned LastMissingDefaultArg = 0;
650  for (; p < NumParams; ++p) {
651    ParmVarDecl *Param = FD->getParamDecl(p);
652    if (!Param->hasDefaultArg()) {
653      if (Param->isInvalidDecl())
654        /* We already complained about this parameter. */;
655      else if (Param->getIdentifier())
656        Diag(Param->getLocation(),
657             diag::err_param_default_argument_missing_name)
658          << Param->getIdentifier();
659      else
660        Diag(Param->getLocation(),
661             diag::err_param_default_argument_missing);
662
663      LastMissingDefaultArg = p;
664    }
665  }
666
667  if (LastMissingDefaultArg > 0) {
668    // Some default arguments were missing. Clear out all of the
669    // default arguments up to (and including) the last missing
670    // default argument, so that we leave the function parameters
671    // in a semantically valid state.
672    for (p = 0; p <= LastMissingDefaultArg; ++p) {
673      ParmVarDecl *Param = FD->getParamDecl(p);
674      if (Param->hasDefaultArg()) {
675        Param->setDefaultArg(0);
676      }
677    }
678  }
679}
680
681// CheckConstexprParameterTypes - Check whether a function's parameter types
682// are all literal types. If so, return true. If not, produce a suitable
683// diagnostic and return false.
684static bool CheckConstexprParameterTypes(Sema &SemaRef,
685                                         const FunctionDecl *FD) {
686  unsigned ArgIndex = 0;
687  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
688  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
689       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
690    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
691    SourceLocation ParamLoc = PD->getLocation();
692    if (!(*i)->isDependentType() &&
693        SemaRef.RequireLiteralType(ParamLoc, *i,
694                                   diag::err_constexpr_non_literal_param,
695                                   ArgIndex+1, PD->getSourceRange(),
696                                   isa<CXXConstructorDecl>(FD)))
697      return false;
698  }
699  return true;
700}
701
702/// \brief Get diagnostic %select index for tag kind for
703/// record diagnostic message.
704/// WARNING: Indexes apply to particular diagnostics only!
705///
706/// \returns diagnostic %select index.
707static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
708  switch (Tag) {
709  case TTK_Struct: return 0;
710  case TTK_Interface: return 1;
711  case TTK_Class:  return 2;
712  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
713  }
714}
715
716// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
717// the requirements of a constexpr function definition or a constexpr
718// constructor definition. If so, return true. If not, produce appropriate
719// diagnostics and return false.
720//
721// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
722bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
723  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
724  if (MD && MD->isInstance()) {
725    // C++11 [dcl.constexpr]p4:
726    //  The definition of a constexpr constructor shall satisfy the following
727    //  constraints:
728    //  - the class shall not have any virtual base classes;
729    const CXXRecordDecl *RD = MD->getParent();
730    if (RD->getNumVBases()) {
731      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
732        << isa<CXXConstructorDecl>(NewFD)
733        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
734      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
735             E = RD->vbases_end(); I != E; ++I)
736        Diag(I->getLocStart(),
737             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
738      return false;
739    }
740  }
741
742  if (!isa<CXXConstructorDecl>(NewFD)) {
743    // C++11 [dcl.constexpr]p3:
744    //  The definition of a constexpr function shall satisfy the following
745    //  constraints:
746    // - it shall not be virtual;
747    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
748    if (Method && Method->isVirtual()) {
749      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
750
751      // If it's not obvious why this function is virtual, find an overridden
752      // function which uses the 'virtual' keyword.
753      const CXXMethodDecl *WrittenVirtual = Method;
754      while (!WrittenVirtual->isVirtualAsWritten())
755        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
756      if (WrittenVirtual != Method)
757        Diag(WrittenVirtual->getLocation(),
758             diag::note_overridden_virtual_function);
759      return false;
760    }
761
762    // - its return type shall be a literal type;
763    QualType RT = NewFD->getResultType();
764    if (!RT->isDependentType() &&
765        RequireLiteralType(NewFD->getLocation(), RT,
766                           diag::err_constexpr_non_literal_return))
767      return false;
768  }
769
770  // - each of its parameter types shall be a literal type;
771  if (!CheckConstexprParameterTypes(*this, NewFD))
772    return false;
773
774  return true;
775}
776
777/// Check the given declaration statement is legal within a constexpr function
778/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
779///
780/// \return true if the body is OK (maybe only as an extension), false if we
781///         have diagnosed a problem.
782static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
783                                   DeclStmt *DS, SourceLocation &Cxx1yLoc) {
784  // C++11 [dcl.constexpr]p3 and p4:
785  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
786  //  contain only
787  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
788         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
789    switch ((*DclIt)->getKind()) {
790    case Decl::StaticAssert:
791    case Decl::Using:
792    case Decl::UsingShadow:
793    case Decl::UsingDirective:
794    case Decl::UnresolvedUsingTypename:
795    case Decl::UnresolvedUsingValue:
796      //   - static_assert-declarations
797      //   - using-declarations,
798      //   - using-directives,
799      continue;
800
801    case Decl::Typedef:
802    case Decl::TypeAlias: {
803      //   - typedef declarations and alias-declarations that do not define
804      //     classes or enumerations,
805      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
806      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
807        // Don't allow variably-modified types in constexpr functions.
808        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
809        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
810          << TL.getSourceRange() << TL.getType()
811          << isa<CXXConstructorDecl>(Dcl);
812        return false;
813      }
814      continue;
815    }
816
817    case Decl::Enum:
818    case Decl::CXXRecord:
819      // C++1y allows types to be defined, not just declared.
820      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
821        SemaRef.Diag(DS->getLocStart(),
822                     SemaRef.getLangOpts().CPlusPlus1y
823                       ? diag::warn_cxx11_compat_constexpr_type_definition
824                       : diag::ext_constexpr_type_definition)
825          << isa<CXXConstructorDecl>(Dcl);
826      continue;
827
828    case Decl::EnumConstant:
829    case Decl::IndirectField:
830    case Decl::ParmVar:
831      // These can only appear with other declarations which are banned in
832      // C++11 and permitted in C++1y, so ignore them.
833      continue;
834
835    case Decl::Var: {
836      // C++1y [dcl.constexpr]p3 allows anything except:
837      //   a definition of a variable of non-literal type or of static or
838      //   thread storage duration or for which no initialization is performed.
839      VarDecl *VD = cast<VarDecl>(*DclIt);
840      if (VD->isThisDeclarationADefinition()) {
841        if (VD->isStaticLocal()) {
842          SemaRef.Diag(VD->getLocation(),
843                       diag::err_constexpr_local_var_static)
844            << isa<CXXConstructorDecl>(Dcl)
845            << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
846          return false;
847        }
848        if (!VD->getType()->isDependentType() &&
849            SemaRef.RequireLiteralType(
850              VD->getLocation(), VD->getType(),
851              diag::err_constexpr_local_var_non_literal_type,
852              isa<CXXConstructorDecl>(Dcl)))
853          return false;
854        if (!VD->hasInit()) {
855          SemaRef.Diag(VD->getLocation(),
856                       diag::err_constexpr_local_var_no_init)
857            << isa<CXXConstructorDecl>(Dcl);
858          return false;
859        }
860      }
861      SemaRef.Diag(VD->getLocation(),
862                   SemaRef.getLangOpts().CPlusPlus1y
863                    ? diag::warn_cxx11_compat_constexpr_local_var
864                    : diag::ext_constexpr_local_var)
865        << isa<CXXConstructorDecl>(Dcl);
866      continue;
867    }
868
869    case Decl::NamespaceAlias:
870    case Decl::Function:
871      // These are disallowed in C++11 and permitted in C++1y. Allow them
872      // everywhere as an extension.
873      if (!Cxx1yLoc.isValid())
874        Cxx1yLoc = DS->getLocStart();
875      continue;
876
877    default:
878      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
879        << isa<CXXConstructorDecl>(Dcl);
880      return false;
881    }
882  }
883
884  return true;
885}
886
887/// Check that the given field is initialized within a constexpr constructor.
888///
889/// \param Dcl The constexpr constructor being checked.
890/// \param Field The field being checked. This may be a member of an anonymous
891///        struct or union nested within the class being checked.
892/// \param Inits All declarations, including anonymous struct/union members and
893///        indirect members, for which any initialization was provided.
894/// \param Diagnosed Set to true if an error is produced.
895static void CheckConstexprCtorInitializer(Sema &SemaRef,
896                                          const FunctionDecl *Dcl,
897                                          FieldDecl *Field,
898                                          llvm::SmallSet<Decl*, 16> &Inits,
899                                          bool &Diagnosed) {
900  if (Field->isUnnamedBitfield())
901    return;
902
903  if (Field->isAnonymousStructOrUnion() &&
904      Field->getType()->getAsCXXRecordDecl()->isEmpty())
905    return;
906
907  if (!Inits.count(Field)) {
908    if (!Diagnosed) {
909      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
910      Diagnosed = true;
911    }
912    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
913  } else if (Field->isAnonymousStructOrUnion()) {
914    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
915    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
916         I != E; ++I)
917      // If an anonymous union contains an anonymous struct of which any member
918      // is initialized, all members must be initialized.
919      if (!RD->isUnion() || Inits.count(*I))
920        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
921  }
922}
923
924/// Check the provided statement is allowed in a constexpr function
925/// definition.
926static bool
927CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
928                           llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
929                           SourceLocation &Cxx1yLoc) {
930  // - its function-body shall be [...] a compound-statement that contains only
931  switch (S->getStmtClass()) {
932  case Stmt::NullStmtClass:
933    //   - null statements,
934    return true;
935
936  case Stmt::DeclStmtClass:
937    //   - static_assert-declarations
938    //   - using-declarations,
939    //   - using-directives,
940    //   - typedef declarations and alias-declarations that do not define
941    //     classes or enumerations,
942    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
943      return false;
944    return true;
945
946  case Stmt::ReturnStmtClass:
947    //   - and exactly one return statement;
948    if (isa<CXXConstructorDecl>(Dcl)) {
949      // C++1y allows return statements in constexpr constructors.
950      if (!Cxx1yLoc.isValid())
951        Cxx1yLoc = S->getLocStart();
952      return true;
953    }
954
955    ReturnStmts.push_back(S->getLocStart());
956    return true;
957
958  case Stmt::CompoundStmtClass: {
959    // C++1y allows compound-statements.
960    if (!Cxx1yLoc.isValid())
961      Cxx1yLoc = S->getLocStart();
962
963    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
964    for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
965           BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
966      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
967                                      Cxx1yLoc))
968        return false;
969    }
970    return true;
971  }
972
973  case Stmt::AttributedStmtClass:
974    if (!Cxx1yLoc.isValid())
975      Cxx1yLoc = S->getLocStart();
976    return true;
977
978  case Stmt::IfStmtClass: {
979    // C++1y allows if-statements.
980    if (!Cxx1yLoc.isValid())
981      Cxx1yLoc = S->getLocStart();
982
983    IfStmt *If = cast<IfStmt>(S);
984    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
985                                    Cxx1yLoc))
986      return false;
987    if (If->getElse() &&
988        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
989                                    Cxx1yLoc))
990      return false;
991    return true;
992  }
993
994  case Stmt::WhileStmtClass:
995  case Stmt::DoStmtClass:
996  case Stmt::ForStmtClass:
997  case Stmt::CXXForRangeStmtClass:
998  case Stmt::ContinueStmtClass:
999    // C++1y allows all of these. We don't allow them as extensions in C++11,
1000    // because they don't make sense without variable mutation.
1001    if (!SemaRef.getLangOpts().CPlusPlus1y)
1002      break;
1003    if (!Cxx1yLoc.isValid())
1004      Cxx1yLoc = S->getLocStart();
1005    for (Stmt::child_range Children = S->children(); Children; ++Children)
1006      if (*Children &&
1007          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1008                                      Cxx1yLoc))
1009        return false;
1010    return true;
1011
1012  case Stmt::SwitchStmtClass:
1013  case Stmt::CaseStmtClass:
1014  case Stmt::DefaultStmtClass:
1015  case Stmt::BreakStmtClass:
1016    // C++1y allows switch-statements, and since they don't need variable
1017    // mutation, we can reasonably allow them in C++11 as an extension.
1018    if (!Cxx1yLoc.isValid())
1019      Cxx1yLoc = S->getLocStart();
1020    for (Stmt::child_range Children = S->children(); Children; ++Children)
1021      if (*Children &&
1022          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1023                                      Cxx1yLoc))
1024        return false;
1025    return true;
1026
1027  default:
1028    if (!isa<Expr>(S))
1029      break;
1030
1031    // C++1y allows expression-statements.
1032    if (!Cxx1yLoc.isValid())
1033      Cxx1yLoc = S->getLocStart();
1034    return true;
1035  }
1036
1037  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1038    << isa<CXXConstructorDecl>(Dcl);
1039  return false;
1040}
1041
1042/// Check the body for the given constexpr function declaration only contains
1043/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1044///
1045/// \return true if the body is OK, false if we have diagnosed a problem.
1046bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1047  if (isa<CXXTryStmt>(Body)) {
1048    // C++11 [dcl.constexpr]p3:
1049    //  The definition of a constexpr function shall satisfy the following
1050    //  constraints: [...]
1051    // - its function-body shall be = delete, = default, or a
1052    //   compound-statement
1053    //
1054    // C++11 [dcl.constexpr]p4:
1055    //  In the definition of a constexpr constructor, [...]
1056    // - its function-body shall not be a function-try-block;
1057    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1058      << isa<CXXConstructorDecl>(Dcl);
1059    return false;
1060  }
1061
1062  SmallVector<SourceLocation, 4> ReturnStmts;
1063
1064  // - its function-body shall be [...] a compound-statement that contains only
1065  //   [... list of cases ...]
1066  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1067  SourceLocation Cxx1yLoc;
1068  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1069         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1070    if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1071      return false;
1072  }
1073
1074  if (Cxx1yLoc.isValid())
1075    Diag(Cxx1yLoc,
1076         getLangOpts().CPlusPlus1y
1077           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1078           : diag::ext_constexpr_body_invalid_stmt)
1079      << isa<CXXConstructorDecl>(Dcl);
1080
1081  if (const CXXConstructorDecl *Constructor
1082        = dyn_cast<CXXConstructorDecl>(Dcl)) {
1083    const CXXRecordDecl *RD = Constructor->getParent();
1084    // DR1359:
1085    // - every non-variant non-static data member and base class sub-object
1086    //   shall be initialized;
1087    // - if the class is a non-empty union, or for each non-empty anonymous
1088    //   union member of a non-union class, exactly one non-static data member
1089    //   shall be initialized;
1090    if (RD->isUnion()) {
1091      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1092        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1093        return false;
1094      }
1095    } else if (!Constructor->isDependentContext() &&
1096               !Constructor->isDelegatingConstructor()) {
1097      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1098
1099      // Skip detailed checking if we have enough initializers, and we would
1100      // allow at most one initializer per member.
1101      bool AnyAnonStructUnionMembers = false;
1102      unsigned Fields = 0;
1103      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1104           E = RD->field_end(); I != E; ++I, ++Fields) {
1105        if (I->isAnonymousStructOrUnion()) {
1106          AnyAnonStructUnionMembers = true;
1107          break;
1108        }
1109      }
1110      if (AnyAnonStructUnionMembers ||
1111          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1112        // Check initialization of non-static data members. Base classes are
1113        // always initialized so do not need to be checked. Dependent bases
1114        // might not have initializers in the member initializer list.
1115        llvm::SmallSet<Decl*, 16> Inits;
1116        for (CXXConstructorDecl::init_const_iterator
1117               I = Constructor->init_begin(), E = Constructor->init_end();
1118             I != E; ++I) {
1119          if (FieldDecl *FD = (*I)->getMember())
1120            Inits.insert(FD);
1121          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1122            Inits.insert(ID->chain_begin(), ID->chain_end());
1123        }
1124
1125        bool Diagnosed = false;
1126        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1127             E = RD->field_end(); I != E; ++I)
1128          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1129        if (Diagnosed)
1130          return false;
1131      }
1132    }
1133  } else {
1134    if (ReturnStmts.empty()) {
1135      // C++1y doesn't require constexpr functions to contain a 'return'
1136      // statement. We still do, unless the return type is void, because
1137      // otherwise if there's no return statement, the function cannot
1138      // be used in a core constant expression.
1139      bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1140      Diag(Dcl->getLocation(),
1141           OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1142              : diag::err_constexpr_body_no_return);
1143      return OK;
1144    }
1145    if (ReturnStmts.size() > 1) {
1146      Diag(ReturnStmts.back(),
1147           getLangOpts().CPlusPlus1y
1148             ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1149             : diag::ext_constexpr_body_multiple_return);
1150      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1151        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1152    }
1153  }
1154
1155  // C++11 [dcl.constexpr]p5:
1156  //   if no function argument values exist such that the function invocation
1157  //   substitution would produce a constant expression, the program is
1158  //   ill-formed; no diagnostic required.
1159  // C++11 [dcl.constexpr]p3:
1160  //   - every constructor call and implicit conversion used in initializing the
1161  //     return value shall be one of those allowed in a constant expression.
1162  // C++11 [dcl.constexpr]p4:
1163  //   - every constructor involved in initializing non-static data members and
1164  //     base class sub-objects shall be a constexpr constructor.
1165  SmallVector<PartialDiagnosticAt, 8> Diags;
1166  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1167    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1168      << isa<CXXConstructorDecl>(Dcl);
1169    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1170      Diag(Diags[I].first, Diags[I].second);
1171    // Don't return false here: we allow this for compatibility in
1172    // system headers.
1173  }
1174
1175  return true;
1176}
1177
1178/// isCurrentClassName - Determine whether the identifier II is the
1179/// name of the class type currently being defined. In the case of
1180/// nested classes, this will only return true if II is the name of
1181/// the innermost class.
1182bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1183                              const CXXScopeSpec *SS) {
1184  assert(getLangOpts().CPlusPlus && "No class names in C!");
1185
1186  CXXRecordDecl *CurDecl;
1187  if (SS && SS->isSet() && !SS->isInvalid()) {
1188    DeclContext *DC = computeDeclContext(*SS, true);
1189    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1190  } else
1191    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1192
1193  if (CurDecl && CurDecl->getIdentifier())
1194    return &II == CurDecl->getIdentifier();
1195  else
1196    return false;
1197}
1198
1199/// \brief Determine whether the given class is a base class of the given
1200/// class, including looking at dependent bases.
1201static bool findCircularInheritance(const CXXRecordDecl *Class,
1202                                    const CXXRecordDecl *Current) {
1203  SmallVector<const CXXRecordDecl*, 8> Queue;
1204
1205  Class = Class->getCanonicalDecl();
1206  while (true) {
1207    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1208                                                  E = Current->bases_end();
1209         I != E; ++I) {
1210      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1211      if (!Base)
1212        continue;
1213
1214      Base = Base->getDefinition();
1215      if (!Base)
1216        continue;
1217
1218      if (Base->getCanonicalDecl() == Class)
1219        return true;
1220
1221      Queue.push_back(Base);
1222    }
1223
1224    if (Queue.empty())
1225      return false;
1226
1227    Current = Queue.back();
1228    Queue.pop_back();
1229  }
1230
1231  return false;
1232}
1233
1234/// \brief Check the validity of a C++ base class specifier.
1235///
1236/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1237/// and returns NULL otherwise.
1238CXXBaseSpecifier *
1239Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1240                         SourceRange SpecifierRange,
1241                         bool Virtual, AccessSpecifier Access,
1242                         TypeSourceInfo *TInfo,
1243                         SourceLocation EllipsisLoc) {
1244  QualType BaseType = TInfo->getType();
1245
1246  // C++ [class.union]p1:
1247  //   A union shall not have base classes.
1248  if (Class->isUnion()) {
1249    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1250      << SpecifierRange;
1251    return 0;
1252  }
1253
1254  if (EllipsisLoc.isValid() &&
1255      !TInfo->getType()->containsUnexpandedParameterPack()) {
1256    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1257      << TInfo->getTypeLoc().getSourceRange();
1258    EllipsisLoc = SourceLocation();
1259  }
1260
1261  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1262
1263  if (BaseType->isDependentType()) {
1264    // Make sure that we don't have circular inheritance among our dependent
1265    // bases. For non-dependent bases, the check for completeness below handles
1266    // this.
1267    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1268      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1269          ((BaseDecl = BaseDecl->getDefinition()) &&
1270           findCircularInheritance(Class, BaseDecl))) {
1271        Diag(BaseLoc, diag::err_circular_inheritance)
1272          << BaseType << Context.getTypeDeclType(Class);
1273
1274        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1275          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1276            << BaseType;
1277
1278        return 0;
1279      }
1280    }
1281
1282    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1283                                          Class->getTagKind() == TTK_Class,
1284                                          Access, TInfo, EllipsisLoc);
1285  }
1286
1287  // Base specifiers must be record types.
1288  if (!BaseType->isRecordType()) {
1289    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1290    return 0;
1291  }
1292
1293  // C++ [class.union]p1:
1294  //   A union shall not be used as a base class.
1295  if (BaseType->isUnionType()) {
1296    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1297    return 0;
1298  }
1299
1300  // C++ [class.derived]p2:
1301  //   The class-name in a base-specifier shall not be an incompletely
1302  //   defined class.
1303  if (RequireCompleteType(BaseLoc, BaseType,
1304                          diag::err_incomplete_base_class, SpecifierRange)) {
1305    Class->setInvalidDecl();
1306    return 0;
1307  }
1308
1309  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1310  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1311  assert(BaseDecl && "Record type has no declaration");
1312  BaseDecl = BaseDecl->getDefinition();
1313  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1314  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1315  assert(CXXBaseDecl && "Base type is not a C++ type");
1316
1317  // C++ [class]p3:
1318  //   If a class is marked final and it appears as a base-type-specifier in
1319  //   base-clause, the program is ill-formed.
1320  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1321    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1322      << CXXBaseDecl->getDeclName();
1323    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1324      << CXXBaseDecl->getDeclName();
1325    return 0;
1326  }
1327
1328  if (BaseDecl->isInvalidDecl())
1329    Class->setInvalidDecl();
1330
1331  // Create the base specifier.
1332  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1333                                        Class->getTagKind() == TTK_Class,
1334                                        Access, TInfo, EllipsisLoc);
1335}
1336
1337/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1338/// one entry in the base class list of a class specifier, for
1339/// example:
1340///    class foo : public bar, virtual private baz {
1341/// 'public bar' and 'virtual private baz' are each base-specifiers.
1342BaseResult
1343Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1344                         ParsedAttributes &Attributes,
1345                         bool Virtual, AccessSpecifier Access,
1346                         ParsedType basetype, SourceLocation BaseLoc,
1347                         SourceLocation EllipsisLoc) {
1348  if (!classdecl)
1349    return true;
1350
1351  AdjustDeclIfTemplate(classdecl);
1352  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1353  if (!Class)
1354    return true;
1355
1356  // We do not support any C++11 attributes on base-specifiers yet.
1357  // Diagnose any attributes we see.
1358  if (!Attributes.empty()) {
1359    for (AttributeList *Attr = Attributes.getList(); Attr;
1360         Attr = Attr->getNext()) {
1361      if (Attr->isInvalid() ||
1362          Attr->getKind() == AttributeList::IgnoredAttribute)
1363        continue;
1364      Diag(Attr->getLoc(),
1365           Attr->getKind() == AttributeList::UnknownAttribute
1366             ? diag::warn_unknown_attribute_ignored
1367             : diag::err_base_specifier_attribute)
1368        << Attr->getName();
1369    }
1370  }
1371
1372  TypeSourceInfo *TInfo = 0;
1373  GetTypeFromParser(basetype, &TInfo);
1374
1375  if (EllipsisLoc.isInvalid() &&
1376      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1377                                      UPPC_BaseType))
1378    return true;
1379
1380  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1381                                                      Virtual, Access, TInfo,
1382                                                      EllipsisLoc))
1383    return BaseSpec;
1384  else
1385    Class->setInvalidDecl();
1386
1387  return true;
1388}
1389
1390/// \brief Performs the actual work of attaching the given base class
1391/// specifiers to a C++ class.
1392bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1393                                unsigned NumBases) {
1394 if (NumBases == 0)
1395    return false;
1396
1397  // Used to keep track of which base types we have already seen, so
1398  // that we can properly diagnose redundant direct base types. Note
1399  // that the key is always the unqualified canonical type of the base
1400  // class.
1401  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1402
1403  // Copy non-redundant base specifiers into permanent storage.
1404  unsigned NumGoodBases = 0;
1405  bool Invalid = false;
1406  for (unsigned idx = 0; idx < NumBases; ++idx) {
1407    QualType NewBaseType
1408      = Context.getCanonicalType(Bases[idx]->getType());
1409    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1410
1411    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1412    if (KnownBase) {
1413      // C++ [class.mi]p3:
1414      //   A class shall not be specified as a direct base class of a
1415      //   derived class more than once.
1416      Diag(Bases[idx]->getLocStart(),
1417           diag::err_duplicate_base_class)
1418        << KnownBase->getType()
1419        << Bases[idx]->getSourceRange();
1420
1421      // Delete the duplicate base class specifier; we're going to
1422      // overwrite its pointer later.
1423      Context.Deallocate(Bases[idx]);
1424
1425      Invalid = true;
1426    } else {
1427      // Okay, add this new base class.
1428      KnownBase = Bases[idx];
1429      Bases[NumGoodBases++] = Bases[idx];
1430      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1431        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1432        if (Class->isInterface() &&
1433              (!RD->isInterface() ||
1434               KnownBase->getAccessSpecifier() != AS_public)) {
1435          // The Microsoft extension __interface does not permit bases that
1436          // are not themselves public interfaces.
1437          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1438            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1439            << RD->getSourceRange();
1440          Invalid = true;
1441        }
1442        if (RD->hasAttr<WeakAttr>())
1443          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1444      }
1445    }
1446  }
1447
1448  // Attach the remaining base class specifiers to the derived class.
1449  Class->setBases(Bases, NumGoodBases);
1450
1451  // Delete the remaining (good) base class specifiers, since their
1452  // data has been copied into the CXXRecordDecl.
1453  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1454    Context.Deallocate(Bases[idx]);
1455
1456  return Invalid;
1457}
1458
1459/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1460/// class, after checking whether there are any duplicate base
1461/// classes.
1462void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1463                               unsigned NumBases) {
1464  if (!ClassDecl || !Bases || !NumBases)
1465    return;
1466
1467  AdjustDeclIfTemplate(ClassDecl);
1468  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1469                       (CXXBaseSpecifier**)(Bases), NumBases);
1470}
1471
1472/// \brief Determine whether the type \p Derived is a C++ class that is
1473/// derived from the type \p Base.
1474bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1475  if (!getLangOpts().CPlusPlus)
1476    return false;
1477
1478  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1479  if (!DerivedRD)
1480    return false;
1481
1482  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1483  if (!BaseRD)
1484    return false;
1485
1486  // If either the base or the derived type is invalid, don't try to
1487  // check whether one is derived from the other.
1488  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1489    return false;
1490
1491  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1492  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1493}
1494
1495/// \brief Determine whether the type \p Derived is a C++ class that is
1496/// derived from the type \p Base.
1497bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1498  if (!getLangOpts().CPlusPlus)
1499    return false;
1500
1501  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1502  if (!DerivedRD)
1503    return false;
1504
1505  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1506  if (!BaseRD)
1507    return false;
1508
1509  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1510}
1511
1512void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1513                              CXXCastPath &BasePathArray) {
1514  assert(BasePathArray.empty() && "Base path array must be empty!");
1515  assert(Paths.isRecordingPaths() && "Must record paths!");
1516
1517  const CXXBasePath &Path = Paths.front();
1518
1519  // We first go backward and check if we have a virtual base.
1520  // FIXME: It would be better if CXXBasePath had the base specifier for
1521  // the nearest virtual base.
1522  unsigned Start = 0;
1523  for (unsigned I = Path.size(); I != 0; --I) {
1524    if (Path[I - 1].Base->isVirtual()) {
1525      Start = I - 1;
1526      break;
1527    }
1528  }
1529
1530  // Now add all bases.
1531  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1532    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1533}
1534
1535/// \brief Determine whether the given base path includes a virtual
1536/// base class.
1537bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1538  for (CXXCastPath::const_iterator B = BasePath.begin(),
1539                                BEnd = BasePath.end();
1540       B != BEnd; ++B)
1541    if ((*B)->isVirtual())
1542      return true;
1543
1544  return false;
1545}
1546
1547/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1548/// conversion (where Derived and Base are class types) is
1549/// well-formed, meaning that the conversion is unambiguous (and
1550/// that all of the base classes are accessible). Returns true
1551/// and emits a diagnostic if the code is ill-formed, returns false
1552/// otherwise. Loc is the location where this routine should point to
1553/// if there is an error, and Range is the source range to highlight
1554/// if there is an error.
1555bool
1556Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1557                                   unsigned InaccessibleBaseID,
1558                                   unsigned AmbigiousBaseConvID,
1559                                   SourceLocation Loc, SourceRange Range,
1560                                   DeclarationName Name,
1561                                   CXXCastPath *BasePath) {
1562  // First, determine whether the path from Derived to Base is
1563  // ambiguous. This is slightly more expensive than checking whether
1564  // the Derived to Base conversion exists, because here we need to
1565  // explore multiple paths to determine if there is an ambiguity.
1566  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1567                     /*DetectVirtual=*/false);
1568  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1569  assert(DerivationOkay &&
1570         "Can only be used with a derived-to-base conversion");
1571  (void)DerivationOkay;
1572
1573  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1574    if (InaccessibleBaseID) {
1575      // Check that the base class can be accessed.
1576      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1577                                   InaccessibleBaseID)) {
1578        case AR_inaccessible:
1579          return true;
1580        case AR_accessible:
1581        case AR_dependent:
1582        case AR_delayed:
1583          break;
1584      }
1585    }
1586
1587    // Build a base path if necessary.
1588    if (BasePath)
1589      BuildBasePathArray(Paths, *BasePath);
1590    return false;
1591  }
1592
1593  // We know that the derived-to-base conversion is ambiguous, and
1594  // we're going to produce a diagnostic. Perform the derived-to-base
1595  // search just one more time to compute all of the possible paths so
1596  // that we can print them out. This is more expensive than any of
1597  // the previous derived-to-base checks we've done, but at this point
1598  // performance isn't as much of an issue.
1599  Paths.clear();
1600  Paths.setRecordingPaths(true);
1601  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1602  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1603  (void)StillOkay;
1604
1605  // Build up a textual representation of the ambiguous paths, e.g.,
1606  // D -> B -> A, that will be used to illustrate the ambiguous
1607  // conversions in the diagnostic. We only print one of the paths
1608  // to each base class subobject.
1609  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1610
1611  Diag(Loc, AmbigiousBaseConvID)
1612  << Derived << Base << PathDisplayStr << Range << Name;
1613  return true;
1614}
1615
1616bool
1617Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1618                                   SourceLocation Loc, SourceRange Range,
1619                                   CXXCastPath *BasePath,
1620                                   bool IgnoreAccess) {
1621  return CheckDerivedToBaseConversion(Derived, Base,
1622                                      IgnoreAccess ? 0
1623                                       : diag::err_upcast_to_inaccessible_base,
1624                                      diag::err_ambiguous_derived_to_base_conv,
1625                                      Loc, Range, DeclarationName(),
1626                                      BasePath);
1627}
1628
1629
1630/// @brief Builds a string representing ambiguous paths from a
1631/// specific derived class to different subobjects of the same base
1632/// class.
1633///
1634/// This function builds a string that can be used in error messages
1635/// to show the different paths that one can take through the
1636/// inheritance hierarchy to go from the derived class to different
1637/// subobjects of a base class. The result looks something like this:
1638/// @code
1639/// struct D -> struct B -> struct A
1640/// struct D -> struct C -> struct A
1641/// @endcode
1642std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1643  std::string PathDisplayStr;
1644  std::set<unsigned> DisplayedPaths;
1645  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1646       Path != Paths.end(); ++Path) {
1647    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1648      // We haven't displayed a path to this particular base
1649      // class subobject yet.
1650      PathDisplayStr += "\n    ";
1651      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1652      for (CXXBasePath::const_iterator Element = Path->begin();
1653           Element != Path->end(); ++Element)
1654        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1655    }
1656  }
1657
1658  return PathDisplayStr;
1659}
1660
1661//===----------------------------------------------------------------------===//
1662// C++ class member Handling
1663//===----------------------------------------------------------------------===//
1664
1665/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1666bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1667                                SourceLocation ASLoc,
1668                                SourceLocation ColonLoc,
1669                                AttributeList *Attrs) {
1670  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1671  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1672                                                  ASLoc, ColonLoc);
1673  CurContext->addHiddenDecl(ASDecl);
1674  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1675}
1676
1677/// CheckOverrideControl - Check C++11 override control semantics.
1678void Sema::CheckOverrideControl(Decl *D) {
1679  if (D->isInvalidDecl())
1680    return;
1681
1682  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1683
1684  // Do we know which functions this declaration might be overriding?
1685  bool OverridesAreKnown = !MD ||
1686      (!MD->getParent()->hasAnyDependentBases() &&
1687       !MD->getType()->isDependentType());
1688
1689  if (!MD || !MD->isVirtual()) {
1690    if (OverridesAreKnown) {
1691      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1692        Diag(OA->getLocation(),
1693             diag::override_keyword_only_allowed_on_virtual_member_functions)
1694          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1695        D->dropAttr<OverrideAttr>();
1696      }
1697      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1698        Diag(FA->getLocation(),
1699             diag::override_keyword_only_allowed_on_virtual_member_functions)
1700          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1701        D->dropAttr<FinalAttr>();
1702      }
1703    }
1704    return;
1705  }
1706
1707  if (!OverridesAreKnown)
1708    return;
1709
1710  // C++11 [class.virtual]p5:
1711  //   If a virtual function is marked with the virt-specifier override and
1712  //   does not override a member function of a base class, the program is
1713  //   ill-formed.
1714  bool HasOverriddenMethods =
1715    MD->begin_overridden_methods() != MD->end_overridden_methods();
1716  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1717    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1718      << MD->getDeclName();
1719}
1720
1721/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1722/// function overrides a virtual member function marked 'final', according to
1723/// C++11 [class.virtual]p4.
1724bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1725                                                  const CXXMethodDecl *Old) {
1726  if (!Old->hasAttr<FinalAttr>())
1727    return false;
1728
1729  Diag(New->getLocation(), diag::err_final_function_overridden)
1730    << New->getDeclName();
1731  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1732  return true;
1733}
1734
1735static bool InitializationHasSideEffects(const FieldDecl &FD) {
1736  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1737  // FIXME: Destruction of ObjC lifetime types has side-effects.
1738  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1739    return !RD->isCompleteDefinition() ||
1740           !RD->hasTrivialDefaultConstructor() ||
1741           !RD->hasTrivialDestructor();
1742  return false;
1743}
1744
1745static AttributeList *getMSPropertyAttr(AttributeList *list) {
1746  for (AttributeList* it = list; it != 0; it = it->getNext())
1747    if (it->isDeclspecPropertyAttribute())
1748      return it;
1749  return 0;
1750}
1751
1752/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1753/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1754/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1755/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1756/// present (but parsing it has been deferred).
1757NamedDecl *
1758Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1759                               MultiTemplateParamsArg TemplateParameterLists,
1760                               Expr *BW, const VirtSpecifiers &VS,
1761                               InClassInitStyle InitStyle) {
1762  const DeclSpec &DS = D.getDeclSpec();
1763  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1764  DeclarationName Name = NameInfo.getName();
1765  SourceLocation Loc = NameInfo.getLoc();
1766
1767  // For anonymous bitfields, the location should point to the type.
1768  if (Loc.isInvalid())
1769    Loc = D.getLocStart();
1770
1771  Expr *BitWidth = static_cast<Expr*>(BW);
1772
1773  assert(isa<CXXRecordDecl>(CurContext));
1774  assert(!DS.isFriendSpecified());
1775
1776  bool isFunc = D.isDeclarationOfFunction();
1777
1778  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1779    // The Microsoft extension __interface only permits public member functions
1780    // and prohibits constructors, destructors, operators, non-public member
1781    // functions, static methods and data members.
1782    unsigned InvalidDecl;
1783    bool ShowDeclName = true;
1784    if (!isFunc)
1785      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1786    else if (AS != AS_public)
1787      InvalidDecl = 2;
1788    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1789      InvalidDecl = 3;
1790    else switch (Name.getNameKind()) {
1791      case DeclarationName::CXXConstructorName:
1792        InvalidDecl = 4;
1793        ShowDeclName = false;
1794        break;
1795
1796      case DeclarationName::CXXDestructorName:
1797        InvalidDecl = 5;
1798        ShowDeclName = false;
1799        break;
1800
1801      case DeclarationName::CXXOperatorName:
1802      case DeclarationName::CXXConversionFunctionName:
1803        InvalidDecl = 6;
1804        break;
1805
1806      default:
1807        InvalidDecl = 0;
1808        break;
1809    }
1810
1811    if (InvalidDecl) {
1812      if (ShowDeclName)
1813        Diag(Loc, diag::err_invalid_member_in_interface)
1814          << (InvalidDecl-1) << Name;
1815      else
1816        Diag(Loc, diag::err_invalid_member_in_interface)
1817          << (InvalidDecl-1) << "";
1818      return 0;
1819    }
1820  }
1821
1822  // C++ 9.2p6: A member shall not be declared to have automatic storage
1823  // duration (auto, register) or with the extern storage-class-specifier.
1824  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1825  // data members and cannot be applied to names declared const or static,
1826  // and cannot be applied to reference members.
1827  switch (DS.getStorageClassSpec()) {
1828  case DeclSpec::SCS_unspecified:
1829  case DeclSpec::SCS_typedef:
1830  case DeclSpec::SCS_static:
1831    break;
1832  case DeclSpec::SCS_mutable:
1833    if (isFunc) {
1834      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1835
1836      // FIXME: It would be nicer if the keyword was ignored only for this
1837      // declarator. Otherwise we could get follow-up errors.
1838      D.getMutableDeclSpec().ClearStorageClassSpecs();
1839    }
1840    break;
1841  default:
1842    Diag(DS.getStorageClassSpecLoc(),
1843         diag::err_storageclass_invalid_for_member);
1844    D.getMutableDeclSpec().ClearStorageClassSpecs();
1845    break;
1846  }
1847
1848  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1849                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1850                      !isFunc);
1851
1852  if (DS.isConstexprSpecified() && isInstField) {
1853    SemaDiagnosticBuilder B =
1854        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1855    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1856    if (InitStyle == ICIS_NoInit) {
1857      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1858      D.getMutableDeclSpec().ClearConstexprSpec();
1859      const char *PrevSpec;
1860      unsigned DiagID;
1861      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1862                                         PrevSpec, DiagID, getLangOpts());
1863      (void)Failed;
1864      assert(!Failed && "Making a constexpr member const shouldn't fail");
1865    } else {
1866      B << 1;
1867      const char *PrevSpec;
1868      unsigned DiagID;
1869      if (D.getMutableDeclSpec().SetStorageClassSpec(
1870          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1871        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1872               "This is the only DeclSpec that should fail to be applied");
1873        B << 1;
1874      } else {
1875        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1876        isInstField = false;
1877      }
1878    }
1879  }
1880
1881  NamedDecl *Member;
1882  if (isInstField) {
1883    CXXScopeSpec &SS = D.getCXXScopeSpec();
1884
1885    // Data members must have identifiers for names.
1886    if (!Name.isIdentifier()) {
1887      Diag(Loc, diag::err_bad_variable_name)
1888        << Name;
1889      return 0;
1890    }
1891
1892    IdentifierInfo *II = Name.getAsIdentifierInfo();
1893
1894    // Member field could not be with "template" keyword.
1895    // So TemplateParameterLists should be empty in this case.
1896    if (TemplateParameterLists.size()) {
1897      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1898      if (TemplateParams->size()) {
1899        // There is no such thing as a member field template.
1900        Diag(D.getIdentifierLoc(), diag::err_template_member)
1901            << II
1902            << SourceRange(TemplateParams->getTemplateLoc(),
1903                TemplateParams->getRAngleLoc());
1904      } else {
1905        // There is an extraneous 'template<>' for this member.
1906        Diag(TemplateParams->getTemplateLoc(),
1907            diag::err_template_member_noparams)
1908            << II
1909            << SourceRange(TemplateParams->getTemplateLoc(),
1910                TemplateParams->getRAngleLoc());
1911      }
1912      return 0;
1913    }
1914
1915    if (SS.isSet() && !SS.isInvalid()) {
1916      // The user provided a superfluous scope specifier inside a class
1917      // definition:
1918      //
1919      // class X {
1920      //   int X::member;
1921      // };
1922      if (DeclContext *DC = computeDeclContext(SS, false))
1923        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1924      else
1925        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1926          << Name << SS.getRange();
1927
1928      SS.clear();
1929    }
1930
1931    AttributeList *MSPropertyAttr =
1932      getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1933    if (MSPropertyAttr) {
1934      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1935                                BitWidth, InitStyle, AS, MSPropertyAttr);
1936      isInstField = false;
1937    } else {
1938      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1939                                BitWidth, InitStyle, AS);
1940    }
1941    assert(Member && "HandleField never returns null");
1942  } else {
1943    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1944
1945    Member = HandleDeclarator(S, D, TemplateParameterLists);
1946    if (!Member) {
1947      return 0;
1948    }
1949
1950    // Non-instance-fields can't have a bitfield.
1951    if (BitWidth) {
1952      if (Member->isInvalidDecl()) {
1953        // don't emit another diagnostic.
1954      } else if (isa<VarDecl>(Member)) {
1955        // C++ 9.6p3: A bit-field shall not be a static member.
1956        // "static member 'A' cannot be a bit-field"
1957        Diag(Loc, diag::err_static_not_bitfield)
1958          << Name << BitWidth->getSourceRange();
1959      } else if (isa<TypedefDecl>(Member)) {
1960        // "typedef member 'x' cannot be a bit-field"
1961        Diag(Loc, diag::err_typedef_not_bitfield)
1962          << Name << BitWidth->getSourceRange();
1963      } else {
1964        // A function typedef ("typedef int f(); f a;").
1965        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1966        Diag(Loc, diag::err_not_integral_type_bitfield)
1967          << Name << cast<ValueDecl>(Member)->getType()
1968          << BitWidth->getSourceRange();
1969      }
1970
1971      BitWidth = 0;
1972      Member->setInvalidDecl();
1973    }
1974
1975    Member->setAccess(AS);
1976
1977    // If we have declared a member function template, set the access of the
1978    // templated declaration as well.
1979    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1980      FunTmpl->getTemplatedDecl()->setAccess(AS);
1981  }
1982
1983  if (VS.isOverrideSpecified())
1984    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1985  if (VS.isFinalSpecified())
1986    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1987
1988  if (VS.getLastLocation().isValid()) {
1989    // Update the end location of a method that has a virt-specifiers.
1990    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1991      MD->setRangeEnd(VS.getLastLocation());
1992  }
1993
1994  CheckOverrideControl(Member);
1995
1996  assert((Name || isInstField) && "No identifier for non-field ?");
1997
1998  if (isInstField) {
1999    FieldDecl *FD = cast<FieldDecl>(Member);
2000    FieldCollector->Add(FD);
2001
2002    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2003                                 FD->getLocation())
2004          != DiagnosticsEngine::Ignored) {
2005      // Remember all explicit private FieldDecls that have a name, no side
2006      // effects and are not part of a dependent type declaration.
2007      if (!FD->isImplicit() && FD->getDeclName() &&
2008          FD->getAccess() == AS_private &&
2009          !FD->hasAttr<UnusedAttr>() &&
2010          !FD->getParent()->isDependentContext() &&
2011          !InitializationHasSideEffects(*FD))
2012        UnusedPrivateFields.insert(FD);
2013    }
2014  }
2015
2016  return Member;
2017}
2018
2019namespace {
2020  class UninitializedFieldVisitor
2021      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2022    Sema &S;
2023    ValueDecl *VD;
2024  public:
2025    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2026    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2027                                                        S(S) {
2028      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2029        this->VD = IFD->getAnonField();
2030      else
2031        this->VD = VD;
2032    }
2033
2034    void HandleExpr(Expr *E) {
2035      if (!E) return;
2036
2037      // Expressions like x(x) sometimes lack the surrounding expressions
2038      // but need to be checked anyways.
2039      HandleValue(E);
2040      Visit(E);
2041    }
2042
2043    void HandleValue(Expr *E) {
2044      E = E->IgnoreParens();
2045
2046      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2047        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2048          return;
2049
2050        // FieldME is the inner-most MemberExpr that is not an anonymous struct
2051        // or union.
2052        MemberExpr *FieldME = ME;
2053
2054        Expr *Base = E;
2055        while (isa<MemberExpr>(Base)) {
2056          ME = cast<MemberExpr>(Base);
2057
2058          if (isa<VarDecl>(ME->getMemberDecl()))
2059            return;
2060
2061          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2062            if (!FD->isAnonymousStructOrUnion())
2063              FieldME = ME;
2064
2065          Base = ME->getBase();
2066        }
2067
2068        if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2069          unsigned diag = VD->getType()->isReferenceType()
2070              ? diag::warn_reference_field_is_uninit
2071              : diag::warn_field_is_uninit;
2072          S.Diag(FieldME->getExprLoc(), diag) << VD;
2073        }
2074        return;
2075      }
2076
2077      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2078        HandleValue(CO->getTrueExpr());
2079        HandleValue(CO->getFalseExpr());
2080        return;
2081      }
2082
2083      if (BinaryConditionalOperator *BCO =
2084              dyn_cast<BinaryConditionalOperator>(E)) {
2085        HandleValue(BCO->getCommon());
2086        HandleValue(BCO->getFalseExpr());
2087        return;
2088      }
2089
2090      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2091        switch (BO->getOpcode()) {
2092        default:
2093          return;
2094        case(BO_PtrMemD):
2095        case(BO_PtrMemI):
2096          HandleValue(BO->getLHS());
2097          return;
2098        case(BO_Comma):
2099          HandleValue(BO->getRHS());
2100          return;
2101        }
2102      }
2103    }
2104
2105    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2106      if (E->getCastKind() == CK_LValueToRValue)
2107        HandleValue(E->getSubExpr());
2108
2109      Inherited::VisitImplicitCastExpr(E);
2110    }
2111
2112    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2113      Expr *Callee = E->getCallee();
2114      if (isa<MemberExpr>(Callee))
2115        HandleValue(Callee);
2116
2117      Inherited::VisitCXXMemberCallExpr(E);
2118    }
2119  };
2120  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2121                                                       ValueDecl *VD) {
2122    UninitializedFieldVisitor(S, VD).HandleExpr(E);
2123  }
2124} // namespace
2125
2126/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2127/// in-class initializer for a non-static C++ class member, and after
2128/// instantiating an in-class initializer in a class template. Such actions
2129/// are deferred until the class is complete.
2130void
2131Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2132                                       Expr *InitExpr) {
2133  FieldDecl *FD = cast<FieldDecl>(D);
2134  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2135         "must set init style when field is created");
2136
2137  if (!InitExpr) {
2138    FD->setInvalidDecl();
2139    FD->removeInClassInitializer();
2140    return;
2141  }
2142
2143  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2144    FD->setInvalidDecl();
2145    FD->removeInClassInitializer();
2146    return;
2147  }
2148
2149  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2150      != DiagnosticsEngine::Ignored) {
2151    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2152  }
2153
2154  ExprResult Init = InitExpr;
2155  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2156    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2157    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2158        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2159        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2160    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2161    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2162    if (Init.isInvalid()) {
2163      FD->setInvalidDecl();
2164      return;
2165    }
2166  }
2167
2168  // C++11 [class.base.init]p7:
2169  //   The initialization of each base and member constitutes a
2170  //   full-expression.
2171  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2172  if (Init.isInvalid()) {
2173    FD->setInvalidDecl();
2174    return;
2175  }
2176
2177  InitExpr = Init.release();
2178
2179  FD->setInClassInitializer(InitExpr);
2180}
2181
2182/// \brief Find the direct and/or virtual base specifiers that
2183/// correspond to the given base type, for use in base initialization
2184/// within a constructor.
2185static bool FindBaseInitializer(Sema &SemaRef,
2186                                CXXRecordDecl *ClassDecl,
2187                                QualType BaseType,
2188                                const CXXBaseSpecifier *&DirectBaseSpec,
2189                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2190  // First, check for a direct base class.
2191  DirectBaseSpec = 0;
2192  for (CXXRecordDecl::base_class_const_iterator Base
2193         = ClassDecl->bases_begin();
2194       Base != ClassDecl->bases_end(); ++Base) {
2195    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2196      // We found a direct base of this type. That's what we're
2197      // initializing.
2198      DirectBaseSpec = &*Base;
2199      break;
2200    }
2201  }
2202
2203  // Check for a virtual base class.
2204  // FIXME: We might be able to short-circuit this if we know in advance that
2205  // there are no virtual bases.
2206  VirtualBaseSpec = 0;
2207  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2208    // We haven't found a base yet; search the class hierarchy for a
2209    // virtual base class.
2210    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2211                       /*DetectVirtual=*/false);
2212    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2213                              BaseType, Paths)) {
2214      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2215           Path != Paths.end(); ++Path) {
2216        if (Path->back().Base->isVirtual()) {
2217          VirtualBaseSpec = Path->back().Base;
2218          break;
2219        }
2220      }
2221    }
2222  }
2223
2224  return DirectBaseSpec || VirtualBaseSpec;
2225}
2226
2227/// \brief Handle a C++ member initializer using braced-init-list syntax.
2228MemInitResult
2229Sema::ActOnMemInitializer(Decl *ConstructorD,
2230                          Scope *S,
2231                          CXXScopeSpec &SS,
2232                          IdentifierInfo *MemberOrBase,
2233                          ParsedType TemplateTypeTy,
2234                          const DeclSpec &DS,
2235                          SourceLocation IdLoc,
2236                          Expr *InitList,
2237                          SourceLocation EllipsisLoc) {
2238  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2239                             DS, IdLoc, InitList,
2240                             EllipsisLoc);
2241}
2242
2243/// \brief Handle a C++ member initializer using parentheses syntax.
2244MemInitResult
2245Sema::ActOnMemInitializer(Decl *ConstructorD,
2246                          Scope *S,
2247                          CXXScopeSpec &SS,
2248                          IdentifierInfo *MemberOrBase,
2249                          ParsedType TemplateTypeTy,
2250                          const DeclSpec &DS,
2251                          SourceLocation IdLoc,
2252                          SourceLocation LParenLoc,
2253                          ArrayRef<Expr *> Args,
2254                          SourceLocation RParenLoc,
2255                          SourceLocation EllipsisLoc) {
2256  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2257                                           Args, RParenLoc);
2258  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2259                             DS, IdLoc, List, EllipsisLoc);
2260}
2261
2262namespace {
2263
2264// Callback to only accept typo corrections that can be a valid C++ member
2265// intializer: either a non-static field member or a base class.
2266class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2267 public:
2268  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2269      : ClassDecl(ClassDecl) {}
2270
2271  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2272    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2273      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2274        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2275      else
2276        return isa<TypeDecl>(ND);
2277    }
2278    return false;
2279  }
2280
2281 private:
2282  CXXRecordDecl *ClassDecl;
2283};
2284
2285}
2286
2287/// \brief Handle a C++ member initializer.
2288MemInitResult
2289Sema::BuildMemInitializer(Decl *ConstructorD,
2290                          Scope *S,
2291                          CXXScopeSpec &SS,
2292                          IdentifierInfo *MemberOrBase,
2293                          ParsedType TemplateTypeTy,
2294                          const DeclSpec &DS,
2295                          SourceLocation IdLoc,
2296                          Expr *Init,
2297                          SourceLocation EllipsisLoc) {
2298  if (!ConstructorD)
2299    return true;
2300
2301  AdjustDeclIfTemplate(ConstructorD);
2302
2303  CXXConstructorDecl *Constructor
2304    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2305  if (!Constructor) {
2306    // The user wrote a constructor initializer on a function that is
2307    // not a C++ constructor. Ignore the error for now, because we may
2308    // have more member initializers coming; we'll diagnose it just
2309    // once in ActOnMemInitializers.
2310    return true;
2311  }
2312
2313  CXXRecordDecl *ClassDecl = Constructor->getParent();
2314
2315  // C++ [class.base.init]p2:
2316  //   Names in a mem-initializer-id are looked up in the scope of the
2317  //   constructor's class and, if not found in that scope, are looked
2318  //   up in the scope containing the constructor's definition.
2319  //   [Note: if the constructor's class contains a member with the
2320  //   same name as a direct or virtual base class of the class, a
2321  //   mem-initializer-id naming the member or base class and composed
2322  //   of a single identifier refers to the class member. A
2323  //   mem-initializer-id for the hidden base class may be specified
2324  //   using a qualified name. ]
2325  if (!SS.getScopeRep() && !TemplateTypeTy) {
2326    // Look for a member, first.
2327    DeclContext::lookup_result Result
2328      = ClassDecl->lookup(MemberOrBase);
2329    if (!Result.empty()) {
2330      ValueDecl *Member;
2331      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2332          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2333        if (EllipsisLoc.isValid())
2334          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2335            << MemberOrBase
2336            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2337
2338        return BuildMemberInitializer(Member, Init, IdLoc);
2339      }
2340    }
2341  }
2342  // It didn't name a member, so see if it names a class.
2343  QualType BaseType;
2344  TypeSourceInfo *TInfo = 0;
2345
2346  if (TemplateTypeTy) {
2347    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2348  } else if (DS.getTypeSpecType() == TST_decltype) {
2349    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2350  } else {
2351    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2352    LookupParsedName(R, S, &SS);
2353
2354    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2355    if (!TyD) {
2356      if (R.isAmbiguous()) return true;
2357
2358      // We don't want access-control diagnostics here.
2359      R.suppressDiagnostics();
2360
2361      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2362        bool NotUnknownSpecialization = false;
2363        DeclContext *DC = computeDeclContext(SS, false);
2364        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2365          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2366
2367        if (!NotUnknownSpecialization) {
2368          // When the scope specifier can refer to a member of an unknown
2369          // specialization, we take it as a type name.
2370          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2371                                       SS.getWithLocInContext(Context),
2372                                       *MemberOrBase, IdLoc);
2373          if (BaseType.isNull())
2374            return true;
2375
2376          R.clear();
2377          R.setLookupName(MemberOrBase);
2378        }
2379      }
2380
2381      // If no results were found, try to correct typos.
2382      TypoCorrection Corr;
2383      MemInitializerValidatorCCC Validator(ClassDecl);
2384      if (R.empty() && BaseType.isNull() &&
2385          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2386                              Validator, ClassDecl))) {
2387        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2388        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2389        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2390          // We have found a non-static data member with a similar
2391          // name to what was typed; complain and initialize that
2392          // member.
2393          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2394            << MemberOrBase << true << CorrectedQuotedStr
2395            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2396          Diag(Member->getLocation(), diag::note_previous_decl)
2397            << CorrectedQuotedStr;
2398
2399          return BuildMemberInitializer(Member, Init, IdLoc);
2400        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2401          const CXXBaseSpecifier *DirectBaseSpec;
2402          const CXXBaseSpecifier *VirtualBaseSpec;
2403          if (FindBaseInitializer(*this, ClassDecl,
2404                                  Context.getTypeDeclType(Type),
2405                                  DirectBaseSpec, VirtualBaseSpec)) {
2406            // We have found a direct or virtual base class with a
2407            // similar name to what was typed; complain and initialize
2408            // that base class.
2409            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2410              << MemberOrBase << false << CorrectedQuotedStr
2411              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2412
2413            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2414                                                             : VirtualBaseSpec;
2415            Diag(BaseSpec->getLocStart(),
2416                 diag::note_base_class_specified_here)
2417              << BaseSpec->getType()
2418              << BaseSpec->getSourceRange();
2419
2420            TyD = Type;
2421          }
2422        }
2423      }
2424
2425      if (!TyD && BaseType.isNull()) {
2426        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2427          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2428        return true;
2429      }
2430    }
2431
2432    if (BaseType.isNull()) {
2433      BaseType = Context.getTypeDeclType(TyD);
2434      if (SS.isSet()) {
2435        NestedNameSpecifier *Qualifier =
2436          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2437
2438        // FIXME: preserve source range information
2439        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2440      }
2441    }
2442  }
2443
2444  if (!TInfo)
2445    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2446
2447  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2448}
2449
2450/// Checks a member initializer expression for cases where reference (or
2451/// pointer) members are bound to by-value parameters (or their addresses).
2452static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2453                                               Expr *Init,
2454                                               SourceLocation IdLoc) {
2455  QualType MemberTy = Member->getType();
2456
2457  // We only handle pointers and references currently.
2458  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2459  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2460    return;
2461
2462  const bool IsPointer = MemberTy->isPointerType();
2463  if (IsPointer) {
2464    if (const UnaryOperator *Op
2465          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2466      // The only case we're worried about with pointers requires taking the
2467      // address.
2468      if (Op->getOpcode() != UO_AddrOf)
2469        return;
2470
2471      Init = Op->getSubExpr();
2472    } else {
2473      // We only handle address-of expression initializers for pointers.
2474      return;
2475    }
2476  }
2477
2478  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2479    // We only warn when referring to a non-reference parameter declaration.
2480    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2481    if (!Parameter || Parameter->getType()->isReferenceType())
2482      return;
2483
2484    S.Diag(Init->getExprLoc(),
2485           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2486                     : diag::warn_bind_ref_member_to_parameter)
2487      << Member << Parameter << Init->getSourceRange();
2488  } else {
2489    // Other initializers are fine.
2490    return;
2491  }
2492
2493  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2494    << (unsigned)IsPointer;
2495}
2496
2497MemInitResult
2498Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2499                             SourceLocation IdLoc) {
2500  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2501  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2502  assert((DirectMember || IndirectMember) &&
2503         "Member must be a FieldDecl or IndirectFieldDecl");
2504
2505  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2506    return true;
2507
2508  if (Member->isInvalidDecl())
2509    return true;
2510
2511  // Diagnose value-uses of fields to initialize themselves, e.g.
2512  //   foo(foo)
2513  // where foo is not also a parameter to the constructor.
2514  // TODO: implement -Wuninitialized and fold this into that framework.
2515  MultiExprArg Args;
2516  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2517    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2518  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2519    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2520  } else {
2521    // Template instantiation doesn't reconstruct ParenListExprs for us.
2522    Args = Init;
2523  }
2524
2525  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2526        != DiagnosticsEngine::Ignored)
2527    for (unsigned i = 0, e = Args.size(); i != e; ++i)
2528      // FIXME: Warn about the case when other fields are used before being
2529      // initialized. For example, let this field be the i'th field. When
2530      // initializing the i'th field, throw a warning if any of the >= i'th
2531      // fields are used, as they are not yet initialized.
2532      // Right now we are only handling the case where the i'th field uses
2533      // itself in its initializer.
2534      // Also need to take into account that some fields may be initialized by
2535      // in-class initializers, see C++11 [class.base.init]p9.
2536      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2537
2538  SourceRange InitRange = Init->getSourceRange();
2539
2540  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2541    // Can't check initialization for a member of dependent type or when
2542    // any of the arguments are type-dependent expressions.
2543    DiscardCleanupsInEvaluationContext();
2544  } else {
2545    bool InitList = false;
2546    if (isa<InitListExpr>(Init)) {
2547      InitList = true;
2548      Args = Init;
2549    }
2550
2551    // Initialize the member.
2552    InitializedEntity MemberEntity =
2553      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2554                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2555    InitializationKind Kind =
2556      InitList ? InitializationKind::CreateDirectList(IdLoc)
2557               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2558                                                  InitRange.getEnd());
2559
2560    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2561    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2562    if (MemberInit.isInvalid())
2563      return true;
2564
2565    CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2566
2567    // C++11 [class.base.init]p7:
2568    //   The initialization of each base and member constitutes a
2569    //   full-expression.
2570    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2571    if (MemberInit.isInvalid())
2572      return true;
2573
2574    Init = MemberInit.get();
2575  }
2576
2577  if (DirectMember) {
2578    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2579                                            InitRange.getBegin(), Init,
2580                                            InitRange.getEnd());
2581  } else {
2582    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2583                                            InitRange.getBegin(), Init,
2584                                            InitRange.getEnd());
2585  }
2586}
2587
2588MemInitResult
2589Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2590                                 CXXRecordDecl *ClassDecl) {
2591  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2592  if (!LangOpts.CPlusPlus11)
2593    return Diag(NameLoc, diag::err_delegating_ctor)
2594      << TInfo->getTypeLoc().getLocalSourceRange();
2595  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2596
2597  bool InitList = true;
2598  MultiExprArg Args = Init;
2599  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2600    InitList = false;
2601    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2602  }
2603
2604  SourceRange InitRange = Init->getSourceRange();
2605  // Initialize the object.
2606  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2607                                     QualType(ClassDecl->getTypeForDecl(), 0));
2608  InitializationKind Kind =
2609    InitList ? InitializationKind::CreateDirectList(NameLoc)
2610             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2611                                                InitRange.getEnd());
2612  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2613  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2614                                              Args, 0);
2615  if (DelegationInit.isInvalid())
2616    return true;
2617
2618  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2619         "Delegating constructor with no target?");
2620
2621  // C++11 [class.base.init]p7:
2622  //   The initialization of each base and member constitutes a
2623  //   full-expression.
2624  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2625                                       InitRange.getBegin());
2626  if (DelegationInit.isInvalid())
2627    return true;
2628
2629  // If we are in a dependent context, template instantiation will
2630  // perform this type-checking again. Just save the arguments that we
2631  // received in a ParenListExpr.
2632  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2633  // of the information that we have about the base
2634  // initializer. However, deconstructing the ASTs is a dicey process,
2635  // and this approach is far more likely to get the corner cases right.
2636  if (CurContext->isDependentContext())
2637    DelegationInit = Owned(Init);
2638
2639  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2640                                          DelegationInit.takeAs<Expr>(),
2641                                          InitRange.getEnd());
2642}
2643
2644MemInitResult
2645Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2646                           Expr *Init, CXXRecordDecl *ClassDecl,
2647                           SourceLocation EllipsisLoc) {
2648  SourceLocation BaseLoc
2649    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2650
2651  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2652    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2653             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2654
2655  // C++ [class.base.init]p2:
2656  //   [...] Unless the mem-initializer-id names a nonstatic data
2657  //   member of the constructor's class or a direct or virtual base
2658  //   of that class, the mem-initializer is ill-formed. A
2659  //   mem-initializer-list can initialize a base class using any
2660  //   name that denotes that base class type.
2661  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2662
2663  SourceRange InitRange = Init->getSourceRange();
2664  if (EllipsisLoc.isValid()) {
2665    // This is a pack expansion.
2666    if (!BaseType->containsUnexpandedParameterPack())  {
2667      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2668        << SourceRange(BaseLoc, InitRange.getEnd());
2669
2670      EllipsisLoc = SourceLocation();
2671    }
2672  } else {
2673    // Check for any unexpanded parameter packs.
2674    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2675      return true;
2676
2677    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2678      return true;
2679  }
2680
2681  // Check for direct and virtual base classes.
2682  const CXXBaseSpecifier *DirectBaseSpec = 0;
2683  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2684  if (!Dependent) {
2685    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2686                                       BaseType))
2687      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2688
2689    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2690                        VirtualBaseSpec);
2691
2692    // C++ [base.class.init]p2:
2693    // Unless the mem-initializer-id names a nonstatic data member of the
2694    // constructor's class or a direct or virtual base of that class, the
2695    // mem-initializer is ill-formed.
2696    if (!DirectBaseSpec && !VirtualBaseSpec) {
2697      // If the class has any dependent bases, then it's possible that
2698      // one of those types will resolve to the same type as
2699      // BaseType. Therefore, just treat this as a dependent base
2700      // class initialization.  FIXME: Should we try to check the
2701      // initialization anyway? It seems odd.
2702      if (ClassDecl->hasAnyDependentBases())
2703        Dependent = true;
2704      else
2705        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2706          << BaseType << Context.getTypeDeclType(ClassDecl)
2707          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2708    }
2709  }
2710
2711  if (Dependent) {
2712    DiscardCleanupsInEvaluationContext();
2713
2714    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2715                                            /*IsVirtual=*/false,
2716                                            InitRange.getBegin(), Init,
2717                                            InitRange.getEnd(), EllipsisLoc);
2718  }
2719
2720  // C++ [base.class.init]p2:
2721  //   If a mem-initializer-id is ambiguous because it designates both
2722  //   a direct non-virtual base class and an inherited virtual base
2723  //   class, the mem-initializer is ill-formed.
2724  if (DirectBaseSpec && VirtualBaseSpec)
2725    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2726      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2727
2728  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2729  if (!BaseSpec)
2730    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2731
2732  // Initialize the base.
2733  bool InitList = true;
2734  MultiExprArg Args = Init;
2735  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2736    InitList = false;
2737    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2738  }
2739
2740  InitializedEntity BaseEntity =
2741    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2742  InitializationKind Kind =
2743    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2744             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2745                                                InitRange.getEnd());
2746  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2747  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2748  if (BaseInit.isInvalid())
2749    return true;
2750
2751  // C++11 [class.base.init]p7:
2752  //   The initialization of each base and member constitutes a
2753  //   full-expression.
2754  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2755  if (BaseInit.isInvalid())
2756    return true;
2757
2758  // If we are in a dependent context, template instantiation will
2759  // perform this type-checking again. Just save the arguments that we
2760  // received in a ParenListExpr.
2761  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2762  // of the information that we have about the base
2763  // initializer. However, deconstructing the ASTs is a dicey process,
2764  // and this approach is far more likely to get the corner cases right.
2765  if (CurContext->isDependentContext())
2766    BaseInit = Owned(Init);
2767
2768  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2769                                          BaseSpec->isVirtual(),
2770                                          InitRange.getBegin(),
2771                                          BaseInit.takeAs<Expr>(),
2772                                          InitRange.getEnd(), EllipsisLoc);
2773}
2774
2775// Create a static_cast\<T&&>(expr).
2776static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2777  if (T.isNull()) T = E->getType();
2778  QualType TargetType = SemaRef.BuildReferenceType(
2779      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2780  SourceLocation ExprLoc = E->getLocStart();
2781  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2782      TargetType, ExprLoc);
2783
2784  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2785                                   SourceRange(ExprLoc, ExprLoc),
2786                                   E->getSourceRange()).take();
2787}
2788
2789/// ImplicitInitializerKind - How an implicit base or member initializer should
2790/// initialize its base or member.
2791enum ImplicitInitializerKind {
2792  IIK_Default,
2793  IIK_Copy,
2794  IIK_Move,
2795  IIK_Inherit
2796};
2797
2798static bool
2799BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2800                             ImplicitInitializerKind ImplicitInitKind,
2801                             CXXBaseSpecifier *BaseSpec,
2802                             bool IsInheritedVirtualBase,
2803                             CXXCtorInitializer *&CXXBaseInit) {
2804  InitializedEntity InitEntity
2805    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2806                                        IsInheritedVirtualBase);
2807
2808  ExprResult BaseInit;
2809
2810  switch (ImplicitInitKind) {
2811  case IIK_Inherit: {
2812    const CXXRecordDecl *Inherited =
2813        Constructor->getInheritedConstructor()->getParent();
2814    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2815    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2816      // C++11 [class.inhctor]p8:
2817      //   Each expression in the expression-list is of the form
2818      //   static_cast<T&&>(p), where p is the name of the corresponding
2819      //   constructor parameter and T is the declared type of p.
2820      SmallVector<Expr*, 16> Args;
2821      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2822        ParmVarDecl *PD = Constructor->getParamDecl(I);
2823        ExprResult ArgExpr =
2824            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2825                                     VK_LValue, SourceLocation());
2826        if (ArgExpr.isInvalid())
2827          return true;
2828        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2829      }
2830
2831      InitializationKind InitKind = InitializationKind::CreateDirect(
2832          Constructor->getLocation(), SourceLocation(), SourceLocation());
2833      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
2834      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2835      break;
2836    }
2837  }
2838  // Fall through.
2839  case IIK_Default: {
2840    InitializationKind InitKind
2841      = InitializationKind::CreateDefault(Constructor->getLocation());
2842    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2843    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
2844    break;
2845  }
2846
2847  case IIK_Move:
2848  case IIK_Copy: {
2849    bool Moving = ImplicitInitKind == IIK_Move;
2850    ParmVarDecl *Param = Constructor->getParamDecl(0);
2851    QualType ParamType = Param->getType().getNonReferenceType();
2852
2853    Expr *CopyCtorArg =
2854      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2855                          SourceLocation(), Param, false,
2856                          Constructor->getLocation(), ParamType,
2857                          VK_LValue, 0);
2858
2859    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2860
2861    // Cast to the base class to avoid ambiguities.
2862    QualType ArgTy =
2863      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2864                                       ParamType.getQualifiers());
2865
2866    if (Moving) {
2867      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2868    }
2869
2870    CXXCastPath BasePath;
2871    BasePath.push_back(BaseSpec);
2872    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2873                                            CK_UncheckedDerivedToBase,
2874                                            Moving ? VK_XValue : VK_LValue,
2875                                            &BasePath).take();
2876
2877    InitializationKind InitKind
2878      = InitializationKind::CreateDirect(Constructor->getLocation(),
2879                                         SourceLocation(), SourceLocation());
2880    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2881    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
2882    break;
2883  }
2884  }
2885
2886  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2887  if (BaseInit.isInvalid())
2888    return true;
2889
2890  CXXBaseInit =
2891    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2892               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2893                                                        SourceLocation()),
2894                                             BaseSpec->isVirtual(),
2895                                             SourceLocation(),
2896                                             BaseInit.takeAs<Expr>(),
2897                                             SourceLocation(),
2898                                             SourceLocation());
2899
2900  return false;
2901}
2902
2903static bool RefersToRValueRef(Expr *MemRef) {
2904  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2905  return Referenced->getType()->isRValueReferenceType();
2906}
2907
2908static bool
2909BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2910                               ImplicitInitializerKind ImplicitInitKind,
2911                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2912                               CXXCtorInitializer *&CXXMemberInit) {
2913  if (Field->isInvalidDecl())
2914    return true;
2915
2916  SourceLocation Loc = Constructor->getLocation();
2917
2918  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2919    bool Moving = ImplicitInitKind == IIK_Move;
2920    ParmVarDecl *Param = Constructor->getParamDecl(0);
2921    QualType ParamType = Param->getType().getNonReferenceType();
2922
2923    // Suppress copying zero-width bitfields.
2924    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2925      return false;
2926
2927    Expr *MemberExprBase =
2928      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2929                          SourceLocation(), Param, false,
2930                          Loc, ParamType, VK_LValue, 0);
2931
2932    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2933
2934    if (Moving) {
2935      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2936    }
2937
2938    // Build a reference to this field within the parameter.
2939    CXXScopeSpec SS;
2940    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2941                              Sema::LookupMemberName);
2942    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2943                                  : cast<ValueDecl>(Field), AS_public);
2944    MemberLookup.resolveKind();
2945    ExprResult CtorArg
2946      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2947                                         ParamType, Loc,
2948                                         /*IsArrow=*/false,
2949                                         SS,
2950                                         /*TemplateKWLoc=*/SourceLocation(),
2951                                         /*FirstQualifierInScope=*/0,
2952                                         MemberLookup,
2953                                         /*TemplateArgs=*/0);
2954    if (CtorArg.isInvalid())
2955      return true;
2956
2957    // C++11 [class.copy]p15:
2958    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2959    //     with static_cast<T&&>(x.m);
2960    if (RefersToRValueRef(CtorArg.get())) {
2961      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2962    }
2963
2964    // When the field we are copying is an array, create index variables for
2965    // each dimension of the array. We use these index variables to subscript
2966    // the source array, and other clients (e.g., CodeGen) will perform the
2967    // necessary iteration with these index variables.
2968    SmallVector<VarDecl *, 4> IndexVariables;
2969    QualType BaseType = Field->getType();
2970    QualType SizeType = SemaRef.Context.getSizeType();
2971    bool InitializingArray = false;
2972    while (const ConstantArrayType *Array
2973                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2974      InitializingArray = true;
2975      // Create the iteration variable for this array index.
2976      IdentifierInfo *IterationVarName = 0;
2977      {
2978        SmallString<8> Str;
2979        llvm::raw_svector_ostream OS(Str);
2980        OS << "__i" << IndexVariables.size();
2981        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2982      }
2983      VarDecl *IterationVar
2984        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2985                          IterationVarName, SizeType,
2986                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2987                          SC_None);
2988      IndexVariables.push_back(IterationVar);
2989
2990      // Create a reference to the iteration variable.
2991      ExprResult IterationVarRef
2992        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2993      assert(!IterationVarRef.isInvalid() &&
2994             "Reference to invented variable cannot fail!");
2995      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2996      assert(!IterationVarRef.isInvalid() &&
2997             "Conversion of invented variable cannot fail!");
2998
2999      // Subscript the array with this iteration variable.
3000      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3001                                                        IterationVarRef.take(),
3002                                                        Loc);
3003      if (CtorArg.isInvalid())
3004        return true;
3005
3006      BaseType = Array->getElementType();
3007    }
3008
3009    // The array subscript expression is an lvalue, which is wrong for moving.
3010    if (Moving && InitializingArray)
3011      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3012
3013    // Construct the entity that we will be initializing. For an array, this
3014    // will be first element in the array, which may require several levels
3015    // of array-subscript entities.
3016    SmallVector<InitializedEntity, 4> Entities;
3017    Entities.reserve(1 + IndexVariables.size());
3018    if (Indirect)
3019      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3020    else
3021      Entities.push_back(InitializedEntity::InitializeMember(Field));
3022    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3023      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3024                                                              0,
3025                                                              Entities.back()));
3026
3027    // Direct-initialize to use the copy constructor.
3028    InitializationKind InitKind =
3029      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3030
3031    Expr *CtorArgE = CtorArg.takeAs<Expr>();
3032    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3033
3034    ExprResult MemberInit
3035      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3036                        MultiExprArg(&CtorArgE, 1));
3037    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3038    if (MemberInit.isInvalid())
3039      return true;
3040
3041    if (Indirect) {
3042      assert(IndexVariables.size() == 0 &&
3043             "Indirect field improperly initialized");
3044      CXXMemberInit
3045        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3046                                                   Loc, Loc,
3047                                                   MemberInit.takeAs<Expr>(),
3048                                                   Loc);
3049    } else
3050      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3051                                                 Loc, MemberInit.takeAs<Expr>(),
3052                                                 Loc,
3053                                                 IndexVariables.data(),
3054                                                 IndexVariables.size());
3055    return false;
3056  }
3057
3058  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3059         "Unhandled implicit init kind!");
3060
3061  QualType FieldBaseElementType =
3062    SemaRef.Context.getBaseElementType(Field->getType());
3063
3064  if (FieldBaseElementType->isRecordType()) {
3065    InitializedEntity InitEntity
3066      = Indirect? InitializedEntity::InitializeMember(Indirect)
3067                : InitializedEntity::InitializeMember(Field);
3068    InitializationKind InitKind =
3069      InitializationKind::CreateDefault(Loc);
3070
3071    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3072    ExprResult MemberInit =
3073      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3074
3075    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3076    if (MemberInit.isInvalid())
3077      return true;
3078
3079    if (Indirect)
3080      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3081                                                               Indirect, Loc,
3082                                                               Loc,
3083                                                               MemberInit.get(),
3084                                                               Loc);
3085    else
3086      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3087                                                               Field, Loc, Loc,
3088                                                               MemberInit.get(),
3089                                                               Loc);
3090    return false;
3091  }
3092
3093  if (!Field->getParent()->isUnion()) {
3094    if (FieldBaseElementType->isReferenceType()) {
3095      SemaRef.Diag(Constructor->getLocation(),
3096                   diag::err_uninitialized_member_in_ctor)
3097      << (int)Constructor->isImplicit()
3098      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3099      << 0 << Field->getDeclName();
3100      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3101      return true;
3102    }
3103
3104    if (FieldBaseElementType.isConstQualified()) {
3105      SemaRef.Diag(Constructor->getLocation(),
3106                   diag::err_uninitialized_member_in_ctor)
3107      << (int)Constructor->isImplicit()
3108      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3109      << 1 << Field->getDeclName();
3110      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3111      return true;
3112    }
3113  }
3114
3115  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3116      FieldBaseElementType->isObjCRetainableType() &&
3117      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3118      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3119    // ARC:
3120    //   Default-initialize Objective-C pointers to NULL.
3121    CXXMemberInit
3122      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3123                                                 Loc, Loc,
3124                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3125                                                 Loc);
3126    return false;
3127  }
3128
3129  // Nothing to initialize.
3130  CXXMemberInit = 0;
3131  return false;
3132}
3133
3134namespace {
3135struct BaseAndFieldInfo {
3136  Sema &S;
3137  CXXConstructorDecl *Ctor;
3138  bool AnyErrorsInInits;
3139  ImplicitInitializerKind IIK;
3140  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3141  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3142
3143  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3144    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3145    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3146    if (Generated && Ctor->isCopyConstructor())
3147      IIK = IIK_Copy;
3148    else if (Generated && Ctor->isMoveConstructor())
3149      IIK = IIK_Move;
3150    else if (Ctor->getInheritedConstructor())
3151      IIK = IIK_Inherit;
3152    else
3153      IIK = IIK_Default;
3154  }
3155
3156  bool isImplicitCopyOrMove() const {
3157    switch (IIK) {
3158    case IIK_Copy:
3159    case IIK_Move:
3160      return true;
3161
3162    case IIK_Default:
3163    case IIK_Inherit:
3164      return false;
3165    }
3166
3167    llvm_unreachable("Invalid ImplicitInitializerKind!");
3168  }
3169
3170  bool addFieldInitializer(CXXCtorInitializer *Init) {
3171    AllToInit.push_back(Init);
3172
3173    // Check whether this initializer makes the field "used".
3174    if (Init->getInit()->HasSideEffects(S.Context))
3175      S.UnusedPrivateFields.remove(Init->getAnyMember());
3176
3177    return false;
3178  }
3179};
3180}
3181
3182/// \brief Determine whether the given indirect field declaration is somewhere
3183/// within an anonymous union.
3184static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3185  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3186                                      CEnd = F->chain_end();
3187       C != CEnd; ++C)
3188    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3189      if (Record->isUnion())
3190        return true;
3191
3192  return false;
3193}
3194
3195/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3196/// array type.
3197static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3198  if (T->isIncompleteArrayType())
3199    return true;
3200
3201  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3202    if (!ArrayT->getSize())
3203      return true;
3204
3205    T = ArrayT->getElementType();
3206  }
3207
3208  return false;
3209}
3210
3211static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3212                                    FieldDecl *Field,
3213                                    IndirectFieldDecl *Indirect = 0) {
3214
3215  // Overwhelmingly common case: we have a direct initializer for this field.
3216  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3217    return Info.addFieldInitializer(Init);
3218
3219  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3220  // has a brace-or-equal-initializer, the entity is initialized as specified
3221  // in [dcl.init].
3222  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3223    Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3224                                           Info.Ctor->getLocation(), Field);
3225    CXXCtorInitializer *Init;
3226    if (Indirect)
3227      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3228                                                      SourceLocation(),
3229                                                      SourceLocation(), DIE,
3230                                                      SourceLocation());
3231    else
3232      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3233                                                      SourceLocation(),
3234                                                      SourceLocation(), DIE,
3235                                                      SourceLocation());
3236    return Info.addFieldInitializer(Init);
3237  }
3238
3239  // Don't build an implicit initializer for union members if none was
3240  // explicitly specified.
3241  if (Field->getParent()->isUnion() ||
3242      (Indirect && isWithinAnonymousUnion(Indirect)))
3243    return false;
3244
3245  // Don't initialize incomplete or zero-length arrays.
3246  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3247    return false;
3248
3249  // Don't try to build an implicit initializer if there were semantic
3250  // errors in any of the initializers (and therefore we might be
3251  // missing some that the user actually wrote).
3252  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
3253    return false;
3254
3255  CXXCtorInitializer *Init = 0;
3256  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3257                                     Indirect, Init))
3258    return true;
3259
3260  if (!Init)
3261    return false;
3262
3263  return Info.addFieldInitializer(Init);
3264}
3265
3266bool
3267Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3268                               CXXCtorInitializer *Initializer) {
3269  assert(Initializer->isDelegatingInitializer());
3270  Constructor->setNumCtorInitializers(1);
3271  CXXCtorInitializer **initializer =
3272    new (Context) CXXCtorInitializer*[1];
3273  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3274  Constructor->setCtorInitializers(initializer);
3275
3276  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3277    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3278    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3279  }
3280
3281  DelegatingCtorDecls.push_back(Constructor);
3282
3283  return false;
3284}
3285
3286bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3287                               ArrayRef<CXXCtorInitializer *> Initializers) {
3288  if (Constructor->isDependentContext()) {
3289    // Just store the initializers as written, they will be checked during
3290    // instantiation.
3291    if (!Initializers.empty()) {
3292      Constructor->setNumCtorInitializers(Initializers.size());
3293      CXXCtorInitializer **baseOrMemberInitializers =
3294        new (Context) CXXCtorInitializer*[Initializers.size()];
3295      memcpy(baseOrMemberInitializers, Initializers.data(),
3296             Initializers.size() * sizeof(CXXCtorInitializer*));
3297      Constructor->setCtorInitializers(baseOrMemberInitializers);
3298    }
3299
3300    // Let template instantiation know whether we had errors.
3301    if (AnyErrors)
3302      Constructor->setInvalidDecl();
3303
3304    return false;
3305  }
3306
3307  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3308
3309  // We need to build the initializer AST according to order of construction
3310  // and not what user specified in the Initializers list.
3311  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3312  if (!ClassDecl)
3313    return true;
3314
3315  bool HadError = false;
3316
3317  for (unsigned i = 0; i < Initializers.size(); i++) {
3318    CXXCtorInitializer *Member = Initializers[i];
3319
3320    if (Member->isBaseInitializer())
3321      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3322    else
3323      Info.AllBaseFields[Member->getAnyMember()] = Member;
3324  }
3325
3326  // Keep track of the direct virtual bases.
3327  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3328  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3329       E = ClassDecl->bases_end(); I != E; ++I) {
3330    if (I->isVirtual())
3331      DirectVBases.insert(I);
3332  }
3333
3334  // Push virtual bases before others.
3335  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3336       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3337
3338    if (CXXCtorInitializer *Value
3339        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3340      Info.AllToInit.push_back(Value);
3341    } else if (!AnyErrors) {
3342      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3343      CXXCtorInitializer *CXXBaseInit;
3344      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3345                                       VBase, IsInheritedVirtualBase,
3346                                       CXXBaseInit)) {
3347        HadError = true;
3348        continue;
3349      }
3350
3351      Info.AllToInit.push_back(CXXBaseInit);
3352    }
3353  }
3354
3355  // Non-virtual bases.
3356  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3357       E = ClassDecl->bases_end(); Base != E; ++Base) {
3358    // Virtuals are in the virtual base list and already constructed.
3359    if (Base->isVirtual())
3360      continue;
3361
3362    if (CXXCtorInitializer *Value
3363          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3364      Info.AllToInit.push_back(Value);
3365    } else if (!AnyErrors) {
3366      CXXCtorInitializer *CXXBaseInit;
3367      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3368                                       Base, /*IsInheritedVirtualBase=*/false,
3369                                       CXXBaseInit)) {
3370        HadError = true;
3371        continue;
3372      }
3373
3374      Info.AllToInit.push_back(CXXBaseInit);
3375    }
3376  }
3377
3378  // Fields.
3379  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3380                               MemEnd = ClassDecl->decls_end();
3381       Mem != MemEnd; ++Mem) {
3382    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3383      // C++ [class.bit]p2:
3384      //   A declaration for a bit-field that omits the identifier declares an
3385      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3386      //   initialized.
3387      if (F->isUnnamedBitfield())
3388        continue;
3389
3390      // If we're not generating the implicit copy/move constructor, then we'll
3391      // handle anonymous struct/union fields based on their individual
3392      // indirect fields.
3393      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3394        continue;
3395
3396      if (CollectFieldInitializer(*this, Info, F))
3397        HadError = true;
3398      continue;
3399    }
3400
3401    // Beyond this point, we only consider default initialization.
3402    if (Info.isImplicitCopyOrMove())
3403      continue;
3404
3405    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3406      if (F->getType()->isIncompleteArrayType()) {
3407        assert(ClassDecl->hasFlexibleArrayMember() &&
3408               "Incomplete array type is not valid");
3409        continue;
3410      }
3411
3412      // Initialize each field of an anonymous struct individually.
3413      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3414        HadError = true;
3415
3416      continue;
3417    }
3418  }
3419
3420  unsigned NumInitializers = Info.AllToInit.size();
3421  if (NumInitializers > 0) {
3422    Constructor->setNumCtorInitializers(NumInitializers);
3423    CXXCtorInitializer **baseOrMemberInitializers =
3424      new (Context) CXXCtorInitializer*[NumInitializers];
3425    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3426           NumInitializers * sizeof(CXXCtorInitializer*));
3427    Constructor->setCtorInitializers(baseOrMemberInitializers);
3428
3429    // Constructors implicitly reference the base and member
3430    // destructors.
3431    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3432                                           Constructor->getParent());
3433  }
3434
3435  return HadError;
3436}
3437
3438static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3439  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3440    const RecordDecl *RD = RT->getDecl();
3441    if (RD->isAnonymousStructOrUnion()) {
3442      for (RecordDecl::field_iterator Field = RD->field_begin(),
3443          E = RD->field_end(); Field != E; ++Field)
3444        PopulateKeysForFields(*Field, IdealInits);
3445      return;
3446    }
3447  }
3448  IdealInits.push_back(Field);
3449}
3450
3451static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3452  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3453}
3454
3455static void *GetKeyForMember(ASTContext &Context,
3456                             CXXCtorInitializer *Member) {
3457  if (!Member->isAnyMemberInitializer())
3458    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3459
3460  return Member->getAnyMember();
3461}
3462
3463static void DiagnoseBaseOrMemInitializerOrder(
3464    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3465    ArrayRef<CXXCtorInitializer *> Inits) {
3466  if (Constructor->getDeclContext()->isDependentContext())
3467    return;
3468
3469  // Don't check initializers order unless the warning is enabled at the
3470  // location of at least one initializer.
3471  bool ShouldCheckOrder = false;
3472  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3473    CXXCtorInitializer *Init = Inits[InitIndex];
3474    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3475                                         Init->getSourceLocation())
3476          != DiagnosticsEngine::Ignored) {
3477      ShouldCheckOrder = true;
3478      break;
3479    }
3480  }
3481  if (!ShouldCheckOrder)
3482    return;
3483
3484  // Build the list of bases and members in the order that they'll
3485  // actually be initialized.  The explicit initializers should be in
3486  // this same order but may be missing things.
3487  SmallVector<const void*, 32> IdealInitKeys;
3488
3489  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3490
3491  // 1. Virtual bases.
3492  for (CXXRecordDecl::base_class_const_iterator VBase =
3493       ClassDecl->vbases_begin(),
3494       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3495    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3496
3497  // 2. Non-virtual bases.
3498  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3499       E = ClassDecl->bases_end(); Base != E; ++Base) {
3500    if (Base->isVirtual())
3501      continue;
3502    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3503  }
3504
3505  // 3. Direct fields.
3506  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3507       E = ClassDecl->field_end(); Field != E; ++Field) {
3508    if (Field->isUnnamedBitfield())
3509      continue;
3510
3511    PopulateKeysForFields(*Field, IdealInitKeys);
3512  }
3513
3514  unsigned NumIdealInits = IdealInitKeys.size();
3515  unsigned IdealIndex = 0;
3516
3517  CXXCtorInitializer *PrevInit = 0;
3518  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3519    CXXCtorInitializer *Init = Inits[InitIndex];
3520    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3521
3522    // Scan forward to try to find this initializer in the idealized
3523    // initializers list.
3524    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3525      if (InitKey == IdealInitKeys[IdealIndex])
3526        break;
3527
3528    // If we didn't find this initializer, it must be because we
3529    // scanned past it on a previous iteration.  That can only
3530    // happen if we're out of order;  emit a warning.
3531    if (IdealIndex == NumIdealInits && PrevInit) {
3532      Sema::SemaDiagnosticBuilder D =
3533        SemaRef.Diag(PrevInit->getSourceLocation(),
3534                     diag::warn_initializer_out_of_order);
3535
3536      if (PrevInit->isAnyMemberInitializer())
3537        D << 0 << PrevInit->getAnyMember()->getDeclName();
3538      else
3539        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3540
3541      if (Init->isAnyMemberInitializer())
3542        D << 0 << Init->getAnyMember()->getDeclName();
3543      else
3544        D << 1 << Init->getTypeSourceInfo()->getType();
3545
3546      // Move back to the initializer's location in the ideal list.
3547      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3548        if (InitKey == IdealInitKeys[IdealIndex])
3549          break;
3550
3551      assert(IdealIndex != NumIdealInits &&
3552             "initializer not found in initializer list");
3553    }
3554
3555    PrevInit = Init;
3556  }
3557}
3558
3559namespace {
3560bool CheckRedundantInit(Sema &S,
3561                        CXXCtorInitializer *Init,
3562                        CXXCtorInitializer *&PrevInit) {
3563  if (!PrevInit) {
3564    PrevInit = Init;
3565    return false;
3566  }
3567
3568  if (FieldDecl *Field = Init->getAnyMember())
3569    S.Diag(Init->getSourceLocation(),
3570           diag::err_multiple_mem_initialization)
3571      << Field->getDeclName()
3572      << Init->getSourceRange();
3573  else {
3574    const Type *BaseClass = Init->getBaseClass();
3575    assert(BaseClass && "neither field nor base");
3576    S.Diag(Init->getSourceLocation(),
3577           diag::err_multiple_base_initialization)
3578      << QualType(BaseClass, 0)
3579      << Init->getSourceRange();
3580  }
3581  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3582    << 0 << PrevInit->getSourceRange();
3583
3584  return true;
3585}
3586
3587typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3588typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3589
3590bool CheckRedundantUnionInit(Sema &S,
3591                             CXXCtorInitializer *Init,
3592                             RedundantUnionMap &Unions) {
3593  FieldDecl *Field = Init->getAnyMember();
3594  RecordDecl *Parent = Field->getParent();
3595  NamedDecl *Child = Field;
3596
3597  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3598    if (Parent->isUnion()) {
3599      UnionEntry &En = Unions[Parent];
3600      if (En.first && En.first != Child) {
3601        S.Diag(Init->getSourceLocation(),
3602               diag::err_multiple_mem_union_initialization)
3603          << Field->getDeclName()
3604          << Init->getSourceRange();
3605        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3606          << 0 << En.second->getSourceRange();
3607        return true;
3608      }
3609      if (!En.first) {
3610        En.first = Child;
3611        En.second = Init;
3612      }
3613      if (!Parent->isAnonymousStructOrUnion())
3614        return false;
3615    }
3616
3617    Child = Parent;
3618    Parent = cast<RecordDecl>(Parent->getDeclContext());
3619  }
3620
3621  return false;
3622}
3623}
3624
3625/// ActOnMemInitializers - Handle the member initializers for a constructor.
3626void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3627                                SourceLocation ColonLoc,
3628                                ArrayRef<CXXCtorInitializer*> MemInits,
3629                                bool AnyErrors) {
3630  if (!ConstructorDecl)
3631    return;
3632
3633  AdjustDeclIfTemplate(ConstructorDecl);
3634
3635  CXXConstructorDecl *Constructor
3636    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3637
3638  if (!Constructor) {
3639    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3640    return;
3641  }
3642
3643  // Mapping for the duplicate initializers check.
3644  // For member initializers, this is keyed with a FieldDecl*.
3645  // For base initializers, this is keyed with a Type*.
3646  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3647
3648  // Mapping for the inconsistent anonymous-union initializers check.
3649  RedundantUnionMap MemberUnions;
3650
3651  bool HadError = false;
3652  for (unsigned i = 0; i < MemInits.size(); i++) {
3653    CXXCtorInitializer *Init = MemInits[i];
3654
3655    // Set the source order index.
3656    Init->setSourceOrder(i);
3657
3658    if (Init->isAnyMemberInitializer()) {
3659      FieldDecl *Field = Init->getAnyMember();
3660      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3661          CheckRedundantUnionInit(*this, Init, MemberUnions))
3662        HadError = true;
3663    } else if (Init->isBaseInitializer()) {
3664      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3665      if (CheckRedundantInit(*this, Init, Members[Key]))
3666        HadError = true;
3667    } else {
3668      assert(Init->isDelegatingInitializer());
3669      // This must be the only initializer
3670      if (MemInits.size() != 1) {
3671        Diag(Init->getSourceLocation(),
3672             diag::err_delegating_initializer_alone)
3673          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3674        // We will treat this as being the only initializer.
3675      }
3676      SetDelegatingInitializer(Constructor, MemInits[i]);
3677      // Return immediately as the initializer is set.
3678      return;
3679    }
3680  }
3681
3682  if (HadError)
3683    return;
3684
3685  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3686
3687  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3688}
3689
3690void
3691Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3692                                             CXXRecordDecl *ClassDecl) {
3693  // Ignore dependent contexts. Also ignore unions, since their members never
3694  // have destructors implicitly called.
3695  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3696    return;
3697
3698  // FIXME: all the access-control diagnostics are positioned on the
3699  // field/base declaration.  That's probably good; that said, the
3700  // user might reasonably want to know why the destructor is being
3701  // emitted, and we currently don't say.
3702
3703  // Non-static data members.
3704  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3705       E = ClassDecl->field_end(); I != E; ++I) {
3706    FieldDecl *Field = *I;
3707    if (Field->isInvalidDecl())
3708      continue;
3709
3710    // Don't destroy incomplete or zero-length arrays.
3711    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3712      continue;
3713
3714    QualType FieldType = Context.getBaseElementType(Field->getType());
3715
3716    const RecordType* RT = FieldType->getAs<RecordType>();
3717    if (!RT)
3718      continue;
3719
3720    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3721    if (FieldClassDecl->isInvalidDecl())
3722      continue;
3723    if (FieldClassDecl->hasIrrelevantDestructor())
3724      continue;
3725    // The destructor for an implicit anonymous union member is never invoked.
3726    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3727      continue;
3728
3729    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3730    assert(Dtor && "No dtor found for FieldClassDecl!");
3731    CheckDestructorAccess(Field->getLocation(), Dtor,
3732                          PDiag(diag::err_access_dtor_field)
3733                            << Field->getDeclName()
3734                            << FieldType);
3735
3736    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3737    DiagnoseUseOfDecl(Dtor, Location);
3738  }
3739
3740  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3741
3742  // Bases.
3743  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3744       E = ClassDecl->bases_end(); Base != E; ++Base) {
3745    // Bases are always records in a well-formed non-dependent class.
3746    const RecordType *RT = Base->getType()->getAs<RecordType>();
3747
3748    // Remember direct virtual bases.
3749    if (Base->isVirtual())
3750      DirectVirtualBases.insert(RT);
3751
3752    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3753    // If our base class is invalid, we probably can't get its dtor anyway.
3754    if (BaseClassDecl->isInvalidDecl())
3755      continue;
3756    if (BaseClassDecl->hasIrrelevantDestructor())
3757      continue;
3758
3759    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3760    assert(Dtor && "No dtor found for BaseClassDecl!");
3761
3762    // FIXME: caret should be on the start of the class name
3763    CheckDestructorAccess(Base->getLocStart(), Dtor,
3764                          PDiag(diag::err_access_dtor_base)
3765                            << Base->getType()
3766                            << Base->getSourceRange(),
3767                          Context.getTypeDeclType(ClassDecl));
3768
3769    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3770    DiagnoseUseOfDecl(Dtor, Location);
3771  }
3772
3773  // Virtual bases.
3774  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3775       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3776
3777    // Bases are always records in a well-formed non-dependent class.
3778    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3779
3780    // Ignore direct virtual bases.
3781    if (DirectVirtualBases.count(RT))
3782      continue;
3783
3784    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3785    // If our base class is invalid, we probably can't get its dtor anyway.
3786    if (BaseClassDecl->isInvalidDecl())
3787      continue;
3788    if (BaseClassDecl->hasIrrelevantDestructor())
3789      continue;
3790
3791    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3792    assert(Dtor && "No dtor found for BaseClassDecl!");
3793    if (CheckDestructorAccess(
3794            ClassDecl->getLocation(), Dtor,
3795            PDiag(diag::err_access_dtor_vbase)
3796                << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3797            Context.getTypeDeclType(ClassDecl)) ==
3798        AR_accessible) {
3799      CheckDerivedToBaseConversion(
3800          Context.getTypeDeclType(ClassDecl), VBase->getType(),
3801          diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3802          SourceRange(), DeclarationName(), 0);
3803    }
3804
3805    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3806    DiagnoseUseOfDecl(Dtor, Location);
3807  }
3808}
3809
3810void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3811  if (!CDtorDecl)
3812    return;
3813
3814  if (CXXConstructorDecl *Constructor
3815      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3816    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3817}
3818
3819bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3820                                  unsigned DiagID, AbstractDiagSelID SelID) {
3821  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3822    unsigned DiagID;
3823    AbstractDiagSelID SelID;
3824
3825  public:
3826    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3827      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3828
3829    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3830      if (Suppressed) return;
3831      if (SelID == -1)
3832        S.Diag(Loc, DiagID) << T;
3833      else
3834        S.Diag(Loc, DiagID) << SelID << T;
3835    }
3836  } Diagnoser(DiagID, SelID);
3837
3838  return RequireNonAbstractType(Loc, T, Diagnoser);
3839}
3840
3841bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3842                                  TypeDiagnoser &Diagnoser) {
3843  if (!getLangOpts().CPlusPlus)
3844    return false;
3845
3846  if (const ArrayType *AT = Context.getAsArrayType(T))
3847    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3848
3849  if (const PointerType *PT = T->getAs<PointerType>()) {
3850    // Find the innermost pointer type.
3851    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3852      PT = T;
3853
3854    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3855      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3856  }
3857
3858  const RecordType *RT = T->getAs<RecordType>();
3859  if (!RT)
3860    return false;
3861
3862  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3863
3864  // We can't answer whether something is abstract until it has a
3865  // definition.  If it's currently being defined, we'll walk back
3866  // over all the declarations when we have a full definition.
3867  const CXXRecordDecl *Def = RD->getDefinition();
3868  if (!Def || Def->isBeingDefined())
3869    return false;
3870
3871  if (!RD->isAbstract())
3872    return false;
3873
3874  Diagnoser.diagnose(*this, Loc, T);
3875  DiagnoseAbstractType(RD);
3876
3877  return true;
3878}
3879
3880void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3881  // Check if we've already emitted the list of pure virtual functions
3882  // for this class.
3883  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3884    return;
3885
3886  CXXFinalOverriderMap FinalOverriders;
3887  RD->getFinalOverriders(FinalOverriders);
3888
3889  // Keep a set of seen pure methods so we won't diagnose the same method
3890  // more than once.
3891  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3892
3893  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3894                                   MEnd = FinalOverriders.end();
3895       M != MEnd;
3896       ++M) {
3897    for (OverridingMethods::iterator SO = M->second.begin(),
3898                                  SOEnd = M->second.end();
3899         SO != SOEnd; ++SO) {
3900      // C++ [class.abstract]p4:
3901      //   A class is abstract if it contains or inherits at least one
3902      //   pure virtual function for which the final overrider is pure
3903      //   virtual.
3904
3905      //
3906      if (SO->second.size() != 1)
3907        continue;
3908
3909      if (!SO->second.front().Method->isPure())
3910        continue;
3911
3912      if (!SeenPureMethods.insert(SO->second.front().Method))
3913        continue;
3914
3915      Diag(SO->second.front().Method->getLocation(),
3916           diag::note_pure_virtual_function)
3917        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3918    }
3919  }
3920
3921  if (!PureVirtualClassDiagSet)
3922    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3923  PureVirtualClassDiagSet->insert(RD);
3924}
3925
3926namespace {
3927struct AbstractUsageInfo {
3928  Sema &S;
3929  CXXRecordDecl *Record;
3930  CanQualType AbstractType;
3931  bool Invalid;
3932
3933  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3934    : S(S), Record(Record),
3935      AbstractType(S.Context.getCanonicalType(
3936                   S.Context.getTypeDeclType(Record))),
3937      Invalid(false) {}
3938
3939  void DiagnoseAbstractType() {
3940    if (Invalid) return;
3941    S.DiagnoseAbstractType(Record);
3942    Invalid = true;
3943  }
3944
3945  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3946};
3947
3948struct CheckAbstractUsage {
3949  AbstractUsageInfo &Info;
3950  const NamedDecl *Ctx;
3951
3952  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3953    : Info(Info), Ctx(Ctx) {}
3954
3955  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3956    switch (TL.getTypeLocClass()) {
3957#define ABSTRACT_TYPELOC(CLASS, PARENT)
3958#define TYPELOC(CLASS, PARENT) \
3959    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3960#include "clang/AST/TypeLocNodes.def"
3961    }
3962  }
3963
3964  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3965    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3966    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3967      if (!TL.getArg(I))
3968        continue;
3969
3970      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3971      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3972    }
3973  }
3974
3975  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3976    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3977  }
3978
3979  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3980    // Visit the type parameters from a permissive context.
3981    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3982      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3983      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3984        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3985          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3986      // TODO: other template argument types?
3987    }
3988  }
3989
3990  // Visit pointee types from a permissive context.
3991#define CheckPolymorphic(Type) \
3992  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3993    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3994  }
3995  CheckPolymorphic(PointerTypeLoc)
3996  CheckPolymorphic(ReferenceTypeLoc)
3997  CheckPolymorphic(MemberPointerTypeLoc)
3998  CheckPolymorphic(BlockPointerTypeLoc)
3999  CheckPolymorphic(AtomicTypeLoc)
4000
4001  /// Handle all the types we haven't given a more specific
4002  /// implementation for above.
4003  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4004    // Every other kind of type that we haven't called out already
4005    // that has an inner type is either (1) sugar or (2) contains that
4006    // inner type in some way as a subobject.
4007    if (TypeLoc Next = TL.getNextTypeLoc())
4008      return Visit(Next, Sel);
4009
4010    // If there's no inner type and we're in a permissive context,
4011    // don't diagnose.
4012    if (Sel == Sema::AbstractNone) return;
4013
4014    // Check whether the type matches the abstract type.
4015    QualType T = TL.getType();
4016    if (T->isArrayType()) {
4017      Sel = Sema::AbstractArrayType;
4018      T = Info.S.Context.getBaseElementType(T);
4019    }
4020    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4021    if (CT != Info.AbstractType) return;
4022
4023    // It matched; do some magic.
4024    if (Sel == Sema::AbstractArrayType) {
4025      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4026        << T << TL.getSourceRange();
4027    } else {
4028      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4029        << Sel << T << TL.getSourceRange();
4030    }
4031    Info.DiagnoseAbstractType();
4032  }
4033};
4034
4035void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4036                                  Sema::AbstractDiagSelID Sel) {
4037  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4038}
4039
4040}
4041
4042/// Check for invalid uses of an abstract type in a method declaration.
4043static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4044                                    CXXMethodDecl *MD) {
4045  // No need to do the check on definitions, which require that
4046  // the return/param types be complete.
4047  if (MD->doesThisDeclarationHaveABody())
4048    return;
4049
4050  // For safety's sake, just ignore it if we don't have type source
4051  // information.  This should never happen for non-implicit methods,
4052  // but...
4053  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4054    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4055}
4056
4057/// Check for invalid uses of an abstract type within a class definition.
4058static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4059                                    CXXRecordDecl *RD) {
4060  for (CXXRecordDecl::decl_iterator
4061         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4062    Decl *D = *I;
4063    if (D->isImplicit()) continue;
4064
4065    // Methods and method templates.
4066    if (isa<CXXMethodDecl>(D)) {
4067      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4068    } else if (isa<FunctionTemplateDecl>(D)) {
4069      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4070      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4071
4072    // Fields and static variables.
4073    } else if (isa<FieldDecl>(D)) {
4074      FieldDecl *FD = cast<FieldDecl>(D);
4075      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4076        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4077    } else if (isa<VarDecl>(D)) {
4078      VarDecl *VD = cast<VarDecl>(D);
4079      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4080        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4081
4082    // Nested classes and class templates.
4083    } else if (isa<CXXRecordDecl>(D)) {
4084      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4085    } else if (isa<ClassTemplateDecl>(D)) {
4086      CheckAbstractClassUsage(Info,
4087                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4088    }
4089  }
4090}
4091
4092/// \brief Perform semantic checks on a class definition that has been
4093/// completing, introducing implicitly-declared members, checking for
4094/// abstract types, etc.
4095void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4096  if (!Record)
4097    return;
4098
4099  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4100    AbstractUsageInfo Info(*this, Record);
4101    CheckAbstractClassUsage(Info, Record);
4102  }
4103
4104  // If this is not an aggregate type and has no user-declared constructor,
4105  // complain about any non-static data members of reference or const scalar
4106  // type, since they will never get initializers.
4107  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4108      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4109      !Record->isLambda()) {
4110    bool Complained = false;
4111    for (RecordDecl::field_iterator F = Record->field_begin(),
4112                                 FEnd = Record->field_end();
4113         F != FEnd; ++F) {
4114      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4115        continue;
4116
4117      if (F->getType()->isReferenceType() ||
4118          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4119        if (!Complained) {
4120          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4121            << Record->getTagKind() << Record;
4122          Complained = true;
4123        }
4124
4125        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4126          << F->getType()->isReferenceType()
4127          << F->getDeclName();
4128      }
4129    }
4130  }
4131
4132  if (Record->isDynamicClass() && !Record->isDependentType())
4133    DynamicClasses.push_back(Record);
4134
4135  if (Record->getIdentifier()) {
4136    // C++ [class.mem]p13:
4137    //   If T is the name of a class, then each of the following shall have a
4138    //   name different from T:
4139    //     - every member of every anonymous union that is a member of class T.
4140    //
4141    // C++ [class.mem]p14:
4142    //   In addition, if class T has a user-declared constructor (12.1), every
4143    //   non-static data member of class T shall have a name different from T.
4144    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4145    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4146         ++I) {
4147      NamedDecl *D = *I;
4148      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4149          isa<IndirectFieldDecl>(D)) {
4150        Diag(D->getLocation(), diag::err_member_name_of_class)
4151          << D->getDeclName();
4152        break;
4153      }
4154    }
4155  }
4156
4157  // Warn if the class has virtual methods but non-virtual public destructor.
4158  if (Record->isPolymorphic() && !Record->isDependentType()) {
4159    CXXDestructorDecl *dtor = Record->getDestructor();
4160    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4161      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4162           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4163  }
4164
4165  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4166    Diag(Record->getLocation(), diag::warn_abstract_final_class);
4167    DiagnoseAbstractType(Record);
4168  }
4169
4170  if (!Record->isDependentType()) {
4171    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4172                                     MEnd = Record->method_end();
4173         M != MEnd; ++M) {
4174      // See if a method overloads virtual methods in a base
4175      // class without overriding any.
4176      if (!M->isStatic())
4177        DiagnoseHiddenVirtualMethods(Record, *M);
4178
4179      // Check whether the explicitly-defaulted special members are valid.
4180      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4181        CheckExplicitlyDefaultedSpecialMember(*M);
4182
4183      // For an explicitly defaulted or deleted special member, we defer
4184      // determining triviality until the class is complete. That time is now!
4185      if (!M->isImplicit() && !M->isUserProvided()) {
4186        CXXSpecialMember CSM = getSpecialMember(*M);
4187        if (CSM != CXXInvalid) {
4188          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4189
4190          // Inform the class that we've finished declaring this member.
4191          Record->finishedDefaultedOrDeletedMember(*M);
4192        }
4193      }
4194    }
4195  }
4196
4197  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4198  // function that is not a constructor declares that member function to be
4199  // const. [...] The class of which that function is a member shall be
4200  // a literal type.
4201  //
4202  // If the class has virtual bases, any constexpr members will already have
4203  // been diagnosed by the checks performed on the member declaration, so
4204  // suppress this (less useful) diagnostic.
4205  //
4206  // We delay this until we know whether an explicitly-defaulted (or deleted)
4207  // destructor for the class is trivial.
4208  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4209      !Record->isLiteral() && !Record->getNumVBases()) {
4210    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4211                                     MEnd = Record->method_end();
4212         M != MEnd; ++M) {
4213      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4214        switch (Record->getTemplateSpecializationKind()) {
4215        case TSK_ImplicitInstantiation:
4216        case TSK_ExplicitInstantiationDeclaration:
4217        case TSK_ExplicitInstantiationDefinition:
4218          // If a template instantiates to a non-literal type, but its members
4219          // instantiate to constexpr functions, the template is technically
4220          // ill-formed, but we allow it for sanity.
4221          continue;
4222
4223        case TSK_Undeclared:
4224        case TSK_ExplicitSpecialization:
4225          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4226                             diag::err_constexpr_method_non_literal);
4227          break;
4228        }
4229
4230        // Only produce one error per class.
4231        break;
4232      }
4233    }
4234  }
4235
4236  // Declare inheriting constructors. We do this eagerly here because:
4237  // - The standard requires an eager diagnostic for conflicting inheriting
4238  //   constructors from different classes.
4239  // - The lazy declaration of the other implicit constructors is so as to not
4240  //   waste space and performance on classes that are not meant to be
4241  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4242  //   have inheriting constructors.
4243  DeclareInheritingConstructors(Record);
4244}
4245
4246/// Is the special member function which would be selected to perform the
4247/// specified operation on the specified class type a constexpr constructor?
4248static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4249                                     Sema::CXXSpecialMember CSM,
4250                                     bool ConstArg) {
4251  Sema::SpecialMemberOverloadResult *SMOR =
4252      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4253                            false, false, false, false);
4254  if (!SMOR || !SMOR->getMethod())
4255    // A constructor we wouldn't select can't be "involved in initializing"
4256    // anything.
4257    return true;
4258  return SMOR->getMethod()->isConstexpr();
4259}
4260
4261/// Determine whether the specified special member function would be constexpr
4262/// if it were implicitly defined.
4263static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4264                                              Sema::CXXSpecialMember CSM,
4265                                              bool ConstArg) {
4266  if (!S.getLangOpts().CPlusPlus11)
4267    return false;
4268
4269  // C++11 [dcl.constexpr]p4:
4270  // In the definition of a constexpr constructor [...]
4271  bool Ctor = true;
4272  switch (CSM) {
4273  case Sema::CXXDefaultConstructor:
4274    // Since default constructor lookup is essentially trivial (and cannot
4275    // involve, for instance, template instantiation), we compute whether a
4276    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4277    //
4278    // This is important for performance; we need to know whether the default
4279    // constructor is constexpr to determine whether the type is a literal type.
4280    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4281
4282  case Sema::CXXCopyConstructor:
4283  case Sema::CXXMoveConstructor:
4284    // For copy or move constructors, we need to perform overload resolution.
4285    break;
4286
4287  case Sema::CXXCopyAssignment:
4288  case Sema::CXXMoveAssignment:
4289    if (!S.getLangOpts().CPlusPlus1y)
4290      return false;
4291    // In C++1y, we need to perform overload resolution.
4292    Ctor = false;
4293    break;
4294
4295  case Sema::CXXDestructor:
4296  case Sema::CXXInvalid:
4297    return false;
4298  }
4299
4300  //   -- if the class is a non-empty union, or for each non-empty anonymous
4301  //      union member of a non-union class, exactly one non-static data member
4302  //      shall be initialized; [DR1359]
4303  //
4304  // If we squint, this is guaranteed, since exactly one non-static data member
4305  // will be initialized (if the constructor isn't deleted), we just don't know
4306  // which one.
4307  if (Ctor && ClassDecl->isUnion())
4308    return true;
4309
4310  //   -- the class shall not have any virtual base classes;
4311  if (Ctor && ClassDecl->getNumVBases())
4312    return false;
4313
4314  // C++1y [class.copy]p26:
4315  //   -- [the class] is a literal type, and
4316  if (!Ctor && !ClassDecl->isLiteral())
4317    return false;
4318
4319  //   -- every constructor involved in initializing [...] base class
4320  //      sub-objects shall be a constexpr constructor;
4321  //   -- the assignment operator selected to copy/move each direct base
4322  //      class is a constexpr function, and
4323  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4324                                       BEnd = ClassDecl->bases_end();
4325       B != BEnd; ++B) {
4326    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4327    if (!BaseType) continue;
4328
4329    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4330    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4331      return false;
4332  }
4333
4334  //   -- every constructor involved in initializing non-static data members
4335  //      [...] shall be a constexpr constructor;
4336  //   -- every non-static data member and base class sub-object shall be
4337  //      initialized
4338  //   -- for each non-stastic data member of X that is of class type (or array
4339  //      thereof), the assignment operator selected to copy/move that member is
4340  //      a constexpr function
4341  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4342                               FEnd = ClassDecl->field_end();
4343       F != FEnd; ++F) {
4344    if (F->isInvalidDecl())
4345      continue;
4346    if (const RecordType *RecordTy =
4347            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4348      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4349      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4350        return false;
4351    }
4352  }
4353
4354  // All OK, it's constexpr!
4355  return true;
4356}
4357
4358static Sema::ImplicitExceptionSpecification
4359computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4360  switch (S.getSpecialMember(MD)) {
4361  case Sema::CXXDefaultConstructor:
4362    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4363  case Sema::CXXCopyConstructor:
4364    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4365  case Sema::CXXCopyAssignment:
4366    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4367  case Sema::CXXMoveConstructor:
4368    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4369  case Sema::CXXMoveAssignment:
4370    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4371  case Sema::CXXDestructor:
4372    return S.ComputeDefaultedDtorExceptionSpec(MD);
4373  case Sema::CXXInvalid:
4374    break;
4375  }
4376  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4377         "only special members have implicit exception specs");
4378  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4379}
4380
4381static void
4382updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4383                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4384  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4385  ExceptSpec.getEPI(EPI);
4386  FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4387                                        FPT->getArgTypes(), EPI));
4388}
4389
4390void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4391  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4392  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4393    return;
4394
4395  // Evaluate the exception specification.
4396  ImplicitExceptionSpecification ExceptSpec =
4397      computeImplicitExceptionSpec(*this, Loc, MD);
4398
4399  // Update the type of the special member to use it.
4400  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4401
4402  // A user-provided destructor can be defined outside the class. When that
4403  // happens, be sure to update the exception specification on both
4404  // declarations.
4405  const FunctionProtoType *CanonicalFPT =
4406    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4407  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4408    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4409                        CanonicalFPT, ExceptSpec);
4410}
4411
4412void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4413  CXXRecordDecl *RD = MD->getParent();
4414  CXXSpecialMember CSM = getSpecialMember(MD);
4415
4416  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4417         "not an explicitly-defaulted special member");
4418
4419  // Whether this was the first-declared instance of the constructor.
4420  // This affects whether we implicitly add an exception spec and constexpr.
4421  bool First = MD == MD->getCanonicalDecl();
4422
4423  bool HadError = false;
4424
4425  // C++11 [dcl.fct.def.default]p1:
4426  //   A function that is explicitly defaulted shall
4427  //     -- be a special member function (checked elsewhere),
4428  //     -- have the same type (except for ref-qualifiers, and except that a
4429  //        copy operation can take a non-const reference) as an implicit
4430  //        declaration, and
4431  //     -- not have default arguments.
4432  unsigned ExpectedParams = 1;
4433  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4434    ExpectedParams = 0;
4435  if (MD->getNumParams() != ExpectedParams) {
4436    // This also checks for default arguments: a copy or move constructor with a
4437    // default argument is classified as a default constructor, and assignment
4438    // operations and destructors can't have default arguments.
4439    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4440      << CSM << MD->getSourceRange();
4441    HadError = true;
4442  } else if (MD->isVariadic()) {
4443    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4444      << CSM << MD->getSourceRange();
4445    HadError = true;
4446  }
4447
4448  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4449
4450  bool CanHaveConstParam = false;
4451  if (CSM == CXXCopyConstructor)
4452    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4453  else if (CSM == CXXCopyAssignment)
4454    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4455
4456  QualType ReturnType = Context.VoidTy;
4457  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4458    // Check for return type matching.
4459    ReturnType = Type->getResultType();
4460    QualType ExpectedReturnType =
4461        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4462    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4463      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4464        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4465      HadError = true;
4466    }
4467
4468    // A defaulted special member cannot have cv-qualifiers.
4469    if (Type->getTypeQuals()) {
4470      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4471        << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4472      HadError = true;
4473    }
4474  }
4475
4476  // Check for parameter type matching.
4477  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4478  bool HasConstParam = false;
4479  if (ExpectedParams && ArgType->isReferenceType()) {
4480    // Argument must be reference to possibly-const T.
4481    QualType ReferentType = ArgType->getPointeeType();
4482    HasConstParam = ReferentType.isConstQualified();
4483
4484    if (ReferentType.isVolatileQualified()) {
4485      Diag(MD->getLocation(),
4486           diag::err_defaulted_special_member_volatile_param) << CSM;
4487      HadError = true;
4488    }
4489
4490    if (HasConstParam && !CanHaveConstParam) {
4491      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4492        Diag(MD->getLocation(),
4493             diag::err_defaulted_special_member_copy_const_param)
4494          << (CSM == CXXCopyAssignment);
4495        // FIXME: Explain why this special member can't be const.
4496      } else {
4497        Diag(MD->getLocation(),
4498             diag::err_defaulted_special_member_move_const_param)
4499          << (CSM == CXXMoveAssignment);
4500      }
4501      HadError = true;
4502    }
4503  } else if (ExpectedParams) {
4504    // A copy assignment operator can take its argument by value, but a
4505    // defaulted one cannot.
4506    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4507    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4508    HadError = true;
4509  }
4510
4511  // C++11 [dcl.fct.def.default]p2:
4512  //   An explicitly-defaulted function may be declared constexpr only if it
4513  //   would have been implicitly declared as constexpr,
4514  // Do not apply this rule to members of class templates, since core issue 1358
4515  // makes such functions always instantiate to constexpr functions. For
4516  // functions which cannot be constexpr (for non-constructors in C++11 and for
4517  // destructors in C++1y), this is checked elsewhere.
4518  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4519                                                     HasConstParam);
4520  if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4521                                 : isa<CXXConstructorDecl>(MD)) &&
4522      MD->isConstexpr() && !Constexpr &&
4523      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4524    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4525    // FIXME: Explain why the special member can't be constexpr.
4526    HadError = true;
4527  }
4528
4529  //   and may have an explicit exception-specification only if it is compatible
4530  //   with the exception-specification on the implicit declaration.
4531  if (Type->hasExceptionSpec()) {
4532    // Delay the check if this is the first declaration of the special member,
4533    // since we may not have parsed some necessary in-class initializers yet.
4534    if (First) {
4535      // If the exception specification needs to be instantiated, do so now,
4536      // before we clobber it with an EST_Unevaluated specification below.
4537      if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4538        InstantiateExceptionSpec(MD->getLocStart(), MD);
4539        Type = MD->getType()->getAs<FunctionProtoType>();
4540      }
4541      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4542    } else
4543      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4544  }
4545
4546  //   If a function is explicitly defaulted on its first declaration,
4547  if (First) {
4548    //  -- it is implicitly considered to be constexpr if the implicit
4549    //     definition would be,
4550    MD->setConstexpr(Constexpr);
4551
4552    //  -- it is implicitly considered to have the same exception-specification
4553    //     as if it had been implicitly declared,
4554    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4555    EPI.ExceptionSpecType = EST_Unevaluated;
4556    EPI.ExceptionSpecDecl = MD;
4557    MD->setType(Context.getFunctionType(ReturnType,
4558                                        ArrayRef<QualType>(&ArgType,
4559                                                           ExpectedParams),
4560                                        EPI));
4561  }
4562
4563  if (ShouldDeleteSpecialMember(MD, CSM)) {
4564    if (First) {
4565      SetDeclDeleted(MD, MD->getLocation());
4566    } else {
4567      // C++11 [dcl.fct.def.default]p4:
4568      //   [For a] user-provided explicitly-defaulted function [...] if such a
4569      //   function is implicitly defined as deleted, the program is ill-formed.
4570      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4571      HadError = true;
4572    }
4573  }
4574
4575  if (HadError)
4576    MD->setInvalidDecl();
4577}
4578
4579/// Check whether the exception specification provided for an
4580/// explicitly-defaulted special member matches the exception specification
4581/// that would have been generated for an implicit special member, per
4582/// C++11 [dcl.fct.def.default]p2.
4583void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4584    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4585  // Compute the implicit exception specification.
4586  FunctionProtoType::ExtProtoInfo EPI;
4587  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4588  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4589    Context.getFunctionType(Context.VoidTy, None, EPI));
4590
4591  // Ensure that it matches.
4592  CheckEquivalentExceptionSpec(
4593    PDiag(diag::err_incorrect_defaulted_exception_spec)
4594      << getSpecialMember(MD), PDiag(),
4595    ImplicitType, SourceLocation(),
4596    SpecifiedType, MD->getLocation());
4597}
4598
4599void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4600  for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4601       I != N; ++I)
4602    CheckExplicitlyDefaultedMemberExceptionSpec(
4603      DelayedDefaultedMemberExceptionSpecs[I].first,
4604      DelayedDefaultedMemberExceptionSpecs[I].second);
4605
4606  DelayedDefaultedMemberExceptionSpecs.clear();
4607}
4608
4609namespace {
4610struct SpecialMemberDeletionInfo {
4611  Sema &S;
4612  CXXMethodDecl *MD;
4613  Sema::CXXSpecialMember CSM;
4614  bool Diagnose;
4615
4616  // Properties of the special member, computed for convenience.
4617  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4618  SourceLocation Loc;
4619
4620  bool AllFieldsAreConst;
4621
4622  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4623                            Sema::CXXSpecialMember CSM, bool Diagnose)
4624    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4625      IsConstructor(false), IsAssignment(false), IsMove(false),
4626      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4627      AllFieldsAreConst(true) {
4628    switch (CSM) {
4629      case Sema::CXXDefaultConstructor:
4630      case Sema::CXXCopyConstructor:
4631        IsConstructor = true;
4632        break;
4633      case Sema::CXXMoveConstructor:
4634        IsConstructor = true;
4635        IsMove = true;
4636        break;
4637      case Sema::CXXCopyAssignment:
4638        IsAssignment = true;
4639        break;
4640      case Sema::CXXMoveAssignment:
4641        IsAssignment = true;
4642        IsMove = true;
4643        break;
4644      case Sema::CXXDestructor:
4645        break;
4646      case Sema::CXXInvalid:
4647        llvm_unreachable("invalid special member kind");
4648    }
4649
4650    if (MD->getNumParams()) {
4651      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4652      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4653    }
4654  }
4655
4656  bool inUnion() const { return MD->getParent()->isUnion(); }
4657
4658  /// Look up the corresponding special member in the given class.
4659  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4660                                              unsigned Quals) {
4661    unsigned TQ = MD->getTypeQualifiers();
4662    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4663    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4664      Quals = 0;
4665    return S.LookupSpecialMember(Class, CSM,
4666                                 ConstArg || (Quals & Qualifiers::Const),
4667                                 VolatileArg || (Quals & Qualifiers::Volatile),
4668                                 MD->getRefQualifier() == RQ_RValue,
4669                                 TQ & Qualifiers::Const,
4670                                 TQ & Qualifiers::Volatile);
4671  }
4672
4673  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4674
4675  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4676  bool shouldDeleteForField(FieldDecl *FD);
4677  bool shouldDeleteForAllConstMembers();
4678
4679  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4680                                     unsigned Quals);
4681  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4682                                    Sema::SpecialMemberOverloadResult *SMOR,
4683                                    bool IsDtorCallInCtor);
4684
4685  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4686};
4687}
4688
4689/// Is the given special member inaccessible when used on the given
4690/// sub-object.
4691bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4692                                             CXXMethodDecl *target) {
4693  /// If we're operating on a base class, the object type is the
4694  /// type of this special member.
4695  QualType objectTy;
4696  AccessSpecifier access = target->getAccess();
4697  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4698    objectTy = S.Context.getTypeDeclType(MD->getParent());
4699    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4700
4701  // If we're operating on a field, the object type is the type of the field.
4702  } else {
4703    objectTy = S.Context.getTypeDeclType(target->getParent());
4704  }
4705
4706  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4707}
4708
4709/// Check whether we should delete a special member due to the implicit
4710/// definition containing a call to a special member of a subobject.
4711bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4712    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4713    bool IsDtorCallInCtor) {
4714  CXXMethodDecl *Decl = SMOR->getMethod();
4715  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4716
4717  int DiagKind = -1;
4718
4719  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4720    DiagKind = !Decl ? 0 : 1;
4721  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4722    DiagKind = 2;
4723  else if (!isAccessible(Subobj, Decl))
4724    DiagKind = 3;
4725  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4726           !Decl->isTrivial()) {
4727    // A member of a union must have a trivial corresponding special member.
4728    // As a weird special case, a destructor call from a union's constructor
4729    // must be accessible and non-deleted, but need not be trivial. Such a
4730    // destructor is never actually called, but is semantically checked as
4731    // if it were.
4732    DiagKind = 4;
4733  }
4734
4735  if (DiagKind == -1)
4736    return false;
4737
4738  if (Diagnose) {
4739    if (Field) {
4740      S.Diag(Field->getLocation(),
4741             diag::note_deleted_special_member_class_subobject)
4742        << CSM << MD->getParent() << /*IsField*/true
4743        << Field << DiagKind << IsDtorCallInCtor;
4744    } else {
4745      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4746      S.Diag(Base->getLocStart(),
4747             diag::note_deleted_special_member_class_subobject)
4748        << CSM << MD->getParent() << /*IsField*/false
4749        << Base->getType() << DiagKind << IsDtorCallInCtor;
4750    }
4751
4752    if (DiagKind == 1)
4753      S.NoteDeletedFunction(Decl);
4754    // FIXME: Explain inaccessibility if DiagKind == 3.
4755  }
4756
4757  return true;
4758}
4759
4760/// Check whether we should delete a special member function due to having a
4761/// direct or virtual base class or non-static data member of class type M.
4762bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4763    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4764  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4765
4766  // C++11 [class.ctor]p5:
4767  // -- any direct or virtual base class, or non-static data member with no
4768  //    brace-or-equal-initializer, has class type M (or array thereof) and
4769  //    either M has no default constructor or overload resolution as applied
4770  //    to M's default constructor results in an ambiguity or in a function
4771  //    that is deleted or inaccessible
4772  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4773  // -- a direct or virtual base class B that cannot be copied/moved because
4774  //    overload resolution, as applied to B's corresponding special member,
4775  //    results in an ambiguity or a function that is deleted or inaccessible
4776  //    from the defaulted special member
4777  // C++11 [class.dtor]p5:
4778  // -- any direct or virtual base class [...] has a type with a destructor
4779  //    that is deleted or inaccessible
4780  if (!(CSM == Sema::CXXDefaultConstructor &&
4781        Field && Field->hasInClassInitializer()) &&
4782      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4783    return true;
4784
4785  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4786  // -- any direct or virtual base class or non-static data member has a
4787  //    type with a destructor that is deleted or inaccessible
4788  if (IsConstructor) {
4789    Sema::SpecialMemberOverloadResult *SMOR =
4790        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4791                              false, false, false, false, false);
4792    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4793      return true;
4794  }
4795
4796  return false;
4797}
4798
4799/// Check whether we should delete a special member function due to the class
4800/// having a particular direct or virtual base class.
4801bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4802  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4803  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4804}
4805
4806/// Check whether we should delete a special member function due to the class
4807/// having a particular non-static data member.
4808bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4809  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4810  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4811
4812  if (CSM == Sema::CXXDefaultConstructor) {
4813    // For a default constructor, all references must be initialized in-class
4814    // and, if a union, it must have a non-const member.
4815    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4816      if (Diagnose)
4817        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4818          << MD->getParent() << FD << FieldType << /*Reference*/0;
4819      return true;
4820    }
4821    // C++11 [class.ctor]p5: any non-variant non-static data member of
4822    // const-qualified type (or array thereof) with no
4823    // brace-or-equal-initializer does not have a user-provided default
4824    // constructor.
4825    if (!inUnion() && FieldType.isConstQualified() &&
4826        !FD->hasInClassInitializer() &&
4827        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4828      if (Diagnose)
4829        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4830          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4831      return true;
4832    }
4833
4834    if (inUnion() && !FieldType.isConstQualified())
4835      AllFieldsAreConst = false;
4836  } else if (CSM == Sema::CXXCopyConstructor) {
4837    // For a copy constructor, data members must not be of rvalue reference
4838    // type.
4839    if (FieldType->isRValueReferenceType()) {
4840      if (Diagnose)
4841        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4842          << MD->getParent() << FD << FieldType;
4843      return true;
4844    }
4845  } else if (IsAssignment) {
4846    // For an assignment operator, data members must not be of reference type.
4847    if (FieldType->isReferenceType()) {
4848      if (Diagnose)
4849        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4850          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4851      return true;
4852    }
4853    if (!FieldRecord && FieldType.isConstQualified()) {
4854      // C++11 [class.copy]p23:
4855      // -- a non-static data member of const non-class type (or array thereof)
4856      if (Diagnose)
4857        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4858          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4859      return true;
4860    }
4861  }
4862
4863  if (FieldRecord) {
4864    // Some additional restrictions exist on the variant members.
4865    if (!inUnion() && FieldRecord->isUnion() &&
4866        FieldRecord->isAnonymousStructOrUnion()) {
4867      bool AllVariantFieldsAreConst = true;
4868
4869      // FIXME: Handle anonymous unions declared within anonymous unions.
4870      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4871                                         UE = FieldRecord->field_end();
4872           UI != UE; ++UI) {
4873        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4874
4875        if (!UnionFieldType.isConstQualified())
4876          AllVariantFieldsAreConst = false;
4877
4878        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4879        if (UnionFieldRecord &&
4880            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4881                                          UnionFieldType.getCVRQualifiers()))
4882          return true;
4883      }
4884
4885      // At least one member in each anonymous union must be non-const
4886      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4887          FieldRecord->field_begin() != FieldRecord->field_end()) {
4888        if (Diagnose)
4889          S.Diag(FieldRecord->getLocation(),
4890                 diag::note_deleted_default_ctor_all_const)
4891            << MD->getParent() << /*anonymous union*/1;
4892        return true;
4893      }
4894
4895      // Don't check the implicit member of the anonymous union type.
4896      // This is technically non-conformant, but sanity demands it.
4897      return false;
4898    }
4899
4900    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4901                                      FieldType.getCVRQualifiers()))
4902      return true;
4903  }
4904
4905  return false;
4906}
4907
4908/// C++11 [class.ctor] p5:
4909///   A defaulted default constructor for a class X is defined as deleted if
4910/// X is a union and all of its variant members are of const-qualified type.
4911bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4912  // This is a silly definition, because it gives an empty union a deleted
4913  // default constructor. Don't do that.
4914  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4915      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4916    if (Diagnose)
4917      S.Diag(MD->getParent()->getLocation(),
4918             diag::note_deleted_default_ctor_all_const)
4919        << MD->getParent() << /*not anonymous union*/0;
4920    return true;
4921  }
4922  return false;
4923}
4924
4925/// Determine whether a defaulted special member function should be defined as
4926/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4927/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4928bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4929                                     bool Diagnose) {
4930  if (MD->isInvalidDecl())
4931    return false;
4932  CXXRecordDecl *RD = MD->getParent();
4933  assert(!RD->isDependentType() && "do deletion after instantiation");
4934  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4935    return false;
4936
4937  // C++11 [expr.lambda.prim]p19:
4938  //   The closure type associated with a lambda-expression has a
4939  //   deleted (8.4.3) default constructor and a deleted copy
4940  //   assignment operator.
4941  if (RD->isLambda() &&
4942      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4943    if (Diagnose)
4944      Diag(RD->getLocation(), diag::note_lambda_decl);
4945    return true;
4946  }
4947
4948  // For an anonymous struct or union, the copy and assignment special members
4949  // will never be used, so skip the check. For an anonymous union declared at
4950  // namespace scope, the constructor and destructor are used.
4951  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4952      RD->isAnonymousStructOrUnion())
4953    return false;
4954
4955  // C++11 [class.copy]p7, p18:
4956  //   If the class definition declares a move constructor or move assignment
4957  //   operator, an implicitly declared copy constructor or copy assignment
4958  //   operator is defined as deleted.
4959  if (MD->isImplicit() &&
4960      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4961    CXXMethodDecl *UserDeclaredMove = 0;
4962
4963    // In Microsoft mode, a user-declared move only causes the deletion of the
4964    // corresponding copy operation, not both copy operations.
4965    if (RD->hasUserDeclaredMoveConstructor() &&
4966        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4967      if (!Diagnose) return true;
4968
4969      // Find any user-declared move constructor.
4970      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4971                                        E = RD->ctor_end(); I != E; ++I) {
4972        if (I->isMoveConstructor()) {
4973          UserDeclaredMove = *I;
4974          break;
4975        }
4976      }
4977      assert(UserDeclaredMove);
4978    } else if (RD->hasUserDeclaredMoveAssignment() &&
4979               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4980      if (!Diagnose) return true;
4981
4982      // Find any user-declared move assignment operator.
4983      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
4984                                          E = RD->method_end(); I != E; ++I) {
4985        if (I->isMoveAssignmentOperator()) {
4986          UserDeclaredMove = *I;
4987          break;
4988        }
4989      }
4990      assert(UserDeclaredMove);
4991    }
4992
4993    if (UserDeclaredMove) {
4994      Diag(UserDeclaredMove->getLocation(),
4995           diag::note_deleted_copy_user_declared_move)
4996        << (CSM == CXXCopyAssignment) << RD
4997        << UserDeclaredMove->isMoveAssignmentOperator();
4998      return true;
4999    }
5000  }
5001
5002  // Do access control from the special member function
5003  ContextRAII MethodContext(*this, MD);
5004
5005  // C++11 [class.dtor]p5:
5006  // -- for a virtual destructor, lookup of the non-array deallocation function
5007  //    results in an ambiguity or in a function that is deleted or inaccessible
5008  if (CSM == CXXDestructor && MD->isVirtual()) {
5009    FunctionDecl *OperatorDelete = 0;
5010    DeclarationName Name =
5011      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5012    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5013                                 OperatorDelete, false)) {
5014      if (Diagnose)
5015        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5016      return true;
5017    }
5018  }
5019
5020  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5021
5022  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5023                                          BE = RD->bases_end(); BI != BE; ++BI)
5024    if (!BI->isVirtual() &&
5025        SMI.shouldDeleteForBase(BI))
5026      return true;
5027
5028  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5029                                          BE = RD->vbases_end(); BI != BE; ++BI)
5030    if (SMI.shouldDeleteForBase(BI))
5031      return true;
5032
5033  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5034                                     FE = RD->field_end(); FI != FE; ++FI)
5035    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5036        SMI.shouldDeleteForField(*FI))
5037      return true;
5038
5039  if (SMI.shouldDeleteForAllConstMembers())
5040    return true;
5041
5042  return false;
5043}
5044
5045/// Perform lookup for a special member of the specified kind, and determine
5046/// whether it is trivial. If the triviality can be determined without the
5047/// lookup, skip it. This is intended for use when determining whether a
5048/// special member of a containing object is trivial, and thus does not ever
5049/// perform overload resolution for default constructors.
5050///
5051/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5052/// member that was most likely to be intended to be trivial, if any.
5053static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5054                                     Sema::CXXSpecialMember CSM, unsigned Quals,
5055                                     CXXMethodDecl **Selected) {
5056  if (Selected)
5057    *Selected = 0;
5058
5059  switch (CSM) {
5060  case Sema::CXXInvalid:
5061    llvm_unreachable("not a special member");
5062
5063  case Sema::CXXDefaultConstructor:
5064    // C++11 [class.ctor]p5:
5065    //   A default constructor is trivial if:
5066    //    - all the [direct subobjects] have trivial default constructors
5067    //
5068    // Note, no overload resolution is performed in this case.
5069    if (RD->hasTrivialDefaultConstructor())
5070      return true;
5071
5072    if (Selected) {
5073      // If there's a default constructor which could have been trivial, dig it
5074      // out. Otherwise, if there's any user-provided default constructor, point
5075      // to that as an example of why there's not a trivial one.
5076      CXXConstructorDecl *DefCtor = 0;
5077      if (RD->needsImplicitDefaultConstructor())
5078        S.DeclareImplicitDefaultConstructor(RD);
5079      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5080                                        CE = RD->ctor_end(); CI != CE; ++CI) {
5081        if (!CI->isDefaultConstructor())
5082          continue;
5083        DefCtor = *CI;
5084        if (!DefCtor->isUserProvided())
5085          break;
5086      }
5087
5088      *Selected = DefCtor;
5089    }
5090
5091    return false;
5092
5093  case Sema::CXXDestructor:
5094    // C++11 [class.dtor]p5:
5095    //   A destructor is trivial if:
5096    //    - all the direct [subobjects] have trivial destructors
5097    if (RD->hasTrivialDestructor())
5098      return true;
5099
5100    if (Selected) {
5101      if (RD->needsImplicitDestructor())
5102        S.DeclareImplicitDestructor(RD);
5103      *Selected = RD->getDestructor();
5104    }
5105
5106    return false;
5107
5108  case Sema::CXXCopyConstructor:
5109    // C++11 [class.copy]p12:
5110    //   A copy constructor is trivial if:
5111    //    - the constructor selected to copy each direct [subobject] is trivial
5112    if (RD->hasTrivialCopyConstructor()) {
5113      if (Quals == Qualifiers::Const)
5114        // We must either select the trivial copy constructor or reach an
5115        // ambiguity; no need to actually perform overload resolution.
5116        return true;
5117    } else if (!Selected) {
5118      return false;
5119    }
5120    // In C++98, we are not supposed to perform overload resolution here, but we
5121    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5122    // cases like B as having a non-trivial copy constructor:
5123    //   struct A { template<typename T> A(T&); };
5124    //   struct B { mutable A a; };
5125    goto NeedOverloadResolution;
5126
5127  case Sema::CXXCopyAssignment:
5128    // C++11 [class.copy]p25:
5129    //   A copy assignment operator is trivial if:
5130    //    - the assignment operator selected to copy each direct [subobject] is
5131    //      trivial
5132    if (RD->hasTrivialCopyAssignment()) {
5133      if (Quals == Qualifiers::Const)
5134        return true;
5135    } else if (!Selected) {
5136      return false;
5137    }
5138    // In C++98, we are not supposed to perform overload resolution here, but we
5139    // treat that as a language defect.
5140    goto NeedOverloadResolution;
5141
5142  case Sema::CXXMoveConstructor:
5143  case Sema::CXXMoveAssignment:
5144  NeedOverloadResolution:
5145    Sema::SpecialMemberOverloadResult *SMOR =
5146      S.LookupSpecialMember(RD, CSM,
5147                            Quals & Qualifiers::Const,
5148                            Quals & Qualifiers::Volatile,
5149                            /*RValueThis*/false, /*ConstThis*/false,
5150                            /*VolatileThis*/false);
5151
5152    // The standard doesn't describe how to behave if the lookup is ambiguous.
5153    // We treat it as not making the member non-trivial, just like the standard
5154    // mandates for the default constructor. This should rarely matter, because
5155    // the member will also be deleted.
5156    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5157      return true;
5158
5159    if (!SMOR->getMethod()) {
5160      assert(SMOR->getKind() ==
5161             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5162      return false;
5163    }
5164
5165    // We deliberately don't check if we found a deleted special member. We're
5166    // not supposed to!
5167    if (Selected)
5168      *Selected = SMOR->getMethod();
5169    return SMOR->getMethod()->isTrivial();
5170  }
5171
5172  llvm_unreachable("unknown special method kind");
5173}
5174
5175static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5176  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5177       CI != CE; ++CI)
5178    if (!CI->isImplicit())
5179      return *CI;
5180
5181  // Look for constructor templates.
5182  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5183  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5184    if (CXXConstructorDecl *CD =
5185          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5186      return CD;
5187  }
5188
5189  return 0;
5190}
5191
5192/// The kind of subobject we are checking for triviality. The values of this
5193/// enumeration are used in diagnostics.
5194enum TrivialSubobjectKind {
5195  /// The subobject is a base class.
5196  TSK_BaseClass,
5197  /// The subobject is a non-static data member.
5198  TSK_Field,
5199  /// The object is actually the complete object.
5200  TSK_CompleteObject
5201};
5202
5203/// Check whether the special member selected for a given type would be trivial.
5204static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5205                                      QualType SubType,
5206                                      Sema::CXXSpecialMember CSM,
5207                                      TrivialSubobjectKind Kind,
5208                                      bool Diagnose) {
5209  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5210  if (!SubRD)
5211    return true;
5212
5213  CXXMethodDecl *Selected;
5214  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5215                               Diagnose ? &Selected : 0))
5216    return true;
5217
5218  if (Diagnose) {
5219    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5220      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5221        << Kind << SubType.getUnqualifiedType();
5222      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5223        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5224    } else if (!Selected)
5225      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5226        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5227    else if (Selected->isUserProvided()) {
5228      if (Kind == TSK_CompleteObject)
5229        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5230          << Kind << SubType.getUnqualifiedType() << CSM;
5231      else {
5232        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5233          << Kind << SubType.getUnqualifiedType() << CSM;
5234        S.Diag(Selected->getLocation(), diag::note_declared_at);
5235      }
5236    } else {
5237      if (Kind != TSK_CompleteObject)
5238        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5239          << Kind << SubType.getUnqualifiedType() << CSM;
5240
5241      // Explain why the defaulted or deleted special member isn't trivial.
5242      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5243    }
5244  }
5245
5246  return false;
5247}
5248
5249/// Check whether the members of a class type allow a special member to be
5250/// trivial.
5251static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5252                                     Sema::CXXSpecialMember CSM,
5253                                     bool ConstArg, bool Diagnose) {
5254  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5255                                     FE = RD->field_end(); FI != FE; ++FI) {
5256    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5257      continue;
5258
5259    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5260
5261    // Pretend anonymous struct or union members are members of this class.
5262    if (FI->isAnonymousStructOrUnion()) {
5263      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5264                                    CSM, ConstArg, Diagnose))
5265        return false;
5266      continue;
5267    }
5268
5269    // C++11 [class.ctor]p5:
5270    //   A default constructor is trivial if [...]
5271    //    -- no non-static data member of its class has a
5272    //       brace-or-equal-initializer
5273    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5274      if (Diagnose)
5275        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5276      return false;
5277    }
5278
5279    // Objective C ARC 4.3.5:
5280    //   [...] nontrivally ownership-qualified types are [...] not trivially
5281    //   default constructible, copy constructible, move constructible, copy
5282    //   assignable, move assignable, or destructible [...]
5283    if (S.getLangOpts().ObjCAutoRefCount &&
5284        FieldType.hasNonTrivialObjCLifetime()) {
5285      if (Diagnose)
5286        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5287          << RD << FieldType.getObjCLifetime();
5288      return false;
5289    }
5290
5291    if (ConstArg && !FI->isMutable())
5292      FieldType.addConst();
5293    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5294                                   TSK_Field, Diagnose))
5295      return false;
5296  }
5297
5298  return true;
5299}
5300
5301/// Diagnose why the specified class does not have a trivial special member of
5302/// the given kind.
5303void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5304  QualType Ty = Context.getRecordType(RD);
5305  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5306    Ty.addConst();
5307
5308  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5309                            TSK_CompleteObject, /*Diagnose*/true);
5310}
5311
5312/// Determine whether a defaulted or deleted special member function is trivial,
5313/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5314/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5315bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5316                                  bool Diagnose) {
5317  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5318
5319  CXXRecordDecl *RD = MD->getParent();
5320
5321  bool ConstArg = false;
5322
5323  // C++11 [class.copy]p12, p25:
5324  //   A [special member] is trivial if its declared parameter type is the same
5325  //   as if it had been implicitly declared [...]
5326  switch (CSM) {
5327  case CXXDefaultConstructor:
5328  case CXXDestructor:
5329    // Trivial default constructors and destructors cannot have parameters.
5330    break;
5331
5332  case CXXCopyConstructor:
5333  case CXXCopyAssignment: {
5334    // Trivial copy operations always have const, non-volatile parameter types.
5335    ConstArg = true;
5336    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5337    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5338    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5339      if (Diagnose)
5340        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5341          << Param0->getSourceRange() << Param0->getType()
5342          << Context.getLValueReferenceType(
5343               Context.getRecordType(RD).withConst());
5344      return false;
5345    }
5346    break;
5347  }
5348
5349  case CXXMoveConstructor:
5350  case CXXMoveAssignment: {
5351    // Trivial move operations always have non-cv-qualified parameters.
5352    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5353    const RValueReferenceType *RT =
5354      Param0->getType()->getAs<RValueReferenceType>();
5355    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5356      if (Diagnose)
5357        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5358          << Param0->getSourceRange() << Param0->getType()
5359          << Context.getRValueReferenceType(Context.getRecordType(RD));
5360      return false;
5361    }
5362    break;
5363  }
5364
5365  case CXXInvalid:
5366    llvm_unreachable("not a special member");
5367  }
5368
5369  // FIXME: We require that the parameter-declaration-clause is equivalent to
5370  // that of an implicit declaration, not just that the declared parameter type
5371  // matches, in order to prevent absuridities like a function simultaneously
5372  // being a trivial copy constructor and a non-trivial default constructor.
5373  // This issue has not yet been assigned a core issue number.
5374  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5375    if (Diagnose)
5376      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5377           diag::note_nontrivial_default_arg)
5378        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5379    return false;
5380  }
5381  if (MD->isVariadic()) {
5382    if (Diagnose)
5383      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5384    return false;
5385  }
5386
5387  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5388  //   A copy/move [constructor or assignment operator] is trivial if
5389  //    -- the [member] selected to copy/move each direct base class subobject
5390  //       is trivial
5391  //
5392  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5393  //   A [default constructor or destructor] is trivial if
5394  //    -- all the direct base classes have trivial [default constructors or
5395  //       destructors]
5396  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5397                                          BE = RD->bases_end(); BI != BE; ++BI)
5398    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5399                                   ConstArg ? BI->getType().withConst()
5400                                            : BI->getType(),
5401                                   CSM, TSK_BaseClass, Diagnose))
5402      return false;
5403
5404  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5405  //   A copy/move [constructor or assignment operator] for a class X is
5406  //   trivial if
5407  //    -- for each non-static data member of X that is of class type (or array
5408  //       thereof), the constructor selected to copy/move that member is
5409  //       trivial
5410  //
5411  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5412  //   A [default constructor or destructor] is trivial if
5413  //    -- for all of the non-static data members of its class that are of class
5414  //       type (or array thereof), each such class has a trivial [default
5415  //       constructor or destructor]
5416  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5417    return false;
5418
5419  // C++11 [class.dtor]p5:
5420  //   A destructor is trivial if [...]
5421  //    -- the destructor is not virtual
5422  if (CSM == CXXDestructor && MD->isVirtual()) {
5423    if (Diagnose)
5424      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5425    return false;
5426  }
5427
5428  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5429  //   A [special member] for class X is trivial if [...]
5430  //    -- class X has no virtual functions and no virtual base classes
5431  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5432    if (!Diagnose)
5433      return false;
5434
5435    if (RD->getNumVBases()) {
5436      // Check for virtual bases. We already know that the corresponding
5437      // member in all bases is trivial, so vbases must all be direct.
5438      CXXBaseSpecifier &BS = *RD->vbases_begin();
5439      assert(BS.isVirtual());
5440      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5441      return false;
5442    }
5443
5444    // Must have a virtual method.
5445    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5446                                        ME = RD->method_end(); MI != ME; ++MI) {
5447      if (MI->isVirtual()) {
5448        SourceLocation MLoc = MI->getLocStart();
5449        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5450        return false;
5451      }
5452    }
5453
5454    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5455  }
5456
5457  // Looks like it's trivial!
5458  return true;
5459}
5460
5461/// \brief Data used with FindHiddenVirtualMethod
5462namespace {
5463  struct FindHiddenVirtualMethodData {
5464    Sema *S;
5465    CXXMethodDecl *Method;
5466    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5467    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5468  };
5469}
5470
5471/// \brief Check whether any most overriden method from MD in Methods
5472static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5473                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5474  if (MD->size_overridden_methods() == 0)
5475    return Methods.count(MD->getCanonicalDecl());
5476  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5477                                      E = MD->end_overridden_methods();
5478       I != E; ++I)
5479    if (CheckMostOverridenMethods(*I, Methods))
5480      return true;
5481  return false;
5482}
5483
5484/// \brief Member lookup function that determines whether a given C++
5485/// method overloads virtual methods in a base class without overriding any,
5486/// to be used with CXXRecordDecl::lookupInBases().
5487static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5488                                    CXXBasePath &Path,
5489                                    void *UserData) {
5490  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5491
5492  FindHiddenVirtualMethodData &Data
5493    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5494
5495  DeclarationName Name = Data.Method->getDeclName();
5496  assert(Name.getNameKind() == DeclarationName::Identifier);
5497
5498  bool foundSameNameMethod = false;
5499  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5500  for (Path.Decls = BaseRecord->lookup(Name);
5501       !Path.Decls.empty();
5502       Path.Decls = Path.Decls.slice(1)) {
5503    NamedDecl *D = Path.Decls.front();
5504    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5505      MD = MD->getCanonicalDecl();
5506      foundSameNameMethod = true;
5507      // Interested only in hidden virtual methods.
5508      if (!MD->isVirtual())
5509        continue;
5510      // If the method we are checking overrides a method from its base
5511      // don't warn about the other overloaded methods.
5512      if (!Data.S->IsOverload(Data.Method, MD, false))
5513        return true;
5514      // Collect the overload only if its hidden.
5515      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5516        overloadedMethods.push_back(MD);
5517    }
5518  }
5519
5520  if (foundSameNameMethod)
5521    Data.OverloadedMethods.append(overloadedMethods.begin(),
5522                                   overloadedMethods.end());
5523  return foundSameNameMethod;
5524}
5525
5526/// \brief Add the most overriden methods from MD to Methods
5527static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5528                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5529  if (MD->size_overridden_methods() == 0)
5530    Methods.insert(MD->getCanonicalDecl());
5531  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5532                                      E = MD->end_overridden_methods();
5533       I != E; ++I)
5534    AddMostOverridenMethods(*I, Methods);
5535}
5536
5537/// \brief See if a method overloads virtual methods in a base class without
5538/// overriding any.
5539void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5540  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5541                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5542    return;
5543  if (!MD->getDeclName().isIdentifier())
5544    return;
5545
5546  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5547                     /*bool RecordPaths=*/false,
5548                     /*bool DetectVirtual=*/false);
5549  FindHiddenVirtualMethodData Data;
5550  Data.Method = MD;
5551  Data.S = this;
5552
5553  // Keep the base methods that were overriden or introduced in the subclass
5554  // by 'using' in a set. A base method not in this set is hidden.
5555  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5556  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5557    NamedDecl *ND = *I;
5558    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5559      ND = shad->getTargetDecl();
5560    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5561      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5562  }
5563
5564  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5565      !Data.OverloadedMethods.empty()) {
5566    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5567      << MD << (Data.OverloadedMethods.size() > 1);
5568
5569    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5570      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5571      PartialDiagnostic PD = PDiag(
5572           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5573      HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5574      Diag(overloadedMD->getLocation(), PD);
5575    }
5576  }
5577}
5578
5579void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5580                                             Decl *TagDecl,
5581                                             SourceLocation LBrac,
5582                                             SourceLocation RBrac,
5583                                             AttributeList *AttrList) {
5584  if (!TagDecl)
5585    return;
5586
5587  AdjustDeclIfTemplate(TagDecl);
5588
5589  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5590    if (l->getKind() != AttributeList::AT_Visibility)
5591      continue;
5592    l->setInvalid();
5593    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5594      l->getName();
5595  }
5596
5597  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5598              // strict aliasing violation!
5599              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5600              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5601
5602  CheckCompletedCXXClass(
5603                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5604}
5605
5606/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5607/// special functions, such as the default constructor, copy
5608/// constructor, or destructor, to the given C++ class (C++
5609/// [special]p1).  This routine can only be executed just before the
5610/// definition of the class is complete.
5611void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5612  if (!ClassDecl->hasUserDeclaredConstructor())
5613    ++ASTContext::NumImplicitDefaultConstructors;
5614
5615  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5616    ++ASTContext::NumImplicitCopyConstructors;
5617
5618    // If the properties or semantics of the copy constructor couldn't be
5619    // determined while the class was being declared, force a declaration
5620    // of it now.
5621    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5622      DeclareImplicitCopyConstructor(ClassDecl);
5623  }
5624
5625  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5626    ++ASTContext::NumImplicitMoveConstructors;
5627
5628    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5629      DeclareImplicitMoveConstructor(ClassDecl);
5630  }
5631
5632  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5633    ++ASTContext::NumImplicitCopyAssignmentOperators;
5634
5635    // If we have a dynamic class, then the copy assignment operator may be
5636    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5637    // it shows up in the right place in the vtable and that we diagnose
5638    // problems with the implicit exception specification.
5639    if (ClassDecl->isDynamicClass() ||
5640        ClassDecl->needsOverloadResolutionForCopyAssignment())
5641      DeclareImplicitCopyAssignment(ClassDecl);
5642  }
5643
5644  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5645    ++ASTContext::NumImplicitMoveAssignmentOperators;
5646
5647    // Likewise for the move assignment operator.
5648    if (ClassDecl->isDynamicClass() ||
5649        ClassDecl->needsOverloadResolutionForMoveAssignment())
5650      DeclareImplicitMoveAssignment(ClassDecl);
5651  }
5652
5653  if (!ClassDecl->hasUserDeclaredDestructor()) {
5654    ++ASTContext::NumImplicitDestructors;
5655
5656    // If we have a dynamic class, then the destructor may be virtual, so we
5657    // have to declare the destructor immediately. This ensures that, e.g., it
5658    // shows up in the right place in the vtable and that we diagnose problems
5659    // with the implicit exception specification.
5660    if (ClassDecl->isDynamicClass() ||
5661        ClassDecl->needsOverloadResolutionForDestructor())
5662      DeclareImplicitDestructor(ClassDecl);
5663  }
5664}
5665
5666void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5667  if (!D)
5668    return;
5669
5670  int NumParamList = D->getNumTemplateParameterLists();
5671  for (int i = 0; i < NumParamList; i++) {
5672    TemplateParameterList* Params = D->getTemplateParameterList(i);
5673    for (TemplateParameterList::iterator Param = Params->begin(),
5674                                      ParamEnd = Params->end();
5675          Param != ParamEnd; ++Param) {
5676      NamedDecl *Named = cast<NamedDecl>(*Param);
5677      if (Named->getDeclName()) {
5678        S->AddDecl(Named);
5679        IdResolver.AddDecl(Named);
5680      }
5681    }
5682  }
5683}
5684
5685void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5686  if (!D)
5687    return;
5688
5689  TemplateParameterList *Params = 0;
5690  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5691    Params = Template->getTemplateParameters();
5692  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5693           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5694    Params = PartialSpec->getTemplateParameters();
5695  else
5696    return;
5697
5698  for (TemplateParameterList::iterator Param = Params->begin(),
5699                                    ParamEnd = Params->end();
5700       Param != ParamEnd; ++Param) {
5701    NamedDecl *Named = cast<NamedDecl>(*Param);
5702    if (Named->getDeclName()) {
5703      S->AddDecl(Named);
5704      IdResolver.AddDecl(Named);
5705    }
5706  }
5707}
5708
5709void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5710  if (!RecordD) return;
5711  AdjustDeclIfTemplate(RecordD);
5712  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5713  PushDeclContext(S, Record);
5714}
5715
5716void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5717  if (!RecordD) return;
5718  PopDeclContext();
5719}
5720
5721/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5722/// parsing a top-level (non-nested) C++ class, and we are now
5723/// parsing those parts of the given Method declaration that could
5724/// not be parsed earlier (C++ [class.mem]p2), such as default
5725/// arguments. This action should enter the scope of the given
5726/// Method declaration as if we had just parsed the qualified method
5727/// name. However, it should not bring the parameters into scope;
5728/// that will be performed by ActOnDelayedCXXMethodParameter.
5729void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5730}
5731
5732/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5733/// C++ method declaration. We're (re-)introducing the given
5734/// function parameter into scope for use in parsing later parts of
5735/// the method declaration. For example, we could see an
5736/// ActOnParamDefaultArgument event for this parameter.
5737void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5738  if (!ParamD)
5739    return;
5740
5741  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5742
5743  // If this parameter has an unparsed default argument, clear it out
5744  // to make way for the parsed default argument.
5745  if (Param->hasUnparsedDefaultArg())
5746    Param->setDefaultArg(0);
5747
5748  S->AddDecl(Param);
5749  if (Param->getDeclName())
5750    IdResolver.AddDecl(Param);
5751}
5752
5753/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5754/// processing the delayed method declaration for Method. The method
5755/// declaration is now considered finished. There may be a separate
5756/// ActOnStartOfFunctionDef action later (not necessarily
5757/// immediately!) for this method, if it was also defined inside the
5758/// class body.
5759void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5760  if (!MethodD)
5761    return;
5762
5763  AdjustDeclIfTemplate(MethodD);
5764
5765  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5766
5767  // Now that we have our default arguments, check the constructor
5768  // again. It could produce additional diagnostics or affect whether
5769  // the class has implicitly-declared destructors, among other
5770  // things.
5771  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5772    CheckConstructor(Constructor);
5773
5774  // Check the default arguments, which we may have added.
5775  if (!Method->isInvalidDecl())
5776    CheckCXXDefaultArguments(Method);
5777}
5778
5779/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5780/// the well-formedness of the constructor declarator @p D with type @p
5781/// R. If there are any errors in the declarator, this routine will
5782/// emit diagnostics and set the invalid bit to true.  In any case, the type
5783/// will be updated to reflect a well-formed type for the constructor and
5784/// returned.
5785QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5786                                          StorageClass &SC) {
5787  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5788
5789  // C++ [class.ctor]p3:
5790  //   A constructor shall not be virtual (10.3) or static (9.4). A
5791  //   constructor can be invoked for a const, volatile or const
5792  //   volatile object. A constructor shall not be declared const,
5793  //   volatile, or const volatile (9.3.2).
5794  if (isVirtual) {
5795    if (!D.isInvalidType())
5796      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5797        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5798        << SourceRange(D.getIdentifierLoc());
5799    D.setInvalidType();
5800  }
5801  if (SC == SC_Static) {
5802    if (!D.isInvalidType())
5803      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5804        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5805        << SourceRange(D.getIdentifierLoc());
5806    D.setInvalidType();
5807    SC = SC_None;
5808  }
5809
5810  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5811  if (FTI.TypeQuals != 0) {
5812    if (FTI.TypeQuals & Qualifiers::Const)
5813      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5814        << "const" << SourceRange(D.getIdentifierLoc());
5815    if (FTI.TypeQuals & Qualifiers::Volatile)
5816      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5817        << "volatile" << SourceRange(D.getIdentifierLoc());
5818    if (FTI.TypeQuals & Qualifiers::Restrict)
5819      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5820        << "restrict" << SourceRange(D.getIdentifierLoc());
5821    D.setInvalidType();
5822  }
5823
5824  // C++0x [class.ctor]p4:
5825  //   A constructor shall not be declared with a ref-qualifier.
5826  if (FTI.hasRefQualifier()) {
5827    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5828      << FTI.RefQualifierIsLValueRef
5829      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5830    D.setInvalidType();
5831  }
5832
5833  // Rebuild the function type "R" without any type qualifiers (in
5834  // case any of the errors above fired) and with "void" as the
5835  // return type, since constructors don't have return types.
5836  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5837  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5838    return R;
5839
5840  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5841  EPI.TypeQuals = 0;
5842  EPI.RefQualifier = RQ_None;
5843
5844  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5845}
5846
5847/// CheckConstructor - Checks a fully-formed constructor for
5848/// well-formedness, issuing any diagnostics required. Returns true if
5849/// the constructor declarator is invalid.
5850void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5851  CXXRecordDecl *ClassDecl
5852    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5853  if (!ClassDecl)
5854    return Constructor->setInvalidDecl();
5855
5856  // C++ [class.copy]p3:
5857  //   A declaration of a constructor for a class X is ill-formed if
5858  //   its first parameter is of type (optionally cv-qualified) X and
5859  //   either there are no other parameters or else all other
5860  //   parameters have default arguments.
5861  if (!Constructor->isInvalidDecl() &&
5862      ((Constructor->getNumParams() == 1) ||
5863       (Constructor->getNumParams() > 1 &&
5864        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5865      Constructor->getTemplateSpecializationKind()
5866                                              != TSK_ImplicitInstantiation) {
5867    QualType ParamType = Constructor->getParamDecl(0)->getType();
5868    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5869    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5870      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5871      const char *ConstRef
5872        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5873                                                        : " const &";
5874      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5875        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5876
5877      // FIXME: Rather that making the constructor invalid, we should endeavor
5878      // to fix the type.
5879      Constructor->setInvalidDecl();
5880    }
5881  }
5882}
5883
5884/// CheckDestructor - Checks a fully-formed destructor definition for
5885/// well-formedness, issuing any diagnostics required.  Returns true
5886/// on error.
5887bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5888  CXXRecordDecl *RD = Destructor->getParent();
5889
5890  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
5891    SourceLocation Loc;
5892
5893    if (!Destructor->isImplicit())
5894      Loc = Destructor->getLocation();
5895    else
5896      Loc = RD->getLocation();
5897
5898    // If we have a virtual destructor, look up the deallocation function
5899    FunctionDecl *OperatorDelete = 0;
5900    DeclarationName Name =
5901    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5902    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5903      return true;
5904
5905    MarkFunctionReferenced(Loc, OperatorDelete);
5906
5907    Destructor->setOperatorDelete(OperatorDelete);
5908  }
5909
5910  return false;
5911}
5912
5913static inline bool
5914FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5915  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5916          FTI.ArgInfo[0].Param &&
5917          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5918}
5919
5920/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5921/// the well-formednes of the destructor declarator @p D with type @p
5922/// R. If there are any errors in the declarator, this routine will
5923/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5924/// will be updated to reflect a well-formed type for the destructor and
5925/// returned.
5926QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5927                                         StorageClass& SC) {
5928  // C++ [class.dtor]p1:
5929  //   [...] A typedef-name that names a class is a class-name
5930  //   (7.1.3); however, a typedef-name that names a class shall not
5931  //   be used as the identifier in the declarator for a destructor
5932  //   declaration.
5933  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5934  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5935    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5936      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5937  else if (const TemplateSpecializationType *TST =
5938             DeclaratorType->getAs<TemplateSpecializationType>())
5939    if (TST->isTypeAlias())
5940      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5941        << DeclaratorType << 1;
5942
5943  // C++ [class.dtor]p2:
5944  //   A destructor is used to destroy objects of its class type. A
5945  //   destructor takes no parameters, and no return type can be
5946  //   specified for it (not even void). The address of a destructor
5947  //   shall not be taken. A destructor shall not be static. A
5948  //   destructor can be invoked for a const, volatile or const
5949  //   volatile object. A destructor shall not be declared const,
5950  //   volatile or const volatile (9.3.2).
5951  if (SC == SC_Static) {
5952    if (!D.isInvalidType())
5953      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5954        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5955        << SourceRange(D.getIdentifierLoc())
5956        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5957
5958    SC = SC_None;
5959  }
5960  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5961    // Destructors don't have return types, but the parser will
5962    // happily parse something like:
5963    //
5964    //   class X {
5965    //     float ~X();
5966    //   };
5967    //
5968    // The return type will be eliminated later.
5969    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5970      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5971      << SourceRange(D.getIdentifierLoc());
5972  }
5973
5974  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5975  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5976    if (FTI.TypeQuals & Qualifiers::Const)
5977      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5978        << "const" << SourceRange(D.getIdentifierLoc());
5979    if (FTI.TypeQuals & Qualifiers::Volatile)
5980      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5981        << "volatile" << SourceRange(D.getIdentifierLoc());
5982    if (FTI.TypeQuals & Qualifiers::Restrict)
5983      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5984        << "restrict" << SourceRange(D.getIdentifierLoc());
5985    D.setInvalidType();
5986  }
5987
5988  // C++0x [class.dtor]p2:
5989  //   A destructor shall not be declared with a ref-qualifier.
5990  if (FTI.hasRefQualifier()) {
5991    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5992      << FTI.RefQualifierIsLValueRef
5993      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5994    D.setInvalidType();
5995  }
5996
5997  // Make sure we don't have any parameters.
5998  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5999    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6000
6001    // Delete the parameters.
6002    FTI.freeArgs();
6003    D.setInvalidType();
6004  }
6005
6006  // Make sure the destructor isn't variadic.
6007  if (FTI.isVariadic) {
6008    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6009    D.setInvalidType();
6010  }
6011
6012  // Rebuild the function type "R" without any type qualifiers or
6013  // parameters (in case any of the errors above fired) and with
6014  // "void" as the return type, since destructors don't have return
6015  // types.
6016  if (!D.isInvalidType())
6017    return R;
6018
6019  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6020  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6021  EPI.Variadic = false;
6022  EPI.TypeQuals = 0;
6023  EPI.RefQualifier = RQ_None;
6024  return Context.getFunctionType(Context.VoidTy, None, EPI);
6025}
6026
6027/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6028/// well-formednes of the conversion function declarator @p D with
6029/// type @p R. If there are any errors in the declarator, this routine
6030/// will emit diagnostics and return true. Otherwise, it will return
6031/// false. Either way, the type @p R will be updated to reflect a
6032/// well-formed type for the conversion operator.
6033void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6034                                     StorageClass& SC) {
6035  // C++ [class.conv.fct]p1:
6036  //   Neither parameter types nor return type can be specified. The
6037  //   type of a conversion function (8.3.5) is "function taking no
6038  //   parameter returning conversion-type-id."
6039  if (SC == SC_Static) {
6040    if (!D.isInvalidType())
6041      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6042        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6043        << SourceRange(D.getIdentifierLoc());
6044    D.setInvalidType();
6045    SC = SC_None;
6046  }
6047
6048  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6049
6050  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6051    // Conversion functions don't have return types, but the parser will
6052    // happily parse something like:
6053    //
6054    //   class X {
6055    //     float operator bool();
6056    //   };
6057    //
6058    // The return type will be changed later anyway.
6059    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6060      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6061      << SourceRange(D.getIdentifierLoc());
6062    D.setInvalidType();
6063  }
6064
6065  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6066
6067  // Make sure we don't have any parameters.
6068  if (Proto->getNumArgs() > 0) {
6069    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6070
6071    // Delete the parameters.
6072    D.getFunctionTypeInfo().freeArgs();
6073    D.setInvalidType();
6074  } else if (Proto->isVariadic()) {
6075    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6076    D.setInvalidType();
6077  }
6078
6079  // Diagnose "&operator bool()" and other such nonsense.  This
6080  // is actually a gcc extension which we don't support.
6081  if (Proto->getResultType() != ConvType) {
6082    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6083      << Proto->getResultType();
6084    D.setInvalidType();
6085    ConvType = Proto->getResultType();
6086  }
6087
6088  // C++ [class.conv.fct]p4:
6089  //   The conversion-type-id shall not represent a function type nor
6090  //   an array type.
6091  if (ConvType->isArrayType()) {
6092    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6093    ConvType = Context.getPointerType(ConvType);
6094    D.setInvalidType();
6095  } else if (ConvType->isFunctionType()) {
6096    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6097    ConvType = Context.getPointerType(ConvType);
6098    D.setInvalidType();
6099  }
6100
6101  // Rebuild the function type "R" without any parameters (in case any
6102  // of the errors above fired) and with the conversion type as the
6103  // return type.
6104  if (D.isInvalidType())
6105    R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6106
6107  // C++0x explicit conversion operators.
6108  if (D.getDeclSpec().isExplicitSpecified())
6109    Diag(D.getDeclSpec().getExplicitSpecLoc(),
6110         getLangOpts().CPlusPlus11 ?
6111           diag::warn_cxx98_compat_explicit_conversion_functions :
6112           diag::ext_explicit_conversion_functions)
6113      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6114}
6115
6116/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6117/// the declaration of the given C++ conversion function. This routine
6118/// is responsible for recording the conversion function in the C++
6119/// class, if possible.
6120Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6121  assert(Conversion && "Expected to receive a conversion function declaration");
6122
6123  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6124
6125  // Make sure we aren't redeclaring the conversion function.
6126  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6127
6128  // C++ [class.conv.fct]p1:
6129  //   [...] A conversion function is never used to convert a
6130  //   (possibly cv-qualified) object to the (possibly cv-qualified)
6131  //   same object type (or a reference to it), to a (possibly
6132  //   cv-qualified) base class of that type (or a reference to it),
6133  //   or to (possibly cv-qualified) void.
6134  // FIXME: Suppress this warning if the conversion function ends up being a
6135  // virtual function that overrides a virtual function in a base class.
6136  QualType ClassType
6137    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6138  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6139    ConvType = ConvTypeRef->getPointeeType();
6140  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6141      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6142    /* Suppress diagnostics for instantiations. */;
6143  else if (ConvType->isRecordType()) {
6144    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6145    if (ConvType == ClassType)
6146      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6147        << ClassType;
6148    else if (IsDerivedFrom(ClassType, ConvType))
6149      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6150        <<  ClassType << ConvType;
6151  } else if (ConvType->isVoidType()) {
6152    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6153      << ClassType << ConvType;
6154  }
6155
6156  if (FunctionTemplateDecl *ConversionTemplate
6157                                = Conversion->getDescribedFunctionTemplate())
6158    return ConversionTemplate;
6159
6160  return Conversion;
6161}
6162
6163//===----------------------------------------------------------------------===//
6164// Namespace Handling
6165//===----------------------------------------------------------------------===//
6166
6167/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6168/// reopened.
6169static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6170                                            SourceLocation Loc,
6171                                            IdentifierInfo *II, bool *IsInline,
6172                                            NamespaceDecl *PrevNS) {
6173  assert(*IsInline != PrevNS->isInline());
6174
6175  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6176  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6177  // inline namespaces, with the intention of bringing names into namespace std.
6178  //
6179  // We support this just well enough to get that case working; this is not
6180  // sufficient to support reopening namespaces as inline in general.
6181  if (*IsInline && II && II->getName().startswith("__atomic") &&
6182      S.getSourceManager().isInSystemHeader(Loc)) {
6183    // Mark all prior declarations of the namespace as inline.
6184    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6185         NS = NS->getPreviousDecl())
6186      NS->setInline(*IsInline);
6187    // Patch up the lookup table for the containing namespace. This isn't really
6188    // correct, but it's good enough for this particular case.
6189    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6190                                    E = PrevNS->decls_end(); I != E; ++I)
6191      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6192        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6193    return;
6194  }
6195
6196  if (PrevNS->isInline())
6197    // The user probably just forgot the 'inline', so suggest that it
6198    // be added back.
6199    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6200      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6201  else
6202    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6203      << IsInline;
6204
6205  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6206  *IsInline = PrevNS->isInline();
6207}
6208
6209/// ActOnStartNamespaceDef - This is called at the start of a namespace
6210/// definition.
6211Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6212                                   SourceLocation InlineLoc,
6213                                   SourceLocation NamespaceLoc,
6214                                   SourceLocation IdentLoc,
6215                                   IdentifierInfo *II,
6216                                   SourceLocation LBrace,
6217                                   AttributeList *AttrList) {
6218  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6219  // For anonymous namespace, take the location of the left brace.
6220  SourceLocation Loc = II ? IdentLoc : LBrace;
6221  bool IsInline = InlineLoc.isValid();
6222  bool IsInvalid = false;
6223  bool IsStd = false;
6224  bool AddToKnown = false;
6225  Scope *DeclRegionScope = NamespcScope->getParent();
6226
6227  NamespaceDecl *PrevNS = 0;
6228  if (II) {
6229    // C++ [namespace.def]p2:
6230    //   The identifier in an original-namespace-definition shall not
6231    //   have been previously defined in the declarative region in
6232    //   which the original-namespace-definition appears. The
6233    //   identifier in an original-namespace-definition is the name of
6234    //   the namespace. Subsequently in that declarative region, it is
6235    //   treated as an original-namespace-name.
6236    //
6237    // Since namespace names are unique in their scope, and we don't
6238    // look through using directives, just look for any ordinary names.
6239
6240    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6241    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6242    Decl::IDNS_Namespace;
6243    NamedDecl *PrevDecl = 0;
6244    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6245    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6246         ++I) {
6247      if ((*I)->getIdentifierNamespace() & IDNS) {
6248        PrevDecl = *I;
6249        break;
6250      }
6251    }
6252
6253    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6254
6255    if (PrevNS) {
6256      // This is an extended namespace definition.
6257      if (IsInline != PrevNS->isInline())
6258        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6259                                        &IsInline, PrevNS);
6260    } else if (PrevDecl) {
6261      // This is an invalid name redefinition.
6262      Diag(Loc, diag::err_redefinition_different_kind)
6263        << II;
6264      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6265      IsInvalid = true;
6266      // Continue on to push Namespc as current DeclContext and return it.
6267    } else if (II->isStr("std") &&
6268               CurContext->getRedeclContext()->isTranslationUnit()) {
6269      // This is the first "real" definition of the namespace "std", so update
6270      // our cache of the "std" namespace to point at this definition.
6271      PrevNS = getStdNamespace();
6272      IsStd = true;
6273      AddToKnown = !IsInline;
6274    } else {
6275      // We've seen this namespace for the first time.
6276      AddToKnown = !IsInline;
6277    }
6278  } else {
6279    // Anonymous namespaces.
6280
6281    // Determine whether the parent already has an anonymous namespace.
6282    DeclContext *Parent = CurContext->getRedeclContext();
6283    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6284      PrevNS = TU->getAnonymousNamespace();
6285    } else {
6286      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6287      PrevNS = ND->getAnonymousNamespace();
6288    }
6289
6290    if (PrevNS && IsInline != PrevNS->isInline())
6291      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6292                                      &IsInline, PrevNS);
6293  }
6294
6295  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6296                                                 StartLoc, Loc, II, PrevNS);
6297  if (IsInvalid)
6298    Namespc->setInvalidDecl();
6299
6300  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6301
6302  // FIXME: Should we be merging attributes?
6303  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6304    PushNamespaceVisibilityAttr(Attr, Loc);
6305
6306  if (IsStd)
6307    StdNamespace = Namespc;
6308  if (AddToKnown)
6309    KnownNamespaces[Namespc] = false;
6310
6311  if (II) {
6312    PushOnScopeChains(Namespc, DeclRegionScope);
6313  } else {
6314    // Link the anonymous namespace into its parent.
6315    DeclContext *Parent = CurContext->getRedeclContext();
6316    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6317      TU->setAnonymousNamespace(Namespc);
6318    } else {
6319      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6320    }
6321
6322    CurContext->addDecl(Namespc);
6323
6324    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6325    //   behaves as if it were replaced by
6326    //     namespace unique { /* empty body */ }
6327    //     using namespace unique;
6328    //     namespace unique { namespace-body }
6329    //   where all occurrences of 'unique' in a translation unit are
6330    //   replaced by the same identifier and this identifier differs
6331    //   from all other identifiers in the entire program.
6332
6333    // We just create the namespace with an empty name and then add an
6334    // implicit using declaration, just like the standard suggests.
6335    //
6336    // CodeGen enforces the "universally unique" aspect by giving all
6337    // declarations semantically contained within an anonymous
6338    // namespace internal linkage.
6339
6340    if (!PrevNS) {
6341      UsingDirectiveDecl* UD
6342        = UsingDirectiveDecl::Create(Context, Parent,
6343                                     /* 'using' */ LBrace,
6344                                     /* 'namespace' */ SourceLocation(),
6345                                     /* qualifier */ NestedNameSpecifierLoc(),
6346                                     /* identifier */ SourceLocation(),
6347                                     Namespc,
6348                                     /* Ancestor */ Parent);
6349      UD->setImplicit();
6350      Parent->addDecl(UD);
6351    }
6352  }
6353
6354  ActOnDocumentableDecl(Namespc);
6355
6356  // Although we could have an invalid decl (i.e. the namespace name is a
6357  // redefinition), push it as current DeclContext and try to continue parsing.
6358  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6359  // for the namespace has the declarations that showed up in that particular
6360  // namespace definition.
6361  PushDeclContext(NamespcScope, Namespc);
6362  return Namespc;
6363}
6364
6365/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6366/// is a namespace alias, returns the namespace it points to.
6367static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6368  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6369    return AD->getNamespace();
6370  return dyn_cast_or_null<NamespaceDecl>(D);
6371}
6372
6373/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6374/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6375void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6376  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6377  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6378  Namespc->setRBraceLoc(RBrace);
6379  PopDeclContext();
6380  if (Namespc->hasAttr<VisibilityAttr>())
6381    PopPragmaVisibility(true, RBrace);
6382}
6383
6384CXXRecordDecl *Sema::getStdBadAlloc() const {
6385  return cast_or_null<CXXRecordDecl>(
6386                                  StdBadAlloc.get(Context.getExternalSource()));
6387}
6388
6389NamespaceDecl *Sema::getStdNamespace() const {
6390  return cast_or_null<NamespaceDecl>(
6391                                 StdNamespace.get(Context.getExternalSource()));
6392}
6393
6394/// \brief Retrieve the special "std" namespace, which may require us to
6395/// implicitly define the namespace.
6396NamespaceDecl *Sema::getOrCreateStdNamespace() {
6397  if (!StdNamespace) {
6398    // The "std" namespace has not yet been defined, so build one implicitly.
6399    StdNamespace = NamespaceDecl::Create(Context,
6400                                         Context.getTranslationUnitDecl(),
6401                                         /*Inline=*/false,
6402                                         SourceLocation(), SourceLocation(),
6403                                         &PP.getIdentifierTable().get("std"),
6404                                         /*PrevDecl=*/0);
6405    getStdNamespace()->setImplicit(true);
6406  }
6407
6408  return getStdNamespace();
6409}
6410
6411bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6412  assert(getLangOpts().CPlusPlus &&
6413         "Looking for std::initializer_list outside of C++.");
6414
6415  // We're looking for implicit instantiations of
6416  // template <typename E> class std::initializer_list.
6417
6418  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6419    return false;
6420
6421  ClassTemplateDecl *Template = 0;
6422  const TemplateArgument *Arguments = 0;
6423
6424  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6425
6426    ClassTemplateSpecializationDecl *Specialization =
6427        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6428    if (!Specialization)
6429      return false;
6430
6431    Template = Specialization->getSpecializedTemplate();
6432    Arguments = Specialization->getTemplateArgs().data();
6433  } else if (const TemplateSpecializationType *TST =
6434                 Ty->getAs<TemplateSpecializationType>()) {
6435    Template = dyn_cast_or_null<ClassTemplateDecl>(
6436        TST->getTemplateName().getAsTemplateDecl());
6437    Arguments = TST->getArgs();
6438  }
6439  if (!Template)
6440    return false;
6441
6442  if (!StdInitializerList) {
6443    // Haven't recognized std::initializer_list yet, maybe this is it.
6444    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6445    if (TemplateClass->getIdentifier() !=
6446            &PP.getIdentifierTable().get("initializer_list") ||
6447        !getStdNamespace()->InEnclosingNamespaceSetOf(
6448            TemplateClass->getDeclContext()))
6449      return false;
6450    // This is a template called std::initializer_list, but is it the right
6451    // template?
6452    TemplateParameterList *Params = Template->getTemplateParameters();
6453    if (Params->getMinRequiredArguments() != 1)
6454      return false;
6455    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6456      return false;
6457
6458    // It's the right template.
6459    StdInitializerList = Template;
6460  }
6461
6462  if (Template != StdInitializerList)
6463    return false;
6464
6465  // This is an instance of std::initializer_list. Find the argument type.
6466  if (Element)
6467    *Element = Arguments[0].getAsType();
6468  return true;
6469}
6470
6471static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6472  NamespaceDecl *Std = S.getStdNamespace();
6473  if (!Std) {
6474    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6475    return 0;
6476  }
6477
6478  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6479                      Loc, Sema::LookupOrdinaryName);
6480  if (!S.LookupQualifiedName(Result, Std)) {
6481    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6482    return 0;
6483  }
6484  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6485  if (!Template) {
6486    Result.suppressDiagnostics();
6487    // We found something weird. Complain about the first thing we found.
6488    NamedDecl *Found = *Result.begin();
6489    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6490    return 0;
6491  }
6492
6493  // We found some template called std::initializer_list. Now verify that it's
6494  // correct.
6495  TemplateParameterList *Params = Template->getTemplateParameters();
6496  if (Params->getMinRequiredArguments() != 1 ||
6497      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6498    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6499    return 0;
6500  }
6501
6502  return Template;
6503}
6504
6505QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6506  if (!StdInitializerList) {
6507    StdInitializerList = LookupStdInitializerList(*this, Loc);
6508    if (!StdInitializerList)
6509      return QualType();
6510  }
6511
6512  TemplateArgumentListInfo Args(Loc, Loc);
6513  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6514                                       Context.getTrivialTypeSourceInfo(Element,
6515                                                                        Loc)));
6516  return Context.getCanonicalType(
6517      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6518}
6519
6520bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6521  // C++ [dcl.init.list]p2:
6522  //   A constructor is an initializer-list constructor if its first parameter
6523  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6524  //   std::initializer_list<E> for some type E, and either there are no other
6525  //   parameters or else all other parameters have default arguments.
6526  if (Ctor->getNumParams() < 1 ||
6527      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6528    return false;
6529
6530  QualType ArgType = Ctor->getParamDecl(0)->getType();
6531  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6532    ArgType = RT->getPointeeType().getUnqualifiedType();
6533
6534  return isStdInitializerList(ArgType, 0);
6535}
6536
6537/// \brief Determine whether a using statement is in a context where it will be
6538/// apply in all contexts.
6539static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6540  switch (CurContext->getDeclKind()) {
6541    case Decl::TranslationUnit:
6542      return true;
6543    case Decl::LinkageSpec:
6544      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6545    default:
6546      return false;
6547  }
6548}
6549
6550namespace {
6551
6552// Callback to only accept typo corrections that are namespaces.
6553class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6554 public:
6555  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6556    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6557      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6558    }
6559    return false;
6560  }
6561};
6562
6563}
6564
6565static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6566                                       CXXScopeSpec &SS,
6567                                       SourceLocation IdentLoc,
6568                                       IdentifierInfo *Ident) {
6569  NamespaceValidatorCCC Validator;
6570  R.clear();
6571  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6572                                               R.getLookupKind(), Sc, &SS,
6573                                               Validator)) {
6574    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6575    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6576    if (DeclContext *DC = S.computeDeclContext(SS, false))
6577      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6578        << Ident << DC << CorrectedQuotedStr << SS.getRange()
6579        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
6580                                        CorrectedStr);
6581    else
6582      S.Diag(IdentLoc, diag::err_using_directive_suggest)
6583        << Ident << CorrectedQuotedStr
6584        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6585
6586    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6587         diag::note_namespace_defined_here) << CorrectedQuotedStr;
6588
6589    R.addDecl(Corrected.getCorrectionDecl());
6590    return true;
6591  }
6592  return false;
6593}
6594
6595Decl *Sema::ActOnUsingDirective(Scope *S,
6596                                          SourceLocation UsingLoc,
6597                                          SourceLocation NamespcLoc,
6598                                          CXXScopeSpec &SS,
6599                                          SourceLocation IdentLoc,
6600                                          IdentifierInfo *NamespcName,
6601                                          AttributeList *AttrList) {
6602  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6603  assert(NamespcName && "Invalid NamespcName.");
6604  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6605
6606  // This can only happen along a recovery path.
6607  while (S->getFlags() & Scope::TemplateParamScope)
6608    S = S->getParent();
6609  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6610
6611  UsingDirectiveDecl *UDir = 0;
6612  NestedNameSpecifier *Qualifier = 0;
6613  if (SS.isSet())
6614    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6615
6616  // Lookup namespace name.
6617  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6618  LookupParsedName(R, S, &SS);
6619  if (R.isAmbiguous())
6620    return 0;
6621
6622  if (R.empty()) {
6623    R.clear();
6624    // Allow "using namespace std;" or "using namespace ::std;" even if
6625    // "std" hasn't been defined yet, for GCC compatibility.
6626    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6627        NamespcName->isStr("std")) {
6628      Diag(IdentLoc, diag::ext_using_undefined_std);
6629      R.addDecl(getOrCreateStdNamespace());
6630      R.resolveKind();
6631    }
6632    // Otherwise, attempt typo correction.
6633    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6634  }
6635
6636  if (!R.empty()) {
6637    NamedDecl *Named = R.getFoundDecl();
6638    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6639        && "expected namespace decl");
6640    // C++ [namespace.udir]p1:
6641    //   A using-directive specifies that the names in the nominated
6642    //   namespace can be used in the scope in which the
6643    //   using-directive appears after the using-directive. During
6644    //   unqualified name lookup (3.4.1), the names appear as if they
6645    //   were declared in the nearest enclosing namespace which
6646    //   contains both the using-directive and the nominated
6647    //   namespace. [Note: in this context, "contains" means "contains
6648    //   directly or indirectly". ]
6649
6650    // Find enclosing context containing both using-directive and
6651    // nominated namespace.
6652    NamespaceDecl *NS = getNamespaceDecl(Named);
6653    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6654    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6655      CommonAncestor = CommonAncestor->getParent();
6656
6657    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6658                                      SS.getWithLocInContext(Context),
6659                                      IdentLoc, Named, CommonAncestor);
6660
6661    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6662        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6663      Diag(IdentLoc, diag::warn_using_directive_in_header);
6664    }
6665
6666    PushUsingDirective(S, UDir);
6667  } else {
6668    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6669  }
6670
6671  if (UDir)
6672    ProcessDeclAttributeList(S, UDir, AttrList);
6673
6674  return UDir;
6675}
6676
6677void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6678  // If the scope has an associated entity and the using directive is at
6679  // namespace or translation unit scope, add the UsingDirectiveDecl into
6680  // its lookup structure so qualified name lookup can find it.
6681  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6682  if (Ctx && !Ctx->isFunctionOrMethod())
6683    Ctx->addDecl(UDir);
6684  else
6685    // Otherwise, it is at block sope. The using-directives will affect lookup
6686    // only to the end of the scope.
6687    S->PushUsingDirective(UDir);
6688}
6689
6690
6691Decl *Sema::ActOnUsingDeclaration(Scope *S,
6692                                  AccessSpecifier AS,
6693                                  bool HasUsingKeyword,
6694                                  SourceLocation UsingLoc,
6695                                  CXXScopeSpec &SS,
6696                                  UnqualifiedId &Name,
6697                                  AttributeList *AttrList,
6698                                  bool IsTypeName,
6699                                  SourceLocation TypenameLoc) {
6700  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6701
6702  switch (Name.getKind()) {
6703  case UnqualifiedId::IK_ImplicitSelfParam:
6704  case UnqualifiedId::IK_Identifier:
6705  case UnqualifiedId::IK_OperatorFunctionId:
6706  case UnqualifiedId::IK_LiteralOperatorId:
6707  case UnqualifiedId::IK_ConversionFunctionId:
6708    break;
6709
6710  case UnqualifiedId::IK_ConstructorName:
6711  case UnqualifiedId::IK_ConstructorTemplateId:
6712    // C++11 inheriting constructors.
6713    Diag(Name.getLocStart(),
6714         getLangOpts().CPlusPlus11 ?
6715           diag::warn_cxx98_compat_using_decl_constructor :
6716           diag::err_using_decl_constructor)
6717      << SS.getRange();
6718
6719    if (getLangOpts().CPlusPlus11) break;
6720
6721    return 0;
6722
6723  case UnqualifiedId::IK_DestructorName:
6724    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6725      << SS.getRange();
6726    return 0;
6727
6728  case UnqualifiedId::IK_TemplateId:
6729    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6730      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6731    return 0;
6732  }
6733
6734  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6735  DeclarationName TargetName = TargetNameInfo.getName();
6736  if (!TargetName)
6737    return 0;
6738
6739  // Warn about access declarations.
6740  // TODO: store that the declaration was written without 'using' and
6741  // talk about access decls instead of using decls in the
6742  // diagnostics.
6743  if (!HasUsingKeyword) {
6744    UsingLoc = Name.getLocStart();
6745
6746    Diag(UsingLoc, diag::warn_access_decl_deprecated)
6747      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6748  }
6749
6750  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6751      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6752    return 0;
6753
6754  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6755                                        TargetNameInfo, AttrList,
6756                                        /* IsInstantiation */ false,
6757                                        IsTypeName, TypenameLoc);
6758  if (UD)
6759    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6760
6761  return UD;
6762}
6763
6764/// \brief Determine whether a using declaration considers the given
6765/// declarations as "equivalent", e.g., if they are redeclarations of
6766/// the same entity or are both typedefs of the same type.
6767static bool
6768IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6769                         bool &SuppressRedeclaration) {
6770  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6771    SuppressRedeclaration = false;
6772    return true;
6773  }
6774
6775  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6776    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6777      SuppressRedeclaration = true;
6778      return Context.hasSameType(TD1->getUnderlyingType(),
6779                                 TD2->getUnderlyingType());
6780    }
6781
6782  return false;
6783}
6784
6785
6786/// Determines whether to create a using shadow decl for a particular
6787/// decl, given the set of decls existing prior to this using lookup.
6788bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6789                                const LookupResult &Previous) {
6790  // Diagnose finding a decl which is not from a base class of the
6791  // current class.  We do this now because there are cases where this
6792  // function will silently decide not to build a shadow decl, which
6793  // will pre-empt further diagnostics.
6794  //
6795  // We don't need to do this in C++0x because we do the check once on
6796  // the qualifier.
6797  //
6798  // FIXME: diagnose the following if we care enough:
6799  //   struct A { int foo; };
6800  //   struct B : A { using A::foo; };
6801  //   template <class T> struct C : A {};
6802  //   template <class T> struct D : C<T> { using B::foo; } // <---
6803  // This is invalid (during instantiation) in C++03 because B::foo
6804  // resolves to the using decl in B, which is not a base class of D<T>.
6805  // We can't diagnose it immediately because C<T> is an unknown
6806  // specialization.  The UsingShadowDecl in D<T> then points directly
6807  // to A::foo, which will look well-formed when we instantiate.
6808  // The right solution is to not collapse the shadow-decl chain.
6809  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6810    DeclContext *OrigDC = Orig->getDeclContext();
6811
6812    // Handle enums and anonymous structs.
6813    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6814    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6815    while (OrigRec->isAnonymousStructOrUnion())
6816      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6817
6818    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6819      if (OrigDC == CurContext) {
6820        Diag(Using->getLocation(),
6821             diag::err_using_decl_nested_name_specifier_is_current_class)
6822          << Using->getQualifierLoc().getSourceRange();
6823        Diag(Orig->getLocation(), diag::note_using_decl_target);
6824        return true;
6825      }
6826
6827      Diag(Using->getQualifierLoc().getBeginLoc(),
6828           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6829        << Using->getQualifier()
6830        << cast<CXXRecordDecl>(CurContext)
6831        << Using->getQualifierLoc().getSourceRange();
6832      Diag(Orig->getLocation(), diag::note_using_decl_target);
6833      return true;
6834    }
6835  }
6836
6837  if (Previous.empty()) return false;
6838
6839  NamedDecl *Target = Orig;
6840  if (isa<UsingShadowDecl>(Target))
6841    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6842
6843  // If the target happens to be one of the previous declarations, we
6844  // don't have a conflict.
6845  //
6846  // FIXME: but we might be increasing its access, in which case we
6847  // should redeclare it.
6848  NamedDecl *NonTag = 0, *Tag = 0;
6849  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6850         I != E; ++I) {
6851    NamedDecl *D = (*I)->getUnderlyingDecl();
6852    bool Result;
6853    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6854      return Result;
6855
6856    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6857  }
6858
6859  if (Target->isFunctionOrFunctionTemplate()) {
6860    FunctionDecl *FD;
6861    if (isa<FunctionTemplateDecl>(Target))
6862      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6863    else
6864      FD = cast<FunctionDecl>(Target);
6865
6866    NamedDecl *OldDecl = 0;
6867    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6868    case Ovl_Overload:
6869      return false;
6870
6871    case Ovl_NonFunction:
6872      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6873      break;
6874
6875    // We found a decl with the exact signature.
6876    case Ovl_Match:
6877      // If we're in a record, we want to hide the target, so we
6878      // return true (without a diagnostic) to tell the caller not to
6879      // build a shadow decl.
6880      if (CurContext->isRecord())
6881        return true;
6882
6883      // If we're not in a record, this is an error.
6884      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6885      break;
6886    }
6887
6888    Diag(Target->getLocation(), diag::note_using_decl_target);
6889    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6890    return true;
6891  }
6892
6893  // Target is not a function.
6894
6895  if (isa<TagDecl>(Target)) {
6896    // No conflict between a tag and a non-tag.
6897    if (!Tag) return false;
6898
6899    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6900    Diag(Target->getLocation(), diag::note_using_decl_target);
6901    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6902    return true;
6903  }
6904
6905  // No conflict between a tag and a non-tag.
6906  if (!NonTag) return false;
6907
6908  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6909  Diag(Target->getLocation(), diag::note_using_decl_target);
6910  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6911  return true;
6912}
6913
6914/// Builds a shadow declaration corresponding to a 'using' declaration.
6915UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6916                                            UsingDecl *UD,
6917                                            NamedDecl *Orig) {
6918
6919  // If we resolved to another shadow declaration, just coalesce them.
6920  NamedDecl *Target = Orig;
6921  if (isa<UsingShadowDecl>(Target)) {
6922    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6923    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6924  }
6925
6926  UsingShadowDecl *Shadow
6927    = UsingShadowDecl::Create(Context, CurContext,
6928                              UD->getLocation(), UD, Target);
6929  UD->addShadowDecl(Shadow);
6930
6931  Shadow->setAccess(UD->getAccess());
6932  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6933    Shadow->setInvalidDecl();
6934
6935  if (S)
6936    PushOnScopeChains(Shadow, S);
6937  else
6938    CurContext->addDecl(Shadow);
6939
6940
6941  return Shadow;
6942}
6943
6944/// Hides a using shadow declaration.  This is required by the current
6945/// using-decl implementation when a resolvable using declaration in a
6946/// class is followed by a declaration which would hide or override
6947/// one or more of the using decl's targets; for example:
6948///
6949///   struct Base { void foo(int); };
6950///   struct Derived : Base {
6951///     using Base::foo;
6952///     void foo(int);
6953///   };
6954///
6955/// The governing language is C++03 [namespace.udecl]p12:
6956///
6957///   When a using-declaration brings names from a base class into a
6958///   derived class scope, member functions in the derived class
6959///   override and/or hide member functions with the same name and
6960///   parameter types in a base class (rather than conflicting).
6961///
6962/// There are two ways to implement this:
6963///   (1) optimistically create shadow decls when they're not hidden
6964///       by existing declarations, or
6965///   (2) don't create any shadow decls (or at least don't make them
6966///       visible) until we've fully parsed/instantiated the class.
6967/// The problem with (1) is that we might have to retroactively remove
6968/// a shadow decl, which requires several O(n) operations because the
6969/// decl structures are (very reasonably) not designed for removal.
6970/// (2) avoids this but is very fiddly and phase-dependent.
6971void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6972  if (Shadow->getDeclName().getNameKind() ==
6973        DeclarationName::CXXConversionFunctionName)
6974    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6975
6976  // Remove it from the DeclContext...
6977  Shadow->getDeclContext()->removeDecl(Shadow);
6978
6979  // ...and the scope, if applicable...
6980  if (S) {
6981    S->RemoveDecl(Shadow);
6982    IdResolver.RemoveDecl(Shadow);
6983  }
6984
6985  // ...and the using decl.
6986  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6987
6988  // TODO: complain somehow if Shadow was used.  It shouldn't
6989  // be possible for this to happen, because...?
6990}
6991
6992/// Builds a using declaration.
6993///
6994/// \param IsInstantiation - Whether this call arises from an
6995///   instantiation of an unresolved using declaration.  We treat
6996///   the lookup differently for these declarations.
6997NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6998                                       SourceLocation UsingLoc,
6999                                       CXXScopeSpec &SS,
7000                                       const DeclarationNameInfo &NameInfo,
7001                                       AttributeList *AttrList,
7002                                       bool IsInstantiation,
7003                                       bool IsTypeName,
7004                                       SourceLocation TypenameLoc) {
7005  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7006  SourceLocation IdentLoc = NameInfo.getLoc();
7007  assert(IdentLoc.isValid() && "Invalid TargetName location.");
7008
7009  // FIXME: We ignore attributes for now.
7010
7011  if (SS.isEmpty()) {
7012    Diag(IdentLoc, diag::err_using_requires_qualname);
7013    return 0;
7014  }
7015
7016  // Do the redeclaration lookup in the current scope.
7017  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7018                        ForRedeclaration);
7019  Previous.setHideTags(false);
7020  if (S) {
7021    LookupName(Previous, S);
7022
7023    // It is really dumb that we have to do this.
7024    LookupResult::Filter F = Previous.makeFilter();
7025    while (F.hasNext()) {
7026      NamedDecl *D = F.next();
7027      if (!isDeclInScope(D, CurContext, S))
7028        F.erase();
7029    }
7030    F.done();
7031  } else {
7032    assert(IsInstantiation && "no scope in non-instantiation");
7033    assert(CurContext->isRecord() && "scope not record in instantiation");
7034    LookupQualifiedName(Previous, CurContext);
7035  }
7036
7037  // Check for invalid redeclarations.
7038  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7039    return 0;
7040
7041  // Check for bad qualifiers.
7042  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7043    return 0;
7044
7045  DeclContext *LookupContext = computeDeclContext(SS);
7046  NamedDecl *D;
7047  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7048  if (!LookupContext) {
7049    if (IsTypeName) {
7050      // FIXME: not all declaration name kinds are legal here
7051      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7052                                              UsingLoc, TypenameLoc,
7053                                              QualifierLoc,
7054                                              IdentLoc, NameInfo.getName());
7055    } else {
7056      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7057                                           QualifierLoc, NameInfo);
7058    }
7059  } else {
7060    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7061                          NameInfo, IsTypeName);
7062  }
7063  D->setAccess(AS);
7064  CurContext->addDecl(D);
7065
7066  if (!LookupContext) return D;
7067  UsingDecl *UD = cast<UsingDecl>(D);
7068
7069  if (RequireCompleteDeclContext(SS, LookupContext)) {
7070    UD->setInvalidDecl();
7071    return UD;
7072  }
7073
7074  // The normal rules do not apply to inheriting constructor declarations.
7075  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7076    if (CheckInheritingConstructorUsingDecl(UD))
7077      UD->setInvalidDecl();
7078    return UD;
7079  }
7080
7081  // Otherwise, look up the target name.
7082
7083  LookupResult R(*this, NameInfo, LookupOrdinaryName);
7084
7085  // Unlike most lookups, we don't always want to hide tag
7086  // declarations: tag names are visible through the using declaration
7087  // even if hidden by ordinary names, *except* in a dependent context
7088  // where it's important for the sanity of two-phase lookup.
7089  if (!IsInstantiation)
7090    R.setHideTags(false);
7091
7092  // For the purposes of this lookup, we have a base object type
7093  // equal to that of the current context.
7094  if (CurContext->isRecord()) {
7095    R.setBaseObjectType(
7096                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7097  }
7098
7099  LookupQualifiedName(R, LookupContext);
7100
7101  if (R.empty()) {
7102    Diag(IdentLoc, diag::err_no_member)
7103      << NameInfo.getName() << LookupContext << SS.getRange();
7104    UD->setInvalidDecl();
7105    return UD;
7106  }
7107
7108  if (R.isAmbiguous()) {
7109    UD->setInvalidDecl();
7110    return UD;
7111  }
7112
7113  if (IsTypeName) {
7114    // If we asked for a typename and got a non-type decl, error out.
7115    if (!R.getAsSingle<TypeDecl>()) {
7116      Diag(IdentLoc, diag::err_using_typename_non_type);
7117      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7118        Diag((*I)->getUnderlyingDecl()->getLocation(),
7119             diag::note_using_decl_target);
7120      UD->setInvalidDecl();
7121      return UD;
7122    }
7123  } else {
7124    // If we asked for a non-typename and we got a type, error out,
7125    // but only if this is an instantiation of an unresolved using
7126    // decl.  Otherwise just silently find the type name.
7127    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7128      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7129      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7130      UD->setInvalidDecl();
7131      return UD;
7132    }
7133  }
7134
7135  // C++0x N2914 [namespace.udecl]p6:
7136  // A using-declaration shall not name a namespace.
7137  if (R.getAsSingle<NamespaceDecl>()) {
7138    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7139      << SS.getRange();
7140    UD->setInvalidDecl();
7141    return UD;
7142  }
7143
7144  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7145    if (!CheckUsingShadowDecl(UD, *I, Previous))
7146      BuildUsingShadowDecl(S, UD, *I);
7147  }
7148
7149  return UD;
7150}
7151
7152/// Additional checks for a using declaration referring to a constructor name.
7153bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7154  assert(!UD->isTypeName() && "expecting a constructor name");
7155
7156  const Type *SourceType = UD->getQualifier()->getAsType();
7157  assert(SourceType &&
7158         "Using decl naming constructor doesn't have type in scope spec.");
7159  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7160
7161  // Check whether the named type is a direct base class.
7162  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7163  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7164  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7165       BaseIt != BaseE; ++BaseIt) {
7166    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7167    if (CanonicalSourceType == BaseType)
7168      break;
7169    if (BaseIt->getType()->isDependentType())
7170      break;
7171  }
7172
7173  if (BaseIt == BaseE) {
7174    // Did not find SourceType in the bases.
7175    Diag(UD->getUsingLocation(),
7176         diag::err_using_decl_constructor_not_in_direct_base)
7177      << UD->getNameInfo().getSourceRange()
7178      << QualType(SourceType, 0) << TargetClass;
7179    return true;
7180  }
7181
7182  if (!CurContext->isDependentContext())
7183    BaseIt->setInheritConstructors();
7184
7185  return false;
7186}
7187
7188/// Checks that the given using declaration is not an invalid
7189/// redeclaration.  Note that this is checking only for the using decl
7190/// itself, not for any ill-formedness among the UsingShadowDecls.
7191bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7192                                       bool isTypeName,
7193                                       const CXXScopeSpec &SS,
7194                                       SourceLocation NameLoc,
7195                                       const LookupResult &Prev) {
7196  // C++03 [namespace.udecl]p8:
7197  // C++0x [namespace.udecl]p10:
7198  //   A using-declaration is a declaration and can therefore be used
7199  //   repeatedly where (and only where) multiple declarations are
7200  //   allowed.
7201  //
7202  // That's in non-member contexts.
7203  if (!CurContext->getRedeclContext()->isRecord())
7204    return false;
7205
7206  NestedNameSpecifier *Qual
7207    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7208
7209  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7210    NamedDecl *D = *I;
7211
7212    bool DTypename;
7213    NestedNameSpecifier *DQual;
7214    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7215      DTypename = UD->isTypeName();
7216      DQual = UD->getQualifier();
7217    } else if (UnresolvedUsingValueDecl *UD
7218                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7219      DTypename = false;
7220      DQual = UD->getQualifier();
7221    } else if (UnresolvedUsingTypenameDecl *UD
7222                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7223      DTypename = true;
7224      DQual = UD->getQualifier();
7225    } else continue;
7226
7227    // using decls differ if one says 'typename' and the other doesn't.
7228    // FIXME: non-dependent using decls?
7229    if (isTypeName != DTypename) continue;
7230
7231    // using decls differ if they name different scopes (but note that
7232    // template instantiation can cause this check to trigger when it
7233    // didn't before instantiation).
7234    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7235        Context.getCanonicalNestedNameSpecifier(DQual))
7236      continue;
7237
7238    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7239    Diag(D->getLocation(), diag::note_using_decl) << 1;
7240    return true;
7241  }
7242
7243  return false;
7244}
7245
7246
7247/// Checks that the given nested-name qualifier used in a using decl
7248/// in the current context is appropriately related to the current
7249/// scope.  If an error is found, diagnoses it and returns true.
7250bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7251                                   const CXXScopeSpec &SS,
7252                                   SourceLocation NameLoc) {
7253  DeclContext *NamedContext = computeDeclContext(SS);
7254
7255  if (!CurContext->isRecord()) {
7256    // C++03 [namespace.udecl]p3:
7257    // C++0x [namespace.udecl]p8:
7258    //   A using-declaration for a class member shall be a member-declaration.
7259
7260    // If we weren't able to compute a valid scope, it must be a
7261    // dependent class scope.
7262    if (!NamedContext || NamedContext->isRecord()) {
7263      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7264        << SS.getRange();
7265      return true;
7266    }
7267
7268    // Otherwise, everything is known to be fine.
7269    return false;
7270  }
7271
7272  // The current scope is a record.
7273
7274  // If the named context is dependent, we can't decide much.
7275  if (!NamedContext) {
7276    // FIXME: in C++0x, we can diagnose if we can prove that the
7277    // nested-name-specifier does not refer to a base class, which is
7278    // still possible in some cases.
7279
7280    // Otherwise we have to conservatively report that things might be
7281    // okay.
7282    return false;
7283  }
7284
7285  if (!NamedContext->isRecord()) {
7286    // Ideally this would point at the last name in the specifier,
7287    // but we don't have that level of source info.
7288    Diag(SS.getRange().getBegin(),
7289         diag::err_using_decl_nested_name_specifier_is_not_class)
7290      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7291    return true;
7292  }
7293
7294  if (!NamedContext->isDependentContext() &&
7295      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7296    return true;
7297
7298  if (getLangOpts().CPlusPlus11) {
7299    // C++0x [namespace.udecl]p3:
7300    //   In a using-declaration used as a member-declaration, the
7301    //   nested-name-specifier shall name a base class of the class
7302    //   being defined.
7303
7304    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7305                                 cast<CXXRecordDecl>(NamedContext))) {
7306      if (CurContext == NamedContext) {
7307        Diag(NameLoc,
7308             diag::err_using_decl_nested_name_specifier_is_current_class)
7309          << SS.getRange();
7310        return true;
7311      }
7312
7313      Diag(SS.getRange().getBegin(),
7314           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7315        << (NestedNameSpecifier*) SS.getScopeRep()
7316        << cast<CXXRecordDecl>(CurContext)
7317        << SS.getRange();
7318      return true;
7319    }
7320
7321    return false;
7322  }
7323
7324  // C++03 [namespace.udecl]p4:
7325  //   A using-declaration used as a member-declaration shall refer
7326  //   to a member of a base class of the class being defined [etc.].
7327
7328  // Salient point: SS doesn't have to name a base class as long as
7329  // lookup only finds members from base classes.  Therefore we can
7330  // diagnose here only if we can prove that that can't happen,
7331  // i.e. if the class hierarchies provably don't intersect.
7332
7333  // TODO: it would be nice if "definitely valid" results were cached
7334  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7335  // need to be repeated.
7336
7337  struct UserData {
7338    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7339
7340    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7341      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7342      Data->Bases.insert(Base);
7343      return true;
7344    }
7345
7346    bool hasDependentBases(const CXXRecordDecl *Class) {
7347      return !Class->forallBases(collect, this);
7348    }
7349
7350    /// Returns true if the base is dependent or is one of the
7351    /// accumulated base classes.
7352    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7353      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7354      return !Data->Bases.count(Base);
7355    }
7356
7357    bool mightShareBases(const CXXRecordDecl *Class) {
7358      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7359    }
7360  };
7361
7362  UserData Data;
7363
7364  // Returns false if we find a dependent base.
7365  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7366    return false;
7367
7368  // Returns false if the class has a dependent base or if it or one
7369  // of its bases is present in the base set of the current context.
7370  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7371    return false;
7372
7373  Diag(SS.getRange().getBegin(),
7374       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7375    << (NestedNameSpecifier*) SS.getScopeRep()
7376    << cast<CXXRecordDecl>(CurContext)
7377    << SS.getRange();
7378
7379  return true;
7380}
7381
7382Decl *Sema::ActOnAliasDeclaration(Scope *S,
7383                                  AccessSpecifier AS,
7384                                  MultiTemplateParamsArg TemplateParamLists,
7385                                  SourceLocation UsingLoc,
7386                                  UnqualifiedId &Name,
7387                                  AttributeList *AttrList,
7388                                  TypeResult Type) {
7389  // Skip up to the relevant declaration scope.
7390  while (S->getFlags() & Scope::TemplateParamScope)
7391    S = S->getParent();
7392  assert((S->getFlags() & Scope::DeclScope) &&
7393         "got alias-declaration outside of declaration scope");
7394
7395  if (Type.isInvalid())
7396    return 0;
7397
7398  bool Invalid = false;
7399  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7400  TypeSourceInfo *TInfo = 0;
7401  GetTypeFromParser(Type.get(), &TInfo);
7402
7403  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7404    return 0;
7405
7406  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7407                                      UPPC_DeclarationType)) {
7408    Invalid = true;
7409    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7410                                             TInfo->getTypeLoc().getBeginLoc());
7411  }
7412
7413  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7414  LookupName(Previous, S);
7415
7416  // Warn about shadowing the name of a template parameter.
7417  if (Previous.isSingleResult() &&
7418      Previous.getFoundDecl()->isTemplateParameter()) {
7419    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7420    Previous.clear();
7421  }
7422
7423  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7424         "name in alias declaration must be an identifier");
7425  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7426                                               Name.StartLocation,
7427                                               Name.Identifier, TInfo);
7428
7429  NewTD->setAccess(AS);
7430
7431  if (Invalid)
7432    NewTD->setInvalidDecl();
7433
7434  ProcessDeclAttributeList(S, NewTD, AttrList);
7435
7436  CheckTypedefForVariablyModifiedType(S, NewTD);
7437  Invalid |= NewTD->isInvalidDecl();
7438
7439  bool Redeclaration = false;
7440
7441  NamedDecl *NewND;
7442  if (TemplateParamLists.size()) {
7443    TypeAliasTemplateDecl *OldDecl = 0;
7444    TemplateParameterList *OldTemplateParams = 0;
7445
7446    if (TemplateParamLists.size() != 1) {
7447      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7448        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7449         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7450    }
7451    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7452
7453    // Only consider previous declarations in the same scope.
7454    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7455                         /*ExplicitInstantiationOrSpecialization*/false);
7456    if (!Previous.empty()) {
7457      Redeclaration = true;
7458
7459      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7460      if (!OldDecl && !Invalid) {
7461        Diag(UsingLoc, diag::err_redefinition_different_kind)
7462          << Name.Identifier;
7463
7464        NamedDecl *OldD = Previous.getRepresentativeDecl();
7465        if (OldD->getLocation().isValid())
7466          Diag(OldD->getLocation(), diag::note_previous_definition);
7467
7468        Invalid = true;
7469      }
7470
7471      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7472        if (TemplateParameterListsAreEqual(TemplateParams,
7473                                           OldDecl->getTemplateParameters(),
7474                                           /*Complain=*/true,
7475                                           TPL_TemplateMatch))
7476          OldTemplateParams = OldDecl->getTemplateParameters();
7477        else
7478          Invalid = true;
7479
7480        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7481        if (!Invalid &&
7482            !Context.hasSameType(OldTD->getUnderlyingType(),
7483                                 NewTD->getUnderlyingType())) {
7484          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7485          // but we can't reasonably accept it.
7486          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7487            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7488          if (OldTD->getLocation().isValid())
7489            Diag(OldTD->getLocation(), diag::note_previous_definition);
7490          Invalid = true;
7491        }
7492      }
7493    }
7494
7495    // Merge any previous default template arguments into our parameters,
7496    // and check the parameter list.
7497    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7498                                   TPC_TypeAliasTemplate))
7499      return 0;
7500
7501    TypeAliasTemplateDecl *NewDecl =
7502      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7503                                    Name.Identifier, TemplateParams,
7504                                    NewTD);
7505
7506    NewDecl->setAccess(AS);
7507
7508    if (Invalid)
7509      NewDecl->setInvalidDecl();
7510    else if (OldDecl)
7511      NewDecl->setPreviousDeclaration(OldDecl);
7512
7513    NewND = NewDecl;
7514  } else {
7515    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7516    NewND = NewTD;
7517  }
7518
7519  if (!Redeclaration)
7520    PushOnScopeChains(NewND, S);
7521
7522  ActOnDocumentableDecl(NewND);
7523  return NewND;
7524}
7525
7526Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7527                                             SourceLocation NamespaceLoc,
7528                                             SourceLocation AliasLoc,
7529                                             IdentifierInfo *Alias,
7530                                             CXXScopeSpec &SS,
7531                                             SourceLocation IdentLoc,
7532                                             IdentifierInfo *Ident) {
7533
7534  // Lookup the namespace name.
7535  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7536  LookupParsedName(R, S, &SS);
7537
7538  // Check if we have a previous declaration with the same name.
7539  NamedDecl *PrevDecl
7540    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7541                       ForRedeclaration);
7542  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7543    PrevDecl = 0;
7544
7545  if (PrevDecl) {
7546    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7547      // We already have an alias with the same name that points to the same
7548      // namespace, so don't create a new one.
7549      // FIXME: At some point, we'll want to create the (redundant)
7550      // declaration to maintain better source information.
7551      if (!R.isAmbiguous() && !R.empty() &&
7552          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7553        return 0;
7554    }
7555
7556    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7557      diag::err_redefinition_different_kind;
7558    Diag(AliasLoc, DiagID) << Alias;
7559    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7560    return 0;
7561  }
7562
7563  if (R.isAmbiguous())
7564    return 0;
7565
7566  if (R.empty()) {
7567    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7568      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7569      return 0;
7570    }
7571  }
7572
7573  NamespaceAliasDecl *AliasDecl =
7574    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7575                               Alias, SS.getWithLocInContext(Context),
7576                               IdentLoc, R.getFoundDecl());
7577
7578  PushOnScopeChains(AliasDecl, S);
7579  return AliasDecl;
7580}
7581
7582Sema::ImplicitExceptionSpecification
7583Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7584                                               CXXMethodDecl *MD) {
7585  CXXRecordDecl *ClassDecl = MD->getParent();
7586
7587  // C++ [except.spec]p14:
7588  //   An implicitly declared special member function (Clause 12) shall have an
7589  //   exception-specification. [...]
7590  ImplicitExceptionSpecification ExceptSpec(*this);
7591  if (ClassDecl->isInvalidDecl())
7592    return ExceptSpec;
7593
7594  // Direct base-class constructors.
7595  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7596                                       BEnd = ClassDecl->bases_end();
7597       B != BEnd; ++B) {
7598    if (B->isVirtual()) // Handled below.
7599      continue;
7600
7601    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7602      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7603      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7604      // If this is a deleted function, add it anyway. This might be conformant
7605      // with the standard. This might not. I'm not sure. It might not matter.
7606      if (Constructor)
7607        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7608    }
7609  }
7610
7611  // Virtual base-class constructors.
7612  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7613                                       BEnd = ClassDecl->vbases_end();
7614       B != BEnd; ++B) {
7615    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7616      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7617      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7618      // If this is a deleted function, add it anyway. This might be conformant
7619      // with the standard. This might not. I'm not sure. It might not matter.
7620      if (Constructor)
7621        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7622    }
7623  }
7624
7625  // Field constructors.
7626  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7627                               FEnd = ClassDecl->field_end();
7628       F != FEnd; ++F) {
7629    if (F->hasInClassInitializer()) {
7630      if (Expr *E = F->getInClassInitializer())
7631        ExceptSpec.CalledExpr(E);
7632      else if (!F->isInvalidDecl())
7633        // DR1351:
7634        //   If the brace-or-equal-initializer of a non-static data member
7635        //   invokes a defaulted default constructor of its class or of an
7636        //   enclosing class in a potentially evaluated subexpression, the
7637        //   program is ill-formed.
7638        //
7639        // This resolution is unworkable: the exception specification of the
7640        // default constructor can be needed in an unevaluated context, in
7641        // particular, in the operand of a noexcept-expression, and we can be
7642        // unable to compute an exception specification for an enclosed class.
7643        //
7644        // We do not allow an in-class initializer to require the evaluation
7645        // of the exception specification for any in-class initializer whose
7646        // definition is not lexically complete.
7647        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7648    } else if (const RecordType *RecordTy
7649              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7650      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7651      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7652      // If this is a deleted function, add it anyway. This might be conformant
7653      // with the standard. This might not. I'm not sure. It might not matter.
7654      // In particular, the problem is that this function never gets called. It
7655      // might just be ill-formed because this function attempts to refer to
7656      // a deleted function here.
7657      if (Constructor)
7658        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7659    }
7660  }
7661
7662  return ExceptSpec;
7663}
7664
7665Sema::ImplicitExceptionSpecification
7666Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7667  CXXRecordDecl *ClassDecl = CD->getParent();
7668
7669  // C++ [except.spec]p14:
7670  //   An inheriting constructor [...] shall have an exception-specification. [...]
7671  ImplicitExceptionSpecification ExceptSpec(*this);
7672  if (ClassDecl->isInvalidDecl())
7673    return ExceptSpec;
7674
7675  // Inherited constructor.
7676  const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7677  const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7678  // FIXME: Copying or moving the parameters could add extra exceptions to the
7679  // set, as could the default arguments for the inherited constructor. This
7680  // will be addressed when we implement the resolution of core issue 1351.
7681  ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7682
7683  // Direct base-class constructors.
7684  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7685                                       BEnd = ClassDecl->bases_end();
7686       B != BEnd; ++B) {
7687    if (B->isVirtual()) // Handled below.
7688      continue;
7689
7690    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7691      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7692      if (BaseClassDecl == InheritedDecl)
7693        continue;
7694      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7695      if (Constructor)
7696        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7697    }
7698  }
7699
7700  // Virtual base-class constructors.
7701  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7702                                       BEnd = ClassDecl->vbases_end();
7703       B != BEnd; ++B) {
7704    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7705      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7706      if (BaseClassDecl == InheritedDecl)
7707        continue;
7708      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7709      if (Constructor)
7710        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7711    }
7712  }
7713
7714  // Field constructors.
7715  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7716                               FEnd = ClassDecl->field_end();
7717       F != FEnd; ++F) {
7718    if (F->hasInClassInitializer()) {
7719      if (Expr *E = F->getInClassInitializer())
7720        ExceptSpec.CalledExpr(E);
7721      else if (!F->isInvalidDecl())
7722        Diag(CD->getLocation(),
7723             diag::err_in_class_initializer_references_def_ctor) << CD;
7724    } else if (const RecordType *RecordTy
7725              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7726      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7727      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7728      if (Constructor)
7729        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7730    }
7731  }
7732
7733  return ExceptSpec;
7734}
7735
7736namespace {
7737/// RAII object to register a special member as being currently declared.
7738struct DeclaringSpecialMember {
7739  Sema &S;
7740  Sema::SpecialMemberDecl D;
7741  bool WasAlreadyBeingDeclared;
7742
7743  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7744    : S(S), D(RD, CSM) {
7745    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7746    if (WasAlreadyBeingDeclared)
7747      // This almost never happens, but if it does, ensure that our cache
7748      // doesn't contain a stale result.
7749      S.SpecialMemberCache.clear();
7750
7751    // FIXME: Register a note to be produced if we encounter an error while
7752    // declaring the special member.
7753  }
7754  ~DeclaringSpecialMember() {
7755    if (!WasAlreadyBeingDeclared)
7756      S.SpecialMembersBeingDeclared.erase(D);
7757  }
7758
7759  /// \brief Are we already trying to declare this special member?
7760  bool isAlreadyBeingDeclared() const {
7761    return WasAlreadyBeingDeclared;
7762  }
7763};
7764}
7765
7766CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7767                                                     CXXRecordDecl *ClassDecl) {
7768  // C++ [class.ctor]p5:
7769  //   A default constructor for a class X is a constructor of class X
7770  //   that can be called without an argument. If there is no
7771  //   user-declared constructor for class X, a default constructor is
7772  //   implicitly declared. An implicitly-declared default constructor
7773  //   is an inline public member of its class.
7774  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7775         "Should not build implicit default constructor!");
7776
7777  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7778  if (DSM.isAlreadyBeingDeclared())
7779    return 0;
7780
7781  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7782                                                     CXXDefaultConstructor,
7783                                                     false);
7784
7785  // Create the actual constructor declaration.
7786  CanQualType ClassType
7787    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7788  SourceLocation ClassLoc = ClassDecl->getLocation();
7789  DeclarationName Name
7790    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7791  DeclarationNameInfo NameInfo(Name, ClassLoc);
7792  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7793      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7794      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7795      Constexpr);
7796  DefaultCon->setAccess(AS_public);
7797  DefaultCon->setDefaulted();
7798  DefaultCon->setImplicit();
7799
7800  // Build an exception specification pointing back at this constructor.
7801  FunctionProtoType::ExtProtoInfo EPI;
7802  EPI.ExceptionSpecType = EST_Unevaluated;
7803  EPI.ExceptionSpecDecl = DefaultCon;
7804  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
7805
7806  // We don't need to use SpecialMemberIsTrivial here; triviality for default
7807  // constructors is easy to compute.
7808  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7809
7810  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7811    SetDeclDeleted(DefaultCon, ClassLoc);
7812
7813  // Note that we have declared this constructor.
7814  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7815
7816  if (Scope *S = getScopeForContext(ClassDecl))
7817    PushOnScopeChains(DefaultCon, S, false);
7818  ClassDecl->addDecl(DefaultCon);
7819
7820  return DefaultCon;
7821}
7822
7823void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7824                                            CXXConstructorDecl *Constructor) {
7825  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7826          !Constructor->doesThisDeclarationHaveABody() &&
7827          !Constructor->isDeleted()) &&
7828    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7829
7830  CXXRecordDecl *ClassDecl = Constructor->getParent();
7831  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7832
7833  SynthesizedFunctionScope Scope(*this, Constructor);
7834  DiagnosticErrorTrap Trap(Diags);
7835  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7836      Trap.hasErrorOccurred()) {
7837    Diag(CurrentLocation, diag::note_member_synthesized_at)
7838      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7839    Constructor->setInvalidDecl();
7840    return;
7841  }
7842
7843  SourceLocation Loc = Constructor->getLocation();
7844  Constructor->setBody(new (Context) CompoundStmt(Loc));
7845
7846  Constructor->setUsed();
7847  MarkVTableUsed(CurrentLocation, ClassDecl);
7848
7849  if (ASTMutationListener *L = getASTMutationListener()) {
7850    L->CompletedImplicitDefinition(Constructor);
7851  }
7852}
7853
7854void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7855  // Check that any explicitly-defaulted methods have exception specifications
7856  // compatible with their implicit exception specifications.
7857  CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7858}
7859
7860namespace {
7861/// Information on inheriting constructors to declare.
7862class InheritingConstructorInfo {
7863public:
7864  InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7865      : SemaRef(SemaRef), Derived(Derived) {
7866    // Mark the constructors that we already have in the derived class.
7867    //
7868    // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7869    //   unless there is a user-declared constructor with the same signature in
7870    //   the class where the using-declaration appears.
7871    visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7872  }
7873
7874  void inheritAll(CXXRecordDecl *RD) {
7875    visitAll(RD, &InheritingConstructorInfo::inherit);
7876  }
7877
7878private:
7879  /// Information about an inheriting constructor.
7880  struct InheritingConstructor {
7881    InheritingConstructor()
7882      : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7883
7884    /// If \c true, a constructor with this signature is already declared
7885    /// in the derived class.
7886    bool DeclaredInDerived;
7887
7888    /// The constructor which is inherited.
7889    const CXXConstructorDecl *BaseCtor;
7890
7891    /// The derived constructor we declared.
7892    CXXConstructorDecl *DerivedCtor;
7893  };
7894
7895  /// Inheriting constructors with a given canonical type. There can be at
7896  /// most one such non-template constructor, and any number of templated
7897  /// constructors.
7898  struct InheritingConstructorsForType {
7899    InheritingConstructor NonTemplate;
7900    llvm::SmallVector<
7901      std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7902
7903    InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7904      if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7905        TemplateParameterList *ParamList = FTD->getTemplateParameters();
7906        for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7907          if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7908                                               false, S.TPL_TemplateMatch))
7909            return Templates[I].second;
7910        Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7911        return Templates.back().second;
7912      }
7913
7914      return NonTemplate;
7915    }
7916  };
7917
7918  /// Get or create the inheriting constructor record for a constructor.
7919  InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
7920                                  QualType CtorType) {
7921    return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
7922        .getEntry(SemaRef, Ctor);
7923  }
7924
7925  typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
7926
7927  /// Process all constructors for a class.
7928  void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
7929    for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
7930                                      CtorE = RD->ctor_end();
7931         CtorIt != CtorE; ++CtorIt)
7932      (this->*Callback)(*CtorIt);
7933    for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
7934             I(RD->decls_begin()), E(RD->decls_end());
7935         I != E; ++I) {
7936      const FunctionDecl *FD = (*I)->getTemplatedDecl();
7937      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7938        (this->*Callback)(CD);
7939    }
7940  }
7941
7942  /// Note that a constructor (or constructor template) was declared in Derived.
7943  void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
7944    getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
7945  }
7946
7947  /// Inherit a single constructor.
7948  void inherit(const CXXConstructorDecl *Ctor) {
7949    const FunctionProtoType *CtorType =
7950        Ctor->getType()->castAs<FunctionProtoType>();
7951    ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
7952    FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
7953
7954    SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
7955
7956    // Core issue (no number yet): the ellipsis is always discarded.
7957    if (EPI.Variadic) {
7958      SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
7959      SemaRef.Diag(Ctor->getLocation(),
7960                   diag::note_using_decl_constructor_ellipsis);
7961      EPI.Variadic = false;
7962    }
7963
7964    // Declare a constructor for each number of parameters.
7965    //
7966    // C++11 [class.inhctor]p1:
7967    //   The candidate set of inherited constructors from the class X named in
7968    //   the using-declaration consists of [... modulo defects ...] for each
7969    //   constructor or constructor template of X, the set of constructors or
7970    //   constructor templates that results from omitting any ellipsis parameter
7971    //   specification and successively omitting parameters with a default
7972    //   argument from the end of the parameter-type-list
7973    unsigned MinParams = minParamsToInherit(Ctor);
7974    unsigned Params = Ctor->getNumParams();
7975    if (Params >= MinParams) {
7976      do
7977        declareCtor(UsingLoc, Ctor,
7978                    SemaRef.Context.getFunctionType(
7979                        Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
7980      while (Params > MinParams &&
7981             Ctor->getParamDecl(--Params)->hasDefaultArg());
7982    }
7983  }
7984
7985  /// Find the using-declaration which specified that we should inherit the
7986  /// constructors of \p Base.
7987  SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
7988    // No fancy lookup required; just look for the base constructor name
7989    // directly within the derived class.
7990    ASTContext &Context = SemaRef.Context;
7991    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
7992        Context.getCanonicalType(Context.getRecordType(Base)));
7993    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
7994    return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
7995  }
7996
7997  unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
7998    // C++11 [class.inhctor]p3:
7999    //   [F]or each constructor template in the candidate set of inherited
8000    //   constructors, a constructor template is implicitly declared
8001    if (Ctor->getDescribedFunctionTemplate())
8002      return 0;
8003
8004    //   For each non-template constructor in the candidate set of inherited
8005    //   constructors other than a constructor having no parameters or a
8006    //   copy/move constructor having a single parameter, a constructor is
8007    //   implicitly declared [...]
8008    if (Ctor->getNumParams() == 0)
8009      return 1;
8010    if (Ctor->isCopyOrMoveConstructor())
8011      return 2;
8012
8013    // Per discussion on core reflector, never inherit a constructor which
8014    // would become a default, copy, or move constructor of Derived either.
8015    const ParmVarDecl *PD = Ctor->getParamDecl(0);
8016    const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8017    return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8018  }
8019
8020  /// Declare a single inheriting constructor, inheriting the specified
8021  /// constructor, with the given type.
8022  void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8023                   QualType DerivedType) {
8024    InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8025
8026    // C++11 [class.inhctor]p3:
8027    //   ... a constructor is implicitly declared with the same constructor
8028    //   characteristics unless there is a user-declared constructor with
8029    //   the same signature in the class where the using-declaration appears
8030    if (Entry.DeclaredInDerived)
8031      return;
8032
8033    // C++11 [class.inhctor]p7:
8034    //   If two using-declarations declare inheriting constructors with the
8035    //   same signature, the program is ill-formed
8036    if (Entry.DerivedCtor) {
8037      if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8038        // Only diagnose this once per constructor.
8039        if (Entry.DerivedCtor->isInvalidDecl())
8040          return;
8041        Entry.DerivedCtor->setInvalidDecl();
8042
8043        SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8044        SemaRef.Diag(BaseCtor->getLocation(),
8045                     diag::note_using_decl_constructor_conflict_current_ctor);
8046        SemaRef.Diag(Entry.BaseCtor->getLocation(),
8047                     diag::note_using_decl_constructor_conflict_previous_ctor);
8048        SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8049                     diag::note_using_decl_constructor_conflict_previous_using);
8050      } else {
8051        // Core issue (no number): if the same inheriting constructor is
8052        // produced by multiple base class constructors from the same base
8053        // class, the inheriting constructor is defined as deleted.
8054        SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8055      }
8056
8057      return;
8058    }
8059
8060    ASTContext &Context = SemaRef.Context;
8061    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8062        Context.getCanonicalType(Context.getRecordType(Derived)));
8063    DeclarationNameInfo NameInfo(Name, UsingLoc);
8064
8065    TemplateParameterList *TemplateParams = 0;
8066    if (const FunctionTemplateDecl *FTD =
8067            BaseCtor->getDescribedFunctionTemplate()) {
8068      TemplateParams = FTD->getTemplateParameters();
8069      // We're reusing template parameters from a different DeclContext. This
8070      // is questionable at best, but works out because the template depth in
8071      // both places is guaranteed to be 0.
8072      // FIXME: Rebuild the template parameters in the new context, and
8073      // transform the function type to refer to them.
8074    }
8075
8076    // Build type source info pointing at the using-declaration. This is
8077    // required by template instantiation.
8078    TypeSourceInfo *TInfo =
8079        Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8080    FunctionProtoTypeLoc ProtoLoc =
8081        TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8082
8083    CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8084        Context, Derived, UsingLoc, NameInfo, DerivedType,
8085        TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8086        /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8087
8088    // Build an unevaluated exception specification for this constructor.
8089    const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8090    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8091    EPI.ExceptionSpecType = EST_Unevaluated;
8092    EPI.ExceptionSpecDecl = DerivedCtor;
8093    DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8094                                                 FPT->getArgTypes(), EPI));
8095
8096    // Build the parameter declarations.
8097    SmallVector<ParmVarDecl *, 16> ParamDecls;
8098    for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8099      TypeSourceInfo *TInfo =
8100          Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8101      ParmVarDecl *PD = ParmVarDecl::Create(
8102          Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8103          FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8104      PD->setScopeInfo(0, I);
8105      PD->setImplicit();
8106      ParamDecls.push_back(PD);
8107      ProtoLoc.setArg(I, PD);
8108    }
8109
8110    // Set up the new constructor.
8111    DerivedCtor->setAccess(BaseCtor->getAccess());
8112    DerivedCtor->setParams(ParamDecls);
8113    DerivedCtor->setInheritedConstructor(BaseCtor);
8114    if (BaseCtor->isDeleted())
8115      SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8116
8117    // If this is a constructor template, build the template declaration.
8118    if (TemplateParams) {
8119      FunctionTemplateDecl *DerivedTemplate =
8120          FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8121                                       TemplateParams, DerivedCtor);
8122      DerivedTemplate->setAccess(BaseCtor->getAccess());
8123      DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8124      Derived->addDecl(DerivedTemplate);
8125    } else {
8126      Derived->addDecl(DerivedCtor);
8127    }
8128
8129    Entry.BaseCtor = BaseCtor;
8130    Entry.DerivedCtor = DerivedCtor;
8131  }
8132
8133  Sema &SemaRef;
8134  CXXRecordDecl *Derived;
8135  typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8136  MapType Map;
8137};
8138}
8139
8140void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8141  // Defer declaring the inheriting constructors until the class is
8142  // instantiated.
8143  if (ClassDecl->isDependentContext())
8144    return;
8145
8146  // Find base classes from which we might inherit constructors.
8147  SmallVector<CXXRecordDecl*, 4> InheritedBases;
8148  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8149                                          BaseE = ClassDecl->bases_end();
8150       BaseIt != BaseE; ++BaseIt)
8151    if (BaseIt->getInheritConstructors())
8152      InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8153
8154  // Go no further if we're not inheriting any constructors.
8155  if (InheritedBases.empty())
8156    return;
8157
8158  // Declare the inherited constructors.
8159  InheritingConstructorInfo ICI(*this, ClassDecl);
8160  for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8161    ICI.inheritAll(InheritedBases[I]);
8162}
8163
8164void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8165                                       CXXConstructorDecl *Constructor) {
8166  CXXRecordDecl *ClassDecl = Constructor->getParent();
8167  assert(Constructor->getInheritedConstructor() &&
8168         !Constructor->doesThisDeclarationHaveABody() &&
8169         !Constructor->isDeleted());
8170
8171  SynthesizedFunctionScope Scope(*this, Constructor);
8172  DiagnosticErrorTrap Trap(Diags);
8173  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8174      Trap.hasErrorOccurred()) {
8175    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8176      << Context.getTagDeclType(ClassDecl);
8177    Constructor->setInvalidDecl();
8178    return;
8179  }
8180
8181  SourceLocation Loc = Constructor->getLocation();
8182  Constructor->setBody(new (Context) CompoundStmt(Loc));
8183
8184  Constructor->setUsed();
8185  MarkVTableUsed(CurrentLocation, ClassDecl);
8186
8187  if (ASTMutationListener *L = getASTMutationListener()) {
8188    L->CompletedImplicitDefinition(Constructor);
8189  }
8190}
8191
8192
8193Sema::ImplicitExceptionSpecification
8194Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8195  CXXRecordDecl *ClassDecl = MD->getParent();
8196
8197  // C++ [except.spec]p14:
8198  //   An implicitly declared special member function (Clause 12) shall have
8199  //   an exception-specification.
8200  ImplicitExceptionSpecification ExceptSpec(*this);
8201  if (ClassDecl->isInvalidDecl())
8202    return ExceptSpec;
8203
8204  // Direct base-class destructors.
8205  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8206                                       BEnd = ClassDecl->bases_end();
8207       B != BEnd; ++B) {
8208    if (B->isVirtual()) // Handled below.
8209      continue;
8210
8211    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8212      ExceptSpec.CalledDecl(B->getLocStart(),
8213                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8214  }
8215
8216  // Virtual base-class destructors.
8217  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8218                                       BEnd = ClassDecl->vbases_end();
8219       B != BEnd; ++B) {
8220    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8221      ExceptSpec.CalledDecl(B->getLocStart(),
8222                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8223  }
8224
8225  // Field destructors.
8226  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8227                               FEnd = ClassDecl->field_end();
8228       F != FEnd; ++F) {
8229    if (const RecordType *RecordTy
8230        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8231      ExceptSpec.CalledDecl(F->getLocation(),
8232                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8233  }
8234
8235  return ExceptSpec;
8236}
8237
8238CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8239  // C++ [class.dtor]p2:
8240  //   If a class has no user-declared destructor, a destructor is
8241  //   declared implicitly. An implicitly-declared destructor is an
8242  //   inline public member of its class.
8243  assert(ClassDecl->needsImplicitDestructor());
8244
8245  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8246  if (DSM.isAlreadyBeingDeclared())
8247    return 0;
8248
8249  // Create the actual destructor declaration.
8250  CanQualType ClassType
8251    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8252  SourceLocation ClassLoc = ClassDecl->getLocation();
8253  DeclarationName Name
8254    = Context.DeclarationNames.getCXXDestructorName(ClassType);
8255  DeclarationNameInfo NameInfo(Name, ClassLoc);
8256  CXXDestructorDecl *Destructor
8257      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8258                                  QualType(), 0, /*isInline=*/true,
8259                                  /*isImplicitlyDeclared=*/true);
8260  Destructor->setAccess(AS_public);
8261  Destructor->setDefaulted();
8262  Destructor->setImplicit();
8263
8264  // Build an exception specification pointing back at this destructor.
8265  FunctionProtoType::ExtProtoInfo EPI;
8266  EPI.ExceptionSpecType = EST_Unevaluated;
8267  EPI.ExceptionSpecDecl = Destructor;
8268  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8269
8270  AddOverriddenMethods(ClassDecl, Destructor);
8271
8272  // We don't need to use SpecialMemberIsTrivial here; triviality for
8273  // destructors is easy to compute.
8274  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8275
8276  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8277    SetDeclDeleted(Destructor, ClassLoc);
8278
8279  // Note that we have declared this destructor.
8280  ++ASTContext::NumImplicitDestructorsDeclared;
8281
8282  // Introduce this destructor into its scope.
8283  if (Scope *S = getScopeForContext(ClassDecl))
8284    PushOnScopeChains(Destructor, S, false);
8285  ClassDecl->addDecl(Destructor);
8286
8287  return Destructor;
8288}
8289
8290void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8291                                    CXXDestructorDecl *Destructor) {
8292  assert((Destructor->isDefaulted() &&
8293          !Destructor->doesThisDeclarationHaveABody() &&
8294          !Destructor->isDeleted()) &&
8295         "DefineImplicitDestructor - call it for implicit default dtor");
8296  CXXRecordDecl *ClassDecl = Destructor->getParent();
8297  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8298
8299  if (Destructor->isInvalidDecl())
8300    return;
8301
8302  SynthesizedFunctionScope Scope(*this, Destructor);
8303
8304  DiagnosticErrorTrap Trap(Diags);
8305  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8306                                         Destructor->getParent());
8307
8308  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8309    Diag(CurrentLocation, diag::note_member_synthesized_at)
8310      << CXXDestructor << Context.getTagDeclType(ClassDecl);
8311
8312    Destructor->setInvalidDecl();
8313    return;
8314  }
8315
8316  SourceLocation Loc = Destructor->getLocation();
8317  Destructor->setBody(new (Context) CompoundStmt(Loc));
8318  Destructor->setImplicitlyDefined(true);
8319  Destructor->setUsed();
8320  MarkVTableUsed(CurrentLocation, ClassDecl);
8321
8322  if (ASTMutationListener *L = getASTMutationListener()) {
8323    L->CompletedImplicitDefinition(Destructor);
8324  }
8325}
8326
8327/// \brief Perform any semantic analysis which needs to be delayed until all
8328/// pending class member declarations have been parsed.
8329void Sema::ActOnFinishCXXMemberDecls() {
8330  // If the context is an invalid C++ class, just suppress these checks.
8331  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8332    if (Record->isInvalidDecl()) {
8333      DelayedDestructorExceptionSpecChecks.clear();
8334      return;
8335    }
8336  }
8337
8338  // Perform any deferred checking of exception specifications for virtual
8339  // destructors.
8340  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8341       i != e; ++i) {
8342    const CXXDestructorDecl *Dtor =
8343        DelayedDestructorExceptionSpecChecks[i].first;
8344    assert(!Dtor->getParent()->isDependentType() &&
8345           "Should not ever add destructors of templates into the list.");
8346    CheckOverridingFunctionExceptionSpec(Dtor,
8347        DelayedDestructorExceptionSpecChecks[i].second);
8348  }
8349  DelayedDestructorExceptionSpecChecks.clear();
8350}
8351
8352void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8353                                         CXXDestructorDecl *Destructor) {
8354  assert(getLangOpts().CPlusPlus11 &&
8355         "adjusting dtor exception specs was introduced in c++11");
8356
8357  // C++11 [class.dtor]p3:
8358  //   A declaration of a destructor that does not have an exception-
8359  //   specification is implicitly considered to have the same exception-
8360  //   specification as an implicit declaration.
8361  const FunctionProtoType *DtorType = Destructor->getType()->
8362                                        getAs<FunctionProtoType>();
8363  if (DtorType->hasExceptionSpec())
8364    return;
8365
8366  // Replace the destructor's type, building off the existing one. Fortunately,
8367  // the only thing of interest in the destructor type is its extended info.
8368  // The return and arguments are fixed.
8369  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8370  EPI.ExceptionSpecType = EST_Unevaluated;
8371  EPI.ExceptionSpecDecl = Destructor;
8372  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8373
8374  // FIXME: If the destructor has a body that could throw, and the newly created
8375  // spec doesn't allow exceptions, we should emit a warning, because this
8376  // change in behavior can break conforming C++03 programs at runtime.
8377  // However, we don't have a body or an exception specification yet, so it
8378  // needs to be done somewhere else.
8379}
8380
8381/// When generating a defaulted copy or move assignment operator, if a field
8382/// should be copied with __builtin_memcpy rather than via explicit assignments,
8383/// do so. This optimization only applies for arrays of scalars, and for arrays
8384/// of class type where the selected copy/move-assignment operator is trivial.
8385static StmtResult
8386buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8387                           Expr *To, Expr *From) {
8388  // Compute the size of the memory buffer to be copied.
8389  QualType SizeType = S.Context.getSizeType();
8390  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8391                   S.Context.getTypeSizeInChars(T).getQuantity());
8392
8393  // Take the address of the field references for "from" and "to". We
8394  // directly construct UnaryOperators here because semantic analysis
8395  // does not permit us to take the address of an xvalue.
8396  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8397                         S.Context.getPointerType(From->getType()),
8398                         VK_RValue, OK_Ordinary, Loc);
8399  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8400                       S.Context.getPointerType(To->getType()),
8401                       VK_RValue, OK_Ordinary, Loc);
8402
8403  const Type *E = T->getBaseElementTypeUnsafe();
8404  bool NeedsCollectableMemCpy =
8405    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8406
8407  // Create a reference to the __builtin_objc_memmove_collectable function
8408  StringRef MemCpyName = NeedsCollectableMemCpy ?
8409    "__builtin_objc_memmove_collectable" :
8410    "__builtin_memcpy";
8411  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8412                 Sema::LookupOrdinaryName);
8413  S.LookupName(R, S.TUScope, true);
8414
8415  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8416  if (!MemCpy)
8417    // Something went horribly wrong earlier, and we will have complained
8418    // about it.
8419    return StmtError();
8420
8421  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8422                                            VK_RValue, Loc, 0);
8423  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8424
8425  Expr *CallArgs[] = {
8426    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8427  };
8428  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8429                                    Loc, CallArgs, Loc);
8430
8431  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8432  return S.Owned(Call.takeAs<Stmt>());
8433}
8434
8435/// \brief Builds a statement that copies/moves the given entity from \p From to
8436/// \c To.
8437///
8438/// This routine is used to copy/move the members of a class with an
8439/// implicitly-declared copy/move assignment operator. When the entities being
8440/// copied are arrays, this routine builds for loops to copy them.
8441///
8442/// \param S The Sema object used for type-checking.
8443///
8444/// \param Loc The location where the implicit copy/move is being generated.
8445///
8446/// \param T The type of the expressions being copied/moved. Both expressions
8447/// must have this type.
8448///
8449/// \param To The expression we are copying/moving to.
8450///
8451/// \param From The expression we are copying/moving from.
8452///
8453/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8454/// Otherwise, it's a non-static member subobject.
8455///
8456/// \param Copying Whether we're copying or moving.
8457///
8458/// \param Depth Internal parameter recording the depth of the recursion.
8459///
8460/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8461/// if a memcpy should be used instead.
8462static StmtResult
8463buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8464                                 Expr *To, Expr *From,
8465                                 bool CopyingBaseSubobject, bool Copying,
8466                                 unsigned Depth = 0) {
8467  // C++11 [class.copy]p28:
8468  //   Each subobject is assigned in the manner appropriate to its type:
8469  //
8470  //     - if the subobject is of class type, as if by a call to operator= with
8471  //       the subobject as the object expression and the corresponding
8472  //       subobject of x as a single function argument (as if by explicit
8473  //       qualification; that is, ignoring any possible virtual overriding
8474  //       functions in more derived classes);
8475  //
8476  // C++03 [class.copy]p13:
8477  //     - if the subobject is of class type, the copy assignment operator for
8478  //       the class is used (as if by explicit qualification; that is,
8479  //       ignoring any possible virtual overriding functions in more derived
8480  //       classes);
8481  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8482    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8483
8484    // Look for operator=.
8485    DeclarationName Name
8486      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8487    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8488    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8489
8490    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8491    // operator.
8492    if (!S.getLangOpts().CPlusPlus11) {
8493      LookupResult::Filter F = OpLookup.makeFilter();
8494      while (F.hasNext()) {
8495        NamedDecl *D = F.next();
8496        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8497          if (Method->isCopyAssignmentOperator() ||
8498              (!Copying && Method->isMoveAssignmentOperator()))
8499            continue;
8500
8501        F.erase();
8502      }
8503      F.done();
8504    }
8505
8506    // Suppress the protected check (C++ [class.protected]) for each of the
8507    // assignment operators we found. This strange dance is required when
8508    // we're assigning via a base classes's copy-assignment operator. To
8509    // ensure that we're getting the right base class subobject (without
8510    // ambiguities), we need to cast "this" to that subobject type; to
8511    // ensure that we don't go through the virtual call mechanism, we need
8512    // to qualify the operator= name with the base class (see below). However,
8513    // this means that if the base class has a protected copy assignment
8514    // operator, the protected member access check will fail. So, we
8515    // rewrite "protected" access to "public" access in this case, since we
8516    // know by construction that we're calling from a derived class.
8517    if (CopyingBaseSubobject) {
8518      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8519           L != LEnd; ++L) {
8520        if (L.getAccess() == AS_protected)
8521          L.setAccess(AS_public);
8522      }
8523    }
8524
8525    // Create the nested-name-specifier that will be used to qualify the
8526    // reference to operator=; this is required to suppress the virtual
8527    // call mechanism.
8528    CXXScopeSpec SS;
8529    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8530    SS.MakeTrivial(S.Context,
8531                   NestedNameSpecifier::Create(S.Context, 0, false,
8532                                               CanonicalT),
8533                   Loc);
8534
8535    // Create the reference to operator=.
8536    ExprResult OpEqualRef
8537      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8538                                   /*TemplateKWLoc=*/SourceLocation(),
8539                                   /*FirstQualifierInScope=*/0,
8540                                   OpLookup,
8541                                   /*TemplateArgs=*/0,
8542                                   /*SuppressQualifierCheck=*/true);
8543    if (OpEqualRef.isInvalid())
8544      return StmtError();
8545
8546    // Build the call to the assignment operator.
8547
8548    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8549                                                  OpEqualRef.takeAs<Expr>(),
8550                                                  Loc, From, Loc);
8551    if (Call.isInvalid())
8552      return StmtError();
8553
8554    // If we built a call to a trivial 'operator=' while copying an array,
8555    // bail out. We'll replace the whole shebang with a memcpy.
8556    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8557    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8558      return StmtResult((Stmt*)0);
8559
8560    // Convert to an expression-statement, and clean up any produced
8561    // temporaries.
8562    return S.ActOnExprStmt(Call);
8563  }
8564
8565  //     - if the subobject is of scalar type, the built-in assignment
8566  //       operator is used.
8567  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8568  if (!ArrayTy) {
8569    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8570    if (Assignment.isInvalid())
8571      return StmtError();
8572    return S.ActOnExprStmt(Assignment);
8573  }
8574
8575  //     - if the subobject is an array, each element is assigned, in the
8576  //       manner appropriate to the element type;
8577
8578  // Construct a loop over the array bounds, e.g.,
8579  //
8580  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8581  //
8582  // that will copy each of the array elements.
8583  QualType SizeType = S.Context.getSizeType();
8584
8585  // Create the iteration variable.
8586  IdentifierInfo *IterationVarName = 0;
8587  {
8588    SmallString<8> Str;
8589    llvm::raw_svector_ostream OS(Str);
8590    OS << "__i" << Depth;
8591    IterationVarName = &S.Context.Idents.get(OS.str());
8592  }
8593  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8594                                          IterationVarName, SizeType,
8595                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8596                                          SC_None);
8597
8598  // Initialize the iteration variable to zero.
8599  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8600  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8601
8602  // Create a reference to the iteration variable; we'll use this several
8603  // times throughout.
8604  Expr *IterationVarRef
8605    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8606  assert(IterationVarRef && "Reference to invented variable cannot fail!");
8607  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8608  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8609
8610  // Create the DeclStmt that holds the iteration variable.
8611  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8612
8613  // Subscript the "from" and "to" expressions with the iteration variable.
8614  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8615                                                         IterationVarRefRVal,
8616                                                         Loc));
8617  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8618                                                       IterationVarRefRVal,
8619                                                       Loc));
8620  if (!Copying) // Cast to rvalue
8621    From = CastForMoving(S, From);
8622
8623  // Build the copy/move for an individual element of the array.
8624  StmtResult Copy =
8625    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8626                                     To, From, CopyingBaseSubobject,
8627                                     Copying, Depth + 1);
8628  // Bail out if copying fails or if we determined that we should use memcpy.
8629  if (Copy.isInvalid() || !Copy.get())
8630    return Copy;
8631
8632  // Create the comparison against the array bound.
8633  llvm::APInt Upper
8634    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8635  Expr *Comparison
8636    = new (S.Context) BinaryOperator(IterationVarRefRVal,
8637                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8638                                     BO_NE, S.Context.BoolTy,
8639                                     VK_RValue, OK_Ordinary, Loc, false);
8640
8641  // Create the pre-increment of the iteration variable.
8642  Expr *Increment
8643    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8644                                    VK_LValue, OK_Ordinary, Loc);
8645
8646  // Construct the loop that copies all elements of this array.
8647  return S.ActOnForStmt(Loc, Loc, InitStmt,
8648                        S.MakeFullExpr(Comparison),
8649                        0, S.MakeFullDiscardedValueExpr(Increment),
8650                        Loc, Copy.take());
8651}
8652
8653static StmtResult
8654buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8655                      Expr *To, Expr *From,
8656                      bool CopyingBaseSubobject, bool Copying) {
8657  // Maybe we should use a memcpy?
8658  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8659      T.isTriviallyCopyableType(S.Context))
8660    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8661
8662  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8663                                                     CopyingBaseSubobject,
8664                                                     Copying, 0));
8665
8666  // If we ended up picking a trivial assignment operator for an array of a
8667  // non-trivially-copyable class type, just emit a memcpy.
8668  if (!Result.isInvalid() && !Result.get())
8669    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8670
8671  return Result;
8672}
8673
8674Sema::ImplicitExceptionSpecification
8675Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8676  CXXRecordDecl *ClassDecl = MD->getParent();
8677
8678  ImplicitExceptionSpecification ExceptSpec(*this);
8679  if (ClassDecl->isInvalidDecl())
8680    return ExceptSpec;
8681
8682  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8683  assert(T->getNumArgs() == 1 && "not a copy assignment op");
8684  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8685
8686  // C++ [except.spec]p14:
8687  //   An implicitly declared special member function (Clause 12) shall have an
8688  //   exception-specification. [...]
8689
8690  // It is unspecified whether or not an implicit copy assignment operator
8691  // attempts to deduplicate calls to assignment operators of virtual bases are
8692  // made. As such, this exception specification is effectively unspecified.
8693  // Based on a similar decision made for constness in C++0x, we're erring on
8694  // the side of assuming such calls to be made regardless of whether they
8695  // actually happen.
8696  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8697                                       BaseEnd = ClassDecl->bases_end();
8698       Base != BaseEnd; ++Base) {
8699    if (Base->isVirtual())
8700      continue;
8701
8702    CXXRecordDecl *BaseClassDecl
8703      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8704    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8705                                                            ArgQuals, false, 0))
8706      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8707  }
8708
8709  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8710                                       BaseEnd = ClassDecl->vbases_end();
8711       Base != BaseEnd; ++Base) {
8712    CXXRecordDecl *BaseClassDecl
8713      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8714    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8715                                                            ArgQuals, false, 0))
8716      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8717  }
8718
8719  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8720                                  FieldEnd = ClassDecl->field_end();
8721       Field != FieldEnd;
8722       ++Field) {
8723    QualType FieldType = Context.getBaseElementType(Field->getType());
8724    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8725      if (CXXMethodDecl *CopyAssign =
8726          LookupCopyingAssignment(FieldClassDecl,
8727                                  ArgQuals | FieldType.getCVRQualifiers(),
8728                                  false, 0))
8729        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8730    }
8731  }
8732
8733  return ExceptSpec;
8734}
8735
8736CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8737  // Note: The following rules are largely analoguous to the copy
8738  // constructor rules. Note that virtual bases are not taken into account
8739  // for determining the argument type of the operator. Note also that
8740  // operators taking an object instead of a reference are allowed.
8741  assert(ClassDecl->needsImplicitCopyAssignment());
8742
8743  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8744  if (DSM.isAlreadyBeingDeclared())
8745    return 0;
8746
8747  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8748  QualType RetType = Context.getLValueReferenceType(ArgType);
8749  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8750  if (Const)
8751    ArgType = ArgType.withConst();
8752  ArgType = Context.getLValueReferenceType(ArgType);
8753
8754  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8755                                                     CXXCopyAssignment,
8756                                                     Const);
8757
8758  //   An implicitly-declared copy assignment operator is an inline public
8759  //   member of its class.
8760  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8761  SourceLocation ClassLoc = ClassDecl->getLocation();
8762  DeclarationNameInfo NameInfo(Name, ClassLoc);
8763  CXXMethodDecl *CopyAssignment =
8764      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8765                            /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8766                            /*isInline=*/ true, Constexpr, SourceLocation());
8767  CopyAssignment->setAccess(AS_public);
8768  CopyAssignment->setDefaulted();
8769  CopyAssignment->setImplicit();
8770
8771  // Build an exception specification pointing back at this member.
8772  FunctionProtoType::ExtProtoInfo EPI;
8773  EPI.ExceptionSpecType = EST_Unevaluated;
8774  EPI.ExceptionSpecDecl = CopyAssignment;
8775  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8776
8777  // Add the parameter to the operator.
8778  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8779                                               ClassLoc, ClassLoc, /*Id=*/0,
8780                                               ArgType, /*TInfo=*/0,
8781                                               SC_None, 0);
8782  CopyAssignment->setParams(FromParam);
8783
8784  AddOverriddenMethods(ClassDecl, CopyAssignment);
8785
8786  CopyAssignment->setTrivial(
8787    ClassDecl->needsOverloadResolutionForCopyAssignment()
8788      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8789      : ClassDecl->hasTrivialCopyAssignment());
8790
8791  // C++11 [class.copy]p19:
8792  //   ....  If the class definition does not explicitly declare a copy
8793  //   assignment operator, there is no user-declared move constructor, and
8794  //   there is no user-declared move assignment operator, a copy assignment
8795  //   operator is implicitly declared as defaulted.
8796  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8797    SetDeclDeleted(CopyAssignment, ClassLoc);
8798
8799  // Note that we have added this copy-assignment operator.
8800  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8801
8802  if (Scope *S = getScopeForContext(ClassDecl))
8803    PushOnScopeChains(CopyAssignment, S, false);
8804  ClassDecl->addDecl(CopyAssignment);
8805
8806  return CopyAssignment;
8807}
8808
8809void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8810                                        CXXMethodDecl *CopyAssignOperator) {
8811  assert((CopyAssignOperator->isDefaulted() &&
8812          CopyAssignOperator->isOverloadedOperator() &&
8813          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8814          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8815          !CopyAssignOperator->isDeleted()) &&
8816         "DefineImplicitCopyAssignment called for wrong function");
8817
8818  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8819
8820  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8821    CopyAssignOperator->setInvalidDecl();
8822    return;
8823  }
8824
8825  CopyAssignOperator->setUsed();
8826
8827  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8828  DiagnosticErrorTrap Trap(Diags);
8829
8830  // C++0x [class.copy]p30:
8831  //   The implicitly-defined or explicitly-defaulted copy assignment operator
8832  //   for a non-union class X performs memberwise copy assignment of its
8833  //   subobjects. The direct base classes of X are assigned first, in the
8834  //   order of their declaration in the base-specifier-list, and then the
8835  //   immediate non-static data members of X are assigned, in the order in
8836  //   which they were declared in the class definition.
8837
8838  // The statements that form the synthesized function body.
8839  SmallVector<Stmt*, 8> Statements;
8840
8841  // The parameter for the "other" object, which we are copying from.
8842  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8843  Qualifiers OtherQuals = Other->getType().getQualifiers();
8844  QualType OtherRefType = Other->getType();
8845  if (const LValueReferenceType *OtherRef
8846                                = OtherRefType->getAs<LValueReferenceType>()) {
8847    OtherRefType = OtherRef->getPointeeType();
8848    OtherQuals = OtherRefType.getQualifiers();
8849  }
8850
8851  // Our location for everything implicitly-generated.
8852  SourceLocation Loc = CopyAssignOperator->getLocation();
8853
8854  // Construct a reference to the "other" object. We'll be using this
8855  // throughout the generated ASTs.
8856  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8857  assert(OtherRef && "Reference to parameter cannot fail!");
8858
8859  // Construct the "this" pointer. We'll be using this throughout the generated
8860  // ASTs.
8861  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8862  assert(This && "Reference to this cannot fail!");
8863
8864  // Assign base classes.
8865  bool Invalid = false;
8866  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8867       E = ClassDecl->bases_end(); Base != E; ++Base) {
8868    // Form the assignment:
8869    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
8870    QualType BaseType = Base->getType().getUnqualifiedType();
8871    if (!BaseType->isRecordType()) {
8872      Invalid = true;
8873      continue;
8874    }
8875
8876    CXXCastPath BasePath;
8877    BasePath.push_back(Base);
8878
8879    // Construct the "from" expression, which is an implicit cast to the
8880    // appropriately-qualified base type.
8881    Expr *From = OtherRef;
8882    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
8883                             CK_UncheckedDerivedToBase,
8884                             VK_LValue, &BasePath).take();
8885
8886    // Dereference "this".
8887    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8888
8889    // Implicitly cast "this" to the appropriately-qualified base type.
8890    To = ImpCastExprToType(To.take(),
8891                           Context.getCVRQualifiedType(BaseType,
8892                                     CopyAssignOperator->getTypeQualifiers()),
8893                           CK_UncheckedDerivedToBase,
8894                           VK_LValue, &BasePath);
8895
8896    // Build the copy.
8897    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
8898                                            To.get(), From,
8899                                            /*CopyingBaseSubobject=*/true,
8900                                            /*Copying=*/true);
8901    if (Copy.isInvalid()) {
8902      Diag(CurrentLocation, diag::note_member_synthesized_at)
8903        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8904      CopyAssignOperator->setInvalidDecl();
8905      return;
8906    }
8907
8908    // Success! Record the copy.
8909    Statements.push_back(Copy.takeAs<Expr>());
8910  }
8911
8912  // Assign non-static members.
8913  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8914                                  FieldEnd = ClassDecl->field_end();
8915       Field != FieldEnd; ++Field) {
8916    if (Field->isUnnamedBitfield())
8917      continue;
8918
8919    if (Field->isInvalidDecl()) {
8920      Invalid = true;
8921      continue;
8922    }
8923
8924    // Check for members of reference type; we can't copy those.
8925    if (Field->getType()->isReferenceType()) {
8926      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8927        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8928      Diag(Field->getLocation(), diag::note_declared_at);
8929      Diag(CurrentLocation, diag::note_member_synthesized_at)
8930        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8931      Invalid = true;
8932      continue;
8933    }
8934
8935    // Check for members of const-qualified, non-class type.
8936    QualType BaseType = Context.getBaseElementType(Field->getType());
8937    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8938      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8939        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8940      Diag(Field->getLocation(), diag::note_declared_at);
8941      Diag(CurrentLocation, diag::note_member_synthesized_at)
8942        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8943      Invalid = true;
8944      continue;
8945    }
8946
8947    // Suppress assigning zero-width bitfields.
8948    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8949      continue;
8950
8951    QualType FieldType = Field->getType().getNonReferenceType();
8952    if (FieldType->isIncompleteArrayType()) {
8953      assert(ClassDecl->hasFlexibleArrayMember() &&
8954             "Incomplete array type is not valid");
8955      continue;
8956    }
8957
8958    // Build references to the field in the object we're copying from and to.
8959    CXXScopeSpec SS; // Intentionally empty
8960    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8961                              LookupMemberName);
8962    MemberLookup.addDecl(*Field);
8963    MemberLookup.resolveKind();
8964    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8965                                               Loc, /*IsArrow=*/false,
8966                                               SS, SourceLocation(), 0,
8967                                               MemberLookup, 0);
8968    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8969                                             Loc, /*IsArrow=*/true,
8970                                             SS, SourceLocation(), 0,
8971                                             MemberLookup, 0);
8972    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8973    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8974
8975    // Build the copy of this field.
8976    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
8977                                            To.get(), From.get(),
8978                                            /*CopyingBaseSubobject=*/false,
8979                                            /*Copying=*/true);
8980    if (Copy.isInvalid()) {
8981      Diag(CurrentLocation, diag::note_member_synthesized_at)
8982        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8983      CopyAssignOperator->setInvalidDecl();
8984      return;
8985    }
8986
8987    // Success! Record the copy.
8988    Statements.push_back(Copy.takeAs<Stmt>());
8989  }
8990
8991  if (!Invalid) {
8992    // Add a "return *this;"
8993    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8994
8995    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8996    if (Return.isInvalid())
8997      Invalid = true;
8998    else {
8999      Statements.push_back(Return.takeAs<Stmt>());
9000
9001      if (Trap.hasErrorOccurred()) {
9002        Diag(CurrentLocation, diag::note_member_synthesized_at)
9003          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9004        Invalid = true;
9005      }
9006    }
9007  }
9008
9009  if (Invalid) {
9010    CopyAssignOperator->setInvalidDecl();
9011    return;
9012  }
9013
9014  StmtResult Body;
9015  {
9016    CompoundScopeRAII CompoundScope(*this);
9017    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9018                             /*isStmtExpr=*/false);
9019    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9020  }
9021  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9022
9023  if (ASTMutationListener *L = getASTMutationListener()) {
9024    L->CompletedImplicitDefinition(CopyAssignOperator);
9025  }
9026}
9027
9028Sema::ImplicitExceptionSpecification
9029Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9030  CXXRecordDecl *ClassDecl = MD->getParent();
9031
9032  ImplicitExceptionSpecification ExceptSpec(*this);
9033  if (ClassDecl->isInvalidDecl())
9034    return ExceptSpec;
9035
9036  // C++0x [except.spec]p14:
9037  //   An implicitly declared special member function (Clause 12) shall have an
9038  //   exception-specification. [...]
9039
9040  // It is unspecified whether or not an implicit move assignment operator
9041  // attempts to deduplicate calls to assignment operators of virtual bases are
9042  // made. As such, this exception specification is effectively unspecified.
9043  // Based on a similar decision made for constness in C++0x, we're erring on
9044  // the side of assuming such calls to be made regardless of whether they
9045  // actually happen.
9046  // Note that a move constructor is not implicitly declared when there are
9047  // virtual bases, but it can still be user-declared and explicitly defaulted.
9048  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9049                                       BaseEnd = ClassDecl->bases_end();
9050       Base != BaseEnd; ++Base) {
9051    if (Base->isVirtual())
9052      continue;
9053
9054    CXXRecordDecl *BaseClassDecl
9055      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9056    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9057                                                           0, false, 0))
9058      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9059  }
9060
9061  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9062                                       BaseEnd = ClassDecl->vbases_end();
9063       Base != BaseEnd; ++Base) {
9064    CXXRecordDecl *BaseClassDecl
9065      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9066    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9067                                                           0, false, 0))
9068      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9069  }
9070
9071  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9072                                  FieldEnd = ClassDecl->field_end();
9073       Field != FieldEnd;
9074       ++Field) {
9075    QualType FieldType = Context.getBaseElementType(Field->getType());
9076    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9077      if (CXXMethodDecl *MoveAssign =
9078              LookupMovingAssignment(FieldClassDecl,
9079                                     FieldType.getCVRQualifiers(),
9080                                     false, 0))
9081        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9082    }
9083  }
9084
9085  return ExceptSpec;
9086}
9087
9088/// Determine whether the class type has any direct or indirect virtual base
9089/// classes which have a non-trivial move assignment operator.
9090static bool
9091hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9092  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9093                                          BaseEnd = ClassDecl->vbases_end();
9094       Base != BaseEnd; ++Base) {
9095    CXXRecordDecl *BaseClass =
9096        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9097
9098    // Try to declare the move assignment. If it would be deleted, then the
9099    // class does not have a non-trivial move assignment.
9100    if (BaseClass->needsImplicitMoveAssignment())
9101      S.DeclareImplicitMoveAssignment(BaseClass);
9102
9103    if (BaseClass->hasNonTrivialMoveAssignment())
9104      return true;
9105  }
9106
9107  return false;
9108}
9109
9110/// Determine whether the given type either has a move constructor or is
9111/// trivially copyable.
9112static bool
9113hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9114  Type = S.Context.getBaseElementType(Type);
9115
9116  // FIXME: Technically, non-trivially-copyable non-class types, such as
9117  // reference types, are supposed to return false here, but that appears
9118  // to be a standard defect.
9119  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
9120  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
9121    return true;
9122
9123  if (Type.isTriviallyCopyableType(S.Context))
9124    return true;
9125
9126  if (IsConstructor) {
9127    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9128    // give the right answer.
9129    if (ClassDecl->needsImplicitMoveConstructor())
9130      S.DeclareImplicitMoveConstructor(ClassDecl);
9131    return ClassDecl->hasMoveConstructor();
9132  }
9133
9134  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9135  // give the right answer.
9136  if (ClassDecl->needsImplicitMoveAssignment())
9137    S.DeclareImplicitMoveAssignment(ClassDecl);
9138  return ClassDecl->hasMoveAssignment();
9139}
9140
9141/// Determine whether all non-static data members and direct or virtual bases
9142/// of class \p ClassDecl have either a move operation, or are trivially
9143/// copyable.
9144static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9145                                            bool IsConstructor) {
9146  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9147                                          BaseEnd = ClassDecl->bases_end();
9148       Base != BaseEnd; ++Base) {
9149    if (Base->isVirtual())
9150      continue;
9151
9152    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9153      return false;
9154  }
9155
9156  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9157                                          BaseEnd = ClassDecl->vbases_end();
9158       Base != BaseEnd; ++Base) {
9159    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9160      return false;
9161  }
9162
9163  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9164                                     FieldEnd = ClassDecl->field_end();
9165       Field != FieldEnd; ++Field) {
9166    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9167      return false;
9168  }
9169
9170  return true;
9171}
9172
9173CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9174  // C++11 [class.copy]p20:
9175  //   If the definition of a class X does not explicitly declare a move
9176  //   assignment operator, one will be implicitly declared as defaulted
9177  //   if and only if:
9178  //
9179  //   - [first 4 bullets]
9180  assert(ClassDecl->needsImplicitMoveAssignment());
9181
9182  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9183  if (DSM.isAlreadyBeingDeclared())
9184    return 0;
9185
9186  // [Checked after we build the declaration]
9187  //   - the move assignment operator would not be implicitly defined as
9188  //     deleted,
9189
9190  // [DR1402]:
9191  //   - X has no direct or indirect virtual base class with a non-trivial
9192  //     move assignment operator, and
9193  //   - each of X's non-static data members and direct or virtual base classes
9194  //     has a type that either has a move assignment operator or is trivially
9195  //     copyable.
9196  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9197      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9198    ClassDecl->setFailedImplicitMoveAssignment();
9199    return 0;
9200  }
9201
9202  // Note: The following rules are largely analoguous to the move
9203  // constructor rules.
9204
9205  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9206  QualType RetType = Context.getLValueReferenceType(ArgType);
9207  ArgType = Context.getRValueReferenceType(ArgType);
9208
9209  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9210                                                     CXXMoveAssignment,
9211                                                     false);
9212
9213  //   An implicitly-declared move assignment operator is an inline public
9214  //   member of its class.
9215  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9216  SourceLocation ClassLoc = ClassDecl->getLocation();
9217  DeclarationNameInfo NameInfo(Name, ClassLoc);
9218  CXXMethodDecl *MoveAssignment =
9219      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9220                            /*TInfo=*/0, /*StorageClass=*/SC_None,
9221                            /*isInline=*/true, Constexpr, SourceLocation());
9222  MoveAssignment->setAccess(AS_public);
9223  MoveAssignment->setDefaulted();
9224  MoveAssignment->setImplicit();
9225
9226  // Build an exception specification pointing back at this member.
9227  FunctionProtoType::ExtProtoInfo EPI;
9228  EPI.ExceptionSpecType = EST_Unevaluated;
9229  EPI.ExceptionSpecDecl = MoveAssignment;
9230  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9231
9232  // Add the parameter to the operator.
9233  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9234                                               ClassLoc, ClassLoc, /*Id=*/0,
9235                                               ArgType, /*TInfo=*/0,
9236                                               SC_None, 0);
9237  MoveAssignment->setParams(FromParam);
9238
9239  AddOverriddenMethods(ClassDecl, MoveAssignment);
9240
9241  MoveAssignment->setTrivial(
9242    ClassDecl->needsOverloadResolutionForMoveAssignment()
9243      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9244      : ClassDecl->hasTrivialMoveAssignment());
9245
9246  // C++0x [class.copy]p9:
9247  //   If the definition of a class X does not explicitly declare a move
9248  //   assignment operator, one will be implicitly declared as defaulted if and
9249  //   only if:
9250  //   [...]
9251  //   - the move assignment operator would not be implicitly defined as
9252  //     deleted.
9253  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9254    // Cache this result so that we don't try to generate this over and over
9255    // on every lookup, leaking memory and wasting time.
9256    ClassDecl->setFailedImplicitMoveAssignment();
9257    return 0;
9258  }
9259
9260  // Note that we have added this copy-assignment operator.
9261  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9262
9263  if (Scope *S = getScopeForContext(ClassDecl))
9264    PushOnScopeChains(MoveAssignment, S, false);
9265  ClassDecl->addDecl(MoveAssignment);
9266
9267  return MoveAssignment;
9268}
9269
9270void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9271                                        CXXMethodDecl *MoveAssignOperator) {
9272  assert((MoveAssignOperator->isDefaulted() &&
9273          MoveAssignOperator->isOverloadedOperator() &&
9274          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9275          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9276          !MoveAssignOperator->isDeleted()) &&
9277         "DefineImplicitMoveAssignment called for wrong function");
9278
9279  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9280
9281  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9282    MoveAssignOperator->setInvalidDecl();
9283    return;
9284  }
9285
9286  MoveAssignOperator->setUsed();
9287
9288  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9289  DiagnosticErrorTrap Trap(Diags);
9290
9291  // C++0x [class.copy]p28:
9292  //   The implicitly-defined or move assignment operator for a non-union class
9293  //   X performs memberwise move assignment of its subobjects. The direct base
9294  //   classes of X are assigned first, in the order of their declaration in the
9295  //   base-specifier-list, and then the immediate non-static data members of X
9296  //   are assigned, in the order in which they were declared in the class
9297  //   definition.
9298
9299  // The statements that form the synthesized function body.
9300  SmallVector<Stmt*, 8> Statements;
9301
9302  // The parameter for the "other" object, which we are move from.
9303  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9304  QualType OtherRefType = Other->getType()->
9305      getAs<RValueReferenceType>()->getPointeeType();
9306  assert(!OtherRefType.getQualifiers() &&
9307         "Bad argument type of defaulted move assignment");
9308
9309  // Our location for everything implicitly-generated.
9310  SourceLocation Loc = MoveAssignOperator->getLocation();
9311
9312  // Construct a reference to the "other" object. We'll be using this
9313  // throughout the generated ASTs.
9314  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9315  assert(OtherRef && "Reference to parameter cannot fail!");
9316  // Cast to rvalue.
9317  OtherRef = CastForMoving(*this, OtherRef);
9318
9319  // Construct the "this" pointer. We'll be using this throughout the generated
9320  // ASTs.
9321  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9322  assert(This && "Reference to this cannot fail!");
9323
9324  // Assign base classes.
9325  bool Invalid = false;
9326  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9327       E = ClassDecl->bases_end(); Base != E; ++Base) {
9328    // Form the assignment:
9329    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9330    QualType BaseType = Base->getType().getUnqualifiedType();
9331    if (!BaseType->isRecordType()) {
9332      Invalid = true;
9333      continue;
9334    }
9335
9336    CXXCastPath BasePath;
9337    BasePath.push_back(Base);
9338
9339    // Construct the "from" expression, which is an implicit cast to the
9340    // appropriately-qualified base type.
9341    Expr *From = OtherRef;
9342    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9343                             VK_XValue, &BasePath).take();
9344
9345    // Dereference "this".
9346    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9347
9348    // Implicitly cast "this" to the appropriately-qualified base type.
9349    To = ImpCastExprToType(To.take(),
9350                           Context.getCVRQualifiedType(BaseType,
9351                                     MoveAssignOperator->getTypeQualifiers()),
9352                           CK_UncheckedDerivedToBase,
9353                           VK_LValue, &BasePath);
9354
9355    // Build the move.
9356    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9357                                            To.get(), From,
9358                                            /*CopyingBaseSubobject=*/true,
9359                                            /*Copying=*/false);
9360    if (Move.isInvalid()) {
9361      Diag(CurrentLocation, diag::note_member_synthesized_at)
9362        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9363      MoveAssignOperator->setInvalidDecl();
9364      return;
9365    }
9366
9367    // Success! Record the move.
9368    Statements.push_back(Move.takeAs<Expr>());
9369  }
9370
9371  // Assign non-static members.
9372  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9373                                  FieldEnd = ClassDecl->field_end();
9374       Field != FieldEnd; ++Field) {
9375    if (Field->isUnnamedBitfield())
9376      continue;
9377
9378    if (Field->isInvalidDecl()) {
9379      Invalid = true;
9380      continue;
9381    }
9382
9383    // Check for members of reference type; we can't move those.
9384    if (Field->getType()->isReferenceType()) {
9385      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9386        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9387      Diag(Field->getLocation(), diag::note_declared_at);
9388      Diag(CurrentLocation, diag::note_member_synthesized_at)
9389        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9390      Invalid = true;
9391      continue;
9392    }
9393
9394    // Check for members of const-qualified, non-class type.
9395    QualType BaseType = Context.getBaseElementType(Field->getType());
9396    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9397      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9398        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9399      Diag(Field->getLocation(), diag::note_declared_at);
9400      Diag(CurrentLocation, diag::note_member_synthesized_at)
9401        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9402      Invalid = true;
9403      continue;
9404    }
9405
9406    // Suppress assigning zero-width bitfields.
9407    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9408      continue;
9409
9410    QualType FieldType = Field->getType().getNonReferenceType();
9411    if (FieldType->isIncompleteArrayType()) {
9412      assert(ClassDecl->hasFlexibleArrayMember() &&
9413             "Incomplete array type is not valid");
9414      continue;
9415    }
9416
9417    // Build references to the field in the object we're copying from and to.
9418    CXXScopeSpec SS; // Intentionally empty
9419    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9420                              LookupMemberName);
9421    MemberLookup.addDecl(*Field);
9422    MemberLookup.resolveKind();
9423    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9424                                               Loc, /*IsArrow=*/false,
9425                                               SS, SourceLocation(), 0,
9426                                               MemberLookup, 0);
9427    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9428                                             Loc, /*IsArrow=*/true,
9429                                             SS, SourceLocation(), 0,
9430                                             MemberLookup, 0);
9431    assert(!From.isInvalid() && "Implicit field reference cannot fail");
9432    assert(!To.isInvalid() && "Implicit field reference cannot fail");
9433
9434    assert(!From.get()->isLValue() && // could be xvalue or prvalue
9435        "Member reference with rvalue base must be rvalue except for reference "
9436        "members, which aren't allowed for move assignment.");
9437
9438    // Build the move of this field.
9439    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9440                                            To.get(), From.get(),
9441                                            /*CopyingBaseSubobject=*/false,
9442                                            /*Copying=*/false);
9443    if (Move.isInvalid()) {
9444      Diag(CurrentLocation, diag::note_member_synthesized_at)
9445        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9446      MoveAssignOperator->setInvalidDecl();
9447      return;
9448    }
9449
9450    // Success! Record the copy.
9451    Statements.push_back(Move.takeAs<Stmt>());
9452  }
9453
9454  if (!Invalid) {
9455    // Add a "return *this;"
9456    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9457
9458    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9459    if (Return.isInvalid())
9460      Invalid = true;
9461    else {
9462      Statements.push_back(Return.takeAs<Stmt>());
9463
9464      if (Trap.hasErrorOccurred()) {
9465        Diag(CurrentLocation, diag::note_member_synthesized_at)
9466          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9467        Invalid = true;
9468      }
9469    }
9470  }
9471
9472  if (Invalid) {
9473    MoveAssignOperator->setInvalidDecl();
9474    return;
9475  }
9476
9477  StmtResult Body;
9478  {
9479    CompoundScopeRAII CompoundScope(*this);
9480    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9481                             /*isStmtExpr=*/false);
9482    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9483  }
9484  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9485
9486  if (ASTMutationListener *L = getASTMutationListener()) {
9487    L->CompletedImplicitDefinition(MoveAssignOperator);
9488  }
9489}
9490
9491Sema::ImplicitExceptionSpecification
9492Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9493  CXXRecordDecl *ClassDecl = MD->getParent();
9494
9495  ImplicitExceptionSpecification ExceptSpec(*this);
9496  if (ClassDecl->isInvalidDecl())
9497    return ExceptSpec;
9498
9499  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9500  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9501  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9502
9503  // C++ [except.spec]p14:
9504  //   An implicitly declared special member function (Clause 12) shall have an
9505  //   exception-specification. [...]
9506  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9507                                       BaseEnd = ClassDecl->bases_end();
9508       Base != BaseEnd;
9509       ++Base) {
9510    // Virtual bases are handled below.
9511    if (Base->isVirtual())
9512      continue;
9513
9514    CXXRecordDecl *BaseClassDecl
9515      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9516    if (CXXConstructorDecl *CopyConstructor =
9517          LookupCopyingConstructor(BaseClassDecl, Quals))
9518      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9519  }
9520  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9521                                       BaseEnd = ClassDecl->vbases_end();
9522       Base != BaseEnd;
9523       ++Base) {
9524    CXXRecordDecl *BaseClassDecl
9525      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9526    if (CXXConstructorDecl *CopyConstructor =
9527          LookupCopyingConstructor(BaseClassDecl, Quals))
9528      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9529  }
9530  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9531                                  FieldEnd = ClassDecl->field_end();
9532       Field != FieldEnd;
9533       ++Field) {
9534    QualType FieldType = Context.getBaseElementType(Field->getType());
9535    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9536      if (CXXConstructorDecl *CopyConstructor =
9537              LookupCopyingConstructor(FieldClassDecl,
9538                                       Quals | FieldType.getCVRQualifiers()))
9539      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9540    }
9541  }
9542
9543  return ExceptSpec;
9544}
9545
9546CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9547                                                    CXXRecordDecl *ClassDecl) {
9548  // C++ [class.copy]p4:
9549  //   If the class definition does not explicitly declare a copy
9550  //   constructor, one is declared implicitly.
9551  assert(ClassDecl->needsImplicitCopyConstructor());
9552
9553  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9554  if (DSM.isAlreadyBeingDeclared())
9555    return 0;
9556
9557  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9558  QualType ArgType = ClassType;
9559  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9560  if (Const)
9561    ArgType = ArgType.withConst();
9562  ArgType = Context.getLValueReferenceType(ArgType);
9563
9564  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9565                                                     CXXCopyConstructor,
9566                                                     Const);
9567
9568  DeclarationName Name
9569    = Context.DeclarationNames.getCXXConstructorName(
9570                                           Context.getCanonicalType(ClassType));
9571  SourceLocation ClassLoc = ClassDecl->getLocation();
9572  DeclarationNameInfo NameInfo(Name, ClassLoc);
9573
9574  //   An implicitly-declared copy constructor is an inline public
9575  //   member of its class.
9576  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9577      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9578      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9579      Constexpr);
9580  CopyConstructor->setAccess(AS_public);
9581  CopyConstructor->setDefaulted();
9582
9583  // Build an exception specification pointing back at this member.
9584  FunctionProtoType::ExtProtoInfo EPI;
9585  EPI.ExceptionSpecType = EST_Unevaluated;
9586  EPI.ExceptionSpecDecl = CopyConstructor;
9587  CopyConstructor->setType(
9588      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9589
9590  // Add the parameter to the constructor.
9591  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9592                                               ClassLoc, ClassLoc,
9593                                               /*IdentifierInfo=*/0,
9594                                               ArgType, /*TInfo=*/0,
9595                                               SC_None, 0);
9596  CopyConstructor->setParams(FromParam);
9597
9598  CopyConstructor->setTrivial(
9599    ClassDecl->needsOverloadResolutionForCopyConstructor()
9600      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9601      : ClassDecl->hasTrivialCopyConstructor());
9602
9603  // C++11 [class.copy]p8:
9604  //   ... If the class definition does not explicitly declare a copy
9605  //   constructor, there is no user-declared move constructor, and there is no
9606  //   user-declared move assignment operator, a copy constructor is implicitly
9607  //   declared as defaulted.
9608  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9609    SetDeclDeleted(CopyConstructor, ClassLoc);
9610
9611  // Note that we have declared this constructor.
9612  ++ASTContext::NumImplicitCopyConstructorsDeclared;
9613
9614  if (Scope *S = getScopeForContext(ClassDecl))
9615    PushOnScopeChains(CopyConstructor, S, false);
9616  ClassDecl->addDecl(CopyConstructor);
9617
9618  return CopyConstructor;
9619}
9620
9621void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9622                                   CXXConstructorDecl *CopyConstructor) {
9623  assert((CopyConstructor->isDefaulted() &&
9624          CopyConstructor->isCopyConstructor() &&
9625          !CopyConstructor->doesThisDeclarationHaveABody() &&
9626          !CopyConstructor->isDeleted()) &&
9627         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9628
9629  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9630  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9631
9632  SynthesizedFunctionScope Scope(*this, CopyConstructor);
9633  DiagnosticErrorTrap Trap(Diags);
9634
9635  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9636      Trap.hasErrorOccurred()) {
9637    Diag(CurrentLocation, diag::note_member_synthesized_at)
9638      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9639    CopyConstructor->setInvalidDecl();
9640  }  else {
9641    Sema::CompoundScopeRAII CompoundScope(*this);
9642    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9643                                               CopyConstructor->getLocation(),
9644                                               MultiStmtArg(),
9645                                               /*isStmtExpr=*/false)
9646                                                              .takeAs<Stmt>());
9647    CopyConstructor->setImplicitlyDefined(true);
9648  }
9649
9650  CopyConstructor->setUsed();
9651  if (ASTMutationListener *L = getASTMutationListener()) {
9652    L->CompletedImplicitDefinition(CopyConstructor);
9653  }
9654}
9655
9656Sema::ImplicitExceptionSpecification
9657Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9658  CXXRecordDecl *ClassDecl = MD->getParent();
9659
9660  // C++ [except.spec]p14:
9661  //   An implicitly declared special member function (Clause 12) shall have an
9662  //   exception-specification. [...]
9663  ImplicitExceptionSpecification ExceptSpec(*this);
9664  if (ClassDecl->isInvalidDecl())
9665    return ExceptSpec;
9666
9667  // Direct base-class constructors.
9668  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9669                                       BEnd = ClassDecl->bases_end();
9670       B != BEnd; ++B) {
9671    if (B->isVirtual()) // Handled below.
9672      continue;
9673
9674    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9675      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9676      CXXConstructorDecl *Constructor =
9677          LookupMovingConstructor(BaseClassDecl, 0);
9678      // If this is a deleted function, add it anyway. This might be conformant
9679      // with the standard. This might not. I'm not sure. It might not matter.
9680      if (Constructor)
9681        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9682    }
9683  }
9684
9685  // Virtual base-class constructors.
9686  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9687                                       BEnd = ClassDecl->vbases_end();
9688       B != BEnd; ++B) {
9689    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9690      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9691      CXXConstructorDecl *Constructor =
9692          LookupMovingConstructor(BaseClassDecl, 0);
9693      // If this is a deleted function, add it anyway. This might be conformant
9694      // with the standard. This might not. I'm not sure. It might not matter.
9695      if (Constructor)
9696        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9697    }
9698  }
9699
9700  // Field constructors.
9701  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9702                               FEnd = ClassDecl->field_end();
9703       F != FEnd; ++F) {
9704    QualType FieldType = Context.getBaseElementType(F->getType());
9705    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9706      CXXConstructorDecl *Constructor =
9707          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9708      // If this is a deleted function, add it anyway. This might be conformant
9709      // with the standard. This might not. I'm not sure. It might not matter.
9710      // In particular, the problem is that this function never gets called. It
9711      // might just be ill-formed because this function attempts to refer to
9712      // a deleted function here.
9713      if (Constructor)
9714        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9715    }
9716  }
9717
9718  return ExceptSpec;
9719}
9720
9721CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9722                                                    CXXRecordDecl *ClassDecl) {
9723  // C++11 [class.copy]p9:
9724  //   If the definition of a class X does not explicitly declare a move
9725  //   constructor, one will be implicitly declared as defaulted if and only if:
9726  //
9727  //   - [first 4 bullets]
9728  assert(ClassDecl->needsImplicitMoveConstructor());
9729
9730  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9731  if (DSM.isAlreadyBeingDeclared())
9732    return 0;
9733
9734  // [Checked after we build the declaration]
9735  //   - the move assignment operator would not be implicitly defined as
9736  //     deleted,
9737
9738  // [DR1402]:
9739  //   - each of X's non-static data members and direct or virtual base classes
9740  //     has a type that either has a move constructor or is trivially copyable.
9741  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9742    ClassDecl->setFailedImplicitMoveConstructor();
9743    return 0;
9744  }
9745
9746  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9747  QualType ArgType = Context.getRValueReferenceType(ClassType);
9748
9749  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9750                                                     CXXMoveConstructor,
9751                                                     false);
9752
9753  DeclarationName Name
9754    = Context.DeclarationNames.getCXXConstructorName(
9755                                           Context.getCanonicalType(ClassType));
9756  SourceLocation ClassLoc = ClassDecl->getLocation();
9757  DeclarationNameInfo NameInfo(Name, ClassLoc);
9758
9759  // C++11 [class.copy]p11:
9760  //   An implicitly-declared copy/move constructor is an inline public
9761  //   member of its class.
9762  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9763      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9764      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9765      Constexpr);
9766  MoveConstructor->setAccess(AS_public);
9767  MoveConstructor->setDefaulted();
9768
9769  // Build an exception specification pointing back at this member.
9770  FunctionProtoType::ExtProtoInfo EPI;
9771  EPI.ExceptionSpecType = EST_Unevaluated;
9772  EPI.ExceptionSpecDecl = MoveConstructor;
9773  MoveConstructor->setType(
9774      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9775
9776  // Add the parameter to the constructor.
9777  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9778                                               ClassLoc, ClassLoc,
9779                                               /*IdentifierInfo=*/0,
9780                                               ArgType, /*TInfo=*/0,
9781                                               SC_None, 0);
9782  MoveConstructor->setParams(FromParam);
9783
9784  MoveConstructor->setTrivial(
9785    ClassDecl->needsOverloadResolutionForMoveConstructor()
9786      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9787      : ClassDecl->hasTrivialMoveConstructor());
9788
9789  // C++0x [class.copy]p9:
9790  //   If the definition of a class X does not explicitly declare a move
9791  //   constructor, one will be implicitly declared as defaulted if and only if:
9792  //   [...]
9793  //   - the move constructor would not be implicitly defined as deleted.
9794  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9795    // Cache this result so that we don't try to generate this over and over
9796    // on every lookup, leaking memory and wasting time.
9797    ClassDecl->setFailedImplicitMoveConstructor();
9798    return 0;
9799  }
9800
9801  // Note that we have declared this constructor.
9802  ++ASTContext::NumImplicitMoveConstructorsDeclared;
9803
9804  if (Scope *S = getScopeForContext(ClassDecl))
9805    PushOnScopeChains(MoveConstructor, S, false);
9806  ClassDecl->addDecl(MoveConstructor);
9807
9808  return MoveConstructor;
9809}
9810
9811void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9812                                   CXXConstructorDecl *MoveConstructor) {
9813  assert((MoveConstructor->isDefaulted() &&
9814          MoveConstructor->isMoveConstructor() &&
9815          !MoveConstructor->doesThisDeclarationHaveABody() &&
9816          !MoveConstructor->isDeleted()) &&
9817         "DefineImplicitMoveConstructor - call it for implicit move ctor");
9818
9819  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9820  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9821
9822  SynthesizedFunctionScope Scope(*this, MoveConstructor);
9823  DiagnosticErrorTrap Trap(Diags);
9824
9825  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9826      Trap.hasErrorOccurred()) {
9827    Diag(CurrentLocation, diag::note_member_synthesized_at)
9828      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9829    MoveConstructor->setInvalidDecl();
9830  }  else {
9831    Sema::CompoundScopeRAII CompoundScope(*this);
9832    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9833                                               MoveConstructor->getLocation(),
9834                                               MultiStmtArg(),
9835                                               /*isStmtExpr=*/false)
9836                                                              .takeAs<Stmt>());
9837    MoveConstructor->setImplicitlyDefined(true);
9838  }
9839
9840  MoveConstructor->setUsed();
9841
9842  if (ASTMutationListener *L = getASTMutationListener()) {
9843    L->CompletedImplicitDefinition(MoveConstructor);
9844  }
9845}
9846
9847bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9848  return FD->isDeleted() &&
9849         (FD->isDefaulted() || FD->isImplicit()) &&
9850         isa<CXXMethodDecl>(FD);
9851}
9852
9853/// \brief Mark the call operator of the given lambda closure type as "used".
9854static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9855  CXXMethodDecl *CallOperator
9856    = cast<CXXMethodDecl>(
9857        Lambda->lookup(
9858          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
9859  CallOperator->setReferenced();
9860  CallOperator->setUsed();
9861}
9862
9863void Sema::DefineImplicitLambdaToFunctionPointerConversion(
9864       SourceLocation CurrentLocation,
9865       CXXConversionDecl *Conv)
9866{
9867  CXXRecordDecl *Lambda = Conv->getParent();
9868
9869  // Make sure that the lambda call operator is marked used.
9870  markLambdaCallOperatorUsed(*this, Lambda);
9871
9872  Conv->setUsed();
9873
9874  SynthesizedFunctionScope Scope(*this, Conv);
9875  DiagnosticErrorTrap Trap(Diags);
9876
9877  // Return the address of the __invoke function.
9878  DeclarationName InvokeName = &Context.Idents.get("__invoke");
9879  CXXMethodDecl *Invoke
9880    = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
9881  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
9882                                       VK_LValue, Conv->getLocation()).take();
9883  assert(FunctionRef && "Can't refer to __invoke function?");
9884  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
9885  Conv->setBody(new (Context) CompoundStmt(Context, Return,
9886                                           Conv->getLocation(),
9887                                           Conv->getLocation()));
9888
9889  // Fill in the __invoke function with a dummy implementation. IR generation
9890  // will fill in the actual details.
9891  Invoke->setUsed();
9892  Invoke->setReferenced();
9893  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
9894
9895  if (ASTMutationListener *L = getASTMutationListener()) {
9896    L->CompletedImplicitDefinition(Conv);
9897    L->CompletedImplicitDefinition(Invoke);
9898  }
9899}
9900
9901void Sema::DefineImplicitLambdaToBlockPointerConversion(
9902       SourceLocation CurrentLocation,
9903       CXXConversionDecl *Conv)
9904{
9905  Conv->setUsed();
9906
9907  SynthesizedFunctionScope Scope(*this, Conv);
9908  DiagnosticErrorTrap Trap(Diags);
9909
9910  // Copy-initialize the lambda object as needed to capture it.
9911  Expr *This = ActOnCXXThis(CurrentLocation).take();
9912  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9913
9914  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9915                                                        Conv->getLocation(),
9916                                                        Conv, DerefThis);
9917
9918  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9919  // behavior.  Note that only the general conversion function does this
9920  // (since it's unusable otherwise); in the case where we inline the
9921  // block literal, it has block literal lifetime semantics.
9922  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9923    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9924                                          CK_CopyAndAutoreleaseBlockObject,
9925                                          BuildBlock.get(), 0, VK_RValue);
9926
9927  if (BuildBlock.isInvalid()) {
9928    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9929    Conv->setInvalidDecl();
9930    return;
9931  }
9932
9933  // Create the return statement that returns the block from the conversion
9934  // function.
9935  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9936  if (Return.isInvalid()) {
9937    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9938    Conv->setInvalidDecl();
9939    return;
9940  }
9941
9942  // Set the body of the conversion function.
9943  Stmt *ReturnS = Return.take();
9944  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
9945                                           Conv->getLocation(),
9946                                           Conv->getLocation()));
9947
9948  // We're done; notify the mutation listener, if any.
9949  if (ASTMutationListener *L = getASTMutationListener()) {
9950    L->CompletedImplicitDefinition(Conv);
9951  }
9952}
9953
9954/// \brief Determine whether the given list arguments contains exactly one
9955/// "real" (non-default) argument.
9956static bool hasOneRealArgument(MultiExprArg Args) {
9957  switch (Args.size()) {
9958  case 0:
9959    return false;
9960
9961  default:
9962    if (!Args[1]->isDefaultArgument())
9963      return false;
9964
9965    // fall through
9966  case 1:
9967    return !Args[0]->isDefaultArgument();
9968  }
9969
9970  return false;
9971}
9972
9973ExprResult
9974Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9975                            CXXConstructorDecl *Constructor,
9976                            MultiExprArg ExprArgs,
9977                            bool HadMultipleCandidates,
9978                            bool IsListInitialization,
9979                            bool RequiresZeroInit,
9980                            unsigned ConstructKind,
9981                            SourceRange ParenRange) {
9982  bool Elidable = false;
9983
9984  // C++0x [class.copy]p34:
9985  //   When certain criteria are met, an implementation is allowed to
9986  //   omit the copy/move construction of a class object, even if the
9987  //   copy/move constructor and/or destructor for the object have
9988  //   side effects. [...]
9989  //     - when a temporary class object that has not been bound to a
9990  //       reference (12.2) would be copied/moved to a class object
9991  //       with the same cv-unqualified type, the copy/move operation
9992  //       can be omitted by constructing the temporary object
9993  //       directly into the target of the omitted copy/move
9994  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9995      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9996    Expr *SubExpr = ExprArgs[0];
9997    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9998  }
9999
10000  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10001                               Elidable, ExprArgs, HadMultipleCandidates,
10002                               IsListInitialization, RequiresZeroInit,
10003                               ConstructKind, ParenRange);
10004}
10005
10006/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10007/// including handling of its default argument expressions.
10008ExprResult
10009Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10010                            CXXConstructorDecl *Constructor, bool Elidable,
10011                            MultiExprArg ExprArgs,
10012                            bool HadMultipleCandidates,
10013                            bool IsListInitialization,
10014                            bool RequiresZeroInit,
10015                            unsigned ConstructKind,
10016                            SourceRange ParenRange) {
10017  MarkFunctionReferenced(ConstructLoc, Constructor);
10018  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10019                                        Constructor, Elidable, ExprArgs,
10020                                        HadMultipleCandidates,
10021                                        IsListInitialization, RequiresZeroInit,
10022              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10023                                        ParenRange));
10024}
10025
10026void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10027  if (VD->isInvalidDecl()) return;
10028
10029  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10030  if (ClassDecl->isInvalidDecl()) return;
10031  if (ClassDecl->hasIrrelevantDestructor()) return;
10032  if (ClassDecl->isDependentContext()) return;
10033
10034  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10035  MarkFunctionReferenced(VD->getLocation(), Destructor);
10036  CheckDestructorAccess(VD->getLocation(), Destructor,
10037                        PDiag(diag::err_access_dtor_var)
10038                        << VD->getDeclName()
10039                        << VD->getType());
10040  DiagnoseUseOfDecl(Destructor, VD->getLocation());
10041
10042  if (!VD->hasGlobalStorage()) return;
10043
10044  // Emit warning for non-trivial dtor in global scope (a real global,
10045  // class-static, function-static).
10046  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10047
10048  // TODO: this should be re-enabled for static locals by !CXAAtExit
10049  if (!VD->isStaticLocal())
10050    Diag(VD->getLocation(), diag::warn_global_destructor);
10051}
10052
10053/// \brief Given a constructor and the set of arguments provided for the
10054/// constructor, convert the arguments and add any required default arguments
10055/// to form a proper call to this constructor.
10056///
10057/// \returns true if an error occurred, false otherwise.
10058bool
10059Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10060                              MultiExprArg ArgsPtr,
10061                              SourceLocation Loc,
10062                              SmallVectorImpl<Expr*> &ConvertedArgs,
10063                              bool AllowExplicit,
10064                              bool IsListInitialization) {
10065  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10066  unsigned NumArgs = ArgsPtr.size();
10067  Expr **Args = ArgsPtr.data();
10068
10069  const FunctionProtoType *Proto
10070    = Constructor->getType()->getAs<FunctionProtoType>();
10071  assert(Proto && "Constructor without a prototype?");
10072  unsigned NumArgsInProto = Proto->getNumArgs();
10073
10074  // If too few arguments are available, we'll fill in the rest with defaults.
10075  if (NumArgs < NumArgsInProto)
10076    ConvertedArgs.reserve(NumArgsInProto);
10077  else
10078    ConvertedArgs.reserve(NumArgs);
10079
10080  VariadicCallType CallType =
10081    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10082  SmallVector<Expr *, 8> AllArgs;
10083  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10084                                        Proto, 0,
10085                                        llvm::makeArrayRef(Args, NumArgs),
10086                                        AllArgs,
10087                                        CallType, AllowExplicit,
10088                                        IsListInitialization);
10089  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10090
10091  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10092
10093  CheckConstructorCall(Constructor,
10094                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10095                                                        AllArgs.size()),
10096                       Proto, Loc);
10097
10098  return Invalid;
10099}
10100
10101static inline bool
10102CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10103                                       const FunctionDecl *FnDecl) {
10104  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10105  if (isa<NamespaceDecl>(DC)) {
10106    return SemaRef.Diag(FnDecl->getLocation(),
10107                        diag::err_operator_new_delete_declared_in_namespace)
10108      << FnDecl->getDeclName();
10109  }
10110
10111  if (isa<TranslationUnitDecl>(DC) &&
10112      FnDecl->getStorageClass() == SC_Static) {
10113    return SemaRef.Diag(FnDecl->getLocation(),
10114                        diag::err_operator_new_delete_declared_static)
10115      << FnDecl->getDeclName();
10116  }
10117
10118  return false;
10119}
10120
10121static inline bool
10122CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10123                            CanQualType ExpectedResultType,
10124                            CanQualType ExpectedFirstParamType,
10125                            unsigned DependentParamTypeDiag,
10126                            unsigned InvalidParamTypeDiag) {
10127  QualType ResultType =
10128    FnDecl->getType()->getAs<FunctionType>()->getResultType();
10129
10130  // Check that the result type is not dependent.
10131  if (ResultType->isDependentType())
10132    return SemaRef.Diag(FnDecl->getLocation(),
10133                        diag::err_operator_new_delete_dependent_result_type)
10134    << FnDecl->getDeclName() << ExpectedResultType;
10135
10136  // Check that the result type is what we expect.
10137  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10138    return SemaRef.Diag(FnDecl->getLocation(),
10139                        diag::err_operator_new_delete_invalid_result_type)
10140    << FnDecl->getDeclName() << ExpectedResultType;
10141
10142  // A function template must have at least 2 parameters.
10143  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10144    return SemaRef.Diag(FnDecl->getLocation(),
10145                      diag::err_operator_new_delete_template_too_few_parameters)
10146        << FnDecl->getDeclName();
10147
10148  // The function decl must have at least 1 parameter.
10149  if (FnDecl->getNumParams() == 0)
10150    return SemaRef.Diag(FnDecl->getLocation(),
10151                        diag::err_operator_new_delete_too_few_parameters)
10152      << FnDecl->getDeclName();
10153
10154  // Check the first parameter type is not dependent.
10155  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10156  if (FirstParamType->isDependentType())
10157    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10158      << FnDecl->getDeclName() << ExpectedFirstParamType;
10159
10160  // Check that the first parameter type is what we expect.
10161  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10162      ExpectedFirstParamType)
10163    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10164    << FnDecl->getDeclName() << ExpectedFirstParamType;
10165
10166  return false;
10167}
10168
10169static bool
10170CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10171  // C++ [basic.stc.dynamic.allocation]p1:
10172  //   A program is ill-formed if an allocation function is declared in a
10173  //   namespace scope other than global scope or declared static in global
10174  //   scope.
10175  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10176    return true;
10177
10178  CanQualType SizeTy =
10179    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10180
10181  // C++ [basic.stc.dynamic.allocation]p1:
10182  //  The return type shall be void*. The first parameter shall have type
10183  //  std::size_t.
10184  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10185                                  SizeTy,
10186                                  diag::err_operator_new_dependent_param_type,
10187                                  diag::err_operator_new_param_type))
10188    return true;
10189
10190  // C++ [basic.stc.dynamic.allocation]p1:
10191  //  The first parameter shall not have an associated default argument.
10192  if (FnDecl->getParamDecl(0)->hasDefaultArg())
10193    return SemaRef.Diag(FnDecl->getLocation(),
10194                        diag::err_operator_new_default_arg)
10195      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10196
10197  return false;
10198}
10199
10200static bool
10201CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10202  // C++ [basic.stc.dynamic.deallocation]p1:
10203  //   A program is ill-formed if deallocation functions are declared in a
10204  //   namespace scope other than global scope or declared static in global
10205  //   scope.
10206  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10207    return true;
10208
10209  // C++ [basic.stc.dynamic.deallocation]p2:
10210  //   Each deallocation function shall return void and its first parameter
10211  //   shall be void*.
10212  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10213                                  SemaRef.Context.VoidPtrTy,
10214                                 diag::err_operator_delete_dependent_param_type,
10215                                 diag::err_operator_delete_param_type))
10216    return true;
10217
10218  return false;
10219}
10220
10221/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10222/// of this overloaded operator is well-formed. If so, returns false;
10223/// otherwise, emits appropriate diagnostics and returns true.
10224bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10225  assert(FnDecl && FnDecl->isOverloadedOperator() &&
10226         "Expected an overloaded operator declaration");
10227
10228  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10229
10230  // C++ [over.oper]p5:
10231  //   The allocation and deallocation functions, operator new,
10232  //   operator new[], operator delete and operator delete[], are
10233  //   described completely in 3.7.3. The attributes and restrictions
10234  //   found in the rest of this subclause do not apply to them unless
10235  //   explicitly stated in 3.7.3.
10236  if (Op == OO_Delete || Op == OO_Array_Delete)
10237    return CheckOperatorDeleteDeclaration(*this, FnDecl);
10238
10239  if (Op == OO_New || Op == OO_Array_New)
10240    return CheckOperatorNewDeclaration(*this, FnDecl);
10241
10242  // C++ [over.oper]p6:
10243  //   An operator function shall either be a non-static member
10244  //   function or be a non-member function and have at least one
10245  //   parameter whose type is a class, a reference to a class, an
10246  //   enumeration, or a reference to an enumeration.
10247  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10248    if (MethodDecl->isStatic())
10249      return Diag(FnDecl->getLocation(),
10250                  diag::err_operator_overload_static) << FnDecl->getDeclName();
10251  } else {
10252    bool ClassOrEnumParam = false;
10253    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10254                                   ParamEnd = FnDecl->param_end();
10255         Param != ParamEnd; ++Param) {
10256      QualType ParamType = (*Param)->getType().getNonReferenceType();
10257      if (ParamType->isDependentType() || ParamType->isRecordType() ||
10258          ParamType->isEnumeralType()) {
10259        ClassOrEnumParam = true;
10260        break;
10261      }
10262    }
10263
10264    if (!ClassOrEnumParam)
10265      return Diag(FnDecl->getLocation(),
10266                  diag::err_operator_overload_needs_class_or_enum)
10267        << FnDecl->getDeclName();
10268  }
10269
10270  // C++ [over.oper]p8:
10271  //   An operator function cannot have default arguments (8.3.6),
10272  //   except where explicitly stated below.
10273  //
10274  // Only the function-call operator allows default arguments
10275  // (C++ [over.call]p1).
10276  if (Op != OO_Call) {
10277    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10278         Param != FnDecl->param_end(); ++Param) {
10279      if ((*Param)->hasDefaultArg())
10280        return Diag((*Param)->getLocation(),
10281                    diag::err_operator_overload_default_arg)
10282          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10283    }
10284  }
10285
10286  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10287    { false, false, false }
10288#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10289    , { Unary, Binary, MemberOnly }
10290#include "clang/Basic/OperatorKinds.def"
10291  };
10292
10293  bool CanBeUnaryOperator = OperatorUses[Op][0];
10294  bool CanBeBinaryOperator = OperatorUses[Op][1];
10295  bool MustBeMemberOperator = OperatorUses[Op][2];
10296
10297  // C++ [over.oper]p8:
10298  //   [...] Operator functions cannot have more or fewer parameters
10299  //   than the number required for the corresponding operator, as
10300  //   described in the rest of this subclause.
10301  unsigned NumParams = FnDecl->getNumParams()
10302                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10303  if (Op != OO_Call &&
10304      ((NumParams == 1 && !CanBeUnaryOperator) ||
10305       (NumParams == 2 && !CanBeBinaryOperator) ||
10306       (NumParams < 1) || (NumParams > 2))) {
10307    // We have the wrong number of parameters.
10308    unsigned ErrorKind;
10309    if (CanBeUnaryOperator && CanBeBinaryOperator) {
10310      ErrorKind = 2;  // 2 -> unary or binary.
10311    } else if (CanBeUnaryOperator) {
10312      ErrorKind = 0;  // 0 -> unary
10313    } else {
10314      assert(CanBeBinaryOperator &&
10315             "All non-call overloaded operators are unary or binary!");
10316      ErrorKind = 1;  // 1 -> binary
10317    }
10318
10319    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10320      << FnDecl->getDeclName() << NumParams << ErrorKind;
10321  }
10322
10323  // Overloaded operators other than operator() cannot be variadic.
10324  if (Op != OO_Call &&
10325      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10326    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10327      << FnDecl->getDeclName();
10328  }
10329
10330  // Some operators must be non-static member functions.
10331  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10332    return Diag(FnDecl->getLocation(),
10333                diag::err_operator_overload_must_be_member)
10334      << FnDecl->getDeclName();
10335  }
10336
10337  // C++ [over.inc]p1:
10338  //   The user-defined function called operator++ implements the
10339  //   prefix and postfix ++ operator. If this function is a member
10340  //   function with no parameters, or a non-member function with one
10341  //   parameter of class or enumeration type, it defines the prefix
10342  //   increment operator ++ for objects of that type. If the function
10343  //   is a member function with one parameter (which shall be of type
10344  //   int) or a non-member function with two parameters (the second
10345  //   of which shall be of type int), it defines the postfix
10346  //   increment operator ++ for objects of that type.
10347  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10348    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10349    bool ParamIsInt = false;
10350    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10351      ParamIsInt = BT->getKind() == BuiltinType::Int;
10352
10353    if (!ParamIsInt)
10354      return Diag(LastParam->getLocation(),
10355                  diag::err_operator_overload_post_incdec_must_be_int)
10356        << LastParam->getType() << (Op == OO_MinusMinus);
10357  }
10358
10359  return false;
10360}
10361
10362/// CheckLiteralOperatorDeclaration - Check whether the declaration
10363/// of this literal operator function is well-formed. If so, returns
10364/// false; otherwise, emits appropriate diagnostics and returns true.
10365bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10366  if (isa<CXXMethodDecl>(FnDecl)) {
10367    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10368      << FnDecl->getDeclName();
10369    return true;
10370  }
10371
10372  if (FnDecl->isExternC()) {
10373    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10374    return true;
10375  }
10376
10377  bool Valid = false;
10378
10379  // This might be the definition of a literal operator template.
10380  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10381  // This might be a specialization of a literal operator template.
10382  if (!TpDecl)
10383    TpDecl = FnDecl->getPrimaryTemplate();
10384
10385  // template <char...> type operator "" name() is the only valid template
10386  // signature, and the only valid signature with no parameters.
10387  if (TpDecl) {
10388    if (FnDecl->param_size() == 0) {
10389      // Must have only one template parameter
10390      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10391      if (Params->size() == 1) {
10392        NonTypeTemplateParmDecl *PmDecl =
10393          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10394
10395        // The template parameter must be a char parameter pack.
10396        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10397            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10398          Valid = true;
10399      }
10400    }
10401  } else if (FnDecl->param_size()) {
10402    // Check the first parameter
10403    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10404
10405    QualType T = (*Param)->getType().getUnqualifiedType();
10406
10407    // unsigned long long int, long double, and any character type are allowed
10408    // as the only parameters.
10409    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10410        Context.hasSameType(T, Context.LongDoubleTy) ||
10411        Context.hasSameType(T, Context.CharTy) ||
10412        Context.hasSameType(T, Context.WideCharTy) ||
10413        Context.hasSameType(T, Context.Char16Ty) ||
10414        Context.hasSameType(T, Context.Char32Ty)) {
10415      if (++Param == FnDecl->param_end())
10416        Valid = true;
10417      goto FinishedParams;
10418    }
10419
10420    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10421    const PointerType *PT = T->getAs<PointerType>();
10422    if (!PT)
10423      goto FinishedParams;
10424    T = PT->getPointeeType();
10425    if (!T.isConstQualified() || T.isVolatileQualified())
10426      goto FinishedParams;
10427    T = T.getUnqualifiedType();
10428
10429    // Move on to the second parameter;
10430    ++Param;
10431
10432    // If there is no second parameter, the first must be a const char *
10433    if (Param == FnDecl->param_end()) {
10434      if (Context.hasSameType(T, Context.CharTy))
10435        Valid = true;
10436      goto FinishedParams;
10437    }
10438
10439    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10440    // are allowed as the first parameter to a two-parameter function
10441    if (!(Context.hasSameType(T, Context.CharTy) ||
10442          Context.hasSameType(T, Context.WideCharTy) ||
10443          Context.hasSameType(T, Context.Char16Ty) ||
10444          Context.hasSameType(T, Context.Char32Ty)))
10445      goto FinishedParams;
10446
10447    // The second and final parameter must be an std::size_t
10448    T = (*Param)->getType().getUnqualifiedType();
10449    if (Context.hasSameType(T, Context.getSizeType()) &&
10450        ++Param == FnDecl->param_end())
10451      Valid = true;
10452  }
10453
10454  // FIXME: This diagnostic is absolutely terrible.
10455FinishedParams:
10456  if (!Valid) {
10457    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10458      << FnDecl->getDeclName();
10459    return true;
10460  }
10461
10462  // A parameter-declaration-clause containing a default argument is not
10463  // equivalent to any of the permitted forms.
10464  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10465                                    ParamEnd = FnDecl->param_end();
10466       Param != ParamEnd; ++Param) {
10467    if ((*Param)->hasDefaultArg()) {
10468      Diag((*Param)->getDefaultArgRange().getBegin(),
10469           diag::err_literal_operator_default_argument)
10470        << (*Param)->getDefaultArgRange();
10471      break;
10472    }
10473  }
10474
10475  StringRef LiteralName
10476    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10477  if (LiteralName[0] != '_') {
10478    // C++11 [usrlit.suffix]p1:
10479    //   Literal suffix identifiers that do not start with an underscore
10480    //   are reserved for future standardization.
10481    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10482  }
10483
10484  return false;
10485}
10486
10487/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10488/// linkage specification, including the language and (if present)
10489/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10490/// the location of the language string literal, which is provided
10491/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10492/// the '{' brace. Otherwise, this linkage specification does not
10493/// have any braces.
10494Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10495                                           SourceLocation LangLoc,
10496                                           StringRef Lang,
10497                                           SourceLocation LBraceLoc) {
10498  LinkageSpecDecl::LanguageIDs Language;
10499  if (Lang == "\"C\"")
10500    Language = LinkageSpecDecl::lang_c;
10501  else if (Lang == "\"C++\"")
10502    Language = LinkageSpecDecl::lang_cxx;
10503  else {
10504    Diag(LangLoc, diag::err_bad_language);
10505    return 0;
10506  }
10507
10508  // FIXME: Add all the various semantics of linkage specifications
10509
10510  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10511                                               ExternLoc, LangLoc, Language,
10512                                               LBraceLoc.isValid());
10513  CurContext->addDecl(D);
10514  PushDeclContext(S, D);
10515  return D;
10516}
10517
10518/// ActOnFinishLinkageSpecification - Complete the definition of
10519/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10520/// valid, it's the position of the closing '}' brace in a linkage
10521/// specification that uses braces.
10522Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10523                                            Decl *LinkageSpec,
10524                                            SourceLocation RBraceLoc) {
10525  if (LinkageSpec) {
10526    if (RBraceLoc.isValid()) {
10527      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10528      LSDecl->setRBraceLoc(RBraceLoc);
10529    }
10530    PopDeclContext();
10531  }
10532  return LinkageSpec;
10533}
10534
10535Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10536                                  AttributeList *AttrList,
10537                                  SourceLocation SemiLoc) {
10538  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10539  // Attribute declarations appertain to empty declaration so we handle
10540  // them here.
10541  if (AttrList)
10542    ProcessDeclAttributeList(S, ED, AttrList);
10543
10544  CurContext->addDecl(ED);
10545  return ED;
10546}
10547
10548/// \brief Perform semantic analysis for the variable declaration that
10549/// occurs within a C++ catch clause, returning the newly-created
10550/// variable.
10551VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10552                                         TypeSourceInfo *TInfo,
10553                                         SourceLocation StartLoc,
10554                                         SourceLocation Loc,
10555                                         IdentifierInfo *Name) {
10556  bool Invalid = false;
10557  QualType ExDeclType = TInfo->getType();
10558
10559  // Arrays and functions decay.
10560  if (ExDeclType->isArrayType())
10561    ExDeclType = Context.getArrayDecayedType(ExDeclType);
10562  else if (ExDeclType->isFunctionType())
10563    ExDeclType = Context.getPointerType(ExDeclType);
10564
10565  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10566  // The exception-declaration shall not denote a pointer or reference to an
10567  // incomplete type, other than [cv] void*.
10568  // N2844 forbids rvalue references.
10569  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10570    Diag(Loc, diag::err_catch_rvalue_ref);
10571    Invalid = true;
10572  }
10573
10574  QualType BaseType = ExDeclType;
10575  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10576  unsigned DK = diag::err_catch_incomplete;
10577  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10578    BaseType = Ptr->getPointeeType();
10579    Mode = 1;
10580    DK = diag::err_catch_incomplete_ptr;
10581  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10582    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10583    BaseType = Ref->getPointeeType();
10584    Mode = 2;
10585    DK = diag::err_catch_incomplete_ref;
10586  }
10587  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10588      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10589    Invalid = true;
10590
10591  if (!Invalid && !ExDeclType->isDependentType() &&
10592      RequireNonAbstractType(Loc, ExDeclType,
10593                             diag::err_abstract_type_in_decl,
10594                             AbstractVariableType))
10595    Invalid = true;
10596
10597  // Only the non-fragile NeXT runtime currently supports C++ catches
10598  // of ObjC types, and no runtime supports catching ObjC types by value.
10599  if (!Invalid && getLangOpts().ObjC1) {
10600    QualType T = ExDeclType;
10601    if (const ReferenceType *RT = T->getAs<ReferenceType>())
10602      T = RT->getPointeeType();
10603
10604    if (T->isObjCObjectType()) {
10605      Diag(Loc, diag::err_objc_object_catch);
10606      Invalid = true;
10607    } else if (T->isObjCObjectPointerType()) {
10608      // FIXME: should this be a test for macosx-fragile specifically?
10609      if (getLangOpts().ObjCRuntime.isFragile())
10610        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10611    }
10612  }
10613
10614  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10615                                    ExDeclType, TInfo, SC_None);
10616  ExDecl->setExceptionVariable(true);
10617
10618  // In ARC, infer 'retaining' for variables of retainable type.
10619  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10620    Invalid = true;
10621
10622  if (!Invalid && !ExDeclType->isDependentType()) {
10623    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10624      // Insulate this from anything else we might currently be parsing.
10625      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10626
10627      // C++ [except.handle]p16:
10628      //   The object declared in an exception-declaration or, if the
10629      //   exception-declaration does not specify a name, a temporary (12.2) is
10630      //   copy-initialized (8.5) from the exception object. [...]
10631      //   The object is destroyed when the handler exits, after the destruction
10632      //   of any automatic objects initialized within the handler.
10633      //
10634      // We just pretend to initialize the object with itself, then make sure
10635      // it can be destroyed later.
10636      QualType initType = ExDeclType;
10637
10638      InitializedEntity entity =
10639        InitializedEntity::InitializeVariable(ExDecl);
10640      InitializationKind initKind =
10641        InitializationKind::CreateCopy(Loc, SourceLocation());
10642
10643      Expr *opaqueValue =
10644        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10645      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10646      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
10647      if (result.isInvalid())
10648        Invalid = true;
10649      else {
10650        // If the constructor used was non-trivial, set this as the
10651        // "initializer".
10652        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10653        if (!construct->getConstructor()->isTrivial()) {
10654          Expr *init = MaybeCreateExprWithCleanups(construct);
10655          ExDecl->setInit(init);
10656        }
10657
10658        // And make sure it's destructable.
10659        FinalizeVarWithDestructor(ExDecl, recordType);
10660      }
10661    }
10662  }
10663
10664  if (Invalid)
10665    ExDecl->setInvalidDecl();
10666
10667  return ExDecl;
10668}
10669
10670/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10671/// handler.
10672Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10673  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10674  bool Invalid = D.isInvalidType();
10675
10676  // Check for unexpanded parameter packs.
10677  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10678                                      UPPC_ExceptionType)) {
10679    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10680                                             D.getIdentifierLoc());
10681    Invalid = true;
10682  }
10683
10684  IdentifierInfo *II = D.getIdentifier();
10685  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10686                                             LookupOrdinaryName,
10687                                             ForRedeclaration)) {
10688    // The scope should be freshly made just for us. There is just no way
10689    // it contains any previous declaration.
10690    assert(!S->isDeclScope(PrevDecl));
10691    if (PrevDecl->isTemplateParameter()) {
10692      // Maybe we will complain about the shadowed template parameter.
10693      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10694      PrevDecl = 0;
10695    }
10696  }
10697
10698  if (D.getCXXScopeSpec().isSet() && !Invalid) {
10699    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10700      << D.getCXXScopeSpec().getRange();
10701    Invalid = true;
10702  }
10703
10704  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10705                                              D.getLocStart(),
10706                                              D.getIdentifierLoc(),
10707                                              D.getIdentifier());
10708  if (Invalid)
10709    ExDecl->setInvalidDecl();
10710
10711  // Add the exception declaration into this scope.
10712  if (II)
10713    PushOnScopeChains(ExDecl, S);
10714  else
10715    CurContext->addDecl(ExDecl);
10716
10717  ProcessDeclAttributes(S, ExDecl, D);
10718  return ExDecl;
10719}
10720
10721Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10722                                         Expr *AssertExpr,
10723                                         Expr *AssertMessageExpr,
10724                                         SourceLocation RParenLoc) {
10725  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10726
10727  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10728    return 0;
10729
10730  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10731                                      AssertMessage, RParenLoc, false);
10732}
10733
10734Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10735                                         Expr *AssertExpr,
10736                                         StringLiteral *AssertMessage,
10737                                         SourceLocation RParenLoc,
10738                                         bool Failed) {
10739  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10740      !Failed) {
10741    // In a static_assert-declaration, the constant-expression shall be a
10742    // constant expression that can be contextually converted to bool.
10743    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10744    if (Converted.isInvalid())
10745      Failed = true;
10746
10747    llvm::APSInt Cond;
10748    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10749          diag::err_static_assert_expression_is_not_constant,
10750          /*AllowFold=*/false).isInvalid())
10751      Failed = true;
10752
10753    if (!Failed && !Cond) {
10754      SmallString<256> MsgBuffer;
10755      llvm::raw_svector_ostream Msg(MsgBuffer);
10756      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10757      Diag(StaticAssertLoc, diag::err_static_assert_failed)
10758        << Msg.str() << AssertExpr->getSourceRange();
10759      Failed = true;
10760    }
10761  }
10762
10763  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10764                                        AssertExpr, AssertMessage, RParenLoc,
10765                                        Failed);
10766
10767  CurContext->addDecl(Decl);
10768  return Decl;
10769}
10770
10771/// \brief Perform semantic analysis of the given friend type declaration.
10772///
10773/// \returns A friend declaration that.
10774FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10775                                      SourceLocation FriendLoc,
10776                                      TypeSourceInfo *TSInfo) {
10777  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10778
10779  QualType T = TSInfo->getType();
10780  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10781
10782  // C++03 [class.friend]p2:
10783  //   An elaborated-type-specifier shall be used in a friend declaration
10784  //   for a class.*
10785  //
10786  //   * The class-key of the elaborated-type-specifier is required.
10787  if (!ActiveTemplateInstantiations.empty()) {
10788    // Do not complain about the form of friend template types during
10789    // template instantiation; we will already have complained when the
10790    // template was declared.
10791  } else {
10792    if (!T->isElaboratedTypeSpecifier()) {
10793      // If we evaluated the type to a record type, suggest putting
10794      // a tag in front.
10795      if (const RecordType *RT = T->getAs<RecordType>()) {
10796        RecordDecl *RD = RT->getDecl();
10797
10798        std::string InsertionText = std::string(" ") + RD->getKindName();
10799
10800        Diag(TypeRange.getBegin(),
10801             getLangOpts().CPlusPlus11 ?
10802               diag::warn_cxx98_compat_unelaborated_friend_type :
10803               diag::ext_unelaborated_friend_type)
10804          << (unsigned) RD->getTagKind()
10805          << T
10806          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10807                                        InsertionText);
10808      } else {
10809        Diag(FriendLoc,
10810             getLangOpts().CPlusPlus11 ?
10811               diag::warn_cxx98_compat_nonclass_type_friend :
10812               diag::ext_nonclass_type_friend)
10813          << T
10814          << TypeRange;
10815      }
10816    } else if (T->getAs<EnumType>()) {
10817      Diag(FriendLoc,
10818           getLangOpts().CPlusPlus11 ?
10819             diag::warn_cxx98_compat_enum_friend :
10820             diag::ext_enum_friend)
10821        << T
10822        << TypeRange;
10823    }
10824
10825    // C++11 [class.friend]p3:
10826    //   A friend declaration that does not declare a function shall have one
10827    //   of the following forms:
10828    //     friend elaborated-type-specifier ;
10829    //     friend simple-type-specifier ;
10830    //     friend typename-specifier ;
10831    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10832      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10833  }
10834
10835  //   If the type specifier in a friend declaration designates a (possibly
10836  //   cv-qualified) class type, that class is declared as a friend; otherwise,
10837  //   the friend declaration is ignored.
10838  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10839}
10840
10841/// Handle a friend tag declaration where the scope specifier was
10842/// templated.
10843Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10844                                    unsigned TagSpec, SourceLocation TagLoc,
10845                                    CXXScopeSpec &SS,
10846                                    IdentifierInfo *Name,
10847                                    SourceLocation NameLoc,
10848                                    AttributeList *Attr,
10849                                    MultiTemplateParamsArg TempParamLists) {
10850  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10851
10852  bool isExplicitSpecialization = false;
10853  bool Invalid = false;
10854
10855  if (TemplateParameterList *TemplateParams
10856        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
10857                                                  TempParamLists.data(),
10858                                                  TempParamLists.size(),
10859                                                  /*friend*/ true,
10860                                                  isExplicitSpecialization,
10861                                                  Invalid)) {
10862    if (TemplateParams->size() > 0) {
10863      // This is a declaration of a class template.
10864      if (Invalid)
10865        return 0;
10866
10867      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10868                                SS, Name, NameLoc, Attr,
10869                                TemplateParams, AS_public,
10870                                /*ModulePrivateLoc=*/SourceLocation(),
10871                                TempParamLists.size() - 1,
10872                                TempParamLists.data()).take();
10873    } else {
10874      // The "template<>" header is extraneous.
10875      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10876        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10877      isExplicitSpecialization = true;
10878    }
10879  }
10880
10881  if (Invalid) return 0;
10882
10883  bool isAllExplicitSpecializations = true;
10884  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
10885    if (TempParamLists[I]->size()) {
10886      isAllExplicitSpecializations = false;
10887      break;
10888    }
10889  }
10890
10891  // FIXME: don't ignore attributes.
10892
10893  // If it's explicit specializations all the way down, just forget
10894  // about the template header and build an appropriate non-templated
10895  // friend.  TODO: for source fidelity, remember the headers.
10896  if (isAllExplicitSpecializations) {
10897    if (SS.isEmpty()) {
10898      bool Owned = false;
10899      bool IsDependent = false;
10900      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10901                      Attr, AS_public,
10902                      /*ModulePrivateLoc=*/SourceLocation(),
10903                      MultiTemplateParamsArg(), Owned, IsDependent,
10904                      /*ScopedEnumKWLoc=*/SourceLocation(),
10905                      /*ScopedEnumUsesClassTag=*/false,
10906                      /*UnderlyingType=*/TypeResult());
10907    }
10908
10909    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10910    ElaboratedTypeKeyword Keyword
10911      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10912    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10913                                   *Name, NameLoc);
10914    if (T.isNull())
10915      return 0;
10916
10917    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10918    if (isa<DependentNameType>(T)) {
10919      DependentNameTypeLoc TL =
10920          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10921      TL.setElaboratedKeywordLoc(TagLoc);
10922      TL.setQualifierLoc(QualifierLoc);
10923      TL.setNameLoc(NameLoc);
10924    } else {
10925      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10926      TL.setElaboratedKeywordLoc(TagLoc);
10927      TL.setQualifierLoc(QualifierLoc);
10928      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
10929    }
10930
10931    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10932                                            TSI, FriendLoc, TempParamLists);
10933    Friend->setAccess(AS_public);
10934    CurContext->addDecl(Friend);
10935    return Friend;
10936  }
10937
10938  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10939
10940
10941
10942  // Handle the case of a templated-scope friend class.  e.g.
10943  //   template <class T> class A<T>::B;
10944  // FIXME: we don't support these right now.
10945  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10946  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10947  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10948  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10949  TL.setElaboratedKeywordLoc(TagLoc);
10950  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10951  TL.setNameLoc(NameLoc);
10952
10953  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10954                                          TSI, FriendLoc, TempParamLists);
10955  Friend->setAccess(AS_public);
10956  Friend->setUnsupportedFriend(true);
10957  CurContext->addDecl(Friend);
10958  return Friend;
10959}
10960
10961
10962/// Handle a friend type declaration.  This works in tandem with
10963/// ActOnTag.
10964///
10965/// Notes on friend class templates:
10966///
10967/// We generally treat friend class declarations as if they were
10968/// declaring a class.  So, for example, the elaborated type specifier
10969/// in a friend declaration is required to obey the restrictions of a
10970/// class-head (i.e. no typedefs in the scope chain), template
10971/// parameters are required to match up with simple template-ids, &c.
10972/// However, unlike when declaring a template specialization, it's
10973/// okay to refer to a template specialization without an empty
10974/// template parameter declaration, e.g.
10975///   friend class A<T>::B<unsigned>;
10976/// We permit this as a special case; if there are any template
10977/// parameters present at all, require proper matching, i.e.
10978///   template <> template \<class T> friend class A<int>::B;
10979Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10980                                MultiTemplateParamsArg TempParams) {
10981  SourceLocation Loc = DS.getLocStart();
10982
10983  assert(DS.isFriendSpecified());
10984  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10985
10986  // Try to convert the decl specifier to a type.  This works for
10987  // friend templates because ActOnTag never produces a ClassTemplateDecl
10988  // for a TUK_Friend.
10989  Declarator TheDeclarator(DS, Declarator::MemberContext);
10990  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10991  QualType T = TSI->getType();
10992  if (TheDeclarator.isInvalidType())
10993    return 0;
10994
10995  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10996    return 0;
10997
10998  // This is definitely an error in C++98.  It's probably meant to
10999  // be forbidden in C++0x, too, but the specification is just
11000  // poorly written.
11001  //
11002  // The problem is with declarations like the following:
11003  //   template <T> friend A<T>::foo;
11004  // where deciding whether a class C is a friend or not now hinges
11005  // on whether there exists an instantiation of A that causes
11006  // 'foo' to equal C.  There are restrictions on class-heads
11007  // (which we declare (by fiat) elaborated friend declarations to
11008  // be) that makes this tractable.
11009  //
11010  // FIXME: handle "template <> friend class A<T>;", which
11011  // is possibly well-formed?  Who even knows?
11012  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11013    Diag(Loc, diag::err_tagless_friend_type_template)
11014      << DS.getSourceRange();
11015    return 0;
11016  }
11017
11018  // C++98 [class.friend]p1: A friend of a class is a function
11019  //   or class that is not a member of the class . . .
11020  // This is fixed in DR77, which just barely didn't make the C++03
11021  // deadline.  It's also a very silly restriction that seriously
11022  // affects inner classes and which nobody else seems to implement;
11023  // thus we never diagnose it, not even in -pedantic.
11024  //
11025  // But note that we could warn about it: it's always useless to
11026  // friend one of your own members (it's not, however, worthless to
11027  // friend a member of an arbitrary specialization of your template).
11028
11029  Decl *D;
11030  if (unsigned NumTempParamLists = TempParams.size())
11031    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11032                                   NumTempParamLists,
11033                                   TempParams.data(),
11034                                   TSI,
11035                                   DS.getFriendSpecLoc());
11036  else
11037    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11038
11039  if (!D)
11040    return 0;
11041
11042  D->setAccess(AS_public);
11043  CurContext->addDecl(D);
11044
11045  return D;
11046}
11047
11048NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11049                                        MultiTemplateParamsArg TemplateParams) {
11050  const DeclSpec &DS = D.getDeclSpec();
11051
11052  assert(DS.isFriendSpecified());
11053  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11054
11055  SourceLocation Loc = D.getIdentifierLoc();
11056  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11057
11058  // C++ [class.friend]p1
11059  //   A friend of a class is a function or class....
11060  // Note that this sees through typedefs, which is intended.
11061  // It *doesn't* see through dependent types, which is correct
11062  // according to [temp.arg.type]p3:
11063  //   If a declaration acquires a function type through a
11064  //   type dependent on a template-parameter and this causes
11065  //   a declaration that does not use the syntactic form of a
11066  //   function declarator to have a function type, the program
11067  //   is ill-formed.
11068  if (!TInfo->getType()->isFunctionType()) {
11069    Diag(Loc, diag::err_unexpected_friend);
11070
11071    // It might be worthwhile to try to recover by creating an
11072    // appropriate declaration.
11073    return 0;
11074  }
11075
11076  // C++ [namespace.memdef]p3
11077  //  - If a friend declaration in a non-local class first declares a
11078  //    class or function, the friend class or function is a member
11079  //    of the innermost enclosing namespace.
11080  //  - The name of the friend is not found by simple name lookup
11081  //    until a matching declaration is provided in that namespace
11082  //    scope (either before or after the class declaration granting
11083  //    friendship).
11084  //  - If a friend function is called, its name may be found by the
11085  //    name lookup that considers functions from namespaces and
11086  //    classes associated with the types of the function arguments.
11087  //  - When looking for a prior declaration of a class or a function
11088  //    declared as a friend, scopes outside the innermost enclosing
11089  //    namespace scope are not considered.
11090
11091  CXXScopeSpec &SS = D.getCXXScopeSpec();
11092  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11093  DeclarationName Name = NameInfo.getName();
11094  assert(Name);
11095
11096  // Check for unexpanded parameter packs.
11097  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11098      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11099      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11100    return 0;
11101
11102  // The context we found the declaration in, or in which we should
11103  // create the declaration.
11104  DeclContext *DC;
11105  Scope *DCScope = S;
11106  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11107                        ForRedeclaration);
11108
11109  // FIXME: there are different rules in local classes
11110
11111  // There are four cases here.
11112  //   - There's no scope specifier, in which case we just go to the
11113  //     appropriate scope and look for a function or function template
11114  //     there as appropriate.
11115  // Recover from invalid scope qualifiers as if they just weren't there.
11116  if (SS.isInvalid() || !SS.isSet()) {
11117    // C++0x [namespace.memdef]p3:
11118    //   If the name in a friend declaration is neither qualified nor
11119    //   a template-id and the declaration is a function or an
11120    //   elaborated-type-specifier, the lookup to determine whether
11121    //   the entity has been previously declared shall not consider
11122    //   any scopes outside the innermost enclosing namespace.
11123    // C++0x [class.friend]p11:
11124    //   If a friend declaration appears in a local class and the name
11125    //   specified is an unqualified name, a prior declaration is
11126    //   looked up without considering scopes that are outside the
11127    //   innermost enclosing non-class scope. For a friend function
11128    //   declaration, if there is no prior declaration, the program is
11129    //   ill-formed.
11130    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
11131    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11132
11133    // Find the appropriate context according to the above.
11134    DC = CurContext;
11135
11136    // Skip class contexts.  If someone can cite chapter and verse
11137    // for this behavior, that would be nice --- it's what GCC and
11138    // EDG do, and it seems like a reasonable intent, but the spec
11139    // really only says that checks for unqualified existing
11140    // declarations should stop at the nearest enclosing namespace,
11141    // not that they should only consider the nearest enclosing
11142    // namespace.
11143    while (DC->isRecord())
11144      DC = DC->getParent();
11145
11146    DeclContext *LookupDC = DC;
11147    while (LookupDC->isTransparentContext())
11148      LookupDC = LookupDC->getParent();
11149
11150    while (true) {
11151      LookupQualifiedName(Previous, LookupDC);
11152
11153      // TODO: decide what we think about using declarations.
11154      if (isLocal)
11155        break;
11156
11157      if (!Previous.empty()) {
11158        DC = LookupDC;
11159        break;
11160      }
11161
11162      if (isTemplateId) {
11163        if (isa<TranslationUnitDecl>(LookupDC)) break;
11164      } else {
11165        if (LookupDC->isFileContext()) break;
11166      }
11167      LookupDC = LookupDC->getParent();
11168    }
11169
11170    DCScope = getScopeForDeclContext(S, DC);
11171
11172    // C++ [class.friend]p6:
11173    //   A function can be defined in a friend declaration of a class if and
11174    //   only if the class is a non-local class (9.8), the function name is
11175    //   unqualified, and the function has namespace scope.
11176    if (isLocal && D.isFunctionDefinition()) {
11177      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11178    }
11179
11180  //   - There's a non-dependent scope specifier, in which case we
11181  //     compute it and do a previous lookup there for a function
11182  //     or function template.
11183  } else if (!SS.getScopeRep()->isDependent()) {
11184    DC = computeDeclContext(SS);
11185    if (!DC) return 0;
11186
11187    if (RequireCompleteDeclContext(SS, DC)) return 0;
11188
11189    LookupQualifiedName(Previous, DC);
11190
11191    // Ignore things found implicitly in the wrong scope.
11192    // TODO: better diagnostics for this case.  Suggesting the right
11193    // qualified scope would be nice...
11194    LookupResult::Filter F = Previous.makeFilter();
11195    while (F.hasNext()) {
11196      NamedDecl *D = F.next();
11197      if (!DC->InEnclosingNamespaceSetOf(
11198              D->getDeclContext()->getRedeclContext()))
11199        F.erase();
11200    }
11201    F.done();
11202
11203    if (Previous.empty()) {
11204      D.setInvalidType();
11205      Diag(Loc, diag::err_qualified_friend_not_found)
11206          << Name << TInfo->getType();
11207      return 0;
11208    }
11209
11210    // C++ [class.friend]p1: A friend of a class is a function or
11211    //   class that is not a member of the class . . .
11212    if (DC->Equals(CurContext))
11213      Diag(DS.getFriendSpecLoc(),
11214           getLangOpts().CPlusPlus11 ?
11215             diag::warn_cxx98_compat_friend_is_member :
11216             diag::err_friend_is_member);
11217
11218    if (D.isFunctionDefinition()) {
11219      // C++ [class.friend]p6:
11220      //   A function can be defined in a friend declaration of a class if and
11221      //   only if the class is a non-local class (9.8), the function name is
11222      //   unqualified, and the function has namespace scope.
11223      SemaDiagnosticBuilder DB
11224        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11225
11226      DB << SS.getScopeRep();
11227      if (DC->isFileContext())
11228        DB << FixItHint::CreateRemoval(SS.getRange());
11229      SS.clear();
11230    }
11231
11232  //   - There's a scope specifier that does not match any template
11233  //     parameter lists, in which case we use some arbitrary context,
11234  //     create a method or method template, and wait for instantiation.
11235  //   - There's a scope specifier that does match some template
11236  //     parameter lists, which we don't handle right now.
11237  } else {
11238    if (D.isFunctionDefinition()) {
11239      // C++ [class.friend]p6:
11240      //   A function can be defined in a friend declaration of a class if and
11241      //   only if the class is a non-local class (9.8), the function name is
11242      //   unqualified, and the function has namespace scope.
11243      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11244        << SS.getScopeRep();
11245    }
11246
11247    DC = CurContext;
11248    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11249  }
11250
11251  if (!DC->isRecord()) {
11252    // This implies that it has to be an operator or function.
11253    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11254        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11255        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11256      Diag(Loc, diag::err_introducing_special_friend) <<
11257        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11258         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11259      return 0;
11260    }
11261  }
11262
11263  // FIXME: This is an egregious hack to cope with cases where the scope stack
11264  // does not contain the declaration context, i.e., in an out-of-line
11265  // definition of a class.
11266  Scope FakeDCScope(S, Scope::DeclScope, Diags);
11267  if (!DCScope) {
11268    FakeDCScope.setEntity(DC);
11269    DCScope = &FakeDCScope;
11270  }
11271
11272  bool AddToScope = true;
11273  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11274                                          TemplateParams, AddToScope);
11275  if (!ND) return 0;
11276
11277  assert(ND->getDeclContext() == DC);
11278  assert(ND->getLexicalDeclContext() == CurContext);
11279
11280  // Add the function declaration to the appropriate lookup tables,
11281  // adjusting the redeclarations list as necessary.  We don't
11282  // want to do this yet if the friending class is dependent.
11283  //
11284  // Also update the scope-based lookup if the target context's
11285  // lookup context is in lexical scope.
11286  if (!CurContext->isDependentContext()) {
11287    DC = DC->getRedeclContext();
11288    DC->makeDeclVisibleInContext(ND);
11289    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11290      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11291  }
11292
11293  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11294                                       D.getIdentifierLoc(), ND,
11295                                       DS.getFriendSpecLoc());
11296  FrD->setAccess(AS_public);
11297  CurContext->addDecl(FrD);
11298
11299  if (ND->isInvalidDecl()) {
11300    FrD->setInvalidDecl();
11301  } else {
11302    if (DC->isRecord()) CheckFriendAccess(ND);
11303
11304    FunctionDecl *FD;
11305    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11306      FD = FTD->getTemplatedDecl();
11307    else
11308      FD = cast<FunctionDecl>(ND);
11309
11310    // Mark templated-scope function declarations as unsupported.
11311    if (FD->getNumTemplateParameterLists())
11312      FrD->setUnsupportedFriend(true);
11313  }
11314
11315  return ND;
11316}
11317
11318void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11319  AdjustDeclIfTemplate(Dcl);
11320
11321  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11322  if (!Fn) {
11323    Diag(DelLoc, diag::err_deleted_non_function);
11324    return;
11325  }
11326
11327  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11328    // Don't consider the implicit declaration we generate for explicit
11329    // specializations. FIXME: Do not generate these implicit declarations.
11330    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11331        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11332      Diag(DelLoc, diag::err_deleted_decl_not_first);
11333      Diag(Prev->getLocation(), diag::note_previous_declaration);
11334    }
11335    // If the declaration wasn't the first, we delete the function anyway for
11336    // recovery.
11337    Fn = Fn->getCanonicalDecl();
11338  }
11339
11340  if (Fn->isDeleted())
11341    return;
11342
11343  // See if we're deleting a function which is already known to override a
11344  // non-deleted virtual function.
11345  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11346    bool IssuedDiagnostic = false;
11347    for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11348                                        E = MD->end_overridden_methods();
11349         I != E; ++I) {
11350      if (!(*MD->begin_overridden_methods())->isDeleted()) {
11351        if (!IssuedDiagnostic) {
11352          Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11353          IssuedDiagnostic = true;
11354        }
11355        Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11356      }
11357    }
11358  }
11359
11360  Fn->setDeletedAsWritten();
11361}
11362
11363void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11364  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11365
11366  if (MD) {
11367    if (MD->getParent()->isDependentType()) {
11368      MD->setDefaulted();
11369      MD->setExplicitlyDefaulted();
11370      return;
11371    }
11372
11373    CXXSpecialMember Member = getSpecialMember(MD);
11374    if (Member == CXXInvalid) {
11375      Diag(DefaultLoc, diag::err_default_special_members);
11376      return;
11377    }
11378
11379    MD->setDefaulted();
11380    MD->setExplicitlyDefaulted();
11381
11382    // If this definition appears within the record, do the checking when
11383    // the record is complete.
11384    const FunctionDecl *Primary = MD;
11385    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11386      // Find the uninstantiated declaration that actually had the '= default'
11387      // on it.
11388      Pattern->isDefined(Primary);
11389
11390    // If the method was defaulted on its first declaration, we will have
11391    // already performed the checking in CheckCompletedCXXClass. Such a
11392    // declaration doesn't trigger an implicit definition.
11393    if (Primary == Primary->getCanonicalDecl())
11394      return;
11395
11396    CheckExplicitlyDefaultedSpecialMember(MD);
11397
11398    // The exception specification is needed because we are defining the
11399    // function.
11400    ResolveExceptionSpec(DefaultLoc,
11401                         MD->getType()->castAs<FunctionProtoType>());
11402
11403    switch (Member) {
11404    case CXXDefaultConstructor: {
11405      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11406      if (!CD->isInvalidDecl())
11407        DefineImplicitDefaultConstructor(DefaultLoc, CD);
11408      break;
11409    }
11410
11411    case CXXCopyConstructor: {
11412      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11413      if (!CD->isInvalidDecl())
11414        DefineImplicitCopyConstructor(DefaultLoc, CD);
11415      break;
11416    }
11417
11418    case CXXCopyAssignment: {
11419      if (!MD->isInvalidDecl())
11420        DefineImplicitCopyAssignment(DefaultLoc, MD);
11421      break;
11422    }
11423
11424    case CXXDestructor: {
11425      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11426      if (!DD->isInvalidDecl())
11427        DefineImplicitDestructor(DefaultLoc, DD);
11428      break;
11429    }
11430
11431    case CXXMoveConstructor: {
11432      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11433      if (!CD->isInvalidDecl())
11434        DefineImplicitMoveConstructor(DefaultLoc, CD);
11435      break;
11436    }
11437
11438    case CXXMoveAssignment: {
11439      if (!MD->isInvalidDecl())
11440        DefineImplicitMoveAssignment(DefaultLoc, MD);
11441      break;
11442    }
11443
11444    case CXXInvalid:
11445      llvm_unreachable("Invalid special member.");
11446    }
11447  } else {
11448    Diag(DefaultLoc, diag::err_default_special_members);
11449  }
11450}
11451
11452static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11453  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11454    Stmt *SubStmt = *CI;
11455    if (!SubStmt)
11456      continue;
11457    if (isa<ReturnStmt>(SubStmt))
11458      Self.Diag(SubStmt->getLocStart(),
11459           diag::err_return_in_constructor_handler);
11460    if (!isa<Expr>(SubStmt))
11461      SearchForReturnInStmt(Self, SubStmt);
11462  }
11463}
11464
11465void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11466  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11467    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11468    SearchForReturnInStmt(*this, Handler);
11469  }
11470}
11471
11472bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11473                                             const CXXMethodDecl *Old) {
11474  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11475  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11476
11477  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11478
11479  // If the calling conventions match, everything is fine
11480  if (NewCC == OldCC)
11481    return false;
11482
11483  // If either of the calling conventions are set to "default", we need to pick
11484  // something more sensible based on the target. This supports code where the
11485  // one method explicitly sets thiscall, and another has no explicit calling
11486  // convention.
11487  CallingConv Default =
11488    Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11489  if (NewCC == CC_Default)
11490    NewCC = Default;
11491  if (OldCC == CC_Default)
11492    OldCC = Default;
11493
11494  // If the calling conventions still don't match, then report the error
11495  if (NewCC != OldCC) {
11496    Diag(New->getLocation(),
11497         diag::err_conflicting_overriding_cc_attributes)
11498      << New->getDeclName() << New->getType() << Old->getType();
11499    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11500    return true;
11501  }
11502
11503  return false;
11504}
11505
11506bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11507                                             const CXXMethodDecl *Old) {
11508  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11509  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11510
11511  if (Context.hasSameType(NewTy, OldTy) ||
11512      NewTy->isDependentType() || OldTy->isDependentType())
11513    return false;
11514
11515  // Check if the return types are covariant
11516  QualType NewClassTy, OldClassTy;
11517
11518  /// Both types must be pointers or references to classes.
11519  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11520    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11521      NewClassTy = NewPT->getPointeeType();
11522      OldClassTy = OldPT->getPointeeType();
11523    }
11524  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11525    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11526      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11527        NewClassTy = NewRT->getPointeeType();
11528        OldClassTy = OldRT->getPointeeType();
11529      }
11530    }
11531  }
11532
11533  // The return types aren't either both pointers or references to a class type.
11534  if (NewClassTy.isNull()) {
11535    Diag(New->getLocation(),
11536         diag::err_different_return_type_for_overriding_virtual_function)
11537      << New->getDeclName() << NewTy << OldTy;
11538    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11539
11540    return true;
11541  }
11542
11543  // C++ [class.virtual]p6:
11544  //   If the return type of D::f differs from the return type of B::f, the
11545  //   class type in the return type of D::f shall be complete at the point of
11546  //   declaration of D::f or shall be the class type D.
11547  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11548    if (!RT->isBeingDefined() &&
11549        RequireCompleteType(New->getLocation(), NewClassTy,
11550                            diag::err_covariant_return_incomplete,
11551                            New->getDeclName()))
11552    return true;
11553  }
11554
11555  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11556    // Check if the new class derives from the old class.
11557    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11558      Diag(New->getLocation(),
11559           diag::err_covariant_return_not_derived)
11560      << New->getDeclName() << NewTy << OldTy;
11561      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11562      return true;
11563    }
11564
11565    // Check if we the conversion from derived to base is valid.
11566    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11567                    diag::err_covariant_return_inaccessible_base,
11568                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
11569                    // FIXME: Should this point to the return type?
11570                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11571      // FIXME: this note won't trigger for delayed access control
11572      // diagnostics, and it's impossible to get an undelayed error
11573      // here from access control during the original parse because
11574      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11575      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11576      return true;
11577    }
11578  }
11579
11580  // The qualifiers of the return types must be the same.
11581  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11582    Diag(New->getLocation(),
11583         diag::err_covariant_return_type_different_qualifications)
11584    << New->getDeclName() << NewTy << OldTy;
11585    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11586    return true;
11587  };
11588
11589
11590  // The new class type must have the same or less qualifiers as the old type.
11591  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11592    Diag(New->getLocation(),
11593         diag::err_covariant_return_type_class_type_more_qualified)
11594    << New->getDeclName() << NewTy << OldTy;
11595    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11596    return true;
11597  };
11598
11599  return false;
11600}
11601
11602/// \brief Mark the given method pure.
11603///
11604/// \param Method the method to be marked pure.
11605///
11606/// \param InitRange the source range that covers the "0" initializer.
11607bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11608  SourceLocation EndLoc = InitRange.getEnd();
11609  if (EndLoc.isValid())
11610    Method->setRangeEnd(EndLoc);
11611
11612  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11613    Method->setPure();
11614    return false;
11615  }
11616
11617  if (!Method->isInvalidDecl())
11618    Diag(Method->getLocation(), diag::err_non_virtual_pure)
11619      << Method->getDeclName() << InitRange;
11620  return true;
11621}
11622
11623/// \brief Determine whether the given declaration is a static data member.
11624static bool isStaticDataMember(Decl *D) {
11625  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11626  if (!Var)
11627    return false;
11628
11629  return Var->isStaticDataMember();
11630}
11631/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11632/// an initializer for the out-of-line declaration 'Dcl'.  The scope
11633/// is a fresh scope pushed for just this purpose.
11634///
11635/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11636/// static data member of class X, names should be looked up in the scope of
11637/// class X.
11638void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11639  // If there is no declaration, there was an error parsing it.
11640  if (D == 0 || D->isInvalidDecl()) return;
11641
11642  // We should only get called for declarations with scope specifiers, like:
11643  //   int foo::bar;
11644  assert(D->isOutOfLine());
11645  EnterDeclaratorContext(S, D->getDeclContext());
11646
11647  // If we are parsing the initializer for a static data member, push a
11648  // new expression evaluation context that is associated with this static
11649  // data member.
11650  if (isStaticDataMember(D))
11651    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11652}
11653
11654/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11655/// initializer for the out-of-line declaration 'D'.
11656void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11657  // If there is no declaration, there was an error parsing it.
11658  if (D == 0 || D->isInvalidDecl()) return;
11659
11660  if (isStaticDataMember(D))
11661    PopExpressionEvaluationContext();
11662
11663  assert(D->isOutOfLine());
11664  ExitDeclaratorContext(S);
11665}
11666
11667/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11668/// C++ if/switch/while/for statement.
11669/// e.g: "if (int x = f()) {...}"
11670DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11671  // C++ 6.4p2:
11672  // The declarator shall not specify a function or an array.
11673  // The type-specifier-seq shall not contain typedef and shall not declare a
11674  // new class or enumeration.
11675  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11676         "Parser allowed 'typedef' as storage class of condition decl.");
11677
11678  Decl *Dcl = ActOnDeclarator(S, D);
11679  if (!Dcl)
11680    return true;
11681
11682  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11683    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11684      << D.getSourceRange();
11685    return true;
11686  }
11687
11688  return Dcl;
11689}
11690
11691void Sema::LoadExternalVTableUses() {
11692  if (!ExternalSource)
11693    return;
11694
11695  SmallVector<ExternalVTableUse, 4> VTables;
11696  ExternalSource->ReadUsedVTables(VTables);
11697  SmallVector<VTableUse, 4> NewUses;
11698  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11699    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11700      = VTablesUsed.find(VTables[I].Record);
11701    // Even if a definition wasn't required before, it may be required now.
11702    if (Pos != VTablesUsed.end()) {
11703      if (!Pos->second && VTables[I].DefinitionRequired)
11704        Pos->second = true;
11705      continue;
11706    }
11707
11708    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11709    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11710  }
11711
11712  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11713}
11714
11715void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11716                          bool DefinitionRequired) {
11717  // Ignore any vtable uses in unevaluated operands or for classes that do
11718  // not have a vtable.
11719  if (!Class->isDynamicClass() || Class->isDependentContext() ||
11720      CurContext->isDependentContext() || isUnevaluatedContext())
11721    return;
11722
11723  // Try to insert this class into the map.
11724  LoadExternalVTableUses();
11725  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11726  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11727    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11728  if (!Pos.second) {
11729    // If we already had an entry, check to see if we are promoting this vtable
11730    // to required a definition. If so, we need to reappend to the VTableUses
11731    // list, since we may have already processed the first entry.
11732    if (DefinitionRequired && !Pos.first->second) {
11733      Pos.first->second = true;
11734    } else {
11735      // Otherwise, we can early exit.
11736      return;
11737    }
11738  }
11739
11740  // Local classes need to have their virtual members marked
11741  // immediately. For all other classes, we mark their virtual members
11742  // at the end of the translation unit.
11743  if (Class->isLocalClass())
11744    MarkVirtualMembersReferenced(Loc, Class);
11745  else
11746    VTableUses.push_back(std::make_pair(Class, Loc));
11747}
11748
11749bool Sema::DefineUsedVTables() {
11750  LoadExternalVTableUses();
11751  if (VTableUses.empty())
11752    return false;
11753
11754  // Note: The VTableUses vector could grow as a result of marking
11755  // the members of a class as "used", so we check the size each
11756  // time through the loop and prefer indices (which are stable) to
11757  // iterators (which are not).
11758  bool DefinedAnything = false;
11759  for (unsigned I = 0; I != VTableUses.size(); ++I) {
11760    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11761    if (!Class)
11762      continue;
11763
11764    SourceLocation Loc = VTableUses[I].second;
11765
11766    bool DefineVTable = true;
11767
11768    // If this class has a key function, but that key function is
11769    // defined in another translation unit, we don't need to emit the
11770    // vtable even though we're using it.
11771    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11772    if (KeyFunction && !KeyFunction->hasBody()) {
11773      switch (KeyFunction->getTemplateSpecializationKind()) {
11774      case TSK_Undeclared:
11775      case TSK_ExplicitSpecialization:
11776      case TSK_ExplicitInstantiationDeclaration:
11777        // The key function is in another translation unit.
11778        DefineVTable = false;
11779        break;
11780
11781      case TSK_ExplicitInstantiationDefinition:
11782      case TSK_ImplicitInstantiation:
11783        // We will be instantiating the key function.
11784        break;
11785      }
11786    } else if (!KeyFunction) {
11787      // If we have a class with no key function that is the subject
11788      // of an explicit instantiation declaration, suppress the
11789      // vtable; it will live with the explicit instantiation
11790      // definition.
11791      bool IsExplicitInstantiationDeclaration
11792        = Class->getTemplateSpecializationKind()
11793                                      == TSK_ExplicitInstantiationDeclaration;
11794      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11795                                 REnd = Class->redecls_end();
11796           R != REnd; ++R) {
11797        TemplateSpecializationKind TSK
11798          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11799        if (TSK == TSK_ExplicitInstantiationDeclaration)
11800          IsExplicitInstantiationDeclaration = true;
11801        else if (TSK == TSK_ExplicitInstantiationDefinition) {
11802          IsExplicitInstantiationDeclaration = false;
11803          break;
11804        }
11805      }
11806
11807      if (IsExplicitInstantiationDeclaration)
11808        DefineVTable = false;
11809    }
11810
11811    // The exception specifications for all virtual members may be needed even
11812    // if we are not providing an authoritative form of the vtable in this TU.
11813    // We may choose to emit it available_externally anyway.
11814    if (!DefineVTable) {
11815      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11816      continue;
11817    }
11818
11819    // Mark all of the virtual members of this class as referenced, so
11820    // that we can build a vtable. Then, tell the AST consumer that a
11821    // vtable for this class is required.
11822    DefinedAnything = true;
11823    MarkVirtualMembersReferenced(Loc, Class);
11824    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11825    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11826
11827    // Optionally warn if we're emitting a weak vtable.
11828    if (Class->isExternallyVisible() &&
11829        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11830      const FunctionDecl *KeyFunctionDef = 0;
11831      if (!KeyFunction ||
11832          (KeyFunction->hasBody(KeyFunctionDef) &&
11833           KeyFunctionDef->isInlined()))
11834        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11835             TSK_ExplicitInstantiationDefinition
11836             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11837          << Class;
11838    }
11839  }
11840  VTableUses.clear();
11841
11842  return DefinedAnything;
11843}
11844
11845void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
11846                                                 const CXXRecordDecl *RD) {
11847  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
11848                                      E = RD->method_end(); I != E; ++I)
11849    if ((*I)->isVirtual() && !(*I)->isPure())
11850      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
11851}
11852
11853void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
11854                                        const CXXRecordDecl *RD) {
11855  // Mark all functions which will appear in RD's vtable as used.
11856  CXXFinalOverriderMap FinalOverriders;
11857  RD->getFinalOverriders(FinalOverriders);
11858  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
11859                                            E = FinalOverriders.end();
11860       I != E; ++I) {
11861    for (OverridingMethods::const_iterator OI = I->second.begin(),
11862                                           OE = I->second.end();
11863         OI != OE; ++OI) {
11864      assert(OI->second.size() > 0 && "no final overrider");
11865      CXXMethodDecl *Overrider = OI->second.front().Method;
11866
11867      // C++ [basic.def.odr]p2:
11868      //   [...] A virtual member function is used if it is not pure. [...]
11869      if (!Overrider->isPure())
11870        MarkFunctionReferenced(Loc, Overrider);
11871    }
11872  }
11873
11874  // Only classes that have virtual bases need a VTT.
11875  if (RD->getNumVBases() == 0)
11876    return;
11877
11878  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
11879           e = RD->bases_end(); i != e; ++i) {
11880    const CXXRecordDecl *Base =
11881        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
11882    if (Base->getNumVBases() == 0)
11883      continue;
11884    MarkVirtualMembersReferenced(Loc, Base);
11885  }
11886}
11887
11888/// SetIvarInitializers - This routine builds initialization ASTs for the
11889/// Objective-C implementation whose ivars need be initialized.
11890void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
11891  if (!getLangOpts().CPlusPlus)
11892    return;
11893  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
11894    SmallVector<ObjCIvarDecl*, 8> ivars;
11895    CollectIvarsToConstructOrDestruct(OID, ivars);
11896    if (ivars.empty())
11897      return;
11898    SmallVector<CXXCtorInitializer*, 32> AllToInit;
11899    for (unsigned i = 0; i < ivars.size(); i++) {
11900      FieldDecl *Field = ivars[i];
11901      if (Field->isInvalidDecl())
11902        continue;
11903
11904      CXXCtorInitializer *Member;
11905      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
11906      InitializationKind InitKind =
11907        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
11908
11909      InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
11910      ExprResult MemberInit =
11911        InitSeq.Perform(*this, InitEntity, InitKind, None);
11912      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
11913      // Note, MemberInit could actually come back empty if no initialization
11914      // is required (e.g., because it would call a trivial default constructor)
11915      if (!MemberInit.get() || MemberInit.isInvalid())
11916        continue;
11917
11918      Member =
11919        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
11920                                         SourceLocation(),
11921                                         MemberInit.takeAs<Expr>(),
11922                                         SourceLocation());
11923      AllToInit.push_back(Member);
11924
11925      // Be sure that the destructor is accessible and is marked as referenced.
11926      if (const RecordType *RecordTy
11927                  = Context.getBaseElementType(Field->getType())
11928                                                        ->getAs<RecordType>()) {
11929                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
11930        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
11931          MarkFunctionReferenced(Field->getLocation(), Destructor);
11932          CheckDestructorAccess(Field->getLocation(), Destructor,
11933                            PDiag(diag::err_access_dtor_ivar)
11934                              << Context.getBaseElementType(Field->getType()));
11935        }
11936      }
11937    }
11938    ObjCImplementation->setIvarInitializers(Context,
11939                                            AllToInit.data(), AllToInit.size());
11940  }
11941}
11942
11943static
11944void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
11945                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11946                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11947                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11948                           Sema &S) {
11949  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11950                                                   CE = Current.end();
11951  if (Ctor->isInvalidDecl())
11952    return;
11953
11954  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
11955
11956  // Target may not be determinable yet, for instance if this is a dependent
11957  // call in an uninstantiated template.
11958  if (Target) {
11959    const FunctionDecl *FNTarget = 0;
11960    (void)Target->hasBody(FNTarget);
11961    Target = const_cast<CXXConstructorDecl*>(
11962      cast_or_null<CXXConstructorDecl>(FNTarget));
11963  }
11964
11965  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11966                     // Avoid dereferencing a null pointer here.
11967                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11968
11969  if (!Current.insert(Canonical))
11970    return;
11971
11972  // We know that beyond here, we aren't chaining into a cycle.
11973  if (!Target || !Target->isDelegatingConstructor() ||
11974      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11975    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11976      Valid.insert(*CI);
11977    Current.clear();
11978  // We've hit a cycle.
11979  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11980             Current.count(TCanonical)) {
11981    // If we haven't diagnosed this cycle yet, do so now.
11982    if (!Invalid.count(TCanonical)) {
11983      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11984             diag::warn_delegating_ctor_cycle)
11985        << Ctor;
11986
11987      // Don't add a note for a function delegating directly to itself.
11988      if (TCanonical != Canonical)
11989        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11990
11991      CXXConstructorDecl *C = Target;
11992      while (C->getCanonicalDecl() != Canonical) {
11993        const FunctionDecl *FNTarget = 0;
11994        (void)C->getTargetConstructor()->hasBody(FNTarget);
11995        assert(FNTarget && "Ctor cycle through bodiless function");
11996
11997        C = const_cast<CXXConstructorDecl*>(
11998          cast<CXXConstructorDecl>(FNTarget));
11999        S.Diag(C->getLocation(), diag::note_which_delegates_to);
12000      }
12001    }
12002
12003    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12004      Invalid.insert(*CI);
12005    Current.clear();
12006  } else {
12007    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12008  }
12009}
12010
12011
12012void Sema::CheckDelegatingCtorCycles() {
12013  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12014
12015  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12016                                                   CE = Current.end();
12017
12018  for (DelegatingCtorDeclsType::iterator
12019         I = DelegatingCtorDecls.begin(ExternalSource),
12020         E = DelegatingCtorDecls.end();
12021       I != E; ++I)
12022    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12023
12024  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12025    (*CI)->setInvalidDecl();
12026}
12027
12028namespace {
12029  /// \brief AST visitor that finds references to the 'this' expression.
12030  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12031    Sema &S;
12032
12033  public:
12034    explicit FindCXXThisExpr(Sema &S) : S(S) { }
12035
12036    bool VisitCXXThisExpr(CXXThisExpr *E) {
12037      S.Diag(E->getLocation(), diag::err_this_static_member_func)
12038        << E->isImplicit();
12039      return false;
12040    }
12041  };
12042}
12043
12044bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12045  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12046  if (!TSInfo)
12047    return false;
12048
12049  TypeLoc TL = TSInfo->getTypeLoc();
12050  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12051  if (!ProtoTL)
12052    return false;
12053
12054  // C++11 [expr.prim.general]p3:
12055  //   [The expression this] shall not appear before the optional
12056  //   cv-qualifier-seq and it shall not appear within the declaration of a
12057  //   static member function (although its type and value category are defined
12058  //   within a static member function as they are within a non-static member
12059  //   function). [ Note: this is because declaration matching does not occur
12060  //  until the complete declarator is known. - end note ]
12061  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12062  FindCXXThisExpr Finder(*this);
12063
12064  // If the return type came after the cv-qualifier-seq, check it now.
12065  if (Proto->hasTrailingReturn() &&
12066      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12067    return true;
12068
12069  // Check the exception specification.
12070  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12071    return true;
12072
12073  return checkThisInStaticMemberFunctionAttributes(Method);
12074}
12075
12076bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12077  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12078  if (!TSInfo)
12079    return false;
12080
12081  TypeLoc TL = TSInfo->getTypeLoc();
12082  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12083  if (!ProtoTL)
12084    return false;
12085
12086  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12087  FindCXXThisExpr Finder(*this);
12088
12089  switch (Proto->getExceptionSpecType()) {
12090  case EST_Uninstantiated:
12091  case EST_Unevaluated:
12092  case EST_BasicNoexcept:
12093  case EST_DynamicNone:
12094  case EST_MSAny:
12095  case EST_None:
12096    break;
12097
12098  case EST_ComputedNoexcept:
12099    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12100      return true;
12101
12102  case EST_Dynamic:
12103    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12104         EEnd = Proto->exception_end();
12105         E != EEnd; ++E) {
12106      if (!Finder.TraverseType(*E))
12107        return true;
12108    }
12109    break;
12110  }
12111
12112  return false;
12113}
12114
12115bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12116  FindCXXThisExpr Finder(*this);
12117
12118  // Check attributes.
12119  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12120       A != AEnd; ++A) {
12121    // FIXME: This should be emitted by tblgen.
12122    Expr *Arg = 0;
12123    ArrayRef<Expr *> Args;
12124    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12125      Arg = G->getArg();
12126    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12127      Arg = G->getArg();
12128    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12129      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12130    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12131      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12132    else if (ExclusiveLockFunctionAttr *ELF
12133               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12134      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12135    else if (SharedLockFunctionAttr *SLF
12136               = dyn_cast<SharedLockFunctionAttr>(*A))
12137      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12138    else if (ExclusiveTrylockFunctionAttr *ETLF
12139               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12140      Arg = ETLF->getSuccessValue();
12141      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12142    } else if (SharedTrylockFunctionAttr *STLF
12143                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12144      Arg = STLF->getSuccessValue();
12145      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12146    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12147      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12148    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12149      Arg = LR->getArg();
12150    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12151      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12152    else if (ExclusiveLocksRequiredAttr *ELR
12153               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12154      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12155    else if (SharedLocksRequiredAttr *SLR
12156               = dyn_cast<SharedLocksRequiredAttr>(*A))
12157      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12158
12159    if (Arg && !Finder.TraverseStmt(Arg))
12160      return true;
12161
12162    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12163      if (!Finder.TraverseStmt(Args[I]))
12164        return true;
12165    }
12166  }
12167
12168  return false;
12169}
12170
12171void
12172Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12173                                  ArrayRef<ParsedType> DynamicExceptions,
12174                                  ArrayRef<SourceRange> DynamicExceptionRanges,
12175                                  Expr *NoexceptExpr,
12176                                  SmallVectorImpl<QualType> &Exceptions,
12177                                  FunctionProtoType::ExtProtoInfo &EPI) {
12178  Exceptions.clear();
12179  EPI.ExceptionSpecType = EST;
12180  if (EST == EST_Dynamic) {
12181    Exceptions.reserve(DynamicExceptions.size());
12182    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12183      // FIXME: Preserve type source info.
12184      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12185
12186      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12187      collectUnexpandedParameterPacks(ET, Unexpanded);
12188      if (!Unexpanded.empty()) {
12189        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12190                                         UPPC_ExceptionType,
12191                                         Unexpanded);
12192        continue;
12193      }
12194
12195      // Check that the type is valid for an exception spec, and
12196      // drop it if not.
12197      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12198        Exceptions.push_back(ET);
12199    }
12200    EPI.NumExceptions = Exceptions.size();
12201    EPI.Exceptions = Exceptions.data();
12202    return;
12203  }
12204
12205  if (EST == EST_ComputedNoexcept) {
12206    // If an error occurred, there's no expression here.
12207    if (NoexceptExpr) {
12208      assert((NoexceptExpr->isTypeDependent() ||
12209              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12210              Context.BoolTy) &&
12211             "Parser should have made sure that the expression is boolean");
12212      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12213        EPI.ExceptionSpecType = EST_BasicNoexcept;
12214        return;
12215      }
12216
12217      if (!NoexceptExpr->isValueDependent())
12218        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12219                         diag::err_noexcept_needs_constant_expression,
12220                         /*AllowFold*/ false).take();
12221      EPI.NoexceptExpr = NoexceptExpr;
12222    }
12223    return;
12224  }
12225}
12226
12227/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12228Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12229  // Implicitly declared functions (e.g. copy constructors) are
12230  // __host__ __device__
12231  if (D->isImplicit())
12232    return CFT_HostDevice;
12233
12234  if (D->hasAttr<CUDAGlobalAttr>())
12235    return CFT_Global;
12236
12237  if (D->hasAttr<CUDADeviceAttr>()) {
12238    if (D->hasAttr<CUDAHostAttr>())
12239      return CFT_HostDevice;
12240    else
12241      return CFT_Device;
12242  }
12243
12244  return CFT_Host;
12245}
12246
12247bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12248                           CUDAFunctionTarget CalleeTarget) {
12249  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12250  // Callable from the device only."
12251  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12252    return true;
12253
12254  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12255  // Callable from the host only."
12256  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12257  // Callable from the host only."
12258  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12259      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12260    return true;
12261
12262  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12263    return true;
12264
12265  return false;
12266}
12267
12268/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12269///
12270MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12271                                       SourceLocation DeclStart,
12272                                       Declarator &D, Expr *BitWidth,
12273                                       InClassInitStyle InitStyle,
12274                                       AccessSpecifier AS,
12275                                       AttributeList *MSPropertyAttr) {
12276  IdentifierInfo *II = D.getIdentifier();
12277  if (!II) {
12278    Diag(DeclStart, diag::err_anonymous_property);
12279    return NULL;
12280  }
12281  SourceLocation Loc = D.getIdentifierLoc();
12282
12283  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12284  QualType T = TInfo->getType();
12285  if (getLangOpts().CPlusPlus) {
12286    CheckExtraCXXDefaultArguments(D);
12287
12288    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12289                                        UPPC_DataMemberType)) {
12290      D.setInvalidType();
12291      T = Context.IntTy;
12292      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12293    }
12294  }
12295
12296  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12297
12298  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12299    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12300         diag::err_invalid_thread)
12301      << DeclSpec::getSpecifierName(TSCS);
12302
12303  // Check to see if this name was declared as a member previously
12304  NamedDecl *PrevDecl = 0;
12305  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12306  LookupName(Previous, S);
12307  switch (Previous.getResultKind()) {
12308  case LookupResult::Found:
12309  case LookupResult::FoundUnresolvedValue:
12310    PrevDecl = Previous.getAsSingle<NamedDecl>();
12311    break;
12312
12313  case LookupResult::FoundOverloaded:
12314    PrevDecl = Previous.getRepresentativeDecl();
12315    break;
12316
12317  case LookupResult::NotFound:
12318  case LookupResult::NotFoundInCurrentInstantiation:
12319  case LookupResult::Ambiguous:
12320    break;
12321  }
12322
12323  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12324    // Maybe we will complain about the shadowed template parameter.
12325    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12326    // Just pretend that we didn't see the previous declaration.
12327    PrevDecl = 0;
12328  }
12329
12330  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12331    PrevDecl = 0;
12332
12333  SourceLocation TSSL = D.getLocStart();
12334  MSPropertyDecl *NewPD;
12335  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12336  NewPD = new (Context) MSPropertyDecl(Record, Loc,
12337                                       II, T, TInfo, TSSL,
12338                                       Data.GetterId, Data.SetterId);
12339  ProcessDeclAttributes(TUScope, NewPD, D);
12340  NewPD->setAccess(AS);
12341
12342  if (NewPD->isInvalidDecl())
12343    Record->setInvalidDecl();
12344
12345  if (D.getDeclSpec().isModulePrivateSpecified())
12346    NewPD->setModulePrivate();
12347
12348  if (NewPD->isInvalidDecl() && PrevDecl) {
12349    // Don't introduce NewFD into scope; there's already something
12350    // with the same name in the same scope.
12351  } else if (II) {
12352    PushOnScopeChains(NewPD, S);
12353  } else
12354    Record->addDecl(NewPD);
12355
12356  return NewPD;
12357}
12358