SemaDeclCXX.cpp revision c4ef9485252c6a408acb70aac5a153dcd9d860c7
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
407static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
408  for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
409    const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
410    if (!PVD->hasDefaultArg())
411      return false;
412    if (!PVD->hasInheritedDefaultArg())
413      return true;
414  }
415  return false;
416}
417
418/// MergeCXXFunctionDecl - Merge two declarations of the same C++
419/// function, once we already know that they have the same
420/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
421/// error, false otherwise.
422bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
423                                Scope *S) {
424  bool Invalid = false;
425
426  // C++ [dcl.fct.default]p4:
427  //   For non-template functions, default arguments can be added in
428  //   later declarations of a function in the same
429  //   scope. Declarations in different scopes have completely
430  //   distinct sets of default arguments. That is, declarations in
431  //   inner scopes do not acquire default arguments from
432  //   declarations in outer scopes, and vice versa. In a given
433  //   function declaration, all parameters subsequent to a
434  //   parameter with a default argument shall have default
435  //   arguments supplied in this or previous declarations. A
436  //   default argument shall not be redefined by a later
437  //   declaration (not even to the same value).
438  //
439  // C++ [dcl.fct.default]p6:
440  //   Except for member functions of class templates, the default arguments
441  //   in a member function definition that appears outside of the class
442  //   definition are added to the set of default arguments provided by the
443  //   member function declaration in the class definition.
444  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
445    ParmVarDecl *OldParam = Old->getParamDecl(p);
446    ParmVarDecl *NewParam = New->getParamDecl(p);
447
448    bool OldParamHasDfl = OldParam->hasDefaultArg();
449    bool NewParamHasDfl = NewParam->hasDefaultArg();
450
451    NamedDecl *ND = Old;
452    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
453      // Ignore default parameters of old decl if they are not in
454      // the same scope.
455      OldParamHasDfl = false;
456
457    if (OldParamHasDfl && NewParamHasDfl) {
458
459      unsigned DiagDefaultParamID =
460        diag::err_param_default_argument_redefinition;
461
462      // MSVC accepts that default parameters be redefined for member functions
463      // of template class. The new default parameter's value is ignored.
464      Invalid = true;
465      if (getLangOpts().MicrosoftExt) {
466        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
467        if (MD && MD->getParent()->getDescribedClassTemplate()) {
468          // Merge the old default argument into the new parameter.
469          NewParam->setHasInheritedDefaultArg();
470          if (OldParam->hasUninstantiatedDefaultArg())
471            NewParam->setUninstantiatedDefaultArg(
472                                      OldParam->getUninstantiatedDefaultArg());
473          else
474            NewParam->setDefaultArg(OldParam->getInit());
475          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
476          Invalid = false;
477        }
478      }
479
480      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
481      // hint here. Alternatively, we could walk the type-source information
482      // for NewParam to find the last source location in the type... but it
483      // isn't worth the effort right now. This is the kind of test case that
484      // is hard to get right:
485      //   int f(int);
486      //   void g(int (*fp)(int) = f);
487      //   void g(int (*fp)(int) = &f);
488      Diag(NewParam->getLocation(), DiagDefaultParamID)
489        << NewParam->getDefaultArgRange();
490
491      // Look for the function declaration where the default argument was
492      // actually written, which may be a declaration prior to Old.
493      for (FunctionDecl *Older = Old->getPreviousDecl();
494           Older; Older = Older->getPreviousDecl()) {
495        if (!Older->getParamDecl(p)->hasDefaultArg())
496          break;
497
498        OldParam = Older->getParamDecl(p);
499      }
500
501      Diag(OldParam->getLocation(), diag::note_previous_definition)
502        << OldParam->getDefaultArgRange();
503    } else if (OldParamHasDfl) {
504      // Merge the old default argument into the new parameter.
505      // It's important to use getInit() here;  getDefaultArg()
506      // strips off any top-level ExprWithCleanups.
507      NewParam->setHasInheritedDefaultArg();
508      if (OldParam->hasUninstantiatedDefaultArg())
509        NewParam->setUninstantiatedDefaultArg(
510                                      OldParam->getUninstantiatedDefaultArg());
511      else
512        NewParam->setDefaultArg(OldParam->getInit());
513    } else if (NewParamHasDfl) {
514      if (New->getDescribedFunctionTemplate()) {
515        // Paragraph 4, quoted above, only applies to non-template functions.
516        Diag(NewParam->getLocation(),
517             diag::err_param_default_argument_template_redecl)
518          << NewParam->getDefaultArgRange();
519        Diag(Old->getLocation(), diag::note_template_prev_declaration)
520          << false;
521      } else if (New->getTemplateSpecializationKind()
522                   != TSK_ImplicitInstantiation &&
523                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
524        // C++ [temp.expr.spec]p21:
525        //   Default function arguments shall not be specified in a declaration
526        //   or a definition for one of the following explicit specializations:
527        //     - the explicit specialization of a function template;
528        //     - the explicit specialization of a member function template;
529        //     - the explicit specialization of a member function of a class
530        //       template where the class template specialization to which the
531        //       member function specialization belongs is implicitly
532        //       instantiated.
533        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
534          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
535          << New->getDeclName()
536          << NewParam->getDefaultArgRange();
537      } else if (New->getDeclContext()->isDependentContext()) {
538        // C++ [dcl.fct.default]p6 (DR217):
539        //   Default arguments for a member function of a class template shall
540        //   be specified on the initial declaration of the member function
541        //   within the class template.
542        //
543        // Reading the tea leaves a bit in DR217 and its reference to DR205
544        // leads me to the conclusion that one cannot add default function
545        // arguments for an out-of-line definition of a member function of a
546        // dependent type.
547        int WhichKind = 2;
548        if (CXXRecordDecl *Record
549              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
550          if (Record->getDescribedClassTemplate())
551            WhichKind = 0;
552          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
553            WhichKind = 1;
554          else
555            WhichKind = 2;
556        }
557
558        Diag(NewParam->getLocation(),
559             diag::err_param_default_argument_member_template_redecl)
560          << WhichKind
561          << NewParam->getDefaultArgRange();
562      }
563    }
564  }
565
566  // DR1344: If a default argument is added outside a class definition and that
567  // default argument makes the function a special member function, the program
568  // is ill-formed. This can only happen for constructors.
569  if (isa<CXXConstructorDecl>(New) &&
570      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
571    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
572                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
573    if (NewSM != OldSM) {
574      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
575      assert(NewParam->hasDefaultArg());
576      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
577        << NewParam->getDefaultArgRange() << NewSM;
578      Diag(Old->getLocation(), diag::note_previous_declaration);
579    }
580  }
581
582  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
583  // template has a constexpr specifier then all its declarations shall
584  // contain the constexpr specifier.
585  if (New->isConstexpr() != Old->isConstexpr()) {
586    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
587      << New << New->isConstexpr();
588    Diag(Old->getLocation(), diag::note_previous_declaration);
589    Invalid = true;
590  }
591
592  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
593  // argument expression, that declaration shall be a definition and shall be
594  // the only declaration of the function or function template in the
595  // translation unit.
596  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
597      functionDeclHasDefaultArgument(Old)) {
598    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
599    Diag(Old->getLocation(), diag::note_previous_declaration);
600    Invalid = true;
601  }
602
603  if (CheckEquivalentExceptionSpec(Old, New))
604    Invalid = true;
605
606  return Invalid;
607}
608
609/// \brief Merge the exception specifications of two variable declarations.
610///
611/// This is called when there's a redeclaration of a VarDecl. The function
612/// checks if the redeclaration might have an exception specification and
613/// validates compatibility and merges the specs if necessary.
614void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
615  // Shortcut if exceptions are disabled.
616  if (!getLangOpts().CXXExceptions)
617    return;
618
619  assert(Context.hasSameType(New->getType(), Old->getType()) &&
620         "Should only be called if types are otherwise the same.");
621
622  QualType NewType = New->getType();
623  QualType OldType = Old->getType();
624
625  // We're only interested in pointers and references to functions, as well
626  // as pointers to member functions.
627  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
628    NewType = R->getPointeeType();
629    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
630  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
631    NewType = P->getPointeeType();
632    OldType = OldType->getAs<PointerType>()->getPointeeType();
633  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
634    NewType = M->getPointeeType();
635    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
636  }
637
638  if (!NewType->isFunctionProtoType())
639    return;
640
641  // There's lots of special cases for functions. For function pointers, system
642  // libraries are hopefully not as broken so that we don't need these
643  // workarounds.
644  if (CheckEquivalentExceptionSpec(
645        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
646        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
647    New->setInvalidDecl();
648  }
649}
650
651/// CheckCXXDefaultArguments - Verify that the default arguments for a
652/// function declaration are well-formed according to C++
653/// [dcl.fct.default].
654void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
655  unsigned NumParams = FD->getNumParams();
656  unsigned p;
657
658  // Find first parameter with a default argument
659  for (p = 0; p < NumParams; ++p) {
660    ParmVarDecl *Param = FD->getParamDecl(p);
661    if (Param->hasDefaultArg())
662      break;
663  }
664
665  // C++ [dcl.fct.default]p4:
666  //   In a given function declaration, all parameters
667  //   subsequent to a parameter with a default argument shall
668  //   have default arguments supplied in this or previous
669  //   declarations. A default argument shall not be redefined
670  //   by a later declaration (not even to the same value).
671  unsigned LastMissingDefaultArg = 0;
672  for (; p < NumParams; ++p) {
673    ParmVarDecl *Param = FD->getParamDecl(p);
674    if (!Param->hasDefaultArg()) {
675      if (Param->isInvalidDecl())
676        /* We already complained about this parameter. */;
677      else if (Param->getIdentifier())
678        Diag(Param->getLocation(),
679             diag::err_param_default_argument_missing_name)
680          << Param->getIdentifier();
681      else
682        Diag(Param->getLocation(),
683             diag::err_param_default_argument_missing);
684
685      LastMissingDefaultArg = p;
686    }
687  }
688
689  if (LastMissingDefaultArg > 0) {
690    // Some default arguments were missing. Clear out all of the
691    // default arguments up to (and including) the last missing
692    // default argument, so that we leave the function parameters
693    // in a semantically valid state.
694    for (p = 0; p <= LastMissingDefaultArg; ++p) {
695      ParmVarDecl *Param = FD->getParamDecl(p);
696      if (Param->hasDefaultArg()) {
697        Param->setDefaultArg(0);
698      }
699    }
700  }
701}
702
703// CheckConstexprParameterTypes - Check whether a function's parameter types
704// are all literal types. If so, return true. If not, produce a suitable
705// diagnostic and return false.
706static bool CheckConstexprParameterTypes(Sema &SemaRef,
707                                         const FunctionDecl *FD) {
708  unsigned ArgIndex = 0;
709  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
710  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
711       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
712    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
713    SourceLocation ParamLoc = PD->getLocation();
714    if (!(*i)->isDependentType() &&
715        SemaRef.RequireLiteralType(ParamLoc, *i,
716                                   diag::err_constexpr_non_literal_param,
717                                   ArgIndex+1, PD->getSourceRange(),
718                                   isa<CXXConstructorDecl>(FD)))
719      return false;
720  }
721  return true;
722}
723
724/// \brief Get diagnostic %select index for tag kind for
725/// record diagnostic message.
726/// WARNING: Indexes apply to particular diagnostics only!
727///
728/// \returns diagnostic %select index.
729static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
730  switch (Tag) {
731  case TTK_Struct: return 0;
732  case TTK_Interface: return 1;
733  case TTK_Class:  return 2;
734  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
735  }
736}
737
738// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
739// the requirements of a constexpr function definition or a constexpr
740// constructor definition. If so, return true. If not, produce appropriate
741// diagnostics and return false.
742//
743// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
744bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
745  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
746  if (MD && MD->isInstance()) {
747    // C++11 [dcl.constexpr]p4:
748    //  The definition of a constexpr constructor shall satisfy the following
749    //  constraints:
750    //  - the class shall not have any virtual base classes;
751    const CXXRecordDecl *RD = MD->getParent();
752    if (RD->getNumVBases()) {
753      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
754        << isa<CXXConstructorDecl>(NewFD)
755        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
756      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
757             E = RD->vbases_end(); I != E; ++I)
758        Diag(I->getLocStart(),
759             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
760      return false;
761    }
762  }
763
764  if (!isa<CXXConstructorDecl>(NewFD)) {
765    // C++11 [dcl.constexpr]p3:
766    //  The definition of a constexpr function shall satisfy the following
767    //  constraints:
768    // - it shall not be virtual;
769    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
770    if (Method && Method->isVirtual()) {
771      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
772
773      // If it's not obvious why this function is virtual, find an overridden
774      // function which uses the 'virtual' keyword.
775      const CXXMethodDecl *WrittenVirtual = Method;
776      while (!WrittenVirtual->isVirtualAsWritten())
777        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
778      if (WrittenVirtual != Method)
779        Diag(WrittenVirtual->getLocation(),
780             diag::note_overridden_virtual_function);
781      return false;
782    }
783
784    // - its return type shall be a literal type;
785    QualType RT = NewFD->getResultType();
786    if (!RT->isDependentType() &&
787        RequireLiteralType(NewFD->getLocation(), RT,
788                           diag::err_constexpr_non_literal_return))
789      return false;
790  }
791
792  // - each of its parameter types shall be a literal type;
793  if (!CheckConstexprParameterTypes(*this, NewFD))
794    return false;
795
796  return true;
797}
798
799/// Check the given declaration statement is legal within a constexpr function
800/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
801///
802/// \return true if the body is OK (maybe only as an extension), false if we
803///         have diagnosed a problem.
804static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
805                                   DeclStmt *DS, SourceLocation &Cxx1yLoc) {
806  // C++11 [dcl.constexpr]p3 and p4:
807  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
808  //  contain only
809  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
810         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
811    switch ((*DclIt)->getKind()) {
812    case Decl::StaticAssert:
813    case Decl::Using:
814    case Decl::UsingShadow:
815    case Decl::UsingDirective:
816    case Decl::UnresolvedUsingTypename:
817    case Decl::UnresolvedUsingValue:
818      //   - static_assert-declarations
819      //   - using-declarations,
820      //   - using-directives,
821      continue;
822
823    case Decl::Typedef:
824    case Decl::TypeAlias: {
825      //   - typedef declarations and alias-declarations that do not define
826      //     classes or enumerations,
827      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
828      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
829        // Don't allow variably-modified types in constexpr functions.
830        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
831        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
832          << TL.getSourceRange() << TL.getType()
833          << isa<CXXConstructorDecl>(Dcl);
834        return false;
835      }
836      continue;
837    }
838
839    case Decl::Enum:
840    case Decl::CXXRecord:
841      // C++1y allows types to be defined, not just declared.
842      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
843        SemaRef.Diag(DS->getLocStart(),
844                     SemaRef.getLangOpts().CPlusPlus1y
845                       ? diag::warn_cxx11_compat_constexpr_type_definition
846                       : diag::ext_constexpr_type_definition)
847          << isa<CXXConstructorDecl>(Dcl);
848      continue;
849
850    case Decl::EnumConstant:
851    case Decl::IndirectField:
852    case Decl::ParmVar:
853      // These can only appear with other declarations which are banned in
854      // C++11 and permitted in C++1y, so ignore them.
855      continue;
856
857    case Decl::Var: {
858      // C++1y [dcl.constexpr]p3 allows anything except:
859      //   a definition of a variable of non-literal type or of static or
860      //   thread storage duration or for which no initialization is performed.
861      VarDecl *VD = cast<VarDecl>(*DclIt);
862      if (VD->isThisDeclarationADefinition()) {
863        if (VD->isStaticLocal()) {
864          SemaRef.Diag(VD->getLocation(),
865                       diag::err_constexpr_local_var_static)
866            << isa<CXXConstructorDecl>(Dcl)
867            << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
868          return false;
869        }
870        if (!VD->getType()->isDependentType() &&
871            SemaRef.RequireLiteralType(
872              VD->getLocation(), VD->getType(),
873              diag::err_constexpr_local_var_non_literal_type,
874              isa<CXXConstructorDecl>(Dcl)))
875          return false;
876        if (!VD->hasInit()) {
877          SemaRef.Diag(VD->getLocation(),
878                       diag::err_constexpr_local_var_no_init)
879            << isa<CXXConstructorDecl>(Dcl);
880          return false;
881        }
882      }
883      SemaRef.Diag(VD->getLocation(),
884                   SemaRef.getLangOpts().CPlusPlus1y
885                    ? diag::warn_cxx11_compat_constexpr_local_var
886                    : diag::ext_constexpr_local_var)
887        << isa<CXXConstructorDecl>(Dcl);
888      continue;
889    }
890
891    case Decl::NamespaceAlias:
892    case Decl::Function:
893      // These are disallowed in C++11 and permitted in C++1y. Allow them
894      // everywhere as an extension.
895      if (!Cxx1yLoc.isValid())
896        Cxx1yLoc = DS->getLocStart();
897      continue;
898
899    default:
900      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
901        << isa<CXXConstructorDecl>(Dcl);
902      return false;
903    }
904  }
905
906  return true;
907}
908
909/// Check that the given field is initialized within a constexpr constructor.
910///
911/// \param Dcl The constexpr constructor being checked.
912/// \param Field The field being checked. This may be a member of an anonymous
913///        struct or union nested within the class being checked.
914/// \param Inits All declarations, including anonymous struct/union members and
915///        indirect members, for which any initialization was provided.
916/// \param Diagnosed Set to true if an error is produced.
917static void CheckConstexprCtorInitializer(Sema &SemaRef,
918                                          const FunctionDecl *Dcl,
919                                          FieldDecl *Field,
920                                          llvm::SmallSet<Decl*, 16> &Inits,
921                                          bool &Diagnosed) {
922  if (Field->isInvalidDecl())
923    return;
924
925  if (Field->isUnnamedBitfield())
926    return;
927
928  if (Field->isAnonymousStructOrUnion() &&
929      Field->getType()->getAsCXXRecordDecl()->isEmpty())
930    return;
931
932  if (!Inits.count(Field)) {
933    if (!Diagnosed) {
934      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
935      Diagnosed = true;
936    }
937    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
938  } else if (Field->isAnonymousStructOrUnion()) {
939    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
940    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
941         I != E; ++I)
942      // If an anonymous union contains an anonymous struct of which any member
943      // is initialized, all members must be initialized.
944      if (!RD->isUnion() || Inits.count(*I))
945        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
946  }
947}
948
949/// Check the provided statement is allowed in a constexpr function
950/// definition.
951static bool
952CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
953                           llvm::SmallVectorImpl<SourceLocation> &ReturnStmts,
954                           SourceLocation &Cxx1yLoc) {
955  // - its function-body shall be [...] a compound-statement that contains only
956  switch (S->getStmtClass()) {
957  case Stmt::NullStmtClass:
958    //   - null statements,
959    return true;
960
961  case Stmt::DeclStmtClass:
962    //   - static_assert-declarations
963    //   - using-declarations,
964    //   - using-directives,
965    //   - typedef declarations and alias-declarations that do not define
966    //     classes or enumerations,
967    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
968      return false;
969    return true;
970
971  case Stmt::ReturnStmtClass:
972    //   - and exactly one return statement;
973    if (isa<CXXConstructorDecl>(Dcl)) {
974      // C++1y allows return statements in constexpr constructors.
975      if (!Cxx1yLoc.isValid())
976        Cxx1yLoc = S->getLocStart();
977      return true;
978    }
979
980    ReturnStmts.push_back(S->getLocStart());
981    return true;
982
983  case Stmt::CompoundStmtClass: {
984    // C++1y allows compound-statements.
985    if (!Cxx1yLoc.isValid())
986      Cxx1yLoc = S->getLocStart();
987
988    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
989    for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
990           BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
991      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
992                                      Cxx1yLoc))
993        return false;
994    }
995    return true;
996  }
997
998  case Stmt::AttributedStmtClass:
999    if (!Cxx1yLoc.isValid())
1000      Cxx1yLoc = S->getLocStart();
1001    return true;
1002
1003  case Stmt::IfStmtClass: {
1004    // C++1y allows if-statements.
1005    if (!Cxx1yLoc.isValid())
1006      Cxx1yLoc = S->getLocStart();
1007
1008    IfStmt *If = cast<IfStmt>(S);
1009    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1010                                    Cxx1yLoc))
1011      return false;
1012    if (If->getElse() &&
1013        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1014                                    Cxx1yLoc))
1015      return false;
1016    return true;
1017  }
1018
1019  case Stmt::WhileStmtClass:
1020  case Stmt::DoStmtClass:
1021  case Stmt::ForStmtClass:
1022  case Stmt::CXXForRangeStmtClass:
1023  case Stmt::ContinueStmtClass:
1024    // C++1y allows all of these. We don't allow them as extensions in C++11,
1025    // because they don't make sense without variable mutation.
1026    if (!SemaRef.getLangOpts().CPlusPlus1y)
1027      break;
1028    if (!Cxx1yLoc.isValid())
1029      Cxx1yLoc = S->getLocStart();
1030    for (Stmt::child_range Children = S->children(); Children; ++Children)
1031      if (*Children &&
1032          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1033                                      Cxx1yLoc))
1034        return false;
1035    return true;
1036
1037  case Stmt::SwitchStmtClass:
1038  case Stmt::CaseStmtClass:
1039  case Stmt::DefaultStmtClass:
1040  case Stmt::BreakStmtClass:
1041    // C++1y allows switch-statements, and since they don't need variable
1042    // mutation, we can reasonably allow them in C++11 as an extension.
1043    if (!Cxx1yLoc.isValid())
1044      Cxx1yLoc = S->getLocStart();
1045    for (Stmt::child_range Children = S->children(); Children; ++Children)
1046      if (*Children &&
1047          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1048                                      Cxx1yLoc))
1049        return false;
1050    return true;
1051
1052  default:
1053    if (!isa<Expr>(S))
1054      break;
1055
1056    // C++1y allows expression-statements.
1057    if (!Cxx1yLoc.isValid())
1058      Cxx1yLoc = S->getLocStart();
1059    return true;
1060  }
1061
1062  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1063    << isa<CXXConstructorDecl>(Dcl);
1064  return false;
1065}
1066
1067/// Check the body for the given constexpr function declaration only contains
1068/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1069///
1070/// \return true if the body is OK, false if we have diagnosed a problem.
1071bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1072  if (isa<CXXTryStmt>(Body)) {
1073    // C++11 [dcl.constexpr]p3:
1074    //  The definition of a constexpr function shall satisfy the following
1075    //  constraints: [...]
1076    // - its function-body shall be = delete, = default, or a
1077    //   compound-statement
1078    //
1079    // C++11 [dcl.constexpr]p4:
1080    //  In the definition of a constexpr constructor, [...]
1081    // - its function-body shall not be a function-try-block;
1082    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1083      << isa<CXXConstructorDecl>(Dcl);
1084    return false;
1085  }
1086
1087  SmallVector<SourceLocation, 4> ReturnStmts;
1088
1089  // - its function-body shall be [...] a compound-statement that contains only
1090  //   [... list of cases ...]
1091  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1092  SourceLocation Cxx1yLoc;
1093  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1094         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1095    if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1096      return false;
1097  }
1098
1099  if (Cxx1yLoc.isValid())
1100    Diag(Cxx1yLoc,
1101         getLangOpts().CPlusPlus1y
1102           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1103           : diag::ext_constexpr_body_invalid_stmt)
1104      << isa<CXXConstructorDecl>(Dcl);
1105
1106  if (const CXXConstructorDecl *Constructor
1107        = dyn_cast<CXXConstructorDecl>(Dcl)) {
1108    const CXXRecordDecl *RD = Constructor->getParent();
1109    // DR1359:
1110    // - every non-variant non-static data member and base class sub-object
1111    //   shall be initialized;
1112    // - if the class is a non-empty union, or for each non-empty anonymous
1113    //   union member of a non-union class, exactly one non-static data member
1114    //   shall be initialized;
1115    if (RD->isUnion()) {
1116      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1117        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1118        return false;
1119      }
1120    } else if (!Constructor->isDependentContext() &&
1121               !Constructor->isDelegatingConstructor()) {
1122      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1123
1124      // Skip detailed checking if we have enough initializers, and we would
1125      // allow at most one initializer per member.
1126      bool AnyAnonStructUnionMembers = false;
1127      unsigned Fields = 0;
1128      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1129           E = RD->field_end(); I != E; ++I, ++Fields) {
1130        if (I->isAnonymousStructOrUnion()) {
1131          AnyAnonStructUnionMembers = true;
1132          break;
1133        }
1134      }
1135      if (AnyAnonStructUnionMembers ||
1136          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1137        // Check initialization of non-static data members. Base classes are
1138        // always initialized so do not need to be checked. Dependent bases
1139        // might not have initializers in the member initializer list.
1140        llvm::SmallSet<Decl*, 16> Inits;
1141        for (CXXConstructorDecl::init_const_iterator
1142               I = Constructor->init_begin(), E = Constructor->init_end();
1143             I != E; ++I) {
1144          if (FieldDecl *FD = (*I)->getMember())
1145            Inits.insert(FD);
1146          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1147            Inits.insert(ID->chain_begin(), ID->chain_end());
1148        }
1149
1150        bool Diagnosed = false;
1151        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1152             E = RD->field_end(); I != E; ++I)
1153          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1154        if (Diagnosed)
1155          return false;
1156      }
1157    }
1158  } else {
1159    if (ReturnStmts.empty()) {
1160      // C++1y doesn't require constexpr functions to contain a 'return'
1161      // statement. We still do, unless the return type is void, because
1162      // otherwise if there's no return statement, the function cannot
1163      // be used in a core constant expression.
1164      bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1165      Diag(Dcl->getLocation(),
1166           OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1167              : diag::err_constexpr_body_no_return);
1168      return OK;
1169    }
1170    if (ReturnStmts.size() > 1) {
1171      Diag(ReturnStmts.back(),
1172           getLangOpts().CPlusPlus1y
1173             ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1174             : diag::ext_constexpr_body_multiple_return);
1175      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1176        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1177    }
1178  }
1179
1180  // C++11 [dcl.constexpr]p5:
1181  //   if no function argument values exist such that the function invocation
1182  //   substitution would produce a constant expression, the program is
1183  //   ill-formed; no diagnostic required.
1184  // C++11 [dcl.constexpr]p3:
1185  //   - every constructor call and implicit conversion used in initializing the
1186  //     return value shall be one of those allowed in a constant expression.
1187  // C++11 [dcl.constexpr]p4:
1188  //   - every constructor involved in initializing non-static data members and
1189  //     base class sub-objects shall be a constexpr constructor.
1190  SmallVector<PartialDiagnosticAt, 8> Diags;
1191  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1192    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1193      << isa<CXXConstructorDecl>(Dcl);
1194    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1195      Diag(Diags[I].first, Diags[I].second);
1196    // Don't return false here: we allow this for compatibility in
1197    // system headers.
1198  }
1199
1200  return true;
1201}
1202
1203/// isCurrentClassName - Determine whether the identifier II is the
1204/// name of the class type currently being defined. In the case of
1205/// nested classes, this will only return true if II is the name of
1206/// the innermost class.
1207bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1208                              const CXXScopeSpec *SS) {
1209  assert(getLangOpts().CPlusPlus && "No class names in C!");
1210
1211  CXXRecordDecl *CurDecl;
1212  if (SS && SS->isSet() && !SS->isInvalid()) {
1213    DeclContext *DC = computeDeclContext(*SS, true);
1214    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1215  } else
1216    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1217
1218  if (CurDecl && CurDecl->getIdentifier())
1219    return &II == CurDecl->getIdentifier();
1220  else
1221    return false;
1222}
1223
1224/// \brief Determine whether the given class is a base class of the given
1225/// class, including looking at dependent bases.
1226static bool findCircularInheritance(const CXXRecordDecl *Class,
1227                                    const CXXRecordDecl *Current) {
1228  SmallVector<const CXXRecordDecl*, 8> Queue;
1229
1230  Class = Class->getCanonicalDecl();
1231  while (true) {
1232    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1233                                                  E = Current->bases_end();
1234         I != E; ++I) {
1235      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1236      if (!Base)
1237        continue;
1238
1239      Base = Base->getDefinition();
1240      if (!Base)
1241        continue;
1242
1243      if (Base->getCanonicalDecl() == Class)
1244        return true;
1245
1246      Queue.push_back(Base);
1247    }
1248
1249    if (Queue.empty())
1250      return false;
1251
1252    Current = Queue.back();
1253    Queue.pop_back();
1254  }
1255
1256  return false;
1257}
1258
1259/// \brief Check the validity of a C++ base class specifier.
1260///
1261/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1262/// and returns NULL otherwise.
1263CXXBaseSpecifier *
1264Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1265                         SourceRange SpecifierRange,
1266                         bool Virtual, AccessSpecifier Access,
1267                         TypeSourceInfo *TInfo,
1268                         SourceLocation EllipsisLoc) {
1269  QualType BaseType = TInfo->getType();
1270
1271  // C++ [class.union]p1:
1272  //   A union shall not have base classes.
1273  if (Class->isUnion()) {
1274    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1275      << SpecifierRange;
1276    return 0;
1277  }
1278
1279  if (EllipsisLoc.isValid() &&
1280      !TInfo->getType()->containsUnexpandedParameterPack()) {
1281    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1282      << TInfo->getTypeLoc().getSourceRange();
1283    EllipsisLoc = SourceLocation();
1284  }
1285
1286  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1287
1288  if (BaseType->isDependentType()) {
1289    // Make sure that we don't have circular inheritance among our dependent
1290    // bases. For non-dependent bases, the check for completeness below handles
1291    // this.
1292    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1293      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1294          ((BaseDecl = BaseDecl->getDefinition()) &&
1295           findCircularInheritance(Class, BaseDecl))) {
1296        Diag(BaseLoc, diag::err_circular_inheritance)
1297          << BaseType << Context.getTypeDeclType(Class);
1298
1299        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1300          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1301            << BaseType;
1302
1303        return 0;
1304      }
1305    }
1306
1307    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1308                                          Class->getTagKind() == TTK_Class,
1309                                          Access, TInfo, EllipsisLoc);
1310  }
1311
1312  // Base specifiers must be record types.
1313  if (!BaseType->isRecordType()) {
1314    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1315    return 0;
1316  }
1317
1318  // C++ [class.union]p1:
1319  //   A union shall not be used as a base class.
1320  if (BaseType->isUnionType()) {
1321    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1322    return 0;
1323  }
1324
1325  // C++ [class.derived]p2:
1326  //   The class-name in a base-specifier shall not be an incompletely
1327  //   defined class.
1328  if (RequireCompleteType(BaseLoc, BaseType,
1329                          diag::err_incomplete_base_class, SpecifierRange)) {
1330    Class->setInvalidDecl();
1331    return 0;
1332  }
1333
1334  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1335  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1336  assert(BaseDecl && "Record type has no declaration");
1337  BaseDecl = BaseDecl->getDefinition();
1338  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1339  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1340  assert(CXXBaseDecl && "Base type is not a C++ type");
1341
1342  // C++ [class]p3:
1343  //   If a class is marked final and it appears as a base-type-specifier in
1344  //   base-clause, the program is ill-formed.
1345  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1346    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1347      << CXXBaseDecl->getDeclName();
1348    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1349      << CXXBaseDecl->getDeclName();
1350    return 0;
1351  }
1352
1353  if (BaseDecl->isInvalidDecl())
1354    Class->setInvalidDecl();
1355
1356  // Create the base specifier.
1357  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1358                                        Class->getTagKind() == TTK_Class,
1359                                        Access, TInfo, EllipsisLoc);
1360}
1361
1362/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1363/// one entry in the base class list of a class specifier, for
1364/// example:
1365///    class foo : public bar, virtual private baz {
1366/// 'public bar' and 'virtual private baz' are each base-specifiers.
1367BaseResult
1368Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1369                         ParsedAttributes &Attributes,
1370                         bool Virtual, AccessSpecifier Access,
1371                         ParsedType basetype, SourceLocation BaseLoc,
1372                         SourceLocation EllipsisLoc) {
1373  if (!classdecl)
1374    return true;
1375
1376  AdjustDeclIfTemplate(classdecl);
1377  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1378  if (!Class)
1379    return true;
1380
1381  // We do not support any C++11 attributes on base-specifiers yet.
1382  // Diagnose any attributes we see.
1383  if (!Attributes.empty()) {
1384    for (AttributeList *Attr = Attributes.getList(); Attr;
1385         Attr = Attr->getNext()) {
1386      if (Attr->isInvalid() ||
1387          Attr->getKind() == AttributeList::IgnoredAttribute)
1388        continue;
1389      Diag(Attr->getLoc(),
1390           Attr->getKind() == AttributeList::UnknownAttribute
1391             ? diag::warn_unknown_attribute_ignored
1392             : diag::err_base_specifier_attribute)
1393        << Attr->getName();
1394    }
1395  }
1396
1397  TypeSourceInfo *TInfo = 0;
1398  GetTypeFromParser(basetype, &TInfo);
1399
1400  if (EllipsisLoc.isInvalid() &&
1401      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1402                                      UPPC_BaseType))
1403    return true;
1404
1405  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1406                                                      Virtual, Access, TInfo,
1407                                                      EllipsisLoc))
1408    return BaseSpec;
1409  else
1410    Class->setInvalidDecl();
1411
1412  return true;
1413}
1414
1415/// \brief Performs the actual work of attaching the given base class
1416/// specifiers to a C++ class.
1417bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1418                                unsigned NumBases) {
1419 if (NumBases == 0)
1420    return false;
1421
1422  // Used to keep track of which base types we have already seen, so
1423  // that we can properly diagnose redundant direct base types. Note
1424  // that the key is always the unqualified canonical type of the base
1425  // class.
1426  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1427
1428  // Copy non-redundant base specifiers into permanent storage.
1429  unsigned NumGoodBases = 0;
1430  bool Invalid = false;
1431  for (unsigned idx = 0; idx < NumBases; ++idx) {
1432    QualType NewBaseType
1433      = Context.getCanonicalType(Bases[idx]->getType());
1434    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1435
1436    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1437    if (KnownBase) {
1438      // C++ [class.mi]p3:
1439      //   A class shall not be specified as a direct base class of a
1440      //   derived class more than once.
1441      Diag(Bases[idx]->getLocStart(),
1442           diag::err_duplicate_base_class)
1443        << KnownBase->getType()
1444        << Bases[idx]->getSourceRange();
1445
1446      // Delete the duplicate base class specifier; we're going to
1447      // overwrite its pointer later.
1448      Context.Deallocate(Bases[idx]);
1449
1450      Invalid = true;
1451    } else {
1452      // Okay, add this new base class.
1453      KnownBase = Bases[idx];
1454      Bases[NumGoodBases++] = Bases[idx];
1455      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1456        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1457        if (Class->isInterface() &&
1458              (!RD->isInterface() ||
1459               KnownBase->getAccessSpecifier() != AS_public)) {
1460          // The Microsoft extension __interface does not permit bases that
1461          // are not themselves public interfaces.
1462          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1463            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1464            << RD->getSourceRange();
1465          Invalid = true;
1466        }
1467        if (RD->hasAttr<WeakAttr>())
1468          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1469      }
1470    }
1471  }
1472
1473  // Attach the remaining base class specifiers to the derived class.
1474  Class->setBases(Bases, NumGoodBases);
1475
1476  // Delete the remaining (good) base class specifiers, since their
1477  // data has been copied into the CXXRecordDecl.
1478  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1479    Context.Deallocate(Bases[idx]);
1480
1481  return Invalid;
1482}
1483
1484/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1485/// class, after checking whether there are any duplicate base
1486/// classes.
1487void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1488                               unsigned NumBases) {
1489  if (!ClassDecl || !Bases || !NumBases)
1490    return;
1491
1492  AdjustDeclIfTemplate(ClassDecl);
1493  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1494                       (CXXBaseSpecifier**)(Bases), NumBases);
1495}
1496
1497/// \brief Determine whether the type \p Derived is a C++ class that is
1498/// derived from the type \p Base.
1499bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1500  if (!getLangOpts().CPlusPlus)
1501    return false;
1502
1503  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1504  if (!DerivedRD)
1505    return false;
1506
1507  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1508  if (!BaseRD)
1509    return false;
1510
1511  // If either the base or the derived type is invalid, don't try to
1512  // check whether one is derived from the other.
1513  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1514    return false;
1515
1516  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1517  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1518}
1519
1520/// \brief Determine whether the type \p Derived is a C++ class that is
1521/// derived from the type \p Base.
1522bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1523  if (!getLangOpts().CPlusPlus)
1524    return false;
1525
1526  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1527  if (!DerivedRD)
1528    return false;
1529
1530  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1531  if (!BaseRD)
1532    return false;
1533
1534  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1535}
1536
1537void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1538                              CXXCastPath &BasePathArray) {
1539  assert(BasePathArray.empty() && "Base path array must be empty!");
1540  assert(Paths.isRecordingPaths() && "Must record paths!");
1541
1542  const CXXBasePath &Path = Paths.front();
1543
1544  // We first go backward and check if we have a virtual base.
1545  // FIXME: It would be better if CXXBasePath had the base specifier for
1546  // the nearest virtual base.
1547  unsigned Start = 0;
1548  for (unsigned I = Path.size(); I != 0; --I) {
1549    if (Path[I - 1].Base->isVirtual()) {
1550      Start = I - 1;
1551      break;
1552    }
1553  }
1554
1555  // Now add all bases.
1556  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1557    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1558}
1559
1560/// \brief Determine whether the given base path includes a virtual
1561/// base class.
1562bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1563  for (CXXCastPath::const_iterator B = BasePath.begin(),
1564                                BEnd = BasePath.end();
1565       B != BEnd; ++B)
1566    if ((*B)->isVirtual())
1567      return true;
1568
1569  return false;
1570}
1571
1572/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1573/// conversion (where Derived and Base are class types) is
1574/// well-formed, meaning that the conversion is unambiguous (and
1575/// that all of the base classes are accessible). Returns true
1576/// and emits a diagnostic if the code is ill-formed, returns false
1577/// otherwise. Loc is the location where this routine should point to
1578/// if there is an error, and Range is the source range to highlight
1579/// if there is an error.
1580bool
1581Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1582                                   unsigned InaccessibleBaseID,
1583                                   unsigned AmbigiousBaseConvID,
1584                                   SourceLocation Loc, SourceRange Range,
1585                                   DeclarationName Name,
1586                                   CXXCastPath *BasePath) {
1587  // First, determine whether the path from Derived to Base is
1588  // ambiguous. This is slightly more expensive than checking whether
1589  // the Derived to Base conversion exists, because here we need to
1590  // explore multiple paths to determine if there is an ambiguity.
1591  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1592                     /*DetectVirtual=*/false);
1593  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1594  assert(DerivationOkay &&
1595         "Can only be used with a derived-to-base conversion");
1596  (void)DerivationOkay;
1597
1598  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1599    if (InaccessibleBaseID) {
1600      // Check that the base class can be accessed.
1601      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1602                                   InaccessibleBaseID)) {
1603        case AR_inaccessible:
1604          return true;
1605        case AR_accessible:
1606        case AR_dependent:
1607        case AR_delayed:
1608          break;
1609      }
1610    }
1611
1612    // Build a base path if necessary.
1613    if (BasePath)
1614      BuildBasePathArray(Paths, *BasePath);
1615    return false;
1616  }
1617
1618  if (AmbigiousBaseConvID) {
1619    // We know that the derived-to-base conversion is ambiguous, and
1620    // we're going to produce a diagnostic. Perform the derived-to-base
1621    // search just one more time to compute all of the possible paths so
1622    // that we can print them out. This is more expensive than any of
1623    // the previous derived-to-base checks we've done, but at this point
1624    // performance isn't as much of an issue.
1625    Paths.clear();
1626    Paths.setRecordingPaths(true);
1627    bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1628    assert(StillOkay && "Can only be used with a derived-to-base conversion");
1629    (void)StillOkay;
1630
1631    // Build up a textual representation of the ambiguous paths, e.g.,
1632    // D -> B -> A, that will be used to illustrate the ambiguous
1633    // conversions in the diagnostic. We only print one of the paths
1634    // to each base class subobject.
1635    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1636
1637    Diag(Loc, AmbigiousBaseConvID)
1638    << Derived << Base << PathDisplayStr << Range << Name;
1639  }
1640  return true;
1641}
1642
1643bool
1644Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1645                                   SourceLocation Loc, SourceRange Range,
1646                                   CXXCastPath *BasePath,
1647                                   bool IgnoreAccess) {
1648  return CheckDerivedToBaseConversion(Derived, Base,
1649                                      IgnoreAccess ? 0
1650                                       : diag::err_upcast_to_inaccessible_base,
1651                                      diag::err_ambiguous_derived_to_base_conv,
1652                                      Loc, Range, DeclarationName(),
1653                                      BasePath);
1654}
1655
1656
1657/// @brief Builds a string representing ambiguous paths from a
1658/// specific derived class to different subobjects of the same base
1659/// class.
1660///
1661/// This function builds a string that can be used in error messages
1662/// to show the different paths that one can take through the
1663/// inheritance hierarchy to go from the derived class to different
1664/// subobjects of a base class. The result looks something like this:
1665/// @code
1666/// struct D -> struct B -> struct A
1667/// struct D -> struct C -> struct A
1668/// @endcode
1669std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1670  std::string PathDisplayStr;
1671  std::set<unsigned> DisplayedPaths;
1672  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1673       Path != Paths.end(); ++Path) {
1674    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1675      // We haven't displayed a path to this particular base
1676      // class subobject yet.
1677      PathDisplayStr += "\n    ";
1678      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1679      for (CXXBasePath::const_iterator Element = Path->begin();
1680           Element != Path->end(); ++Element)
1681        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1682    }
1683  }
1684
1685  return PathDisplayStr;
1686}
1687
1688//===----------------------------------------------------------------------===//
1689// C++ class member Handling
1690//===----------------------------------------------------------------------===//
1691
1692/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1693bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1694                                SourceLocation ASLoc,
1695                                SourceLocation ColonLoc,
1696                                AttributeList *Attrs) {
1697  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1698  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1699                                                  ASLoc, ColonLoc);
1700  CurContext->addHiddenDecl(ASDecl);
1701  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1702}
1703
1704/// CheckOverrideControl - Check C++11 override control semantics.
1705void Sema::CheckOverrideControl(Decl *D) {
1706  if (D->isInvalidDecl())
1707    return;
1708
1709  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1710
1711  // Do we know which functions this declaration might be overriding?
1712  bool OverridesAreKnown = !MD ||
1713      (!MD->getParent()->hasAnyDependentBases() &&
1714       !MD->getType()->isDependentType());
1715
1716  if (!MD || !MD->isVirtual()) {
1717    if (OverridesAreKnown) {
1718      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1719        Diag(OA->getLocation(),
1720             diag::override_keyword_only_allowed_on_virtual_member_functions)
1721          << "override" << FixItHint::CreateRemoval(OA->getLocation());
1722        D->dropAttr<OverrideAttr>();
1723      }
1724      if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1725        Diag(FA->getLocation(),
1726             diag::override_keyword_only_allowed_on_virtual_member_functions)
1727          << "final" << FixItHint::CreateRemoval(FA->getLocation());
1728        D->dropAttr<FinalAttr>();
1729      }
1730    }
1731    return;
1732  }
1733
1734  if (!OverridesAreKnown)
1735    return;
1736
1737  // C++11 [class.virtual]p5:
1738  //   If a virtual function is marked with the virt-specifier override and
1739  //   does not override a member function of a base class, the program is
1740  //   ill-formed.
1741  bool HasOverriddenMethods =
1742    MD->begin_overridden_methods() != MD->end_overridden_methods();
1743  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1744    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1745      << MD->getDeclName();
1746}
1747
1748/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1749/// function overrides a virtual member function marked 'final', according to
1750/// C++11 [class.virtual]p4.
1751bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1752                                                  const CXXMethodDecl *Old) {
1753  if (!Old->hasAttr<FinalAttr>())
1754    return false;
1755
1756  Diag(New->getLocation(), diag::err_final_function_overridden)
1757    << New->getDeclName();
1758  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1759  return true;
1760}
1761
1762static bool InitializationHasSideEffects(const FieldDecl &FD) {
1763  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1764  // FIXME: Destruction of ObjC lifetime types has side-effects.
1765  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1766    return !RD->isCompleteDefinition() ||
1767           !RD->hasTrivialDefaultConstructor() ||
1768           !RD->hasTrivialDestructor();
1769  return false;
1770}
1771
1772static AttributeList *getMSPropertyAttr(AttributeList *list) {
1773  for (AttributeList* it = list; it != 0; it = it->getNext())
1774    if (it->isDeclspecPropertyAttribute())
1775      return it;
1776  return 0;
1777}
1778
1779/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1780/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1781/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1782/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1783/// present (but parsing it has been deferred).
1784NamedDecl *
1785Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1786                               MultiTemplateParamsArg TemplateParameterLists,
1787                               Expr *BW, const VirtSpecifiers &VS,
1788                               InClassInitStyle InitStyle) {
1789  const DeclSpec &DS = D.getDeclSpec();
1790  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1791  DeclarationName Name = NameInfo.getName();
1792  SourceLocation Loc = NameInfo.getLoc();
1793
1794  // For anonymous bitfields, the location should point to the type.
1795  if (Loc.isInvalid())
1796    Loc = D.getLocStart();
1797
1798  Expr *BitWidth = static_cast<Expr*>(BW);
1799
1800  assert(isa<CXXRecordDecl>(CurContext));
1801  assert(!DS.isFriendSpecified());
1802
1803  bool isFunc = D.isDeclarationOfFunction();
1804
1805  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1806    // The Microsoft extension __interface only permits public member functions
1807    // and prohibits constructors, destructors, operators, non-public member
1808    // functions, static methods and data members.
1809    unsigned InvalidDecl;
1810    bool ShowDeclName = true;
1811    if (!isFunc)
1812      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1813    else if (AS != AS_public)
1814      InvalidDecl = 2;
1815    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1816      InvalidDecl = 3;
1817    else switch (Name.getNameKind()) {
1818      case DeclarationName::CXXConstructorName:
1819        InvalidDecl = 4;
1820        ShowDeclName = false;
1821        break;
1822
1823      case DeclarationName::CXXDestructorName:
1824        InvalidDecl = 5;
1825        ShowDeclName = false;
1826        break;
1827
1828      case DeclarationName::CXXOperatorName:
1829      case DeclarationName::CXXConversionFunctionName:
1830        InvalidDecl = 6;
1831        break;
1832
1833      default:
1834        InvalidDecl = 0;
1835        break;
1836    }
1837
1838    if (InvalidDecl) {
1839      if (ShowDeclName)
1840        Diag(Loc, diag::err_invalid_member_in_interface)
1841          << (InvalidDecl-1) << Name;
1842      else
1843        Diag(Loc, diag::err_invalid_member_in_interface)
1844          << (InvalidDecl-1) << "";
1845      return 0;
1846    }
1847  }
1848
1849  // C++ 9.2p6: A member shall not be declared to have automatic storage
1850  // duration (auto, register) or with the extern storage-class-specifier.
1851  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1852  // data members and cannot be applied to names declared const or static,
1853  // and cannot be applied to reference members.
1854  switch (DS.getStorageClassSpec()) {
1855  case DeclSpec::SCS_unspecified:
1856  case DeclSpec::SCS_typedef:
1857  case DeclSpec::SCS_static:
1858    break;
1859  case DeclSpec::SCS_mutable:
1860    if (isFunc) {
1861      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1862
1863      // FIXME: It would be nicer if the keyword was ignored only for this
1864      // declarator. Otherwise we could get follow-up errors.
1865      D.getMutableDeclSpec().ClearStorageClassSpecs();
1866    }
1867    break;
1868  default:
1869    Diag(DS.getStorageClassSpecLoc(),
1870         diag::err_storageclass_invalid_for_member);
1871    D.getMutableDeclSpec().ClearStorageClassSpecs();
1872    break;
1873  }
1874
1875  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1876                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1877                      !isFunc);
1878
1879  if (DS.isConstexprSpecified() && isInstField) {
1880    SemaDiagnosticBuilder B =
1881        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1882    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1883    if (InitStyle == ICIS_NoInit) {
1884      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1885      D.getMutableDeclSpec().ClearConstexprSpec();
1886      const char *PrevSpec;
1887      unsigned DiagID;
1888      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1889                                         PrevSpec, DiagID, getLangOpts());
1890      (void)Failed;
1891      assert(!Failed && "Making a constexpr member const shouldn't fail");
1892    } else {
1893      B << 1;
1894      const char *PrevSpec;
1895      unsigned DiagID;
1896      if (D.getMutableDeclSpec().SetStorageClassSpec(
1897          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1898        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1899               "This is the only DeclSpec that should fail to be applied");
1900        B << 1;
1901      } else {
1902        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1903        isInstField = false;
1904      }
1905    }
1906  }
1907
1908  NamedDecl *Member;
1909  if (isInstField) {
1910    CXXScopeSpec &SS = D.getCXXScopeSpec();
1911
1912    // Data members must have identifiers for names.
1913    if (!Name.isIdentifier()) {
1914      Diag(Loc, diag::err_bad_variable_name)
1915        << Name;
1916      return 0;
1917    }
1918
1919    IdentifierInfo *II = Name.getAsIdentifierInfo();
1920
1921    // Member field could not be with "template" keyword.
1922    // So TemplateParameterLists should be empty in this case.
1923    if (TemplateParameterLists.size()) {
1924      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1925      if (TemplateParams->size()) {
1926        // There is no such thing as a member field template.
1927        Diag(D.getIdentifierLoc(), diag::err_template_member)
1928            << II
1929            << SourceRange(TemplateParams->getTemplateLoc(),
1930                TemplateParams->getRAngleLoc());
1931      } else {
1932        // There is an extraneous 'template<>' for this member.
1933        Diag(TemplateParams->getTemplateLoc(),
1934            diag::err_template_member_noparams)
1935            << II
1936            << SourceRange(TemplateParams->getTemplateLoc(),
1937                TemplateParams->getRAngleLoc());
1938      }
1939      return 0;
1940    }
1941
1942    if (SS.isSet() && !SS.isInvalid()) {
1943      // The user provided a superfluous scope specifier inside a class
1944      // definition:
1945      //
1946      // class X {
1947      //   int X::member;
1948      // };
1949      if (DeclContext *DC = computeDeclContext(SS, false))
1950        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1951      else
1952        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1953          << Name << SS.getRange();
1954
1955      SS.clear();
1956    }
1957
1958    AttributeList *MSPropertyAttr =
1959      getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
1960    if (MSPropertyAttr) {
1961      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1962                                BitWidth, InitStyle, AS, MSPropertyAttr);
1963      if (!Member)
1964        return 0;
1965      isInstField = false;
1966    } else {
1967      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
1968                                BitWidth, InitStyle, AS);
1969      assert(Member && "HandleField never returns null");
1970    }
1971  } else {
1972    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
1973
1974    Member = HandleDeclarator(S, D, TemplateParameterLists);
1975    if (!Member)
1976      return 0;
1977
1978    // Non-instance-fields can't have a bitfield.
1979    if (BitWidth) {
1980      if (Member->isInvalidDecl()) {
1981        // don't emit another diagnostic.
1982      } else if (isa<VarDecl>(Member)) {
1983        // C++ 9.6p3: A bit-field shall not be a static member.
1984        // "static member 'A' cannot be a bit-field"
1985        Diag(Loc, diag::err_static_not_bitfield)
1986          << Name << BitWidth->getSourceRange();
1987      } else if (isa<TypedefDecl>(Member)) {
1988        // "typedef member 'x' cannot be a bit-field"
1989        Diag(Loc, diag::err_typedef_not_bitfield)
1990          << Name << BitWidth->getSourceRange();
1991      } else {
1992        // A function typedef ("typedef int f(); f a;").
1993        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1994        Diag(Loc, diag::err_not_integral_type_bitfield)
1995          << Name << cast<ValueDecl>(Member)->getType()
1996          << BitWidth->getSourceRange();
1997      }
1998
1999      BitWidth = 0;
2000      Member->setInvalidDecl();
2001    }
2002
2003    Member->setAccess(AS);
2004
2005    // If we have declared a member function template, set the access of the
2006    // templated declaration as well.
2007    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2008      FunTmpl->getTemplatedDecl()->setAccess(AS);
2009  }
2010
2011  if (VS.isOverrideSpecified())
2012    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2013  if (VS.isFinalSpecified())
2014    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
2015
2016  if (VS.getLastLocation().isValid()) {
2017    // Update the end location of a method that has a virt-specifiers.
2018    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2019      MD->setRangeEnd(VS.getLastLocation());
2020  }
2021
2022  CheckOverrideControl(Member);
2023
2024  assert((Name || isInstField) && "No identifier for non-field ?");
2025
2026  if (isInstField) {
2027    FieldDecl *FD = cast<FieldDecl>(Member);
2028    FieldCollector->Add(FD);
2029
2030    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2031                                 FD->getLocation())
2032          != DiagnosticsEngine::Ignored) {
2033      // Remember all explicit private FieldDecls that have a name, no side
2034      // effects and are not part of a dependent type declaration.
2035      if (!FD->isImplicit() && FD->getDeclName() &&
2036          FD->getAccess() == AS_private &&
2037          !FD->hasAttr<UnusedAttr>() &&
2038          !FD->getParent()->isDependentContext() &&
2039          !InitializationHasSideEffects(*FD))
2040        UnusedPrivateFields.insert(FD);
2041    }
2042  }
2043
2044  return Member;
2045}
2046
2047namespace {
2048  class UninitializedFieldVisitor
2049      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2050    Sema &S;
2051    ValueDecl *VD;
2052  public:
2053    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2054    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2055                                                        S(S) {
2056      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(VD))
2057        this->VD = IFD->getAnonField();
2058      else
2059        this->VD = VD;
2060    }
2061
2062    void HandleExpr(Expr *E) {
2063      if (!E) return;
2064
2065      // Expressions like x(x) sometimes lack the surrounding expressions
2066      // but need to be checked anyways.
2067      HandleValue(E);
2068      Visit(E);
2069    }
2070
2071    void HandleValue(Expr *E) {
2072      E = E->IgnoreParens();
2073
2074      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2075        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2076          return;
2077
2078        // FieldME is the inner-most MemberExpr that is not an anonymous struct
2079        // or union.
2080        MemberExpr *FieldME = ME;
2081
2082        Expr *Base = E;
2083        while (isa<MemberExpr>(Base)) {
2084          ME = cast<MemberExpr>(Base);
2085
2086          if (isa<VarDecl>(ME->getMemberDecl()))
2087            return;
2088
2089          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2090            if (!FD->isAnonymousStructOrUnion())
2091              FieldME = ME;
2092
2093          Base = ME->getBase();
2094        }
2095
2096        if (VD == FieldME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2097          unsigned diag = VD->getType()->isReferenceType()
2098              ? diag::warn_reference_field_is_uninit
2099              : diag::warn_field_is_uninit;
2100          S.Diag(FieldME->getExprLoc(), diag) << VD;
2101        }
2102        return;
2103      }
2104
2105      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2106        HandleValue(CO->getTrueExpr());
2107        HandleValue(CO->getFalseExpr());
2108        return;
2109      }
2110
2111      if (BinaryConditionalOperator *BCO =
2112              dyn_cast<BinaryConditionalOperator>(E)) {
2113        HandleValue(BCO->getCommon());
2114        HandleValue(BCO->getFalseExpr());
2115        return;
2116      }
2117
2118      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2119        switch (BO->getOpcode()) {
2120        default:
2121          return;
2122        case(BO_PtrMemD):
2123        case(BO_PtrMemI):
2124          HandleValue(BO->getLHS());
2125          return;
2126        case(BO_Comma):
2127          HandleValue(BO->getRHS());
2128          return;
2129        }
2130      }
2131    }
2132
2133    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2134      if (E->getCastKind() == CK_LValueToRValue)
2135        HandleValue(E->getSubExpr());
2136
2137      Inherited::VisitImplicitCastExpr(E);
2138    }
2139
2140    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2141      Expr *Callee = E->getCallee();
2142      if (isa<MemberExpr>(Callee))
2143        HandleValue(Callee);
2144
2145      Inherited::VisitCXXMemberCallExpr(E);
2146    }
2147  };
2148  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2149                                                       ValueDecl *VD) {
2150    UninitializedFieldVisitor(S, VD).HandleExpr(E);
2151  }
2152} // namespace
2153
2154/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2155/// in-class initializer for a non-static C++ class member, and after
2156/// instantiating an in-class initializer in a class template. Such actions
2157/// are deferred until the class is complete.
2158void
2159Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2160                                       Expr *InitExpr) {
2161  FieldDecl *FD = cast<FieldDecl>(D);
2162  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2163         "must set init style when field is created");
2164
2165  if (!InitExpr) {
2166    FD->setInvalidDecl();
2167    FD->removeInClassInitializer();
2168    return;
2169  }
2170
2171  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2172    FD->setInvalidDecl();
2173    FD->removeInClassInitializer();
2174    return;
2175  }
2176
2177  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, InitLoc)
2178      != DiagnosticsEngine::Ignored) {
2179    CheckInitExprContainsUninitializedFields(*this, InitExpr, FD);
2180  }
2181
2182  ExprResult Init = InitExpr;
2183  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2184    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2185    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2186        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2187        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2188    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2189    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2190    if (Init.isInvalid()) {
2191      FD->setInvalidDecl();
2192      return;
2193    }
2194  }
2195
2196  // C++11 [class.base.init]p7:
2197  //   The initialization of each base and member constitutes a
2198  //   full-expression.
2199  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2200  if (Init.isInvalid()) {
2201    FD->setInvalidDecl();
2202    return;
2203  }
2204
2205  InitExpr = Init.release();
2206
2207  FD->setInClassInitializer(InitExpr);
2208}
2209
2210/// \brief Find the direct and/or virtual base specifiers that
2211/// correspond to the given base type, for use in base initialization
2212/// within a constructor.
2213static bool FindBaseInitializer(Sema &SemaRef,
2214                                CXXRecordDecl *ClassDecl,
2215                                QualType BaseType,
2216                                const CXXBaseSpecifier *&DirectBaseSpec,
2217                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2218  // First, check for a direct base class.
2219  DirectBaseSpec = 0;
2220  for (CXXRecordDecl::base_class_const_iterator Base
2221         = ClassDecl->bases_begin();
2222       Base != ClassDecl->bases_end(); ++Base) {
2223    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2224      // We found a direct base of this type. That's what we're
2225      // initializing.
2226      DirectBaseSpec = &*Base;
2227      break;
2228    }
2229  }
2230
2231  // Check for a virtual base class.
2232  // FIXME: We might be able to short-circuit this if we know in advance that
2233  // there are no virtual bases.
2234  VirtualBaseSpec = 0;
2235  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2236    // We haven't found a base yet; search the class hierarchy for a
2237    // virtual base class.
2238    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2239                       /*DetectVirtual=*/false);
2240    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2241                              BaseType, Paths)) {
2242      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2243           Path != Paths.end(); ++Path) {
2244        if (Path->back().Base->isVirtual()) {
2245          VirtualBaseSpec = Path->back().Base;
2246          break;
2247        }
2248      }
2249    }
2250  }
2251
2252  return DirectBaseSpec || VirtualBaseSpec;
2253}
2254
2255/// \brief Handle a C++ member initializer using braced-init-list syntax.
2256MemInitResult
2257Sema::ActOnMemInitializer(Decl *ConstructorD,
2258                          Scope *S,
2259                          CXXScopeSpec &SS,
2260                          IdentifierInfo *MemberOrBase,
2261                          ParsedType TemplateTypeTy,
2262                          const DeclSpec &DS,
2263                          SourceLocation IdLoc,
2264                          Expr *InitList,
2265                          SourceLocation EllipsisLoc) {
2266  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2267                             DS, IdLoc, InitList,
2268                             EllipsisLoc);
2269}
2270
2271/// \brief Handle a C++ member initializer using parentheses syntax.
2272MemInitResult
2273Sema::ActOnMemInitializer(Decl *ConstructorD,
2274                          Scope *S,
2275                          CXXScopeSpec &SS,
2276                          IdentifierInfo *MemberOrBase,
2277                          ParsedType TemplateTypeTy,
2278                          const DeclSpec &DS,
2279                          SourceLocation IdLoc,
2280                          SourceLocation LParenLoc,
2281                          ArrayRef<Expr *> Args,
2282                          SourceLocation RParenLoc,
2283                          SourceLocation EllipsisLoc) {
2284  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2285                                           Args, RParenLoc);
2286  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2287                             DS, IdLoc, List, EllipsisLoc);
2288}
2289
2290namespace {
2291
2292// Callback to only accept typo corrections that can be a valid C++ member
2293// intializer: either a non-static field member or a base class.
2294class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2295 public:
2296  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2297      : ClassDecl(ClassDecl) {}
2298
2299  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
2300    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2301      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2302        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2303      else
2304        return isa<TypeDecl>(ND);
2305    }
2306    return false;
2307  }
2308
2309 private:
2310  CXXRecordDecl *ClassDecl;
2311};
2312
2313}
2314
2315/// \brief Handle a C++ member initializer.
2316MemInitResult
2317Sema::BuildMemInitializer(Decl *ConstructorD,
2318                          Scope *S,
2319                          CXXScopeSpec &SS,
2320                          IdentifierInfo *MemberOrBase,
2321                          ParsedType TemplateTypeTy,
2322                          const DeclSpec &DS,
2323                          SourceLocation IdLoc,
2324                          Expr *Init,
2325                          SourceLocation EllipsisLoc) {
2326  if (!ConstructorD)
2327    return true;
2328
2329  AdjustDeclIfTemplate(ConstructorD);
2330
2331  CXXConstructorDecl *Constructor
2332    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2333  if (!Constructor) {
2334    // The user wrote a constructor initializer on a function that is
2335    // not a C++ constructor. Ignore the error for now, because we may
2336    // have more member initializers coming; we'll diagnose it just
2337    // once in ActOnMemInitializers.
2338    return true;
2339  }
2340
2341  CXXRecordDecl *ClassDecl = Constructor->getParent();
2342
2343  // C++ [class.base.init]p2:
2344  //   Names in a mem-initializer-id are looked up in the scope of the
2345  //   constructor's class and, if not found in that scope, are looked
2346  //   up in the scope containing the constructor's definition.
2347  //   [Note: if the constructor's class contains a member with the
2348  //   same name as a direct or virtual base class of the class, a
2349  //   mem-initializer-id naming the member or base class and composed
2350  //   of a single identifier refers to the class member. A
2351  //   mem-initializer-id for the hidden base class may be specified
2352  //   using a qualified name. ]
2353  if (!SS.getScopeRep() && !TemplateTypeTy) {
2354    // Look for a member, first.
2355    DeclContext::lookup_result Result
2356      = ClassDecl->lookup(MemberOrBase);
2357    if (!Result.empty()) {
2358      ValueDecl *Member;
2359      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2360          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2361        if (EllipsisLoc.isValid())
2362          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2363            << MemberOrBase
2364            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2365
2366        return BuildMemberInitializer(Member, Init, IdLoc);
2367      }
2368    }
2369  }
2370  // It didn't name a member, so see if it names a class.
2371  QualType BaseType;
2372  TypeSourceInfo *TInfo = 0;
2373
2374  if (TemplateTypeTy) {
2375    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2376  } else if (DS.getTypeSpecType() == TST_decltype) {
2377    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2378  } else {
2379    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2380    LookupParsedName(R, S, &SS);
2381
2382    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2383    if (!TyD) {
2384      if (R.isAmbiguous()) return true;
2385
2386      // We don't want access-control diagnostics here.
2387      R.suppressDiagnostics();
2388
2389      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2390        bool NotUnknownSpecialization = false;
2391        DeclContext *DC = computeDeclContext(SS, false);
2392        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2393          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2394
2395        if (!NotUnknownSpecialization) {
2396          // When the scope specifier can refer to a member of an unknown
2397          // specialization, we take it as a type name.
2398          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2399                                       SS.getWithLocInContext(Context),
2400                                       *MemberOrBase, IdLoc);
2401          if (BaseType.isNull())
2402            return true;
2403
2404          R.clear();
2405          R.setLookupName(MemberOrBase);
2406        }
2407      }
2408
2409      // If no results were found, try to correct typos.
2410      TypoCorrection Corr;
2411      MemInitializerValidatorCCC Validator(ClassDecl);
2412      if (R.empty() && BaseType.isNull() &&
2413          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2414                              Validator, ClassDecl))) {
2415        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
2416        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
2417        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2418          // We have found a non-static data member with a similar
2419          // name to what was typed; complain and initialize that
2420          // member.
2421          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2422            << MemberOrBase << true << CorrectedQuotedStr
2423            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2424          Diag(Member->getLocation(), diag::note_previous_decl)
2425            << CorrectedQuotedStr;
2426
2427          return BuildMemberInitializer(Member, Init, IdLoc);
2428        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2429          const CXXBaseSpecifier *DirectBaseSpec;
2430          const CXXBaseSpecifier *VirtualBaseSpec;
2431          if (FindBaseInitializer(*this, ClassDecl,
2432                                  Context.getTypeDeclType(Type),
2433                                  DirectBaseSpec, VirtualBaseSpec)) {
2434            // We have found a direct or virtual base class with a
2435            // similar name to what was typed; complain and initialize
2436            // that base class.
2437            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
2438              << MemberOrBase << false << CorrectedQuotedStr
2439              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
2440
2441            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
2442                                                             : VirtualBaseSpec;
2443            Diag(BaseSpec->getLocStart(),
2444                 diag::note_base_class_specified_here)
2445              << BaseSpec->getType()
2446              << BaseSpec->getSourceRange();
2447
2448            TyD = Type;
2449          }
2450        }
2451      }
2452
2453      if (!TyD && BaseType.isNull()) {
2454        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2455          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2456        return true;
2457      }
2458    }
2459
2460    if (BaseType.isNull()) {
2461      BaseType = Context.getTypeDeclType(TyD);
2462      if (SS.isSet()) {
2463        NestedNameSpecifier *Qualifier =
2464          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2465
2466        // FIXME: preserve source range information
2467        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2468      }
2469    }
2470  }
2471
2472  if (!TInfo)
2473    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2474
2475  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2476}
2477
2478/// Checks a member initializer expression for cases where reference (or
2479/// pointer) members are bound to by-value parameters (or their addresses).
2480static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2481                                               Expr *Init,
2482                                               SourceLocation IdLoc) {
2483  QualType MemberTy = Member->getType();
2484
2485  // We only handle pointers and references currently.
2486  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2487  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2488    return;
2489
2490  const bool IsPointer = MemberTy->isPointerType();
2491  if (IsPointer) {
2492    if (const UnaryOperator *Op
2493          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2494      // The only case we're worried about with pointers requires taking the
2495      // address.
2496      if (Op->getOpcode() != UO_AddrOf)
2497        return;
2498
2499      Init = Op->getSubExpr();
2500    } else {
2501      // We only handle address-of expression initializers for pointers.
2502      return;
2503    }
2504  }
2505
2506  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2507    // We only warn when referring to a non-reference parameter declaration.
2508    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2509    if (!Parameter || Parameter->getType()->isReferenceType())
2510      return;
2511
2512    S.Diag(Init->getExprLoc(),
2513           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2514                     : diag::warn_bind_ref_member_to_parameter)
2515      << Member << Parameter << Init->getSourceRange();
2516  } else {
2517    // Other initializers are fine.
2518    return;
2519  }
2520
2521  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2522    << (unsigned)IsPointer;
2523}
2524
2525MemInitResult
2526Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2527                             SourceLocation IdLoc) {
2528  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2529  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2530  assert((DirectMember || IndirectMember) &&
2531         "Member must be a FieldDecl or IndirectFieldDecl");
2532
2533  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2534    return true;
2535
2536  if (Member->isInvalidDecl())
2537    return true;
2538
2539  // Diagnose value-uses of fields to initialize themselves, e.g.
2540  //   foo(foo)
2541  // where foo is not also a parameter to the constructor.
2542  // TODO: implement -Wuninitialized and fold this into that framework.
2543  MultiExprArg Args;
2544  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2545    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2546  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2547    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2548  } else {
2549    // Template instantiation doesn't reconstruct ParenListExprs for us.
2550    Args = Init;
2551  }
2552
2553  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2554        != DiagnosticsEngine::Ignored)
2555    for (unsigned i = 0, e = Args.size(); i != e; ++i)
2556      // FIXME: Warn about the case when other fields are used before being
2557      // initialized. For example, let this field be the i'th field. When
2558      // initializing the i'th field, throw a warning if any of the >= i'th
2559      // fields are used, as they are not yet initialized.
2560      // Right now we are only handling the case where the i'th field uses
2561      // itself in its initializer.
2562      // Also need to take into account that some fields may be initialized by
2563      // in-class initializers, see C++11 [class.base.init]p9.
2564      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2565
2566  SourceRange InitRange = Init->getSourceRange();
2567
2568  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2569    // Can't check initialization for a member of dependent type or when
2570    // any of the arguments are type-dependent expressions.
2571    DiscardCleanupsInEvaluationContext();
2572  } else {
2573    bool InitList = false;
2574    if (isa<InitListExpr>(Init)) {
2575      InitList = true;
2576      Args = Init;
2577    }
2578
2579    // Initialize the member.
2580    InitializedEntity MemberEntity =
2581      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2582                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2583    InitializationKind Kind =
2584      InitList ? InitializationKind::CreateDirectList(IdLoc)
2585               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2586                                                  InitRange.getEnd());
2587
2588    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2589    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2590    if (MemberInit.isInvalid())
2591      return true;
2592
2593    CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2594
2595    // C++11 [class.base.init]p7:
2596    //   The initialization of each base and member constitutes a
2597    //   full-expression.
2598    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2599    if (MemberInit.isInvalid())
2600      return true;
2601
2602    Init = MemberInit.get();
2603  }
2604
2605  if (DirectMember) {
2606    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2607                                            InitRange.getBegin(), Init,
2608                                            InitRange.getEnd());
2609  } else {
2610    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2611                                            InitRange.getBegin(), Init,
2612                                            InitRange.getEnd());
2613  }
2614}
2615
2616MemInitResult
2617Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2618                                 CXXRecordDecl *ClassDecl) {
2619  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2620  if (!LangOpts.CPlusPlus11)
2621    return Diag(NameLoc, diag::err_delegating_ctor)
2622      << TInfo->getTypeLoc().getLocalSourceRange();
2623  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2624
2625  bool InitList = true;
2626  MultiExprArg Args = Init;
2627  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2628    InitList = false;
2629    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2630  }
2631
2632  SourceRange InitRange = Init->getSourceRange();
2633  // Initialize the object.
2634  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2635                                     QualType(ClassDecl->getTypeForDecl(), 0));
2636  InitializationKind Kind =
2637    InitList ? InitializationKind::CreateDirectList(NameLoc)
2638             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2639                                                InitRange.getEnd());
2640  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2641  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2642                                              Args, 0);
2643  if (DelegationInit.isInvalid())
2644    return true;
2645
2646  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2647         "Delegating constructor with no target?");
2648
2649  // C++11 [class.base.init]p7:
2650  //   The initialization of each base and member constitutes a
2651  //   full-expression.
2652  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2653                                       InitRange.getBegin());
2654  if (DelegationInit.isInvalid())
2655    return true;
2656
2657  // If we are in a dependent context, template instantiation will
2658  // perform this type-checking again. Just save the arguments that we
2659  // received in a ParenListExpr.
2660  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2661  // of the information that we have about the base
2662  // initializer. However, deconstructing the ASTs is a dicey process,
2663  // and this approach is far more likely to get the corner cases right.
2664  if (CurContext->isDependentContext())
2665    DelegationInit = Owned(Init);
2666
2667  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2668                                          DelegationInit.takeAs<Expr>(),
2669                                          InitRange.getEnd());
2670}
2671
2672MemInitResult
2673Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2674                           Expr *Init, CXXRecordDecl *ClassDecl,
2675                           SourceLocation EllipsisLoc) {
2676  SourceLocation BaseLoc
2677    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2678
2679  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2680    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2681             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2682
2683  // C++ [class.base.init]p2:
2684  //   [...] Unless the mem-initializer-id names a nonstatic data
2685  //   member of the constructor's class or a direct or virtual base
2686  //   of that class, the mem-initializer is ill-formed. A
2687  //   mem-initializer-list can initialize a base class using any
2688  //   name that denotes that base class type.
2689  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2690
2691  SourceRange InitRange = Init->getSourceRange();
2692  if (EllipsisLoc.isValid()) {
2693    // This is a pack expansion.
2694    if (!BaseType->containsUnexpandedParameterPack())  {
2695      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2696        << SourceRange(BaseLoc, InitRange.getEnd());
2697
2698      EllipsisLoc = SourceLocation();
2699    }
2700  } else {
2701    // Check for any unexpanded parameter packs.
2702    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2703      return true;
2704
2705    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2706      return true;
2707  }
2708
2709  // Check for direct and virtual base classes.
2710  const CXXBaseSpecifier *DirectBaseSpec = 0;
2711  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2712  if (!Dependent) {
2713    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2714                                       BaseType))
2715      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2716
2717    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2718                        VirtualBaseSpec);
2719
2720    // C++ [base.class.init]p2:
2721    // Unless the mem-initializer-id names a nonstatic data member of the
2722    // constructor's class or a direct or virtual base of that class, the
2723    // mem-initializer is ill-formed.
2724    if (!DirectBaseSpec && !VirtualBaseSpec) {
2725      // If the class has any dependent bases, then it's possible that
2726      // one of those types will resolve to the same type as
2727      // BaseType. Therefore, just treat this as a dependent base
2728      // class initialization.  FIXME: Should we try to check the
2729      // initialization anyway? It seems odd.
2730      if (ClassDecl->hasAnyDependentBases())
2731        Dependent = true;
2732      else
2733        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2734          << BaseType << Context.getTypeDeclType(ClassDecl)
2735          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2736    }
2737  }
2738
2739  if (Dependent) {
2740    DiscardCleanupsInEvaluationContext();
2741
2742    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2743                                            /*IsVirtual=*/false,
2744                                            InitRange.getBegin(), Init,
2745                                            InitRange.getEnd(), EllipsisLoc);
2746  }
2747
2748  // C++ [base.class.init]p2:
2749  //   If a mem-initializer-id is ambiguous because it designates both
2750  //   a direct non-virtual base class and an inherited virtual base
2751  //   class, the mem-initializer is ill-formed.
2752  if (DirectBaseSpec && VirtualBaseSpec)
2753    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2754      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2755
2756  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2757  if (!BaseSpec)
2758    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2759
2760  // Initialize the base.
2761  bool InitList = true;
2762  MultiExprArg Args = Init;
2763  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2764    InitList = false;
2765    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2766  }
2767
2768  InitializedEntity BaseEntity =
2769    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2770  InitializationKind Kind =
2771    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2772             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2773                                                InitRange.getEnd());
2774  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2775  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2776  if (BaseInit.isInvalid())
2777    return true;
2778
2779  // C++11 [class.base.init]p7:
2780  //   The initialization of each base and member constitutes a
2781  //   full-expression.
2782  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2783  if (BaseInit.isInvalid())
2784    return true;
2785
2786  // If we are in a dependent context, template instantiation will
2787  // perform this type-checking again. Just save the arguments that we
2788  // received in a ParenListExpr.
2789  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2790  // of the information that we have about the base
2791  // initializer. However, deconstructing the ASTs is a dicey process,
2792  // and this approach is far more likely to get the corner cases right.
2793  if (CurContext->isDependentContext())
2794    BaseInit = Owned(Init);
2795
2796  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2797                                          BaseSpec->isVirtual(),
2798                                          InitRange.getBegin(),
2799                                          BaseInit.takeAs<Expr>(),
2800                                          InitRange.getEnd(), EllipsisLoc);
2801}
2802
2803// Create a static_cast\<T&&>(expr).
2804static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2805  if (T.isNull()) T = E->getType();
2806  QualType TargetType = SemaRef.BuildReferenceType(
2807      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2808  SourceLocation ExprLoc = E->getLocStart();
2809  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2810      TargetType, ExprLoc);
2811
2812  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2813                                   SourceRange(ExprLoc, ExprLoc),
2814                                   E->getSourceRange()).take();
2815}
2816
2817/// ImplicitInitializerKind - How an implicit base or member initializer should
2818/// initialize its base or member.
2819enum ImplicitInitializerKind {
2820  IIK_Default,
2821  IIK_Copy,
2822  IIK_Move,
2823  IIK_Inherit
2824};
2825
2826static bool
2827BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2828                             ImplicitInitializerKind ImplicitInitKind,
2829                             CXXBaseSpecifier *BaseSpec,
2830                             bool IsInheritedVirtualBase,
2831                             CXXCtorInitializer *&CXXBaseInit) {
2832  InitializedEntity InitEntity
2833    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2834                                        IsInheritedVirtualBase);
2835
2836  ExprResult BaseInit;
2837
2838  switch (ImplicitInitKind) {
2839  case IIK_Inherit: {
2840    const CXXRecordDecl *Inherited =
2841        Constructor->getInheritedConstructor()->getParent();
2842    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2843    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2844      // C++11 [class.inhctor]p8:
2845      //   Each expression in the expression-list is of the form
2846      //   static_cast<T&&>(p), where p is the name of the corresponding
2847      //   constructor parameter and T is the declared type of p.
2848      SmallVector<Expr*, 16> Args;
2849      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2850        ParmVarDecl *PD = Constructor->getParamDecl(I);
2851        ExprResult ArgExpr =
2852            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2853                                     VK_LValue, SourceLocation());
2854        if (ArgExpr.isInvalid())
2855          return true;
2856        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2857      }
2858
2859      InitializationKind InitKind = InitializationKind::CreateDirect(
2860          Constructor->getLocation(), SourceLocation(), SourceLocation());
2861      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
2862      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
2863      break;
2864    }
2865  }
2866  // Fall through.
2867  case IIK_Default: {
2868    InitializationKind InitKind
2869      = InitializationKind::CreateDefault(Constructor->getLocation());
2870    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
2871    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
2872    break;
2873  }
2874
2875  case IIK_Move:
2876  case IIK_Copy: {
2877    bool Moving = ImplicitInitKind == IIK_Move;
2878    ParmVarDecl *Param = Constructor->getParamDecl(0);
2879    QualType ParamType = Param->getType().getNonReferenceType();
2880
2881    Expr *CopyCtorArg =
2882      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2883                          SourceLocation(), Param, false,
2884                          Constructor->getLocation(), ParamType,
2885                          VK_LValue, 0);
2886
2887    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2888
2889    // Cast to the base class to avoid ambiguities.
2890    QualType ArgTy =
2891      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2892                                       ParamType.getQualifiers());
2893
2894    if (Moving) {
2895      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2896    }
2897
2898    CXXCastPath BasePath;
2899    BasePath.push_back(BaseSpec);
2900    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2901                                            CK_UncheckedDerivedToBase,
2902                                            Moving ? VK_XValue : VK_LValue,
2903                                            &BasePath).take();
2904
2905    InitializationKind InitKind
2906      = InitializationKind::CreateDirect(Constructor->getLocation(),
2907                                         SourceLocation(), SourceLocation());
2908    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
2909    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
2910    break;
2911  }
2912  }
2913
2914  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2915  if (BaseInit.isInvalid())
2916    return true;
2917
2918  CXXBaseInit =
2919    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2920               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2921                                                        SourceLocation()),
2922                                             BaseSpec->isVirtual(),
2923                                             SourceLocation(),
2924                                             BaseInit.takeAs<Expr>(),
2925                                             SourceLocation(),
2926                                             SourceLocation());
2927
2928  return false;
2929}
2930
2931static bool RefersToRValueRef(Expr *MemRef) {
2932  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2933  return Referenced->getType()->isRValueReferenceType();
2934}
2935
2936static bool
2937BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2938                               ImplicitInitializerKind ImplicitInitKind,
2939                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2940                               CXXCtorInitializer *&CXXMemberInit) {
2941  if (Field->isInvalidDecl())
2942    return true;
2943
2944  SourceLocation Loc = Constructor->getLocation();
2945
2946  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2947    bool Moving = ImplicitInitKind == IIK_Move;
2948    ParmVarDecl *Param = Constructor->getParamDecl(0);
2949    QualType ParamType = Param->getType().getNonReferenceType();
2950
2951    // Suppress copying zero-width bitfields.
2952    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2953      return false;
2954
2955    Expr *MemberExprBase =
2956      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2957                          SourceLocation(), Param, false,
2958                          Loc, ParamType, VK_LValue, 0);
2959
2960    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2961
2962    if (Moving) {
2963      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2964    }
2965
2966    // Build a reference to this field within the parameter.
2967    CXXScopeSpec SS;
2968    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2969                              Sema::LookupMemberName);
2970    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2971                                  : cast<ValueDecl>(Field), AS_public);
2972    MemberLookup.resolveKind();
2973    ExprResult CtorArg
2974      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2975                                         ParamType, Loc,
2976                                         /*IsArrow=*/false,
2977                                         SS,
2978                                         /*TemplateKWLoc=*/SourceLocation(),
2979                                         /*FirstQualifierInScope=*/0,
2980                                         MemberLookup,
2981                                         /*TemplateArgs=*/0);
2982    if (CtorArg.isInvalid())
2983      return true;
2984
2985    // C++11 [class.copy]p15:
2986    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2987    //     with static_cast<T&&>(x.m);
2988    if (RefersToRValueRef(CtorArg.get())) {
2989      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2990    }
2991
2992    // When the field we are copying is an array, create index variables for
2993    // each dimension of the array. We use these index variables to subscript
2994    // the source array, and other clients (e.g., CodeGen) will perform the
2995    // necessary iteration with these index variables.
2996    SmallVector<VarDecl *, 4> IndexVariables;
2997    QualType BaseType = Field->getType();
2998    QualType SizeType = SemaRef.Context.getSizeType();
2999    bool InitializingArray = false;
3000    while (const ConstantArrayType *Array
3001                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3002      InitializingArray = true;
3003      // Create the iteration variable for this array index.
3004      IdentifierInfo *IterationVarName = 0;
3005      {
3006        SmallString<8> Str;
3007        llvm::raw_svector_ostream OS(Str);
3008        OS << "__i" << IndexVariables.size();
3009        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3010      }
3011      VarDecl *IterationVar
3012        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3013                          IterationVarName, SizeType,
3014                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3015                          SC_None);
3016      IndexVariables.push_back(IterationVar);
3017
3018      // Create a reference to the iteration variable.
3019      ExprResult IterationVarRef
3020        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3021      assert(!IterationVarRef.isInvalid() &&
3022             "Reference to invented variable cannot fail!");
3023      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3024      assert(!IterationVarRef.isInvalid() &&
3025             "Conversion of invented variable cannot fail!");
3026
3027      // Subscript the array with this iteration variable.
3028      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3029                                                        IterationVarRef.take(),
3030                                                        Loc);
3031      if (CtorArg.isInvalid())
3032        return true;
3033
3034      BaseType = Array->getElementType();
3035    }
3036
3037    // The array subscript expression is an lvalue, which is wrong for moving.
3038    if (Moving && InitializingArray)
3039      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3040
3041    // Construct the entity that we will be initializing. For an array, this
3042    // will be first element in the array, which may require several levels
3043    // of array-subscript entities.
3044    SmallVector<InitializedEntity, 4> Entities;
3045    Entities.reserve(1 + IndexVariables.size());
3046    if (Indirect)
3047      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3048    else
3049      Entities.push_back(InitializedEntity::InitializeMember(Field));
3050    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3051      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3052                                                              0,
3053                                                              Entities.back()));
3054
3055    // Direct-initialize to use the copy constructor.
3056    InitializationKind InitKind =
3057      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3058
3059    Expr *CtorArgE = CtorArg.takeAs<Expr>();
3060    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3061
3062    ExprResult MemberInit
3063      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3064                        MultiExprArg(&CtorArgE, 1));
3065    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3066    if (MemberInit.isInvalid())
3067      return true;
3068
3069    if (Indirect) {
3070      assert(IndexVariables.size() == 0 &&
3071             "Indirect field improperly initialized");
3072      CXXMemberInit
3073        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3074                                                   Loc, Loc,
3075                                                   MemberInit.takeAs<Expr>(),
3076                                                   Loc);
3077    } else
3078      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3079                                                 Loc, MemberInit.takeAs<Expr>(),
3080                                                 Loc,
3081                                                 IndexVariables.data(),
3082                                                 IndexVariables.size());
3083    return false;
3084  }
3085
3086  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3087         "Unhandled implicit init kind!");
3088
3089  QualType FieldBaseElementType =
3090    SemaRef.Context.getBaseElementType(Field->getType());
3091
3092  if (FieldBaseElementType->isRecordType()) {
3093    InitializedEntity InitEntity
3094      = Indirect? InitializedEntity::InitializeMember(Indirect)
3095                : InitializedEntity::InitializeMember(Field);
3096    InitializationKind InitKind =
3097      InitializationKind::CreateDefault(Loc);
3098
3099    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3100    ExprResult MemberInit =
3101      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3102
3103    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3104    if (MemberInit.isInvalid())
3105      return true;
3106
3107    if (Indirect)
3108      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3109                                                               Indirect, Loc,
3110                                                               Loc,
3111                                                               MemberInit.get(),
3112                                                               Loc);
3113    else
3114      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3115                                                               Field, Loc, Loc,
3116                                                               MemberInit.get(),
3117                                                               Loc);
3118    return false;
3119  }
3120
3121  if (!Field->getParent()->isUnion()) {
3122    if (FieldBaseElementType->isReferenceType()) {
3123      SemaRef.Diag(Constructor->getLocation(),
3124                   diag::err_uninitialized_member_in_ctor)
3125      << (int)Constructor->isImplicit()
3126      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3127      << 0 << Field->getDeclName();
3128      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3129      return true;
3130    }
3131
3132    if (FieldBaseElementType.isConstQualified()) {
3133      SemaRef.Diag(Constructor->getLocation(),
3134                   diag::err_uninitialized_member_in_ctor)
3135      << (int)Constructor->isImplicit()
3136      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3137      << 1 << Field->getDeclName();
3138      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3139      return true;
3140    }
3141  }
3142
3143  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3144      FieldBaseElementType->isObjCRetainableType() &&
3145      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3146      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3147    // ARC:
3148    //   Default-initialize Objective-C pointers to NULL.
3149    CXXMemberInit
3150      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3151                                                 Loc, Loc,
3152                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3153                                                 Loc);
3154    return false;
3155  }
3156
3157  // Nothing to initialize.
3158  CXXMemberInit = 0;
3159  return false;
3160}
3161
3162namespace {
3163struct BaseAndFieldInfo {
3164  Sema &S;
3165  CXXConstructorDecl *Ctor;
3166  bool AnyErrorsInInits;
3167  ImplicitInitializerKind IIK;
3168  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3169  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3170
3171  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3172    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3173    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3174    if (Generated && Ctor->isCopyConstructor())
3175      IIK = IIK_Copy;
3176    else if (Generated && Ctor->isMoveConstructor())
3177      IIK = IIK_Move;
3178    else if (Ctor->getInheritedConstructor())
3179      IIK = IIK_Inherit;
3180    else
3181      IIK = IIK_Default;
3182  }
3183
3184  bool isImplicitCopyOrMove() const {
3185    switch (IIK) {
3186    case IIK_Copy:
3187    case IIK_Move:
3188      return true;
3189
3190    case IIK_Default:
3191    case IIK_Inherit:
3192      return false;
3193    }
3194
3195    llvm_unreachable("Invalid ImplicitInitializerKind!");
3196  }
3197
3198  bool addFieldInitializer(CXXCtorInitializer *Init) {
3199    AllToInit.push_back(Init);
3200
3201    // Check whether this initializer makes the field "used".
3202    if (Init->getInit()->HasSideEffects(S.Context))
3203      S.UnusedPrivateFields.remove(Init->getAnyMember());
3204
3205    return false;
3206  }
3207};
3208}
3209
3210/// \brief Determine whether the given indirect field declaration is somewhere
3211/// within an anonymous union.
3212static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3213  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3214                                      CEnd = F->chain_end();
3215       C != CEnd; ++C)
3216    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3217      if (Record->isUnion())
3218        return true;
3219
3220  return false;
3221}
3222
3223/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3224/// array type.
3225static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3226  if (T->isIncompleteArrayType())
3227    return true;
3228
3229  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3230    if (!ArrayT->getSize())
3231      return true;
3232
3233    T = ArrayT->getElementType();
3234  }
3235
3236  return false;
3237}
3238
3239static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3240                                    FieldDecl *Field,
3241                                    IndirectFieldDecl *Indirect = 0) {
3242  if (Field->isInvalidDecl())
3243    return false;
3244
3245  // Overwhelmingly common case: we have a direct initializer for this field.
3246  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3247    return Info.addFieldInitializer(Init);
3248
3249  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3250  // has a brace-or-equal-initializer, the entity is initialized as specified
3251  // in [dcl.init].
3252  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3253    Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3254                                           Info.Ctor->getLocation(), Field);
3255    CXXCtorInitializer *Init;
3256    if (Indirect)
3257      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3258                                                      SourceLocation(),
3259                                                      SourceLocation(), DIE,
3260                                                      SourceLocation());
3261    else
3262      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3263                                                      SourceLocation(),
3264                                                      SourceLocation(), DIE,
3265                                                      SourceLocation());
3266    return Info.addFieldInitializer(Init);
3267  }
3268
3269  // Don't build an implicit initializer for union members if none was
3270  // explicitly specified.
3271  if (Field->getParent()->isUnion() ||
3272      (Indirect && isWithinAnonymousUnion(Indirect)))
3273    return false;
3274
3275  // Don't initialize incomplete or zero-length arrays.
3276  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3277    return false;
3278
3279  // Don't try to build an implicit initializer if there were semantic
3280  // errors in any of the initializers (and therefore we might be
3281  // missing some that the user actually wrote).
3282  if (Info.AnyErrorsInInits)
3283    return false;
3284
3285  CXXCtorInitializer *Init = 0;
3286  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3287                                     Indirect, Init))
3288    return true;
3289
3290  if (!Init)
3291    return false;
3292
3293  return Info.addFieldInitializer(Init);
3294}
3295
3296bool
3297Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3298                               CXXCtorInitializer *Initializer) {
3299  assert(Initializer->isDelegatingInitializer());
3300  Constructor->setNumCtorInitializers(1);
3301  CXXCtorInitializer **initializer =
3302    new (Context) CXXCtorInitializer*[1];
3303  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3304  Constructor->setCtorInitializers(initializer);
3305
3306  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3307    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3308    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3309  }
3310
3311  DelegatingCtorDecls.push_back(Constructor);
3312
3313  return false;
3314}
3315
3316bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3317                               ArrayRef<CXXCtorInitializer *> Initializers) {
3318  if (Constructor->isDependentContext()) {
3319    // Just store the initializers as written, they will be checked during
3320    // instantiation.
3321    if (!Initializers.empty()) {
3322      Constructor->setNumCtorInitializers(Initializers.size());
3323      CXXCtorInitializer **baseOrMemberInitializers =
3324        new (Context) CXXCtorInitializer*[Initializers.size()];
3325      memcpy(baseOrMemberInitializers, Initializers.data(),
3326             Initializers.size() * sizeof(CXXCtorInitializer*));
3327      Constructor->setCtorInitializers(baseOrMemberInitializers);
3328    }
3329
3330    // Let template instantiation know whether we had errors.
3331    if (AnyErrors)
3332      Constructor->setInvalidDecl();
3333
3334    return false;
3335  }
3336
3337  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3338
3339  // We need to build the initializer AST according to order of construction
3340  // and not what user specified in the Initializers list.
3341  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3342  if (!ClassDecl)
3343    return true;
3344
3345  bool HadError = false;
3346
3347  for (unsigned i = 0; i < Initializers.size(); i++) {
3348    CXXCtorInitializer *Member = Initializers[i];
3349
3350    if (Member->isBaseInitializer())
3351      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3352    else
3353      Info.AllBaseFields[Member->getAnyMember()] = Member;
3354  }
3355
3356  // Keep track of the direct virtual bases.
3357  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3358  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3359       E = ClassDecl->bases_end(); I != E; ++I) {
3360    if (I->isVirtual())
3361      DirectVBases.insert(I);
3362  }
3363
3364  // Push virtual bases before others.
3365  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3366       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3367
3368    if (CXXCtorInitializer *Value
3369        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3370      Info.AllToInit.push_back(Value);
3371    } else if (!AnyErrors) {
3372      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3373      CXXCtorInitializer *CXXBaseInit;
3374      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3375                                       VBase, IsInheritedVirtualBase,
3376                                       CXXBaseInit)) {
3377        HadError = true;
3378        continue;
3379      }
3380
3381      Info.AllToInit.push_back(CXXBaseInit);
3382    }
3383  }
3384
3385  // Non-virtual bases.
3386  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3387       E = ClassDecl->bases_end(); Base != E; ++Base) {
3388    // Virtuals are in the virtual base list and already constructed.
3389    if (Base->isVirtual())
3390      continue;
3391
3392    if (CXXCtorInitializer *Value
3393          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3394      Info.AllToInit.push_back(Value);
3395    } else if (!AnyErrors) {
3396      CXXCtorInitializer *CXXBaseInit;
3397      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3398                                       Base, /*IsInheritedVirtualBase=*/false,
3399                                       CXXBaseInit)) {
3400        HadError = true;
3401        continue;
3402      }
3403
3404      Info.AllToInit.push_back(CXXBaseInit);
3405    }
3406  }
3407
3408  // Fields.
3409  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3410                               MemEnd = ClassDecl->decls_end();
3411       Mem != MemEnd; ++Mem) {
3412    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3413      // C++ [class.bit]p2:
3414      //   A declaration for a bit-field that omits the identifier declares an
3415      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3416      //   initialized.
3417      if (F->isUnnamedBitfield())
3418        continue;
3419
3420      // If we're not generating the implicit copy/move constructor, then we'll
3421      // handle anonymous struct/union fields based on their individual
3422      // indirect fields.
3423      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3424        continue;
3425
3426      if (CollectFieldInitializer(*this, Info, F))
3427        HadError = true;
3428      continue;
3429    }
3430
3431    // Beyond this point, we only consider default initialization.
3432    if (Info.isImplicitCopyOrMove())
3433      continue;
3434
3435    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3436      if (F->getType()->isIncompleteArrayType()) {
3437        assert(ClassDecl->hasFlexibleArrayMember() &&
3438               "Incomplete array type is not valid");
3439        continue;
3440      }
3441
3442      // Initialize each field of an anonymous struct individually.
3443      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3444        HadError = true;
3445
3446      continue;
3447    }
3448  }
3449
3450  unsigned NumInitializers = Info.AllToInit.size();
3451  if (NumInitializers > 0) {
3452    Constructor->setNumCtorInitializers(NumInitializers);
3453    CXXCtorInitializer **baseOrMemberInitializers =
3454      new (Context) CXXCtorInitializer*[NumInitializers];
3455    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3456           NumInitializers * sizeof(CXXCtorInitializer*));
3457    Constructor->setCtorInitializers(baseOrMemberInitializers);
3458
3459    // Constructors implicitly reference the base and member
3460    // destructors.
3461    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3462                                           Constructor->getParent());
3463  }
3464
3465  return HadError;
3466}
3467
3468static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3469  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3470    const RecordDecl *RD = RT->getDecl();
3471    if (RD->isAnonymousStructOrUnion()) {
3472      for (RecordDecl::field_iterator Field = RD->field_begin(),
3473          E = RD->field_end(); Field != E; ++Field)
3474        PopulateKeysForFields(*Field, IdealInits);
3475      return;
3476    }
3477  }
3478  IdealInits.push_back(Field);
3479}
3480
3481static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3482  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3483}
3484
3485static void *GetKeyForMember(ASTContext &Context,
3486                             CXXCtorInitializer *Member) {
3487  if (!Member->isAnyMemberInitializer())
3488    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3489
3490  return Member->getAnyMember();
3491}
3492
3493static void DiagnoseBaseOrMemInitializerOrder(
3494    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3495    ArrayRef<CXXCtorInitializer *> Inits) {
3496  if (Constructor->getDeclContext()->isDependentContext())
3497    return;
3498
3499  // Don't check initializers order unless the warning is enabled at the
3500  // location of at least one initializer.
3501  bool ShouldCheckOrder = false;
3502  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3503    CXXCtorInitializer *Init = Inits[InitIndex];
3504    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3505                                         Init->getSourceLocation())
3506          != DiagnosticsEngine::Ignored) {
3507      ShouldCheckOrder = true;
3508      break;
3509    }
3510  }
3511  if (!ShouldCheckOrder)
3512    return;
3513
3514  // Build the list of bases and members in the order that they'll
3515  // actually be initialized.  The explicit initializers should be in
3516  // this same order but may be missing things.
3517  SmallVector<const void*, 32> IdealInitKeys;
3518
3519  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3520
3521  // 1. Virtual bases.
3522  for (CXXRecordDecl::base_class_const_iterator VBase =
3523       ClassDecl->vbases_begin(),
3524       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3525    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3526
3527  // 2. Non-virtual bases.
3528  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3529       E = ClassDecl->bases_end(); Base != E; ++Base) {
3530    if (Base->isVirtual())
3531      continue;
3532    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3533  }
3534
3535  // 3. Direct fields.
3536  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3537       E = ClassDecl->field_end(); Field != E; ++Field) {
3538    if (Field->isUnnamedBitfield())
3539      continue;
3540
3541    PopulateKeysForFields(*Field, IdealInitKeys);
3542  }
3543
3544  unsigned NumIdealInits = IdealInitKeys.size();
3545  unsigned IdealIndex = 0;
3546
3547  CXXCtorInitializer *PrevInit = 0;
3548  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3549    CXXCtorInitializer *Init = Inits[InitIndex];
3550    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3551
3552    // Scan forward to try to find this initializer in the idealized
3553    // initializers list.
3554    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3555      if (InitKey == IdealInitKeys[IdealIndex])
3556        break;
3557
3558    // If we didn't find this initializer, it must be because we
3559    // scanned past it on a previous iteration.  That can only
3560    // happen if we're out of order;  emit a warning.
3561    if (IdealIndex == NumIdealInits && PrevInit) {
3562      Sema::SemaDiagnosticBuilder D =
3563        SemaRef.Diag(PrevInit->getSourceLocation(),
3564                     diag::warn_initializer_out_of_order);
3565
3566      if (PrevInit->isAnyMemberInitializer())
3567        D << 0 << PrevInit->getAnyMember()->getDeclName();
3568      else
3569        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3570
3571      if (Init->isAnyMemberInitializer())
3572        D << 0 << Init->getAnyMember()->getDeclName();
3573      else
3574        D << 1 << Init->getTypeSourceInfo()->getType();
3575
3576      // Move back to the initializer's location in the ideal list.
3577      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3578        if (InitKey == IdealInitKeys[IdealIndex])
3579          break;
3580
3581      assert(IdealIndex != NumIdealInits &&
3582             "initializer not found in initializer list");
3583    }
3584
3585    PrevInit = Init;
3586  }
3587}
3588
3589namespace {
3590bool CheckRedundantInit(Sema &S,
3591                        CXXCtorInitializer *Init,
3592                        CXXCtorInitializer *&PrevInit) {
3593  if (!PrevInit) {
3594    PrevInit = Init;
3595    return false;
3596  }
3597
3598  if (FieldDecl *Field = Init->getAnyMember())
3599    S.Diag(Init->getSourceLocation(),
3600           diag::err_multiple_mem_initialization)
3601      << Field->getDeclName()
3602      << Init->getSourceRange();
3603  else {
3604    const Type *BaseClass = Init->getBaseClass();
3605    assert(BaseClass && "neither field nor base");
3606    S.Diag(Init->getSourceLocation(),
3607           diag::err_multiple_base_initialization)
3608      << QualType(BaseClass, 0)
3609      << Init->getSourceRange();
3610  }
3611  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3612    << 0 << PrevInit->getSourceRange();
3613
3614  return true;
3615}
3616
3617typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3618typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3619
3620bool CheckRedundantUnionInit(Sema &S,
3621                             CXXCtorInitializer *Init,
3622                             RedundantUnionMap &Unions) {
3623  FieldDecl *Field = Init->getAnyMember();
3624  RecordDecl *Parent = Field->getParent();
3625  NamedDecl *Child = Field;
3626
3627  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3628    if (Parent->isUnion()) {
3629      UnionEntry &En = Unions[Parent];
3630      if (En.first && En.first != Child) {
3631        S.Diag(Init->getSourceLocation(),
3632               diag::err_multiple_mem_union_initialization)
3633          << Field->getDeclName()
3634          << Init->getSourceRange();
3635        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3636          << 0 << En.second->getSourceRange();
3637        return true;
3638      }
3639      if (!En.first) {
3640        En.first = Child;
3641        En.second = Init;
3642      }
3643      if (!Parent->isAnonymousStructOrUnion())
3644        return false;
3645    }
3646
3647    Child = Parent;
3648    Parent = cast<RecordDecl>(Parent->getDeclContext());
3649  }
3650
3651  return false;
3652}
3653}
3654
3655/// ActOnMemInitializers - Handle the member initializers for a constructor.
3656void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3657                                SourceLocation ColonLoc,
3658                                ArrayRef<CXXCtorInitializer*> MemInits,
3659                                bool AnyErrors) {
3660  if (!ConstructorDecl)
3661    return;
3662
3663  AdjustDeclIfTemplate(ConstructorDecl);
3664
3665  CXXConstructorDecl *Constructor
3666    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3667
3668  if (!Constructor) {
3669    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3670    return;
3671  }
3672
3673  // Mapping for the duplicate initializers check.
3674  // For member initializers, this is keyed with a FieldDecl*.
3675  // For base initializers, this is keyed with a Type*.
3676  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3677
3678  // Mapping for the inconsistent anonymous-union initializers check.
3679  RedundantUnionMap MemberUnions;
3680
3681  bool HadError = false;
3682  for (unsigned i = 0; i < MemInits.size(); i++) {
3683    CXXCtorInitializer *Init = MemInits[i];
3684
3685    // Set the source order index.
3686    Init->setSourceOrder(i);
3687
3688    if (Init->isAnyMemberInitializer()) {
3689      FieldDecl *Field = Init->getAnyMember();
3690      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3691          CheckRedundantUnionInit(*this, Init, MemberUnions))
3692        HadError = true;
3693    } else if (Init->isBaseInitializer()) {
3694      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3695      if (CheckRedundantInit(*this, Init, Members[Key]))
3696        HadError = true;
3697    } else {
3698      assert(Init->isDelegatingInitializer());
3699      // This must be the only initializer
3700      if (MemInits.size() != 1) {
3701        Diag(Init->getSourceLocation(),
3702             diag::err_delegating_initializer_alone)
3703          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3704        // We will treat this as being the only initializer.
3705      }
3706      SetDelegatingInitializer(Constructor, MemInits[i]);
3707      // Return immediately as the initializer is set.
3708      return;
3709    }
3710  }
3711
3712  if (HadError)
3713    return;
3714
3715  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3716
3717  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3718}
3719
3720void
3721Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3722                                             CXXRecordDecl *ClassDecl) {
3723  // Ignore dependent contexts. Also ignore unions, since their members never
3724  // have destructors implicitly called.
3725  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3726    return;
3727
3728  // FIXME: all the access-control diagnostics are positioned on the
3729  // field/base declaration.  That's probably good; that said, the
3730  // user might reasonably want to know why the destructor is being
3731  // emitted, and we currently don't say.
3732
3733  // Non-static data members.
3734  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3735       E = ClassDecl->field_end(); I != E; ++I) {
3736    FieldDecl *Field = *I;
3737    if (Field->isInvalidDecl())
3738      continue;
3739
3740    // Don't destroy incomplete or zero-length arrays.
3741    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3742      continue;
3743
3744    QualType FieldType = Context.getBaseElementType(Field->getType());
3745
3746    const RecordType* RT = FieldType->getAs<RecordType>();
3747    if (!RT)
3748      continue;
3749
3750    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3751    if (FieldClassDecl->isInvalidDecl())
3752      continue;
3753    if (FieldClassDecl->hasIrrelevantDestructor())
3754      continue;
3755    // The destructor for an implicit anonymous union member is never invoked.
3756    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3757      continue;
3758
3759    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3760    assert(Dtor && "No dtor found for FieldClassDecl!");
3761    CheckDestructorAccess(Field->getLocation(), Dtor,
3762                          PDiag(diag::err_access_dtor_field)
3763                            << Field->getDeclName()
3764                            << FieldType);
3765
3766    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3767    DiagnoseUseOfDecl(Dtor, Location);
3768  }
3769
3770  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3771
3772  // Bases.
3773  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3774       E = ClassDecl->bases_end(); Base != E; ++Base) {
3775    // Bases are always records in a well-formed non-dependent class.
3776    const RecordType *RT = Base->getType()->getAs<RecordType>();
3777
3778    // Remember direct virtual bases.
3779    if (Base->isVirtual())
3780      DirectVirtualBases.insert(RT);
3781
3782    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3783    // If our base class is invalid, we probably can't get its dtor anyway.
3784    if (BaseClassDecl->isInvalidDecl())
3785      continue;
3786    if (BaseClassDecl->hasIrrelevantDestructor())
3787      continue;
3788
3789    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3790    assert(Dtor && "No dtor found for BaseClassDecl!");
3791
3792    // FIXME: caret should be on the start of the class name
3793    CheckDestructorAccess(Base->getLocStart(), Dtor,
3794                          PDiag(diag::err_access_dtor_base)
3795                            << Base->getType()
3796                            << Base->getSourceRange(),
3797                          Context.getTypeDeclType(ClassDecl));
3798
3799    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3800    DiagnoseUseOfDecl(Dtor, Location);
3801  }
3802
3803  // Virtual bases.
3804  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3805       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3806
3807    // Bases are always records in a well-formed non-dependent class.
3808    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3809
3810    // Ignore direct virtual bases.
3811    if (DirectVirtualBases.count(RT))
3812      continue;
3813
3814    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3815    // If our base class is invalid, we probably can't get its dtor anyway.
3816    if (BaseClassDecl->isInvalidDecl())
3817      continue;
3818    if (BaseClassDecl->hasIrrelevantDestructor())
3819      continue;
3820
3821    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3822    assert(Dtor && "No dtor found for BaseClassDecl!");
3823    if (CheckDestructorAccess(
3824            ClassDecl->getLocation(), Dtor,
3825            PDiag(diag::err_access_dtor_vbase)
3826                << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3827            Context.getTypeDeclType(ClassDecl)) ==
3828        AR_accessible) {
3829      CheckDerivedToBaseConversion(
3830          Context.getTypeDeclType(ClassDecl), VBase->getType(),
3831          diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3832          SourceRange(), DeclarationName(), 0);
3833    }
3834
3835    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3836    DiagnoseUseOfDecl(Dtor, Location);
3837  }
3838}
3839
3840void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3841  if (!CDtorDecl)
3842    return;
3843
3844  if (CXXConstructorDecl *Constructor
3845      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3846    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
3847}
3848
3849bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3850                                  unsigned DiagID, AbstractDiagSelID SelID) {
3851  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3852    unsigned DiagID;
3853    AbstractDiagSelID SelID;
3854
3855  public:
3856    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3857      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3858
3859    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3860      if (Suppressed) return;
3861      if (SelID == -1)
3862        S.Diag(Loc, DiagID) << T;
3863      else
3864        S.Diag(Loc, DiagID) << SelID << T;
3865    }
3866  } Diagnoser(DiagID, SelID);
3867
3868  return RequireNonAbstractType(Loc, T, Diagnoser);
3869}
3870
3871bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3872                                  TypeDiagnoser &Diagnoser) {
3873  if (!getLangOpts().CPlusPlus)
3874    return false;
3875
3876  if (const ArrayType *AT = Context.getAsArrayType(T))
3877    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3878
3879  if (const PointerType *PT = T->getAs<PointerType>()) {
3880    // Find the innermost pointer type.
3881    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3882      PT = T;
3883
3884    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3885      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3886  }
3887
3888  const RecordType *RT = T->getAs<RecordType>();
3889  if (!RT)
3890    return false;
3891
3892  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3893
3894  // We can't answer whether something is abstract until it has a
3895  // definition.  If it's currently being defined, we'll walk back
3896  // over all the declarations when we have a full definition.
3897  const CXXRecordDecl *Def = RD->getDefinition();
3898  if (!Def || Def->isBeingDefined())
3899    return false;
3900
3901  if (!RD->isAbstract())
3902    return false;
3903
3904  Diagnoser.diagnose(*this, Loc, T);
3905  DiagnoseAbstractType(RD);
3906
3907  return true;
3908}
3909
3910void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3911  // Check if we've already emitted the list of pure virtual functions
3912  // for this class.
3913  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3914    return;
3915
3916  CXXFinalOverriderMap FinalOverriders;
3917  RD->getFinalOverriders(FinalOverriders);
3918
3919  // Keep a set of seen pure methods so we won't diagnose the same method
3920  // more than once.
3921  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3922
3923  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3924                                   MEnd = FinalOverriders.end();
3925       M != MEnd;
3926       ++M) {
3927    for (OverridingMethods::iterator SO = M->second.begin(),
3928                                  SOEnd = M->second.end();
3929         SO != SOEnd; ++SO) {
3930      // C++ [class.abstract]p4:
3931      //   A class is abstract if it contains or inherits at least one
3932      //   pure virtual function for which the final overrider is pure
3933      //   virtual.
3934
3935      //
3936      if (SO->second.size() != 1)
3937        continue;
3938
3939      if (!SO->second.front().Method->isPure())
3940        continue;
3941
3942      if (!SeenPureMethods.insert(SO->second.front().Method))
3943        continue;
3944
3945      Diag(SO->second.front().Method->getLocation(),
3946           diag::note_pure_virtual_function)
3947        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3948    }
3949  }
3950
3951  if (!PureVirtualClassDiagSet)
3952    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3953  PureVirtualClassDiagSet->insert(RD);
3954}
3955
3956namespace {
3957struct AbstractUsageInfo {
3958  Sema &S;
3959  CXXRecordDecl *Record;
3960  CanQualType AbstractType;
3961  bool Invalid;
3962
3963  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3964    : S(S), Record(Record),
3965      AbstractType(S.Context.getCanonicalType(
3966                   S.Context.getTypeDeclType(Record))),
3967      Invalid(false) {}
3968
3969  void DiagnoseAbstractType() {
3970    if (Invalid) return;
3971    S.DiagnoseAbstractType(Record);
3972    Invalid = true;
3973  }
3974
3975  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3976};
3977
3978struct CheckAbstractUsage {
3979  AbstractUsageInfo &Info;
3980  const NamedDecl *Ctx;
3981
3982  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3983    : Info(Info), Ctx(Ctx) {}
3984
3985  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3986    switch (TL.getTypeLocClass()) {
3987#define ABSTRACT_TYPELOC(CLASS, PARENT)
3988#define TYPELOC(CLASS, PARENT) \
3989    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
3990#include "clang/AST/TypeLocNodes.def"
3991    }
3992  }
3993
3994  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3995    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3996    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3997      if (!TL.getArg(I))
3998        continue;
3999
4000      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4001      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4002    }
4003  }
4004
4005  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4006    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4007  }
4008
4009  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4010    // Visit the type parameters from a permissive context.
4011    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4012      TemplateArgumentLoc TAL = TL.getArgLoc(I);
4013      if (TAL.getArgument().getKind() == TemplateArgument::Type)
4014        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4015          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4016      // TODO: other template argument types?
4017    }
4018  }
4019
4020  // Visit pointee types from a permissive context.
4021#define CheckPolymorphic(Type) \
4022  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4023    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4024  }
4025  CheckPolymorphic(PointerTypeLoc)
4026  CheckPolymorphic(ReferenceTypeLoc)
4027  CheckPolymorphic(MemberPointerTypeLoc)
4028  CheckPolymorphic(BlockPointerTypeLoc)
4029  CheckPolymorphic(AtomicTypeLoc)
4030
4031  /// Handle all the types we haven't given a more specific
4032  /// implementation for above.
4033  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4034    // Every other kind of type that we haven't called out already
4035    // that has an inner type is either (1) sugar or (2) contains that
4036    // inner type in some way as a subobject.
4037    if (TypeLoc Next = TL.getNextTypeLoc())
4038      return Visit(Next, Sel);
4039
4040    // If there's no inner type and we're in a permissive context,
4041    // don't diagnose.
4042    if (Sel == Sema::AbstractNone) return;
4043
4044    // Check whether the type matches the abstract type.
4045    QualType T = TL.getType();
4046    if (T->isArrayType()) {
4047      Sel = Sema::AbstractArrayType;
4048      T = Info.S.Context.getBaseElementType(T);
4049    }
4050    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4051    if (CT != Info.AbstractType) return;
4052
4053    // It matched; do some magic.
4054    if (Sel == Sema::AbstractArrayType) {
4055      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4056        << T << TL.getSourceRange();
4057    } else {
4058      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4059        << Sel << T << TL.getSourceRange();
4060    }
4061    Info.DiagnoseAbstractType();
4062  }
4063};
4064
4065void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4066                                  Sema::AbstractDiagSelID Sel) {
4067  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4068}
4069
4070}
4071
4072/// Check for invalid uses of an abstract type in a method declaration.
4073static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4074                                    CXXMethodDecl *MD) {
4075  // No need to do the check on definitions, which require that
4076  // the return/param types be complete.
4077  if (MD->doesThisDeclarationHaveABody())
4078    return;
4079
4080  // For safety's sake, just ignore it if we don't have type source
4081  // information.  This should never happen for non-implicit methods,
4082  // but...
4083  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4084    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4085}
4086
4087/// Check for invalid uses of an abstract type within a class definition.
4088static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4089                                    CXXRecordDecl *RD) {
4090  for (CXXRecordDecl::decl_iterator
4091         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4092    Decl *D = *I;
4093    if (D->isImplicit()) continue;
4094
4095    // Methods and method templates.
4096    if (isa<CXXMethodDecl>(D)) {
4097      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4098    } else if (isa<FunctionTemplateDecl>(D)) {
4099      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4100      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4101
4102    // Fields and static variables.
4103    } else if (isa<FieldDecl>(D)) {
4104      FieldDecl *FD = cast<FieldDecl>(D);
4105      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4106        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4107    } else if (isa<VarDecl>(D)) {
4108      VarDecl *VD = cast<VarDecl>(D);
4109      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4110        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4111
4112    // Nested classes and class templates.
4113    } else if (isa<CXXRecordDecl>(D)) {
4114      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4115    } else if (isa<ClassTemplateDecl>(D)) {
4116      CheckAbstractClassUsage(Info,
4117                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4118    }
4119  }
4120}
4121
4122/// \brief Perform semantic checks on a class definition that has been
4123/// completing, introducing implicitly-declared members, checking for
4124/// abstract types, etc.
4125void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4126  if (!Record)
4127    return;
4128
4129  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4130    AbstractUsageInfo Info(*this, Record);
4131    CheckAbstractClassUsage(Info, Record);
4132  }
4133
4134  // If this is not an aggregate type and has no user-declared constructor,
4135  // complain about any non-static data members of reference or const scalar
4136  // type, since they will never get initializers.
4137  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4138      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4139      !Record->isLambda()) {
4140    bool Complained = false;
4141    for (RecordDecl::field_iterator F = Record->field_begin(),
4142                                 FEnd = Record->field_end();
4143         F != FEnd; ++F) {
4144      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4145        continue;
4146
4147      if (F->getType()->isReferenceType() ||
4148          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4149        if (!Complained) {
4150          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4151            << Record->getTagKind() << Record;
4152          Complained = true;
4153        }
4154
4155        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4156          << F->getType()->isReferenceType()
4157          << F->getDeclName();
4158      }
4159    }
4160  }
4161
4162  if (Record->isDynamicClass() && !Record->isDependentType())
4163    DynamicClasses.push_back(Record);
4164
4165  if (Record->getIdentifier()) {
4166    // C++ [class.mem]p13:
4167    //   If T is the name of a class, then each of the following shall have a
4168    //   name different from T:
4169    //     - every member of every anonymous union that is a member of class T.
4170    //
4171    // C++ [class.mem]p14:
4172    //   In addition, if class T has a user-declared constructor (12.1), every
4173    //   non-static data member of class T shall have a name different from T.
4174    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4175    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4176         ++I) {
4177      NamedDecl *D = *I;
4178      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4179          isa<IndirectFieldDecl>(D)) {
4180        Diag(D->getLocation(), diag::err_member_name_of_class)
4181          << D->getDeclName();
4182        break;
4183      }
4184    }
4185  }
4186
4187  // Warn if the class has virtual methods but non-virtual public destructor.
4188  if (Record->isPolymorphic() && !Record->isDependentType()) {
4189    CXXDestructorDecl *dtor = Record->getDestructor();
4190    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4191      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4192           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4193  }
4194
4195  if (Record->isAbstract() && Record->hasAttr<FinalAttr>()) {
4196    Diag(Record->getLocation(), diag::warn_abstract_final_class);
4197    DiagnoseAbstractType(Record);
4198  }
4199
4200  if (!Record->isDependentType()) {
4201    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4202                                     MEnd = Record->method_end();
4203         M != MEnd; ++M) {
4204      // See if a method overloads virtual methods in a base
4205      // class without overriding any.
4206      if (!M->isStatic())
4207        DiagnoseHiddenVirtualMethods(Record, *M);
4208
4209      // Check whether the explicitly-defaulted special members are valid.
4210      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4211        CheckExplicitlyDefaultedSpecialMember(*M);
4212
4213      // For an explicitly defaulted or deleted special member, we defer
4214      // determining triviality until the class is complete. That time is now!
4215      if (!M->isImplicit() && !M->isUserProvided()) {
4216        CXXSpecialMember CSM = getSpecialMember(*M);
4217        if (CSM != CXXInvalid) {
4218          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4219
4220          // Inform the class that we've finished declaring this member.
4221          Record->finishedDefaultedOrDeletedMember(*M);
4222        }
4223      }
4224    }
4225  }
4226
4227  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4228  // function that is not a constructor declares that member function to be
4229  // const. [...] The class of which that function is a member shall be
4230  // a literal type.
4231  //
4232  // If the class has virtual bases, any constexpr members will already have
4233  // been diagnosed by the checks performed on the member declaration, so
4234  // suppress this (less useful) diagnostic.
4235  //
4236  // We delay this until we know whether an explicitly-defaulted (or deleted)
4237  // destructor for the class is trivial.
4238  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4239      !Record->isLiteral() && !Record->getNumVBases()) {
4240    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4241                                     MEnd = Record->method_end();
4242         M != MEnd; ++M) {
4243      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4244        switch (Record->getTemplateSpecializationKind()) {
4245        case TSK_ImplicitInstantiation:
4246        case TSK_ExplicitInstantiationDeclaration:
4247        case TSK_ExplicitInstantiationDefinition:
4248          // If a template instantiates to a non-literal type, but its members
4249          // instantiate to constexpr functions, the template is technically
4250          // ill-formed, but we allow it for sanity.
4251          continue;
4252
4253        case TSK_Undeclared:
4254        case TSK_ExplicitSpecialization:
4255          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4256                             diag::err_constexpr_method_non_literal);
4257          break;
4258        }
4259
4260        // Only produce one error per class.
4261        break;
4262      }
4263    }
4264  }
4265
4266  // Declare inheriting constructors. We do this eagerly here because:
4267  // - The standard requires an eager diagnostic for conflicting inheriting
4268  //   constructors from different classes.
4269  // - The lazy declaration of the other implicit constructors is so as to not
4270  //   waste space and performance on classes that are not meant to be
4271  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4272  //   have inheriting constructors.
4273  DeclareInheritingConstructors(Record);
4274}
4275
4276/// Is the special member function which would be selected to perform the
4277/// specified operation on the specified class type a constexpr constructor?
4278static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4279                                     Sema::CXXSpecialMember CSM,
4280                                     bool ConstArg) {
4281  Sema::SpecialMemberOverloadResult *SMOR =
4282      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4283                            false, false, false, false);
4284  if (!SMOR || !SMOR->getMethod())
4285    // A constructor we wouldn't select can't be "involved in initializing"
4286    // anything.
4287    return true;
4288  return SMOR->getMethod()->isConstexpr();
4289}
4290
4291/// Determine whether the specified special member function would be constexpr
4292/// if it were implicitly defined.
4293static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4294                                              Sema::CXXSpecialMember CSM,
4295                                              bool ConstArg) {
4296  if (!S.getLangOpts().CPlusPlus11)
4297    return false;
4298
4299  // C++11 [dcl.constexpr]p4:
4300  // In the definition of a constexpr constructor [...]
4301  bool Ctor = true;
4302  switch (CSM) {
4303  case Sema::CXXDefaultConstructor:
4304    // Since default constructor lookup is essentially trivial (and cannot
4305    // involve, for instance, template instantiation), we compute whether a
4306    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4307    //
4308    // This is important for performance; we need to know whether the default
4309    // constructor is constexpr to determine whether the type is a literal type.
4310    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4311
4312  case Sema::CXXCopyConstructor:
4313  case Sema::CXXMoveConstructor:
4314    // For copy or move constructors, we need to perform overload resolution.
4315    break;
4316
4317  case Sema::CXXCopyAssignment:
4318  case Sema::CXXMoveAssignment:
4319    if (!S.getLangOpts().CPlusPlus1y)
4320      return false;
4321    // In C++1y, we need to perform overload resolution.
4322    Ctor = false;
4323    break;
4324
4325  case Sema::CXXDestructor:
4326  case Sema::CXXInvalid:
4327    return false;
4328  }
4329
4330  //   -- if the class is a non-empty union, or for each non-empty anonymous
4331  //      union member of a non-union class, exactly one non-static data member
4332  //      shall be initialized; [DR1359]
4333  //
4334  // If we squint, this is guaranteed, since exactly one non-static data member
4335  // will be initialized (if the constructor isn't deleted), we just don't know
4336  // which one.
4337  if (Ctor && ClassDecl->isUnion())
4338    return true;
4339
4340  //   -- the class shall not have any virtual base classes;
4341  if (Ctor && ClassDecl->getNumVBases())
4342    return false;
4343
4344  // C++1y [class.copy]p26:
4345  //   -- [the class] is a literal type, and
4346  if (!Ctor && !ClassDecl->isLiteral())
4347    return false;
4348
4349  //   -- every constructor involved in initializing [...] base class
4350  //      sub-objects shall be a constexpr constructor;
4351  //   -- the assignment operator selected to copy/move each direct base
4352  //      class is a constexpr function, and
4353  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4354                                       BEnd = ClassDecl->bases_end();
4355       B != BEnd; ++B) {
4356    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4357    if (!BaseType) continue;
4358
4359    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4360    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4361      return false;
4362  }
4363
4364  //   -- every constructor involved in initializing non-static data members
4365  //      [...] shall be a constexpr constructor;
4366  //   -- every non-static data member and base class sub-object shall be
4367  //      initialized
4368  //   -- for each non-stastic data member of X that is of class type (or array
4369  //      thereof), the assignment operator selected to copy/move that member is
4370  //      a constexpr function
4371  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4372                               FEnd = ClassDecl->field_end();
4373       F != FEnd; ++F) {
4374    if (F->isInvalidDecl())
4375      continue;
4376    if (const RecordType *RecordTy =
4377            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4378      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4379      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4380        return false;
4381    }
4382  }
4383
4384  // All OK, it's constexpr!
4385  return true;
4386}
4387
4388static Sema::ImplicitExceptionSpecification
4389computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4390  switch (S.getSpecialMember(MD)) {
4391  case Sema::CXXDefaultConstructor:
4392    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4393  case Sema::CXXCopyConstructor:
4394    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4395  case Sema::CXXCopyAssignment:
4396    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4397  case Sema::CXXMoveConstructor:
4398    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4399  case Sema::CXXMoveAssignment:
4400    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4401  case Sema::CXXDestructor:
4402    return S.ComputeDefaultedDtorExceptionSpec(MD);
4403  case Sema::CXXInvalid:
4404    break;
4405  }
4406  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4407         "only special members have implicit exception specs");
4408  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4409}
4410
4411static void
4412updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4413                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4414  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4415  ExceptSpec.getEPI(EPI);
4416  FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4417                                        FPT->getArgTypes(), EPI));
4418}
4419
4420void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4421  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4422  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4423    return;
4424
4425  // Evaluate the exception specification.
4426  ImplicitExceptionSpecification ExceptSpec =
4427      computeImplicitExceptionSpec(*this, Loc, MD);
4428
4429  // Update the type of the special member to use it.
4430  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4431
4432  // A user-provided destructor can be defined outside the class. When that
4433  // happens, be sure to update the exception specification on both
4434  // declarations.
4435  const FunctionProtoType *CanonicalFPT =
4436    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4437  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4438    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4439                        CanonicalFPT, ExceptSpec);
4440}
4441
4442void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4443  CXXRecordDecl *RD = MD->getParent();
4444  CXXSpecialMember CSM = getSpecialMember(MD);
4445
4446  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4447         "not an explicitly-defaulted special member");
4448
4449  // Whether this was the first-declared instance of the constructor.
4450  // This affects whether we implicitly add an exception spec and constexpr.
4451  bool First = MD == MD->getCanonicalDecl();
4452
4453  bool HadError = false;
4454
4455  // C++11 [dcl.fct.def.default]p1:
4456  //   A function that is explicitly defaulted shall
4457  //     -- be a special member function (checked elsewhere),
4458  //     -- have the same type (except for ref-qualifiers, and except that a
4459  //        copy operation can take a non-const reference) as an implicit
4460  //        declaration, and
4461  //     -- not have default arguments.
4462  unsigned ExpectedParams = 1;
4463  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4464    ExpectedParams = 0;
4465  if (MD->getNumParams() != ExpectedParams) {
4466    // This also checks for default arguments: a copy or move constructor with a
4467    // default argument is classified as a default constructor, and assignment
4468    // operations and destructors can't have default arguments.
4469    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4470      << CSM << MD->getSourceRange();
4471    HadError = true;
4472  } else if (MD->isVariadic()) {
4473    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4474      << CSM << MD->getSourceRange();
4475    HadError = true;
4476  }
4477
4478  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4479
4480  bool CanHaveConstParam = false;
4481  if (CSM == CXXCopyConstructor)
4482    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4483  else if (CSM == CXXCopyAssignment)
4484    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4485
4486  QualType ReturnType = Context.VoidTy;
4487  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4488    // Check for return type matching.
4489    ReturnType = Type->getResultType();
4490    QualType ExpectedReturnType =
4491        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4492    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4493      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4494        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4495      HadError = true;
4496    }
4497
4498    // A defaulted special member cannot have cv-qualifiers.
4499    if (Type->getTypeQuals()) {
4500      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4501        << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4502      HadError = true;
4503    }
4504  }
4505
4506  // Check for parameter type matching.
4507  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4508  bool HasConstParam = false;
4509  if (ExpectedParams && ArgType->isReferenceType()) {
4510    // Argument must be reference to possibly-const T.
4511    QualType ReferentType = ArgType->getPointeeType();
4512    HasConstParam = ReferentType.isConstQualified();
4513
4514    if (ReferentType.isVolatileQualified()) {
4515      Diag(MD->getLocation(),
4516           diag::err_defaulted_special_member_volatile_param) << CSM;
4517      HadError = true;
4518    }
4519
4520    if (HasConstParam && !CanHaveConstParam) {
4521      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4522        Diag(MD->getLocation(),
4523             diag::err_defaulted_special_member_copy_const_param)
4524          << (CSM == CXXCopyAssignment);
4525        // FIXME: Explain why this special member can't be const.
4526      } else {
4527        Diag(MD->getLocation(),
4528             diag::err_defaulted_special_member_move_const_param)
4529          << (CSM == CXXMoveAssignment);
4530      }
4531      HadError = true;
4532    }
4533  } else if (ExpectedParams) {
4534    // A copy assignment operator can take its argument by value, but a
4535    // defaulted one cannot.
4536    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4537    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4538    HadError = true;
4539  }
4540
4541  // C++11 [dcl.fct.def.default]p2:
4542  //   An explicitly-defaulted function may be declared constexpr only if it
4543  //   would have been implicitly declared as constexpr,
4544  // Do not apply this rule to members of class templates, since core issue 1358
4545  // makes such functions always instantiate to constexpr functions. For
4546  // functions which cannot be constexpr (for non-constructors in C++11 and for
4547  // destructors in C++1y), this is checked elsewhere.
4548  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4549                                                     HasConstParam);
4550  if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4551                                 : isa<CXXConstructorDecl>(MD)) &&
4552      MD->isConstexpr() && !Constexpr &&
4553      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4554    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4555    // FIXME: Explain why the special member can't be constexpr.
4556    HadError = true;
4557  }
4558
4559  //   and may have an explicit exception-specification only if it is compatible
4560  //   with the exception-specification on the implicit declaration.
4561  if (Type->hasExceptionSpec()) {
4562    // Delay the check if this is the first declaration of the special member,
4563    // since we may not have parsed some necessary in-class initializers yet.
4564    if (First) {
4565      // If the exception specification needs to be instantiated, do so now,
4566      // before we clobber it with an EST_Unevaluated specification below.
4567      if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4568        InstantiateExceptionSpec(MD->getLocStart(), MD);
4569        Type = MD->getType()->getAs<FunctionProtoType>();
4570      }
4571      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4572    } else
4573      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4574  }
4575
4576  //   If a function is explicitly defaulted on its first declaration,
4577  if (First) {
4578    //  -- it is implicitly considered to be constexpr if the implicit
4579    //     definition would be,
4580    MD->setConstexpr(Constexpr);
4581
4582    //  -- it is implicitly considered to have the same exception-specification
4583    //     as if it had been implicitly declared,
4584    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4585    EPI.ExceptionSpecType = EST_Unevaluated;
4586    EPI.ExceptionSpecDecl = MD;
4587    MD->setType(Context.getFunctionType(ReturnType,
4588                                        ArrayRef<QualType>(&ArgType,
4589                                                           ExpectedParams),
4590                                        EPI));
4591  }
4592
4593  if (ShouldDeleteSpecialMember(MD, CSM)) {
4594    if (First) {
4595      SetDeclDeleted(MD, MD->getLocation());
4596    } else {
4597      // C++11 [dcl.fct.def.default]p4:
4598      //   [For a] user-provided explicitly-defaulted function [...] if such a
4599      //   function is implicitly defined as deleted, the program is ill-formed.
4600      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4601      HadError = true;
4602    }
4603  }
4604
4605  if (HadError)
4606    MD->setInvalidDecl();
4607}
4608
4609/// Check whether the exception specification provided for an
4610/// explicitly-defaulted special member matches the exception specification
4611/// that would have been generated for an implicit special member, per
4612/// C++11 [dcl.fct.def.default]p2.
4613void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4614    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4615  // Compute the implicit exception specification.
4616  FunctionProtoType::ExtProtoInfo EPI;
4617  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4618  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4619    Context.getFunctionType(Context.VoidTy, None, EPI));
4620
4621  // Ensure that it matches.
4622  CheckEquivalentExceptionSpec(
4623    PDiag(diag::err_incorrect_defaulted_exception_spec)
4624      << getSpecialMember(MD), PDiag(),
4625    ImplicitType, SourceLocation(),
4626    SpecifiedType, MD->getLocation());
4627}
4628
4629void Sema::CheckDelayedExplicitlyDefaultedMemberExceptionSpecs() {
4630  for (unsigned I = 0, N = DelayedDefaultedMemberExceptionSpecs.size();
4631       I != N; ++I)
4632    CheckExplicitlyDefaultedMemberExceptionSpec(
4633      DelayedDefaultedMemberExceptionSpecs[I].first,
4634      DelayedDefaultedMemberExceptionSpecs[I].second);
4635
4636  DelayedDefaultedMemberExceptionSpecs.clear();
4637}
4638
4639namespace {
4640struct SpecialMemberDeletionInfo {
4641  Sema &S;
4642  CXXMethodDecl *MD;
4643  Sema::CXXSpecialMember CSM;
4644  bool Diagnose;
4645
4646  // Properties of the special member, computed for convenience.
4647  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4648  SourceLocation Loc;
4649
4650  bool AllFieldsAreConst;
4651
4652  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4653                            Sema::CXXSpecialMember CSM, bool Diagnose)
4654    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4655      IsConstructor(false), IsAssignment(false), IsMove(false),
4656      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4657      AllFieldsAreConst(true) {
4658    switch (CSM) {
4659      case Sema::CXXDefaultConstructor:
4660      case Sema::CXXCopyConstructor:
4661        IsConstructor = true;
4662        break;
4663      case Sema::CXXMoveConstructor:
4664        IsConstructor = true;
4665        IsMove = true;
4666        break;
4667      case Sema::CXXCopyAssignment:
4668        IsAssignment = true;
4669        break;
4670      case Sema::CXXMoveAssignment:
4671        IsAssignment = true;
4672        IsMove = true;
4673        break;
4674      case Sema::CXXDestructor:
4675        break;
4676      case Sema::CXXInvalid:
4677        llvm_unreachable("invalid special member kind");
4678    }
4679
4680    if (MD->getNumParams()) {
4681      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4682      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4683    }
4684  }
4685
4686  bool inUnion() const { return MD->getParent()->isUnion(); }
4687
4688  /// Look up the corresponding special member in the given class.
4689  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4690                                              unsigned Quals) {
4691    unsigned TQ = MD->getTypeQualifiers();
4692    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4693    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4694      Quals = 0;
4695    return S.LookupSpecialMember(Class, CSM,
4696                                 ConstArg || (Quals & Qualifiers::Const),
4697                                 VolatileArg || (Quals & Qualifiers::Volatile),
4698                                 MD->getRefQualifier() == RQ_RValue,
4699                                 TQ & Qualifiers::Const,
4700                                 TQ & Qualifiers::Volatile);
4701  }
4702
4703  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4704
4705  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4706  bool shouldDeleteForField(FieldDecl *FD);
4707  bool shouldDeleteForAllConstMembers();
4708
4709  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4710                                     unsigned Quals);
4711  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4712                                    Sema::SpecialMemberOverloadResult *SMOR,
4713                                    bool IsDtorCallInCtor);
4714
4715  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4716};
4717}
4718
4719/// Is the given special member inaccessible when used on the given
4720/// sub-object.
4721bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4722                                             CXXMethodDecl *target) {
4723  /// If we're operating on a base class, the object type is the
4724  /// type of this special member.
4725  QualType objectTy;
4726  AccessSpecifier access = target->getAccess();
4727  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4728    objectTy = S.Context.getTypeDeclType(MD->getParent());
4729    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4730
4731  // If we're operating on a field, the object type is the type of the field.
4732  } else {
4733    objectTy = S.Context.getTypeDeclType(target->getParent());
4734  }
4735
4736  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4737}
4738
4739/// Check whether we should delete a special member due to the implicit
4740/// definition containing a call to a special member of a subobject.
4741bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4742    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4743    bool IsDtorCallInCtor) {
4744  CXXMethodDecl *Decl = SMOR->getMethod();
4745  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4746
4747  int DiagKind = -1;
4748
4749  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4750    DiagKind = !Decl ? 0 : 1;
4751  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4752    DiagKind = 2;
4753  else if (!isAccessible(Subobj, Decl))
4754    DiagKind = 3;
4755  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4756           !Decl->isTrivial()) {
4757    // A member of a union must have a trivial corresponding special member.
4758    // As a weird special case, a destructor call from a union's constructor
4759    // must be accessible and non-deleted, but need not be trivial. Such a
4760    // destructor is never actually called, but is semantically checked as
4761    // if it were.
4762    DiagKind = 4;
4763  }
4764
4765  if (DiagKind == -1)
4766    return false;
4767
4768  if (Diagnose) {
4769    if (Field) {
4770      S.Diag(Field->getLocation(),
4771             diag::note_deleted_special_member_class_subobject)
4772        << CSM << MD->getParent() << /*IsField*/true
4773        << Field << DiagKind << IsDtorCallInCtor;
4774    } else {
4775      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4776      S.Diag(Base->getLocStart(),
4777             diag::note_deleted_special_member_class_subobject)
4778        << CSM << MD->getParent() << /*IsField*/false
4779        << Base->getType() << DiagKind << IsDtorCallInCtor;
4780    }
4781
4782    if (DiagKind == 1)
4783      S.NoteDeletedFunction(Decl);
4784    // FIXME: Explain inaccessibility if DiagKind == 3.
4785  }
4786
4787  return true;
4788}
4789
4790/// Check whether we should delete a special member function due to having a
4791/// direct or virtual base class or non-static data member of class type M.
4792bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4793    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
4794  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4795
4796  // C++11 [class.ctor]p5:
4797  // -- any direct or virtual base class, or non-static data member with no
4798  //    brace-or-equal-initializer, has class type M (or array thereof) and
4799  //    either M has no default constructor or overload resolution as applied
4800  //    to M's default constructor results in an ambiguity or in a function
4801  //    that is deleted or inaccessible
4802  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4803  // -- a direct or virtual base class B that cannot be copied/moved because
4804  //    overload resolution, as applied to B's corresponding special member,
4805  //    results in an ambiguity or a function that is deleted or inaccessible
4806  //    from the defaulted special member
4807  // C++11 [class.dtor]p5:
4808  // -- any direct or virtual base class [...] has a type with a destructor
4809  //    that is deleted or inaccessible
4810  if (!(CSM == Sema::CXXDefaultConstructor &&
4811        Field && Field->hasInClassInitializer()) &&
4812      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
4813    return true;
4814
4815  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4816  // -- any direct or virtual base class or non-static data member has a
4817  //    type with a destructor that is deleted or inaccessible
4818  if (IsConstructor) {
4819    Sema::SpecialMemberOverloadResult *SMOR =
4820        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4821                              false, false, false, false, false);
4822    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4823      return true;
4824  }
4825
4826  return false;
4827}
4828
4829/// Check whether we should delete a special member function due to the class
4830/// having a particular direct or virtual base class.
4831bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4832  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4833  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
4834}
4835
4836/// Check whether we should delete a special member function due to the class
4837/// having a particular non-static data member.
4838bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4839  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4840  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4841
4842  if (CSM == Sema::CXXDefaultConstructor) {
4843    // For a default constructor, all references must be initialized in-class
4844    // and, if a union, it must have a non-const member.
4845    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4846      if (Diagnose)
4847        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4848          << MD->getParent() << FD << FieldType << /*Reference*/0;
4849      return true;
4850    }
4851    // C++11 [class.ctor]p5: any non-variant non-static data member of
4852    // const-qualified type (or array thereof) with no
4853    // brace-or-equal-initializer does not have a user-provided default
4854    // constructor.
4855    if (!inUnion() && FieldType.isConstQualified() &&
4856        !FD->hasInClassInitializer() &&
4857        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4858      if (Diagnose)
4859        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4860          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4861      return true;
4862    }
4863
4864    if (inUnion() && !FieldType.isConstQualified())
4865      AllFieldsAreConst = false;
4866  } else if (CSM == Sema::CXXCopyConstructor) {
4867    // For a copy constructor, data members must not be of rvalue reference
4868    // type.
4869    if (FieldType->isRValueReferenceType()) {
4870      if (Diagnose)
4871        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4872          << MD->getParent() << FD << FieldType;
4873      return true;
4874    }
4875  } else if (IsAssignment) {
4876    // For an assignment operator, data members must not be of reference type.
4877    if (FieldType->isReferenceType()) {
4878      if (Diagnose)
4879        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4880          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4881      return true;
4882    }
4883    if (!FieldRecord && FieldType.isConstQualified()) {
4884      // C++11 [class.copy]p23:
4885      // -- a non-static data member of const non-class type (or array thereof)
4886      if (Diagnose)
4887        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4888          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4889      return true;
4890    }
4891  }
4892
4893  if (FieldRecord) {
4894    // Some additional restrictions exist on the variant members.
4895    if (!inUnion() && FieldRecord->isUnion() &&
4896        FieldRecord->isAnonymousStructOrUnion()) {
4897      bool AllVariantFieldsAreConst = true;
4898
4899      // FIXME: Handle anonymous unions declared within anonymous unions.
4900      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4901                                         UE = FieldRecord->field_end();
4902           UI != UE; ++UI) {
4903        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4904
4905        if (!UnionFieldType.isConstQualified())
4906          AllVariantFieldsAreConst = false;
4907
4908        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4909        if (UnionFieldRecord &&
4910            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
4911                                          UnionFieldType.getCVRQualifiers()))
4912          return true;
4913      }
4914
4915      // At least one member in each anonymous union must be non-const
4916      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4917          FieldRecord->field_begin() != FieldRecord->field_end()) {
4918        if (Diagnose)
4919          S.Diag(FieldRecord->getLocation(),
4920                 diag::note_deleted_default_ctor_all_const)
4921            << MD->getParent() << /*anonymous union*/1;
4922        return true;
4923      }
4924
4925      // Don't check the implicit member of the anonymous union type.
4926      // This is technically non-conformant, but sanity demands it.
4927      return false;
4928    }
4929
4930    if (shouldDeleteForClassSubobject(FieldRecord, FD,
4931                                      FieldType.getCVRQualifiers()))
4932      return true;
4933  }
4934
4935  return false;
4936}
4937
4938/// C++11 [class.ctor] p5:
4939///   A defaulted default constructor for a class X is defined as deleted if
4940/// X is a union and all of its variant members are of const-qualified type.
4941bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4942  // This is a silly definition, because it gives an empty union a deleted
4943  // default constructor. Don't do that.
4944  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4945      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4946    if (Diagnose)
4947      S.Diag(MD->getParent()->getLocation(),
4948             diag::note_deleted_default_ctor_all_const)
4949        << MD->getParent() << /*not anonymous union*/0;
4950    return true;
4951  }
4952  return false;
4953}
4954
4955/// Determine whether a defaulted special member function should be defined as
4956/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4957/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4958bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4959                                     bool Diagnose) {
4960  if (MD->isInvalidDecl())
4961    return false;
4962  CXXRecordDecl *RD = MD->getParent();
4963  assert(!RD->isDependentType() && "do deletion after instantiation");
4964  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
4965    return false;
4966
4967  // C++11 [expr.lambda.prim]p19:
4968  //   The closure type associated with a lambda-expression has a
4969  //   deleted (8.4.3) default constructor and a deleted copy
4970  //   assignment operator.
4971  if (RD->isLambda() &&
4972      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4973    if (Diagnose)
4974      Diag(RD->getLocation(), diag::note_lambda_decl);
4975    return true;
4976  }
4977
4978  // For an anonymous struct or union, the copy and assignment special members
4979  // will never be used, so skip the check. For an anonymous union declared at
4980  // namespace scope, the constructor and destructor are used.
4981  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4982      RD->isAnonymousStructOrUnion())
4983    return false;
4984
4985  // C++11 [class.copy]p7, p18:
4986  //   If the class definition declares a move constructor or move assignment
4987  //   operator, an implicitly declared copy constructor or copy assignment
4988  //   operator is defined as deleted.
4989  if (MD->isImplicit() &&
4990      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4991    CXXMethodDecl *UserDeclaredMove = 0;
4992
4993    // In Microsoft mode, a user-declared move only causes the deletion of the
4994    // corresponding copy operation, not both copy operations.
4995    if (RD->hasUserDeclaredMoveConstructor() &&
4996        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4997      if (!Diagnose) return true;
4998
4999      // Find any user-declared move constructor.
5000      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5001                                        E = RD->ctor_end(); I != E; ++I) {
5002        if (I->isMoveConstructor()) {
5003          UserDeclaredMove = *I;
5004          break;
5005        }
5006      }
5007      assert(UserDeclaredMove);
5008    } else if (RD->hasUserDeclaredMoveAssignment() &&
5009               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5010      if (!Diagnose) return true;
5011
5012      // Find any user-declared move assignment operator.
5013      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5014                                          E = RD->method_end(); I != E; ++I) {
5015        if (I->isMoveAssignmentOperator()) {
5016          UserDeclaredMove = *I;
5017          break;
5018        }
5019      }
5020      assert(UserDeclaredMove);
5021    }
5022
5023    if (UserDeclaredMove) {
5024      Diag(UserDeclaredMove->getLocation(),
5025           diag::note_deleted_copy_user_declared_move)
5026        << (CSM == CXXCopyAssignment) << RD
5027        << UserDeclaredMove->isMoveAssignmentOperator();
5028      return true;
5029    }
5030  }
5031
5032  // Do access control from the special member function
5033  ContextRAII MethodContext(*this, MD);
5034
5035  // C++11 [class.dtor]p5:
5036  // -- for a virtual destructor, lookup of the non-array deallocation function
5037  //    results in an ambiguity or in a function that is deleted or inaccessible
5038  if (CSM == CXXDestructor && MD->isVirtual()) {
5039    FunctionDecl *OperatorDelete = 0;
5040    DeclarationName Name =
5041      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5042    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5043                                 OperatorDelete, false)) {
5044      if (Diagnose)
5045        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5046      return true;
5047    }
5048  }
5049
5050  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5051
5052  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5053                                          BE = RD->bases_end(); BI != BE; ++BI)
5054    if (!BI->isVirtual() &&
5055        SMI.shouldDeleteForBase(BI))
5056      return true;
5057
5058  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5059                                          BE = RD->vbases_end(); BI != BE; ++BI)
5060    if (SMI.shouldDeleteForBase(BI))
5061      return true;
5062
5063  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5064                                     FE = RD->field_end(); FI != FE; ++FI)
5065    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5066        SMI.shouldDeleteForField(*FI))
5067      return true;
5068
5069  if (SMI.shouldDeleteForAllConstMembers())
5070    return true;
5071
5072  return false;
5073}
5074
5075/// Perform lookup for a special member of the specified kind, and determine
5076/// whether it is trivial. If the triviality can be determined without the
5077/// lookup, skip it. This is intended for use when determining whether a
5078/// special member of a containing object is trivial, and thus does not ever
5079/// perform overload resolution for default constructors.
5080///
5081/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5082/// member that was most likely to be intended to be trivial, if any.
5083static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5084                                     Sema::CXXSpecialMember CSM, unsigned Quals,
5085                                     CXXMethodDecl **Selected) {
5086  if (Selected)
5087    *Selected = 0;
5088
5089  switch (CSM) {
5090  case Sema::CXXInvalid:
5091    llvm_unreachable("not a special member");
5092
5093  case Sema::CXXDefaultConstructor:
5094    // C++11 [class.ctor]p5:
5095    //   A default constructor is trivial if:
5096    //    - all the [direct subobjects] have trivial default constructors
5097    //
5098    // Note, no overload resolution is performed in this case.
5099    if (RD->hasTrivialDefaultConstructor())
5100      return true;
5101
5102    if (Selected) {
5103      // If there's a default constructor which could have been trivial, dig it
5104      // out. Otherwise, if there's any user-provided default constructor, point
5105      // to that as an example of why there's not a trivial one.
5106      CXXConstructorDecl *DefCtor = 0;
5107      if (RD->needsImplicitDefaultConstructor())
5108        S.DeclareImplicitDefaultConstructor(RD);
5109      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5110                                        CE = RD->ctor_end(); CI != CE; ++CI) {
5111        if (!CI->isDefaultConstructor())
5112          continue;
5113        DefCtor = *CI;
5114        if (!DefCtor->isUserProvided())
5115          break;
5116      }
5117
5118      *Selected = DefCtor;
5119    }
5120
5121    return false;
5122
5123  case Sema::CXXDestructor:
5124    // C++11 [class.dtor]p5:
5125    //   A destructor is trivial if:
5126    //    - all the direct [subobjects] have trivial destructors
5127    if (RD->hasTrivialDestructor())
5128      return true;
5129
5130    if (Selected) {
5131      if (RD->needsImplicitDestructor())
5132        S.DeclareImplicitDestructor(RD);
5133      *Selected = RD->getDestructor();
5134    }
5135
5136    return false;
5137
5138  case Sema::CXXCopyConstructor:
5139    // C++11 [class.copy]p12:
5140    //   A copy constructor is trivial if:
5141    //    - the constructor selected to copy each direct [subobject] is trivial
5142    if (RD->hasTrivialCopyConstructor()) {
5143      if (Quals == Qualifiers::Const)
5144        // We must either select the trivial copy constructor or reach an
5145        // ambiguity; no need to actually perform overload resolution.
5146        return true;
5147    } else if (!Selected) {
5148      return false;
5149    }
5150    // In C++98, we are not supposed to perform overload resolution here, but we
5151    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5152    // cases like B as having a non-trivial copy constructor:
5153    //   struct A { template<typename T> A(T&); };
5154    //   struct B { mutable A a; };
5155    goto NeedOverloadResolution;
5156
5157  case Sema::CXXCopyAssignment:
5158    // C++11 [class.copy]p25:
5159    //   A copy assignment operator is trivial if:
5160    //    - the assignment operator selected to copy each direct [subobject] is
5161    //      trivial
5162    if (RD->hasTrivialCopyAssignment()) {
5163      if (Quals == Qualifiers::Const)
5164        return true;
5165    } else if (!Selected) {
5166      return false;
5167    }
5168    // In C++98, we are not supposed to perform overload resolution here, but we
5169    // treat that as a language defect.
5170    goto NeedOverloadResolution;
5171
5172  case Sema::CXXMoveConstructor:
5173  case Sema::CXXMoveAssignment:
5174  NeedOverloadResolution:
5175    Sema::SpecialMemberOverloadResult *SMOR =
5176      S.LookupSpecialMember(RD, CSM,
5177                            Quals & Qualifiers::Const,
5178                            Quals & Qualifiers::Volatile,
5179                            /*RValueThis*/false, /*ConstThis*/false,
5180                            /*VolatileThis*/false);
5181
5182    // The standard doesn't describe how to behave if the lookup is ambiguous.
5183    // We treat it as not making the member non-trivial, just like the standard
5184    // mandates for the default constructor. This should rarely matter, because
5185    // the member will also be deleted.
5186    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5187      return true;
5188
5189    if (!SMOR->getMethod()) {
5190      assert(SMOR->getKind() ==
5191             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5192      return false;
5193    }
5194
5195    // We deliberately don't check if we found a deleted special member. We're
5196    // not supposed to!
5197    if (Selected)
5198      *Selected = SMOR->getMethod();
5199    return SMOR->getMethod()->isTrivial();
5200  }
5201
5202  llvm_unreachable("unknown special method kind");
5203}
5204
5205static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5206  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5207       CI != CE; ++CI)
5208    if (!CI->isImplicit())
5209      return *CI;
5210
5211  // Look for constructor templates.
5212  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5213  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5214    if (CXXConstructorDecl *CD =
5215          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5216      return CD;
5217  }
5218
5219  return 0;
5220}
5221
5222/// The kind of subobject we are checking for triviality. The values of this
5223/// enumeration are used in diagnostics.
5224enum TrivialSubobjectKind {
5225  /// The subobject is a base class.
5226  TSK_BaseClass,
5227  /// The subobject is a non-static data member.
5228  TSK_Field,
5229  /// The object is actually the complete object.
5230  TSK_CompleteObject
5231};
5232
5233/// Check whether the special member selected for a given type would be trivial.
5234static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5235                                      QualType SubType,
5236                                      Sema::CXXSpecialMember CSM,
5237                                      TrivialSubobjectKind Kind,
5238                                      bool Diagnose) {
5239  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5240  if (!SubRD)
5241    return true;
5242
5243  CXXMethodDecl *Selected;
5244  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5245                               Diagnose ? &Selected : 0))
5246    return true;
5247
5248  if (Diagnose) {
5249    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5250      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5251        << Kind << SubType.getUnqualifiedType();
5252      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5253        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5254    } else if (!Selected)
5255      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5256        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5257    else if (Selected->isUserProvided()) {
5258      if (Kind == TSK_CompleteObject)
5259        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5260          << Kind << SubType.getUnqualifiedType() << CSM;
5261      else {
5262        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5263          << Kind << SubType.getUnqualifiedType() << CSM;
5264        S.Diag(Selected->getLocation(), diag::note_declared_at);
5265      }
5266    } else {
5267      if (Kind != TSK_CompleteObject)
5268        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5269          << Kind << SubType.getUnqualifiedType() << CSM;
5270
5271      // Explain why the defaulted or deleted special member isn't trivial.
5272      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5273    }
5274  }
5275
5276  return false;
5277}
5278
5279/// Check whether the members of a class type allow a special member to be
5280/// trivial.
5281static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5282                                     Sema::CXXSpecialMember CSM,
5283                                     bool ConstArg, bool Diagnose) {
5284  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5285                                     FE = RD->field_end(); FI != FE; ++FI) {
5286    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5287      continue;
5288
5289    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5290
5291    // Pretend anonymous struct or union members are members of this class.
5292    if (FI->isAnonymousStructOrUnion()) {
5293      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5294                                    CSM, ConstArg, Diagnose))
5295        return false;
5296      continue;
5297    }
5298
5299    // C++11 [class.ctor]p5:
5300    //   A default constructor is trivial if [...]
5301    //    -- no non-static data member of its class has a
5302    //       brace-or-equal-initializer
5303    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5304      if (Diagnose)
5305        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5306      return false;
5307    }
5308
5309    // Objective C ARC 4.3.5:
5310    //   [...] nontrivally ownership-qualified types are [...] not trivially
5311    //   default constructible, copy constructible, move constructible, copy
5312    //   assignable, move assignable, or destructible [...]
5313    if (S.getLangOpts().ObjCAutoRefCount &&
5314        FieldType.hasNonTrivialObjCLifetime()) {
5315      if (Diagnose)
5316        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5317          << RD << FieldType.getObjCLifetime();
5318      return false;
5319    }
5320
5321    if (ConstArg && !FI->isMutable())
5322      FieldType.addConst();
5323    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5324                                   TSK_Field, Diagnose))
5325      return false;
5326  }
5327
5328  return true;
5329}
5330
5331/// Diagnose why the specified class does not have a trivial special member of
5332/// the given kind.
5333void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5334  QualType Ty = Context.getRecordType(RD);
5335  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5336    Ty.addConst();
5337
5338  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5339                            TSK_CompleteObject, /*Diagnose*/true);
5340}
5341
5342/// Determine whether a defaulted or deleted special member function is trivial,
5343/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5344/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5345bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5346                                  bool Diagnose) {
5347  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5348
5349  CXXRecordDecl *RD = MD->getParent();
5350
5351  bool ConstArg = false;
5352
5353  // C++11 [class.copy]p12, p25:
5354  //   A [special member] is trivial if its declared parameter type is the same
5355  //   as if it had been implicitly declared [...]
5356  switch (CSM) {
5357  case CXXDefaultConstructor:
5358  case CXXDestructor:
5359    // Trivial default constructors and destructors cannot have parameters.
5360    break;
5361
5362  case CXXCopyConstructor:
5363  case CXXCopyAssignment: {
5364    // Trivial copy operations always have const, non-volatile parameter types.
5365    ConstArg = true;
5366    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5367    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5368    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5369      if (Diagnose)
5370        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5371          << Param0->getSourceRange() << Param0->getType()
5372          << Context.getLValueReferenceType(
5373               Context.getRecordType(RD).withConst());
5374      return false;
5375    }
5376    break;
5377  }
5378
5379  case CXXMoveConstructor:
5380  case CXXMoveAssignment: {
5381    // Trivial move operations always have non-cv-qualified parameters.
5382    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5383    const RValueReferenceType *RT =
5384      Param0->getType()->getAs<RValueReferenceType>();
5385    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5386      if (Diagnose)
5387        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5388          << Param0->getSourceRange() << Param0->getType()
5389          << Context.getRValueReferenceType(Context.getRecordType(RD));
5390      return false;
5391    }
5392    break;
5393  }
5394
5395  case CXXInvalid:
5396    llvm_unreachable("not a special member");
5397  }
5398
5399  // FIXME: We require that the parameter-declaration-clause is equivalent to
5400  // that of an implicit declaration, not just that the declared parameter type
5401  // matches, in order to prevent absuridities like a function simultaneously
5402  // being a trivial copy constructor and a non-trivial default constructor.
5403  // This issue has not yet been assigned a core issue number.
5404  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5405    if (Diagnose)
5406      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5407           diag::note_nontrivial_default_arg)
5408        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5409    return false;
5410  }
5411  if (MD->isVariadic()) {
5412    if (Diagnose)
5413      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5414    return false;
5415  }
5416
5417  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5418  //   A copy/move [constructor or assignment operator] is trivial if
5419  //    -- the [member] selected to copy/move each direct base class subobject
5420  //       is trivial
5421  //
5422  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5423  //   A [default constructor or destructor] is trivial if
5424  //    -- all the direct base classes have trivial [default constructors or
5425  //       destructors]
5426  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5427                                          BE = RD->bases_end(); BI != BE; ++BI)
5428    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5429                                   ConstArg ? BI->getType().withConst()
5430                                            : BI->getType(),
5431                                   CSM, TSK_BaseClass, Diagnose))
5432      return false;
5433
5434  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5435  //   A copy/move [constructor or assignment operator] for a class X is
5436  //   trivial if
5437  //    -- for each non-static data member of X that is of class type (or array
5438  //       thereof), the constructor selected to copy/move that member is
5439  //       trivial
5440  //
5441  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5442  //   A [default constructor or destructor] is trivial if
5443  //    -- for all of the non-static data members of its class that are of class
5444  //       type (or array thereof), each such class has a trivial [default
5445  //       constructor or destructor]
5446  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5447    return false;
5448
5449  // C++11 [class.dtor]p5:
5450  //   A destructor is trivial if [...]
5451  //    -- the destructor is not virtual
5452  if (CSM == CXXDestructor && MD->isVirtual()) {
5453    if (Diagnose)
5454      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5455    return false;
5456  }
5457
5458  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5459  //   A [special member] for class X is trivial if [...]
5460  //    -- class X has no virtual functions and no virtual base classes
5461  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5462    if (!Diagnose)
5463      return false;
5464
5465    if (RD->getNumVBases()) {
5466      // Check for virtual bases. We already know that the corresponding
5467      // member in all bases is trivial, so vbases must all be direct.
5468      CXXBaseSpecifier &BS = *RD->vbases_begin();
5469      assert(BS.isVirtual());
5470      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5471      return false;
5472    }
5473
5474    // Must have a virtual method.
5475    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5476                                        ME = RD->method_end(); MI != ME; ++MI) {
5477      if (MI->isVirtual()) {
5478        SourceLocation MLoc = MI->getLocStart();
5479        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5480        return false;
5481      }
5482    }
5483
5484    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5485  }
5486
5487  // Looks like it's trivial!
5488  return true;
5489}
5490
5491/// \brief Data used with FindHiddenVirtualMethod
5492namespace {
5493  struct FindHiddenVirtualMethodData {
5494    Sema *S;
5495    CXXMethodDecl *Method;
5496    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5497    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5498  };
5499}
5500
5501/// \brief Check whether any most overriden method from MD in Methods
5502static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5503                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5504  if (MD->size_overridden_methods() == 0)
5505    return Methods.count(MD->getCanonicalDecl());
5506  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5507                                      E = MD->end_overridden_methods();
5508       I != E; ++I)
5509    if (CheckMostOverridenMethods(*I, Methods))
5510      return true;
5511  return false;
5512}
5513
5514/// \brief Member lookup function that determines whether a given C++
5515/// method overloads virtual methods in a base class without overriding any,
5516/// to be used with CXXRecordDecl::lookupInBases().
5517static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5518                                    CXXBasePath &Path,
5519                                    void *UserData) {
5520  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5521
5522  FindHiddenVirtualMethodData &Data
5523    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5524
5525  DeclarationName Name = Data.Method->getDeclName();
5526  assert(Name.getNameKind() == DeclarationName::Identifier);
5527
5528  bool foundSameNameMethod = false;
5529  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5530  for (Path.Decls = BaseRecord->lookup(Name);
5531       !Path.Decls.empty();
5532       Path.Decls = Path.Decls.slice(1)) {
5533    NamedDecl *D = Path.Decls.front();
5534    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5535      MD = MD->getCanonicalDecl();
5536      foundSameNameMethod = true;
5537      // Interested only in hidden virtual methods.
5538      if (!MD->isVirtual())
5539        continue;
5540      // If the method we are checking overrides a method from its base
5541      // don't warn about the other overloaded methods.
5542      if (!Data.S->IsOverload(Data.Method, MD, false))
5543        return true;
5544      // Collect the overload only if its hidden.
5545      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5546        overloadedMethods.push_back(MD);
5547    }
5548  }
5549
5550  if (foundSameNameMethod)
5551    Data.OverloadedMethods.append(overloadedMethods.begin(),
5552                                   overloadedMethods.end());
5553  return foundSameNameMethod;
5554}
5555
5556/// \brief Add the most overriden methods from MD to Methods
5557static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5558                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5559  if (MD->size_overridden_methods() == 0)
5560    Methods.insert(MD->getCanonicalDecl());
5561  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5562                                      E = MD->end_overridden_methods();
5563       I != E; ++I)
5564    AddMostOverridenMethods(*I, Methods);
5565}
5566
5567/// \brief See if a method overloads virtual methods in a base class without
5568/// overriding any.
5569void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5570  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5571                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5572    return;
5573  if (!MD->getDeclName().isIdentifier())
5574    return;
5575
5576  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5577                     /*bool RecordPaths=*/false,
5578                     /*bool DetectVirtual=*/false);
5579  FindHiddenVirtualMethodData Data;
5580  Data.Method = MD;
5581  Data.S = this;
5582
5583  // Keep the base methods that were overriden or introduced in the subclass
5584  // by 'using' in a set. A base method not in this set is hidden.
5585  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5586  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5587    NamedDecl *ND = *I;
5588    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5589      ND = shad->getTargetDecl();
5590    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5591      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5592  }
5593
5594  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5595      !Data.OverloadedMethods.empty()) {
5596    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5597      << MD << (Data.OverloadedMethods.size() > 1);
5598
5599    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5600      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5601      PartialDiagnostic PD = PDiag(
5602           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5603      HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5604      Diag(overloadedMD->getLocation(), PD);
5605    }
5606  }
5607}
5608
5609void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5610                                             Decl *TagDecl,
5611                                             SourceLocation LBrac,
5612                                             SourceLocation RBrac,
5613                                             AttributeList *AttrList) {
5614  if (!TagDecl)
5615    return;
5616
5617  AdjustDeclIfTemplate(TagDecl);
5618
5619  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5620    if (l->getKind() != AttributeList::AT_Visibility)
5621      continue;
5622    l->setInvalid();
5623    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5624      l->getName();
5625  }
5626
5627  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5628              // strict aliasing violation!
5629              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5630              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5631
5632  CheckCompletedCXXClass(
5633                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5634}
5635
5636/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5637/// special functions, such as the default constructor, copy
5638/// constructor, or destructor, to the given C++ class (C++
5639/// [special]p1).  This routine can only be executed just before the
5640/// definition of the class is complete.
5641void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5642  if (!ClassDecl->hasUserDeclaredConstructor())
5643    ++ASTContext::NumImplicitDefaultConstructors;
5644
5645  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5646    ++ASTContext::NumImplicitCopyConstructors;
5647
5648    // If the properties or semantics of the copy constructor couldn't be
5649    // determined while the class was being declared, force a declaration
5650    // of it now.
5651    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5652      DeclareImplicitCopyConstructor(ClassDecl);
5653  }
5654
5655  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5656    ++ASTContext::NumImplicitMoveConstructors;
5657
5658    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5659      DeclareImplicitMoveConstructor(ClassDecl);
5660  }
5661
5662  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5663    ++ASTContext::NumImplicitCopyAssignmentOperators;
5664
5665    // If we have a dynamic class, then the copy assignment operator may be
5666    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5667    // it shows up in the right place in the vtable and that we diagnose
5668    // problems with the implicit exception specification.
5669    if (ClassDecl->isDynamicClass() ||
5670        ClassDecl->needsOverloadResolutionForCopyAssignment())
5671      DeclareImplicitCopyAssignment(ClassDecl);
5672  }
5673
5674  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5675    ++ASTContext::NumImplicitMoveAssignmentOperators;
5676
5677    // Likewise for the move assignment operator.
5678    if (ClassDecl->isDynamicClass() ||
5679        ClassDecl->needsOverloadResolutionForMoveAssignment())
5680      DeclareImplicitMoveAssignment(ClassDecl);
5681  }
5682
5683  if (!ClassDecl->hasUserDeclaredDestructor()) {
5684    ++ASTContext::NumImplicitDestructors;
5685
5686    // If we have a dynamic class, then the destructor may be virtual, so we
5687    // have to declare the destructor immediately. This ensures that, e.g., it
5688    // shows up in the right place in the vtable and that we diagnose problems
5689    // with the implicit exception specification.
5690    if (ClassDecl->isDynamicClass() ||
5691        ClassDecl->needsOverloadResolutionForDestructor())
5692      DeclareImplicitDestructor(ClassDecl);
5693  }
5694}
5695
5696void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5697  if (!D)
5698    return;
5699
5700  int NumParamList = D->getNumTemplateParameterLists();
5701  for (int i = 0; i < NumParamList; i++) {
5702    TemplateParameterList* Params = D->getTemplateParameterList(i);
5703    for (TemplateParameterList::iterator Param = Params->begin(),
5704                                      ParamEnd = Params->end();
5705          Param != ParamEnd; ++Param) {
5706      NamedDecl *Named = cast<NamedDecl>(*Param);
5707      if (Named->getDeclName()) {
5708        S->AddDecl(Named);
5709        IdResolver.AddDecl(Named);
5710      }
5711    }
5712  }
5713}
5714
5715void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5716  if (!D)
5717    return;
5718
5719  TemplateParameterList *Params = 0;
5720  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5721    Params = Template->getTemplateParameters();
5722  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5723           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5724    Params = PartialSpec->getTemplateParameters();
5725  else
5726    return;
5727
5728  for (TemplateParameterList::iterator Param = Params->begin(),
5729                                    ParamEnd = Params->end();
5730       Param != ParamEnd; ++Param) {
5731    NamedDecl *Named = cast<NamedDecl>(*Param);
5732    if (Named->getDeclName()) {
5733      S->AddDecl(Named);
5734      IdResolver.AddDecl(Named);
5735    }
5736  }
5737}
5738
5739void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5740  if (!RecordD) return;
5741  AdjustDeclIfTemplate(RecordD);
5742  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5743  PushDeclContext(S, Record);
5744}
5745
5746void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5747  if (!RecordD) return;
5748  PopDeclContext();
5749}
5750
5751/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5752/// parsing a top-level (non-nested) C++ class, and we are now
5753/// parsing those parts of the given Method declaration that could
5754/// not be parsed earlier (C++ [class.mem]p2), such as default
5755/// arguments. This action should enter the scope of the given
5756/// Method declaration as if we had just parsed the qualified method
5757/// name. However, it should not bring the parameters into scope;
5758/// that will be performed by ActOnDelayedCXXMethodParameter.
5759void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5760}
5761
5762/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5763/// C++ method declaration. We're (re-)introducing the given
5764/// function parameter into scope for use in parsing later parts of
5765/// the method declaration. For example, we could see an
5766/// ActOnParamDefaultArgument event for this parameter.
5767void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
5768  if (!ParamD)
5769    return;
5770
5771  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
5772
5773  // If this parameter has an unparsed default argument, clear it out
5774  // to make way for the parsed default argument.
5775  if (Param->hasUnparsedDefaultArg())
5776    Param->setDefaultArg(0);
5777
5778  S->AddDecl(Param);
5779  if (Param->getDeclName())
5780    IdResolver.AddDecl(Param);
5781}
5782
5783/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5784/// processing the delayed method declaration for Method. The method
5785/// declaration is now considered finished. There may be a separate
5786/// ActOnStartOfFunctionDef action later (not necessarily
5787/// immediately!) for this method, if it was also defined inside the
5788/// class body.
5789void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5790  if (!MethodD)
5791    return;
5792
5793  AdjustDeclIfTemplate(MethodD);
5794
5795  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5796
5797  // Now that we have our default arguments, check the constructor
5798  // again. It could produce additional diagnostics or affect whether
5799  // the class has implicitly-declared destructors, among other
5800  // things.
5801  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5802    CheckConstructor(Constructor);
5803
5804  // Check the default arguments, which we may have added.
5805  if (!Method->isInvalidDecl())
5806    CheckCXXDefaultArguments(Method);
5807}
5808
5809/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5810/// the well-formedness of the constructor declarator @p D with type @p
5811/// R. If there are any errors in the declarator, this routine will
5812/// emit diagnostics and set the invalid bit to true.  In any case, the type
5813/// will be updated to reflect a well-formed type for the constructor and
5814/// returned.
5815QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5816                                          StorageClass &SC) {
5817  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5818
5819  // C++ [class.ctor]p3:
5820  //   A constructor shall not be virtual (10.3) or static (9.4). A
5821  //   constructor can be invoked for a const, volatile or const
5822  //   volatile object. A constructor shall not be declared const,
5823  //   volatile, or const volatile (9.3.2).
5824  if (isVirtual) {
5825    if (!D.isInvalidType())
5826      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5827        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5828        << SourceRange(D.getIdentifierLoc());
5829    D.setInvalidType();
5830  }
5831  if (SC == SC_Static) {
5832    if (!D.isInvalidType())
5833      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5834        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5835        << SourceRange(D.getIdentifierLoc());
5836    D.setInvalidType();
5837    SC = SC_None;
5838  }
5839
5840  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5841  if (FTI.TypeQuals != 0) {
5842    if (FTI.TypeQuals & Qualifiers::Const)
5843      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5844        << "const" << SourceRange(D.getIdentifierLoc());
5845    if (FTI.TypeQuals & Qualifiers::Volatile)
5846      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5847        << "volatile" << SourceRange(D.getIdentifierLoc());
5848    if (FTI.TypeQuals & Qualifiers::Restrict)
5849      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5850        << "restrict" << SourceRange(D.getIdentifierLoc());
5851    D.setInvalidType();
5852  }
5853
5854  // C++0x [class.ctor]p4:
5855  //   A constructor shall not be declared with a ref-qualifier.
5856  if (FTI.hasRefQualifier()) {
5857    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5858      << FTI.RefQualifierIsLValueRef
5859      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5860    D.setInvalidType();
5861  }
5862
5863  // Rebuild the function type "R" without any type qualifiers (in
5864  // case any of the errors above fired) and with "void" as the
5865  // return type, since constructors don't have return types.
5866  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5867  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5868    return R;
5869
5870  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5871  EPI.TypeQuals = 0;
5872  EPI.RefQualifier = RQ_None;
5873
5874  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
5875}
5876
5877/// CheckConstructor - Checks a fully-formed constructor for
5878/// well-formedness, issuing any diagnostics required. Returns true if
5879/// the constructor declarator is invalid.
5880void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5881  CXXRecordDecl *ClassDecl
5882    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5883  if (!ClassDecl)
5884    return Constructor->setInvalidDecl();
5885
5886  // C++ [class.copy]p3:
5887  //   A declaration of a constructor for a class X is ill-formed if
5888  //   its first parameter is of type (optionally cv-qualified) X and
5889  //   either there are no other parameters or else all other
5890  //   parameters have default arguments.
5891  if (!Constructor->isInvalidDecl() &&
5892      ((Constructor->getNumParams() == 1) ||
5893       (Constructor->getNumParams() > 1 &&
5894        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5895      Constructor->getTemplateSpecializationKind()
5896                                              != TSK_ImplicitInstantiation) {
5897    QualType ParamType = Constructor->getParamDecl(0)->getType();
5898    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5899    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5900      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5901      const char *ConstRef
5902        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5903                                                        : " const &";
5904      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5905        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5906
5907      // FIXME: Rather that making the constructor invalid, we should endeavor
5908      // to fix the type.
5909      Constructor->setInvalidDecl();
5910    }
5911  }
5912}
5913
5914/// CheckDestructor - Checks a fully-formed destructor definition for
5915/// well-formedness, issuing any diagnostics required.  Returns true
5916/// on error.
5917bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5918  CXXRecordDecl *RD = Destructor->getParent();
5919
5920  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
5921    SourceLocation Loc;
5922
5923    if (!Destructor->isImplicit())
5924      Loc = Destructor->getLocation();
5925    else
5926      Loc = RD->getLocation();
5927
5928    // If we have a virtual destructor, look up the deallocation function
5929    FunctionDecl *OperatorDelete = 0;
5930    DeclarationName Name =
5931    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5932    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5933      return true;
5934
5935    MarkFunctionReferenced(Loc, OperatorDelete);
5936
5937    Destructor->setOperatorDelete(OperatorDelete);
5938  }
5939
5940  return false;
5941}
5942
5943static inline bool
5944FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5945  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5946          FTI.ArgInfo[0].Param &&
5947          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5948}
5949
5950/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5951/// the well-formednes of the destructor declarator @p D with type @p
5952/// R. If there are any errors in the declarator, this routine will
5953/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5954/// will be updated to reflect a well-formed type for the destructor and
5955/// returned.
5956QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5957                                         StorageClass& SC) {
5958  // C++ [class.dtor]p1:
5959  //   [...] A typedef-name that names a class is a class-name
5960  //   (7.1.3); however, a typedef-name that names a class shall not
5961  //   be used as the identifier in the declarator for a destructor
5962  //   declaration.
5963  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5964  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5965    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5966      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5967  else if (const TemplateSpecializationType *TST =
5968             DeclaratorType->getAs<TemplateSpecializationType>())
5969    if (TST->isTypeAlias())
5970      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5971        << DeclaratorType << 1;
5972
5973  // C++ [class.dtor]p2:
5974  //   A destructor is used to destroy objects of its class type. A
5975  //   destructor takes no parameters, and no return type can be
5976  //   specified for it (not even void). The address of a destructor
5977  //   shall not be taken. A destructor shall not be static. A
5978  //   destructor can be invoked for a const, volatile or const
5979  //   volatile object. A destructor shall not be declared const,
5980  //   volatile or const volatile (9.3.2).
5981  if (SC == SC_Static) {
5982    if (!D.isInvalidType())
5983      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5984        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5985        << SourceRange(D.getIdentifierLoc())
5986        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5987
5988    SC = SC_None;
5989  }
5990  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5991    // Destructors don't have return types, but the parser will
5992    // happily parse something like:
5993    //
5994    //   class X {
5995    //     float ~X();
5996    //   };
5997    //
5998    // The return type will be eliminated later.
5999    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6000      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6001      << SourceRange(D.getIdentifierLoc());
6002  }
6003
6004  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6005  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6006    if (FTI.TypeQuals & Qualifiers::Const)
6007      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6008        << "const" << SourceRange(D.getIdentifierLoc());
6009    if (FTI.TypeQuals & Qualifiers::Volatile)
6010      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6011        << "volatile" << SourceRange(D.getIdentifierLoc());
6012    if (FTI.TypeQuals & Qualifiers::Restrict)
6013      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6014        << "restrict" << SourceRange(D.getIdentifierLoc());
6015    D.setInvalidType();
6016  }
6017
6018  // C++0x [class.dtor]p2:
6019  //   A destructor shall not be declared with a ref-qualifier.
6020  if (FTI.hasRefQualifier()) {
6021    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6022      << FTI.RefQualifierIsLValueRef
6023      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6024    D.setInvalidType();
6025  }
6026
6027  // Make sure we don't have any parameters.
6028  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
6029    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6030
6031    // Delete the parameters.
6032    FTI.freeArgs();
6033    D.setInvalidType();
6034  }
6035
6036  // Make sure the destructor isn't variadic.
6037  if (FTI.isVariadic) {
6038    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6039    D.setInvalidType();
6040  }
6041
6042  // Rebuild the function type "R" without any type qualifiers or
6043  // parameters (in case any of the errors above fired) and with
6044  // "void" as the return type, since destructors don't have return
6045  // types.
6046  if (!D.isInvalidType())
6047    return R;
6048
6049  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6050  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6051  EPI.Variadic = false;
6052  EPI.TypeQuals = 0;
6053  EPI.RefQualifier = RQ_None;
6054  return Context.getFunctionType(Context.VoidTy, None, EPI);
6055}
6056
6057/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6058/// well-formednes of the conversion function declarator @p D with
6059/// type @p R. If there are any errors in the declarator, this routine
6060/// will emit diagnostics and return true. Otherwise, it will return
6061/// false. Either way, the type @p R will be updated to reflect a
6062/// well-formed type for the conversion operator.
6063void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6064                                     StorageClass& SC) {
6065  // C++ [class.conv.fct]p1:
6066  //   Neither parameter types nor return type can be specified. The
6067  //   type of a conversion function (8.3.5) is "function taking no
6068  //   parameter returning conversion-type-id."
6069  if (SC == SC_Static) {
6070    if (!D.isInvalidType())
6071      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6072        << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6073        << D.getName().getSourceRange();
6074    D.setInvalidType();
6075    SC = SC_None;
6076  }
6077
6078  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6079
6080  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6081    // Conversion functions don't have return types, but the parser will
6082    // happily parse something like:
6083    //
6084    //   class X {
6085    //     float operator bool();
6086    //   };
6087    //
6088    // The return type will be changed later anyway.
6089    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6090      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6091      << SourceRange(D.getIdentifierLoc());
6092    D.setInvalidType();
6093  }
6094
6095  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6096
6097  // Make sure we don't have any parameters.
6098  if (Proto->getNumArgs() > 0) {
6099    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6100
6101    // Delete the parameters.
6102    D.getFunctionTypeInfo().freeArgs();
6103    D.setInvalidType();
6104  } else if (Proto->isVariadic()) {
6105    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6106    D.setInvalidType();
6107  }
6108
6109  // Diagnose "&operator bool()" and other such nonsense.  This
6110  // is actually a gcc extension which we don't support.
6111  if (Proto->getResultType() != ConvType) {
6112    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6113      << Proto->getResultType();
6114    D.setInvalidType();
6115    ConvType = Proto->getResultType();
6116  }
6117
6118  // C++ [class.conv.fct]p4:
6119  //   The conversion-type-id shall not represent a function type nor
6120  //   an array type.
6121  if (ConvType->isArrayType()) {
6122    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6123    ConvType = Context.getPointerType(ConvType);
6124    D.setInvalidType();
6125  } else if (ConvType->isFunctionType()) {
6126    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6127    ConvType = Context.getPointerType(ConvType);
6128    D.setInvalidType();
6129  }
6130
6131  // Rebuild the function type "R" without any parameters (in case any
6132  // of the errors above fired) and with the conversion type as the
6133  // return type.
6134  if (D.isInvalidType())
6135    R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6136
6137  // C++0x explicit conversion operators.
6138  if (D.getDeclSpec().isExplicitSpecified())
6139    Diag(D.getDeclSpec().getExplicitSpecLoc(),
6140         getLangOpts().CPlusPlus11 ?
6141           diag::warn_cxx98_compat_explicit_conversion_functions :
6142           diag::ext_explicit_conversion_functions)
6143      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6144}
6145
6146/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6147/// the declaration of the given C++ conversion function. This routine
6148/// is responsible for recording the conversion function in the C++
6149/// class, if possible.
6150Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6151  assert(Conversion && "Expected to receive a conversion function declaration");
6152
6153  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6154
6155  // Make sure we aren't redeclaring the conversion function.
6156  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6157
6158  // C++ [class.conv.fct]p1:
6159  //   [...] A conversion function is never used to convert a
6160  //   (possibly cv-qualified) object to the (possibly cv-qualified)
6161  //   same object type (or a reference to it), to a (possibly
6162  //   cv-qualified) base class of that type (or a reference to it),
6163  //   or to (possibly cv-qualified) void.
6164  // FIXME: Suppress this warning if the conversion function ends up being a
6165  // virtual function that overrides a virtual function in a base class.
6166  QualType ClassType
6167    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6168  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6169    ConvType = ConvTypeRef->getPointeeType();
6170  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6171      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6172    /* Suppress diagnostics for instantiations. */;
6173  else if (ConvType->isRecordType()) {
6174    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6175    if (ConvType == ClassType)
6176      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6177        << ClassType;
6178    else if (IsDerivedFrom(ClassType, ConvType))
6179      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6180        <<  ClassType << ConvType;
6181  } else if (ConvType->isVoidType()) {
6182    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6183      << ClassType << ConvType;
6184  }
6185
6186  if (FunctionTemplateDecl *ConversionTemplate
6187                                = Conversion->getDescribedFunctionTemplate())
6188    return ConversionTemplate;
6189
6190  return Conversion;
6191}
6192
6193//===----------------------------------------------------------------------===//
6194// Namespace Handling
6195//===----------------------------------------------------------------------===//
6196
6197/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6198/// reopened.
6199static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6200                                            SourceLocation Loc,
6201                                            IdentifierInfo *II, bool *IsInline,
6202                                            NamespaceDecl *PrevNS) {
6203  assert(*IsInline != PrevNS->isInline());
6204
6205  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6206  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6207  // inline namespaces, with the intention of bringing names into namespace std.
6208  //
6209  // We support this just well enough to get that case working; this is not
6210  // sufficient to support reopening namespaces as inline in general.
6211  if (*IsInline && II && II->getName().startswith("__atomic") &&
6212      S.getSourceManager().isInSystemHeader(Loc)) {
6213    // Mark all prior declarations of the namespace as inline.
6214    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6215         NS = NS->getPreviousDecl())
6216      NS->setInline(*IsInline);
6217    // Patch up the lookup table for the containing namespace. This isn't really
6218    // correct, but it's good enough for this particular case.
6219    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6220                                    E = PrevNS->decls_end(); I != E; ++I)
6221      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6222        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6223    return;
6224  }
6225
6226  if (PrevNS->isInline())
6227    // The user probably just forgot the 'inline', so suggest that it
6228    // be added back.
6229    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6230      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6231  else
6232    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6233      << IsInline;
6234
6235  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6236  *IsInline = PrevNS->isInline();
6237}
6238
6239/// ActOnStartNamespaceDef - This is called at the start of a namespace
6240/// definition.
6241Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6242                                   SourceLocation InlineLoc,
6243                                   SourceLocation NamespaceLoc,
6244                                   SourceLocation IdentLoc,
6245                                   IdentifierInfo *II,
6246                                   SourceLocation LBrace,
6247                                   AttributeList *AttrList) {
6248  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6249  // For anonymous namespace, take the location of the left brace.
6250  SourceLocation Loc = II ? IdentLoc : LBrace;
6251  bool IsInline = InlineLoc.isValid();
6252  bool IsInvalid = false;
6253  bool IsStd = false;
6254  bool AddToKnown = false;
6255  Scope *DeclRegionScope = NamespcScope->getParent();
6256
6257  NamespaceDecl *PrevNS = 0;
6258  if (II) {
6259    // C++ [namespace.def]p2:
6260    //   The identifier in an original-namespace-definition shall not
6261    //   have been previously defined in the declarative region in
6262    //   which the original-namespace-definition appears. The
6263    //   identifier in an original-namespace-definition is the name of
6264    //   the namespace. Subsequently in that declarative region, it is
6265    //   treated as an original-namespace-name.
6266    //
6267    // Since namespace names are unique in their scope, and we don't
6268    // look through using directives, just look for any ordinary names.
6269
6270    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6271    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6272    Decl::IDNS_Namespace;
6273    NamedDecl *PrevDecl = 0;
6274    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6275    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6276         ++I) {
6277      if ((*I)->getIdentifierNamespace() & IDNS) {
6278        PrevDecl = *I;
6279        break;
6280      }
6281    }
6282
6283    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6284
6285    if (PrevNS) {
6286      // This is an extended namespace definition.
6287      if (IsInline != PrevNS->isInline())
6288        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6289                                        &IsInline, PrevNS);
6290    } else if (PrevDecl) {
6291      // This is an invalid name redefinition.
6292      Diag(Loc, diag::err_redefinition_different_kind)
6293        << II;
6294      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6295      IsInvalid = true;
6296      // Continue on to push Namespc as current DeclContext and return it.
6297    } else if (II->isStr("std") &&
6298               CurContext->getRedeclContext()->isTranslationUnit()) {
6299      // This is the first "real" definition of the namespace "std", so update
6300      // our cache of the "std" namespace to point at this definition.
6301      PrevNS = getStdNamespace();
6302      IsStd = true;
6303      AddToKnown = !IsInline;
6304    } else {
6305      // We've seen this namespace for the first time.
6306      AddToKnown = !IsInline;
6307    }
6308  } else {
6309    // Anonymous namespaces.
6310
6311    // Determine whether the parent already has an anonymous namespace.
6312    DeclContext *Parent = CurContext->getRedeclContext();
6313    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6314      PrevNS = TU->getAnonymousNamespace();
6315    } else {
6316      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6317      PrevNS = ND->getAnonymousNamespace();
6318    }
6319
6320    if (PrevNS && IsInline != PrevNS->isInline())
6321      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6322                                      &IsInline, PrevNS);
6323  }
6324
6325  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6326                                                 StartLoc, Loc, II, PrevNS);
6327  if (IsInvalid)
6328    Namespc->setInvalidDecl();
6329
6330  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6331
6332  // FIXME: Should we be merging attributes?
6333  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6334    PushNamespaceVisibilityAttr(Attr, Loc);
6335
6336  if (IsStd)
6337    StdNamespace = Namespc;
6338  if (AddToKnown)
6339    KnownNamespaces[Namespc] = false;
6340
6341  if (II) {
6342    PushOnScopeChains(Namespc, DeclRegionScope);
6343  } else {
6344    // Link the anonymous namespace into its parent.
6345    DeclContext *Parent = CurContext->getRedeclContext();
6346    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6347      TU->setAnonymousNamespace(Namespc);
6348    } else {
6349      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6350    }
6351
6352    CurContext->addDecl(Namespc);
6353
6354    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6355    //   behaves as if it were replaced by
6356    //     namespace unique { /* empty body */ }
6357    //     using namespace unique;
6358    //     namespace unique { namespace-body }
6359    //   where all occurrences of 'unique' in a translation unit are
6360    //   replaced by the same identifier and this identifier differs
6361    //   from all other identifiers in the entire program.
6362
6363    // We just create the namespace with an empty name and then add an
6364    // implicit using declaration, just like the standard suggests.
6365    //
6366    // CodeGen enforces the "universally unique" aspect by giving all
6367    // declarations semantically contained within an anonymous
6368    // namespace internal linkage.
6369
6370    if (!PrevNS) {
6371      UsingDirectiveDecl* UD
6372        = UsingDirectiveDecl::Create(Context, Parent,
6373                                     /* 'using' */ LBrace,
6374                                     /* 'namespace' */ SourceLocation(),
6375                                     /* qualifier */ NestedNameSpecifierLoc(),
6376                                     /* identifier */ SourceLocation(),
6377                                     Namespc,
6378                                     /* Ancestor */ Parent);
6379      UD->setImplicit();
6380      Parent->addDecl(UD);
6381    }
6382  }
6383
6384  ActOnDocumentableDecl(Namespc);
6385
6386  // Although we could have an invalid decl (i.e. the namespace name is a
6387  // redefinition), push it as current DeclContext and try to continue parsing.
6388  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6389  // for the namespace has the declarations that showed up in that particular
6390  // namespace definition.
6391  PushDeclContext(NamespcScope, Namespc);
6392  return Namespc;
6393}
6394
6395/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6396/// is a namespace alias, returns the namespace it points to.
6397static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6398  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6399    return AD->getNamespace();
6400  return dyn_cast_or_null<NamespaceDecl>(D);
6401}
6402
6403/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6404/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6405void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6406  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6407  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6408  Namespc->setRBraceLoc(RBrace);
6409  PopDeclContext();
6410  if (Namespc->hasAttr<VisibilityAttr>())
6411    PopPragmaVisibility(true, RBrace);
6412}
6413
6414CXXRecordDecl *Sema::getStdBadAlloc() const {
6415  return cast_or_null<CXXRecordDecl>(
6416                                  StdBadAlloc.get(Context.getExternalSource()));
6417}
6418
6419NamespaceDecl *Sema::getStdNamespace() const {
6420  return cast_or_null<NamespaceDecl>(
6421                                 StdNamespace.get(Context.getExternalSource()));
6422}
6423
6424/// \brief Retrieve the special "std" namespace, which may require us to
6425/// implicitly define the namespace.
6426NamespaceDecl *Sema::getOrCreateStdNamespace() {
6427  if (!StdNamespace) {
6428    // The "std" namespace has not yet been defined, so build one implicitly.
6429    StdNamespace = NamespaceDecl::Create(Context,
6430                                         Context.getTranslationUnitDecl(),
6431                                         /*Inline=*/false,
6432                                         SourceLocation(), SourceLocation(),
6433                                         &PP.getIdentifierTable().get("std"),
6434                                         /*PrevDecl=*/0);
6435    getStdNamespace()->setImplicit(true);
6436  }
6437
6438  return getStdNamespace();
6439}
6440
6441bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6442  assert(getLangOpts().CPlusPlus &&
6443         "Looking for std::initializer_list outside of C++.");
6444
6445  // We're looking for implicit instantiations of
6446  // template <typename E> class std::initializer_list.
6447
6448  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6449    return false;
6450
6451  ClassTemplateDecl *Template = 0;
6452  const TemplateArgument *Arguments = 0;
6453
6454  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6455
6456    ClassTemplateSpecializationDecl *Specialization =
6457        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6458    if (!Specialization)
6459      return false;
6460
6461    Template = Specialization->getSpecializedTemplate();
6462    Arguments = Specialization->getTemplateArgs().data();
6463  } else if (const TemplateSpecializationType *TST =
6464                 Ty->getAs<TemplateSpecializationType>()) {
6465    Template = dyn_cast_or_null<ClassTemplateDecl>(
6466        TST->getTemplateName().getAsTemplateDecl());
6467    Arguments = TST->getArgs();
6468  }
6469  if (!Template)
6470    return false;
6471
6472  if (!StdInitializerList) {
6473    // Haven't recognized std::initializer_list yet, maybe this is it.
6474    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6475    if (TemplateClass->getIdentifier() !=
6476            &PP.getIdentifierTable().get("initializer_list") ||
6477        !getStdNamespace()->InEnclosingNamespaceSetOf(
6478            TemplateClass->getDeclContext()))
6479      return false;
6480    // This is a template called std::initializer_list, but is it the right
6481    // template?
6482    TemplateParameterList *Params = Template->getTemplateParameters();
6483    if (Params->getMinRequiredArguments() != 1)
6484      return false;
6485    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6486      return false;
6487
6488    // It's the right template.
6489    StdInitializerList = Template;
6490  }
6491
6492  if (Template != StdInitializerList)
6493    return false;
6494
6495  // This is an instance of std::initializer_list. Find the argument type.
6496  if (Element)
6497    *Element = Arguments[0].getAsType();
6498  return true;
6499}
6500
6501static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6502  NamespaceDecl *Std = S.getStdNamespace();
6503  if (!Std) {
6504    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6505    return 0;
6506  }
6507
6508  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6509                      Loc, Sema::LookupOrdinaryName);
6510  if (!S.LookupQualifiedName(Result, Std)) {
6511    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6512    return 0;
6513  }
6514  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6515  if (!Template) {
6516    Result.suppressDiagnostics();
6517    // We found something weird. Complain about the first thing we found.
6518    NamedDecl *Found = *Result.begin();
6519    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6520    return 0;
6521  }
6522
6523  // We found some template called std::initializer_list. Now verify that it's
6524  // correct.
6525  TemplateParameterList *Params = Template->getTemplateParameters();
6526  if (Params->getMinRequiredArguments() != 1 ||
6527      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6528    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6529    return 0;
6530  }
6531
6532  return Template;
6533}
6534
6535QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6536  if (!StdInitializerList) {
6537    StdInitializerList = LookupStdInitializerList(*this, Loc);
6538    if (!StdInitializerList)
6539      return QualType();
6540  }
6541
6542  TemplateArgumentListInfo Args(Loc, Loc);
6543  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6544                                       Context.getTrivialTypeSourceInfo(Element,
6545                                                                        Loc)));
6546  return Context.getCanonicalType(
6547      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6548}
6549
6550bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6551  // C++ [dcl.init.list]p2:
6552  //   A constructor is an initializer-list constructor if its first parameter
6553  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6554  //   std::initializer_list<E> for some type E, and either there are no other
6555  //   parameters or else all other parameters have default arguments.
6556  if (Ctor->getNumParams() < 1 ||
6557      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6558    return false;
6559
6560  QualType ArgType = Ctor->getParamDecl(0)->getType();
6561  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6562    ArgType = RT->getPointeeType().getUnqualifiedType();
6563
6564  return isStdInitializerList(ArgType, 0);
6565}
6566
6567/// \brief Determine whether a using statement is in a context where it will be
6568/// apply in all contexts.
6569static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6570  switch (CurContext->getDeclKind()) {
6571    case Decl::TranslationUnit:
6572      return true;
6573    case Decl::LinkageSpec:
6574      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6575    default:
6576      return false;
6577  }
6578}
6579
6580namespace {
6581
6582// Callback to only accept typo corrections that are namespaces.
6583class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6584 public:
6585  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6586    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
6587      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6588    }
6589    return false;
6590  }
6591};
6592
6593}
6594
6595static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6596                                       CXXScopeSpec &SS,
6597                                       SourceLocation IdentLoc,
6598                                       IdentifierInfo *Ident) {
6599  NamespaceValidatorCCC Validator;
6600  R.clear();
6601  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6602                                               R.getLookupKind(), Sc, &SS,
6603                                               Validator)) {
6604    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6605    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
6606    if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6607      bool droppedSpecifier = Corrected.WillReplaceSpecifier() &&
6608                              Ident->getName().equals(CorrectedStr);
6609      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
6610          << Ident << DC << droppedSpecifier << CorrectedQuotedStr
6611          << SS.getRange() << FixItHint::CreateReplacement(
6612                                  Corrected.getCorrectionRange(), CorrectedStr);
6613    } else {
6614      S.Diag(IdentLoc, diag::err_using_directive_suggest)
6615        << Ident << CorrectedQuotedStr
6616        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
6617    }
6618
6619    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
6620         diag::note_namespace_defined_here) << CorrectedQuotedStr;
6621
6622    R.addDecl(Corrected.getCorrectionDecl());
6623    return true;
6624  }
6625  return false;
6626}
6627
6628Decl *Sema::ActOnUsingDirective(Scope *S,
6629                                          SourceLocation UsingLoc,
6630                                          SourceLocation NamespcLoc,
6631                                          CXXScopeSpec &SS,
6632                                          SourceLocation IdentLoc,
6633                                          IdentifierInfo *NamespcName,
6634                                          AttributeList *AttrList) {
6635  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6636  assert(NamespcName && "Invalid NamespcName.");
6637  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6638
6639  // This can only happen along a recovery path.
6640  while (S->getFlags() & Scope::TemplateParamScope)
6641    S = S->getParent();
6642  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6643
6644  UsingDirectiveDecl *UDir = 0;
6645  NestedNameSpecifier *Qualifier = 0;
6646  if (SS.isSet())
6647    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6648
6649  // Lookup namespace name.
6650  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6651  LookupParsedName(R, S, &SS);
6652  if (R.isAmbiguous())
6653    return 0;
6654
6655  if (R.empty()) {
6656    R.clear();
6657    // Allow "using namespace std;" or "using namespace ::std;" even if
6658    // "std" hasn't been defined yet, for GCC compatibility.
6659    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6660        NamespcName->isStr("std")) {
6661      Diag(IdentLoc, diag::ext_using_undefined_std);
6662      R.addDecl(getOrCreateStdNamespace());
6663      R.resolveKind();
6664    }
6665    // Otherwise, attempt typo correction.
6666    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6667  }
6668
6669  if (!R.empty()) {
6670    NamedDecl *Named = R.getFoundDecl();
6671    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6672        && "expected namespace decl");
6673    // C++ [namespace.udir]p1:
6674    //   A using-directive specifies that the names in the nominated
6675    //   namespace can be used in the scope in which the
6676    //   using-directive appears after the using-directive. During
6677    //   unqualified name lookup (3.4.1), the names appear as if they
6678    //   were declared in the nearest enclosing namespace which
6679    //   contains both the using-directive and the nominated
6680    //   namespace. [Note: in this context, "contains" means "contains
6681    //   directly or indirectly". ]
6682
6683    // Find enclosing context containing both using-directive and
6684    // nominated namespace.
6685    NamespaceDecl *NS = getNamespaceDecl(Named);
6686    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6687    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6688      CommonAncestor = CommonAncestor->getParent();
6689
6690    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6691                                      SS.getWithLocInContext(Context),
6692                                      IdentLoc, Named, CommonAncestor);
6693
6694    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6695        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6696      Diag(IdentLoc, diag::warn_using_directive_in_header);
6697    }
6698
6699    PushUsingDirective(S, UDir);
6700  } else {
6701    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6702  }
6703
6704  if (UDir)
6705    ProcessDeclAttributeList(S, UDir, AttrList);
6706
6707  return UDir;
6708}
6709
6710void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6711  // If the scope has an associated entity and the using directive is at
6712  // namespace or translation unit scope, add the UsingDirectiveDecl into
6713  // its lookup structure so qualified name lookup can find it.
6714  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
6715  if (Ctx && !Ctx->isFunctionOrMethod())
6716    Ctx->addDecl(UDir);
6717  else
6718    // Otherwise, it is at block sope. The using-directives will affect lookup
6719    // only to the end of the scope.
6720    S->PushUsingDirective(UDir);
6721}
6722
6723
6724Decl *Sema::ActOnUsingDeclaration(Scope *S,
6725                                  AccessSpecifier AS,
6726                                  bool HasUsingKeyword,
6727                                  SourceLocation UsingLoc,
6728                                  CXXScopeSpec &SS,
6729                                  UnqualifiedId &Name,
6730                                  AttributeList *AttrList,
6731                                  bool IsTypeName,
6732                                  SourceLocation TypenameLoc) {
6733  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6734
6735  switch (Name.getKind()) {
6736  case UnqualifiedId::IK_ImplicitSelfParam:
6737  case UnqualifiedId::IK_Identifier:
6738  case UnqualifiedId::IK_OperatorFunctionId:
6739  case UnqualifiedId::IK_LiteralOperatorId:
6740  case UnqualifiedId::IK_ConversionFunctionId:
6741    break;
6742
6743  case UnqualifiedId::IK_ConstructorName:
6744  case UnqualifiedId::IK_ConstructorTemplateId:
6745    // C++11 inheriting constructors.
6746    Diag(Name.getLocStart(),
6747         getLangOpts().CPlusPlus11 ?
6748           diag::warn_cxx98_compat_using_decl_constructor :
6749           diag::err_using_decl_constructor)
6750      << SS.getRange();
6751
6752    if (getLangOpts().CPlusPlus11) break;
6753
6754    return 0;
6755
6756  case UnqualifiedId::IK_DestructorName:
6757    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6758      << SS.getRange();
6759    return 0;
6760
6761  case UnqualifiedId::IK_TemplateId:
6762    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6763      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6764    return 0;
6765  }
6766
6767  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6768  DeclarationName TargetName = TargetNameInfo.getName();
6769  if (!TargetName)
6770    return 0;
6771
6772  // Warn about access declarations.
6773  if (!HasUsingKeyword) {
6774    Diag(Name.getLocStart(),
6775         getLangOpts().CPlusPlus11 ? diag::err_access_decl
6776                                   : diag::warn_access_decl_deprecated)
6777      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
6778  }
6779
6780  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6781      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6782    return 0;
6783
6784  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
6785                                        TargetNameInfo, AttrList,
6786                                        /* IsInstantiation */ false,
6787                                        IsTypeName, TypenameLoc);
6788  if (UD)
6789    PushOnScopeChains(UD, S, /*AddToContext*/ false);
6790
6791  return UD;
6792}
6793
6794/// \brief Determine whether a using declaration considers the given
6795/// declarations as "equivalent", e.g., if they are redeclarations of
6796/// the same entity or are both typedefs of the same type.
6797static bool
6798IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6799                         bool &SuppressRedeclaration) {
6800  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6801    SuppressRedeclaration = false;
6802    return true;
6803  }
6804
6805  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6806    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
6807      SuppressRedeclaration = true;
6808      return Context.hasSameType(TD1->getUnderlyingType(),
6809                                 TD2->getUnderlyingType());
6810    }
6811
6812  return false;
6813}
6814
6815
6816/// Determines whether to create a using shadow decl for a particular
6817/// decl, given the set of decls existing prior to this using lookup.
6818bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6819                                const LookupResult &Previous) {
6820  // Diagnose finding a decl which is not from a base class of the
6821  // current class.  We do this now because there are cases where this
6822  // function will silently decide not to build a shadow decl, which
6823  // will pre-empt further diagnostics.
6824  //
6825  // We don't need to do this in C++0x because we do the check once on
6826  // the qualifier.
6827  //
6828  // FIXME: diagnose the following if we care enough:
6829  //   struct A { int foo; };
6830  //   struct B : A { using A::foo; };
6831  //   template <class T> struct C : A {};
6832  //   template <class T> struct D : C<T> { using B::foo; } // <---
6833  // This is invalid (during instantiation) in C++03 because B::foo
6834  // resolves to the using decl in B, which is not a base class of D<T>.
6835  // We can't diagnose it immediately because C<T> is an unknown
6836  // specialization.  The UsingShadowDecl in D<T> then points directly
6837  // to A::foo, which will look well-formed when we instantiate.
6838  // The right solution is to not collapse the shadow-decl chain.
6839  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
6840    DeclContext *OrigDC = Orig->getDeclContext();
6841
6842    // Handle enums and anonymous structs.
6843    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6844    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6845    while (OrigRec->isAnonymousStructOrUnion())
6846      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6847
6848    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6849      if (OrigDC == CurContext) {
6850        Diag(Using->getLocation(),
6851             diag::err_using_decl_nested_name_specifier_is_current_class)
6852          << Using->getQualifierLoc().getSourceRange();
6853        Diag(Orig->getLocation(), diag::note_using_decl_target);
6854        return true;
6855      }
6856
6857      Diag(Using->getQualifierLoc().getBeginLoc(),
6858           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6859        << Using->getQualifier()
6860        << cast<CXXRecordDecl>(CurContext)
6861        << Using->getQualifierLoc().getSourceRange();
6862      Diag(Orig->getLocation(), diag::note_using_decl_target);
6863      return true;
6864    }
6865  }
6866
6867  if (Previous.empty()) return false;
6868
6869  NamedDecl *Target = Orig;
6870  if (isa<UsingShadowDecl>(Target))
6871    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6872
6873  // If the target happens to be one of the previous declarations, we
6874  // don't have a conflict.
6875  //
6876  // FIXME: but we might be increasing its access, in which case we
6877  // should redeclare it.
6878  NamedDecl *NonTag = 0, *Tag = 0;
6879  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6880         I != E; ++I) {
6881    NamedDecl *D = (*I)->getUnderlyingDecl();
6882    bool Result;
6883    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6884      return Result;
6885
6886    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6887  }
6888
6889  if (Target->isFunctionOrFunctionTemplate()) {
6890    FunctionDecl *FD;
6891    if (isa<FunctionTemplateDecl>(Target))
6892      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6893    else
6894      FD = cast<FunctionDecl>(Target);
6895
6896    NamedDecl *OldDecl = 0;
6897    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6898    case Ovl_Overload:
6899      return false;
6900
6901    case Ovl_NonFunction:
6902      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6903      break;
6904
6905    // We found a decl with the exact signature.
6906    case Ovl_Match:
6907      // If we're in a record, we want to hide the target, so we
6908      // return true (without a diagnostic) to tell the caller not to
6909      // build a shadow decl.
6910      if (CurContext->isRecord())
6911        return true;
6912
6913      // If we're not in a record, this is an error.
6914      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6915      break;
6916    }
6917
6918    Diag(Target->getLocation(), diag::note_using_decl_target);
6919    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6920    return true;
6921  }
6922
6923  // Target is not a function.
6924
6925  if (isa<TagDecl>(Target)) {
6926    // No conflict between a tag and a non-tag.
6927    if (!Tag) return false;
6928
6929    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6930    Diag(Target->getLocation(), diag::note_using_decl_target);
6931    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6932    return true;
6933  }
6934
6935  // No conflict between a tag and a non-tag.
6936  if (!NonTag) return false;
6937
6938  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6939  Diag(Target->getLocation(), diag::note_using_decl_target);
6940  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6941  return true;
6942}
6943
6944/// Builds a shadow declaration corresponding to a 'using' declaration.
6945UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6946                                            UsingDecl *UD,
6947                                            NamedDecl *Orig) {
6948
6949  // If we resolved to another shadow declaration, just coalesce them.
6950  NamedDecl *Target = Orig;
6951  if (isa<UsingShadowDecl>(Target)) {
6952    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6953    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6954  }
6955
6956  UsingShadowDecl *Shadow
6957    = UsingShadowDecl::Create(Context, CurContext,
6958                              UD->getLocation(), UD, Target);
6959  UD->addShadowDecl(Shadow);
6960
6961  Shadow->setAccess(UD->getAccess());
6962  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6963    Shadow->setInvalidDecl();
6964
6965  if (S)
6966    PushOnScopeChains(Shadow, S);
6967  else
6968    CurContext->addDecl(Shadow);
6969
6970
6971  return Shadow;
6972}
6973
6974/// Hides a using shadow declaration.  This is required by the current
6975/// using-decl implementation when a resolvable using declaration in a
6976/// class is followed by a declaration which would hide or override
6977/// one or more of the using decl's targets; for example:
6978///
6979///   struct Base { void foo(int); };
6980///   struct Derived : Base {
6981///     using Base::foo;
6982///     void foo(int);
6983///   };
6984///
6985/// The governing language is C++03 [namespace.udecl]p12:
6986///
6987///   When a using-declaration brings names from a base class into a
6988///   derived class scope, member functions in the derived class
6989///   override and/or hide member functions with the same name and
6990///   parameter types in a base class (rather than conflicting).
6991///
6992/// There are two ways to implement this:
6993///   (1) optimistically create shadow decls when they're not hidden
6994///       by existing declarations, or
6995///   (2) don't create any shadow decls (or at least don't make them
6996///       visible) until we've fully parsed/instantiated the class.
6997/// The problem with (1) is that we might have to retroactively remove
6998/// a shadow decl, which requires several O(n) operations because the
6999/// decl structures are (very reasonably) not designed for removal.
7000/// (2) avoids this but is very fiddly and phase-dependent.
7001void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7002  if (Shadow->getDeclName().getNameKind() ==
7003        DeclarationName::CXXConversionFunctionName)
7004    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7005
7006  // Remove it from the DeclContext...
7007  Shadow->getDeclContext()->removeDecl(Shadow);
7008
7009  // ...and the scope, if applicable...
7010  if (S) {
7011    S->RemoveDecl(Shadow);
7012    IdResolver.RemoveDecl(Shadow);
7013  }
7014
7015  // ...and the using decl.
7016  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7017
7018  // TODO: complain somehow if Shadow was used.  It shouldn't
7019  // be possible for this to happen, because...?
7020}
7021
7022class UsingValidatorCCC : public CorrectionCandidateCallback {
7023public:
7024  UsingValidatorCCC(bool IsTypeName, bool IsInstantiation)
7025      : IsTypeName(IsTypeName), IsInstantiation(IsInstantiation) {}
7026
7027  virtual bool ValidateCandidate(const TypoCorrection &Candidate) {
7028    if (NamedDecl *ND = Candidate.getCorrectionDecl()) {
7029      if (isa<NamespaceDecl>(ND))
7030        return false;
7031      // Completely unqualified names are invalid for a 'using' declaration.
7032      bool droppedSpecifier = Candidate.WillReplaceSpecifier() &&
7033                              !Candidate.getCorrectionSpecifier();
7034      if (droppedSpecifier)
7035        return false;
7036      else if (isa<TypeDecl>(ND))
7037        return IsTypeName || !IsInstantiation;
7038      else
7039        return !IsTypeName;
7040    } else {
7041      // Keywords are not valid here.
7042      return false;
7043    }
7044  }
7045
7046private:
7047  bool IsTypeName;
7048  bool IsInstantiation;
7049};
7050
7051/// Builds a using declaration.
7052///
7053/// \param IsInstantiation - Whether this call arises from an
7054///   instantiation of an unresolved using declaration.  We treat
7055///   the lookup differently for these declarations.
7056NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7057                                       SourceLocation UsingLoc,
7058                                       CXXScopeSpec &SS,
7059                                       const DeclarationNameInfo &NameInfo,
7060                                       AttributeList *AttrList,
7061                                       bool IsInstantiation,
7062                                       bool IsTypeName,
7063                                       SourceLocation TypenameLoc) {
7064  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7065  SourceLocation IdentLoc = NameInfo.getLoc();
7066  assert(IdentLoc.isValid() && "Invalid TargetName location.");
7067
7068  // FIXME: We ignore attributes for now.
7069
7070  if (SS.isEmpty()) {
7071    Diag(IdentLoc, diag::err_using_requires_qualname);
7072    return 0;
7073  }
7074
7075  // Do the redeclaration lookup in the current scope.
7076  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7077                        ForRedeclaration);
7078  Previous.setHideTags(false);
7079  if (S) {
7080    LookupName(Previous, S);
7081
7082    // It is really dumb that we have to do this.
7083    LookupResult::Filter F = Previous.makeFilter();
7084    while (F.hasNext()) {
7085      NamedDecl *D = F.next();
7086      if (!isDeclInScope(D, CurContext, S))
7087        F.erase();
7088    }
7089    F.done();
7090  } else {
7091    assert(IsInstantiation && "no scope in non-instantiation");
7092    assert(CurContext->isRecord() && "scope not record in instantiation");
7093    LookupQualifiedName(Previous, CurContext);
7094  }
7095
7096  // Check for invalid redeclarations.
7097  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
7098    return 0;
7099
7100  // Check for bad qualifiers.
7101  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7102    return 0;
7103
7104  DeclContext *LookupContext = computeDeclContext(SS);
7105  NamedDecl *D;
7106  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7107  if (!LookupContext) {
7108    if (IsTypeName) {
7109      // FIXME: not all declaration name kinds are legal here
7110      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7111                                              UsingLoc, TypenameLoc,
7112                                              QualifierLoc,
7113                                              IdentLoc, NameInfo.getName());
7114    } else {
7115      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7116                                           QualifierLoc, NameInfo);
7117    }
7118  } else {
7119    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7120                          NameInfo, IsTypeName);
7121  }
7122  D->setAccess(AS);
7123  CurContext->addDecl(D);
7124
7125  if (!LookupContext) return D;
7126  UsingDecl *UD = cast<UsingDecl>(D);
7127
7128  if (RequireCompleteDeclContext(SS, LookupContext)) {
7129    UD->setInvalidDecl();
7130    return UD;
7131  }
7132
7133  // The normal rules do not apply to inheriting constructor declarations.
7134  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7135    if (CheckInheritingConstructorUsingDecl(UD))
7136      UD->setInvalidDecl();
7137    return UD;
7138  }
7139
7140  // Otherwise, look up the target name.
7141
7142  LookupResult R(*this, NameInfo, LookupOrdinaryName);
7143
7144  // Unlike most lookups, we don't always want to hide tag
7145  // declarations: tag names are visible through the using declaration
7146  // even if hidden by ordinary names, *except* in a dependent context
7147  // where it's important for the sanity of two-phase lookup.
7148  if (!IsInstantiation)
7149    R.setHideTags(false);
7150
7151  // For the purposes of this lookup, we have a base object type
7152  // equal to that of the current context.
7153  if (CurContext->isRecord()) {
7154    R.setBaseObjectType(
7155                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7156  }
7157
7158  LookupQualifiedName(R, LookupContext);
7159
7160  // Try to correct typos if possible.
7161  if (R.empty()) {
7162    UsingValidatorCCC CCC(IsTypeName, IsInstantiation);
7163    if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7164                                               R.getLookupKind(), S, &SS, CCC)){
7165      // We reject any correction for which ND would be NULL.
7166      NamedDecl *ND = Corrected.getCorrectionDecl();
7167      std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
7168      std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
7169      R.setLookupName(Corrected.getCorrection());
7170      R.addDecl(ND);
7171      // We reject candidates where droppedSpecifier == true, hence the
7172      // literal '0' below.
7173      Diag(R.getNameLoc(), diag::err_no_member_suggest)
7174        << NameInfo.getName() << LookupContext << 0
7175        << CorrectedQuotedStr << SS.getRange()
7176        << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
7177                                        CorrectedStr);
7178      Diag(ND->getLocation(), diag::note_previous_decl)
7179        << CorrectedQuotedStr;
7180    } else {
7181      Diag(IdentLoc, diag::err_no_member)
7182        << NameInfo.getName() << LookupContext << SS.getRange();
7183      UD->setInvalidDecl();
7184      return UD;
7185    }
7186  }
7187
7188  if (R.isAmbiguous()) {
7189    UD->setInvalidDecl();
7190    return UD;
7191  }
7192
7193  if (IsTypeName) {
7194    // If we asked for a typename and got a non-type decl, error out.
7195    if (!R.getAsSingle<TypeDecl>()) {
7196      Diag(IdentLoc, diag::err_using_typename_non_type);
7197      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7198        Diag((*I)->getUnderlyingDecl()->getLocation(),
7199             diag::note_using_decl_target);
7200      UD->setInvalidDecl();
7201      return UD;
7202    }
7203  } else {
7204    // If we asked for a non-typename and we got a type, error out,
7205    // but only if this is an instantiation of an unresolved using
7206    // decl.  Otherwise just silently find the type name.
7207    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7208      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7209      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7210      UD->setInvalidDecl();
7211      return UD;
7212    }
7213  }
7214
7215  // C++0x N2914 [namespace.udecl]p6:
7216  // A using-declaration shall not name a namespace.
7217  if (R.getAsSingle<NamespaceDecl>()) {
7218    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7219      << SS.getRange();
7220    UD->setInvalidDecl();
7221    return UD;
7222  }
7223
7224  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7225    if (!CheckUsingShadowDecl(UD, *I, Previous))
7226      BuildUsingShadowDecl(S, UD, *I);
7227  }
7228
7229  return UD;
7230}
7231
7232/// Additional checks for a using declaration referring to a constructor name.
7233bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7234  assert(!UD->isTypeName() && "expecting a constructor name");
7235
7236  const Type *SourceType = UD->getQualifier()->getAsType();
7237  assert(SourceType &&
7238         "Using decl naming constructor doesn't have type in scope spec.");
7239  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7240
7241  // Check whether the named type is a direct base class.
7242  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7243  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7244  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7245       BaseIt != BaseE; ++BaseIt) {
7246    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7247    if (CanonicalSourceType == BaseType)
7248      break;
7249    if (BaseIt->getType()->isDependentType())
7250      break;
7251  }
7252
7253  if (BaseIt == BaseE) {
7254    // Did not find SourceType in the bases.
7255    Diag(UD->getUsingLocation(),
7256         diag::err_using_decl_constructor_not_in_direct_base)
7257      << UD->getNameInfo().getSourceRange()
7258      << QualType(SourceType, 0) << TargetClass;
7259    return true;
7260  }
7261
7262  if (!CurContext->isDependentContext())
7263    BaseIt->setInheritConstructors();
7264
7265  return false;
7266}
7267
7268/// Checks that the given using declaration is not an invalid
7269/// redeclaration.  Note that this is checking only for the using decl
7270/// itself, not for any ill-formedness among the UsingShadowDecls.
7271bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7272                                       bool isTypeName,
7273                                       const CXXScopeSpec &SS,
7274                                       SourceLocation NameLoc,
7275                                       const LookupResult &Prev) {
7276  // C++03 [namespace.udecl]p8:
7277  // C++0x [namespace.udecl]p10:
7278  //   A using-declaration is a declaration and can therefore be used
7279  //   repeatedly where (and only where) multiple declarations are
7280  //   allowed.
7281  //
7282  // That's in non-member contexts.
7283  if (!CurContext->getRedeclContext()->isRecord())
7284    return false;
7285
7286  NestedNameSpecifier *Qual
7287    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7288
7289  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7290    NamedDecl *D = *I;
7291
7292    bool DTypename;
7293    NestedNameSpecifier *DQual;
7294    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7295      DTypename = UD->isTypeName();
7296      DQual = UD->getQualifier();
7297    } else if (UnresolvedUsingValueDecl *UD
7298                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7299      DTypename = false;
7300      DQual = UD->getQualifier();
7301    } else if (UnresolvedUsingTypenameDecl *UD
7302                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7303      DTypename = true;
7304      DQual = UD->getQualifier();
7305    } else continue;
7306
7307    // using decls differ if one says 'typename' and the other doesn't.
7308    // FIXME: non-dependent using decls?
7309    if (isTypeName != DTypename) continue;
7310
7311    // using decls differ if they name different scopes (but note that
7312    // template instantiation can cause this check to trigger when it
7313    // didn't before instantiation).
7314    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7315        Context.getCanonicalNestedNameSpecifier(DQual))
7316      continue;
7317
7318    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7319    Diag(D->getLocation(), diag::note_using_decl) << 1;
7320    return true;
7321  }
7322
7323  return false;
7324}
7325
7326
7327/// Checks that the given nested-name qualifier used in a using decl
7328/// in the current context is appropriately related to the current
7329/// scope.  If an error is found, diagnoses it and returns true.
7330bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7331                                   const CXXScopeSpec &SS,
7332                                   SourceLocation NameLoc) {
7333  DeclContext *NamedContext = computeDeclContext(SS);
7334
7335  if (!CurContext->isRecord()) {
7336    // C++03 [namespace.udecl]p3:
7337    // C++0x [namespace.udecl]p8:
7338    //   A using-declaration for a class member shall be a member-declaration.
7339
7340    // If we weren't able to compute a valid scope, it must be a
7341    // dependent class scope.
7342    if (!NamedContext || NamedContext->isRecord()) {
7343      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7344        << SS.getRange();
7345      return true;
7346    }
7347
7348    // Otherwise, everything is known to be fine.
7349    return false;
7350  }
7351
7352  // The current scope is a record.
7353
7354  // If the named context is dependent, we can't decide much.
7355  if (!NamedContext) {
7356    // FIXME: in C++0x, we can diagnose if we can prove that the
7357    // nested-name-specifier does not refer to a base class, which is
7358    // still possible in some cases.
7359
7360    // Otherwise we have to conservatively report that things might be
7361    // okay.
7362    return false;
7363  }
7364
7365  if (!NamedContext->isRecord()) {
7366    // Ideally this would point at the last name in the specifier,
7367    // but we don't have that level of source info.
7368    Diag(SS.getRange().getBegin(),
7369         diag::err_using_decl_nested_name_specifier_is_not_class)
7370      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7371    return true;
7372  }
7373
7374  if (!NamedContext->isDependentContext() &&
7375      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7376    return true;
7377
7378  if (getLangOpts().CPlusPlus11) {
7379    // C++0x [namespace.udecl]p3:
7380    //   In a using-declaration used as a member-declaration, the
7381    //   nested-name-specifier shall name a base class of the class
7382    //   being defined.
7383
7384    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7385                                 cast<CXXRecordDecl>(NamedContext))) {
7386      if (CurContext == NamedContext) {
7387        Diag(NameLoc,
7388             diag::err_using_decl_nested_name_specifier_is_current_class)
7389          << SS.getRange();
7390        return true;
7391      }
7392
7393      Diag(SS.getRange().getBegin(),
7394           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7395        << (NestedNameSpecifier*) SS.getScopeRep()
7396        << cast<CXXRecordDecl>(CurContext)
7397        << SS.getRange();
7398      return true;
7399    }
7400
7401    return false;
7402  }
7403
7404  // C++03 [namespace.udecl]p4:
7405  //   A using-declaration used as a member-declaration shall refer
7406  //   to a member of a base class of the class being defined [etc.].
7407
7408  // Salient point: SS doesn't have to name a base class as long as
7409  // lookup only finds members from base classes.  Therefore we can
7410  // diagnose here only if we can prove that that can't happen,
7411  // i.e. if the class hierarchies provably don't intersect.
7412
7413  // TODO: it would be nice if "definitely valid" results were cached
7414  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7415  // need to be repeated.
7416
7417  struct UserData {
7418    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7419
7420    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7421      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7422      Data->Bases.insert(Base);
7423      return true;
7424    }
7425
7426    bool hasDependentBases(const CXXRecordDecl *Class) {
7427      return !Class->forallBases(collect, this);
7428    }
7429
7430    /// Returns true if the base is dependent or is one of the
7431    /// accumulated base classes.
7432    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7433      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7434      return !Data->Bases.count(Base);
7435    }
7436
7437    bool mightShareBases(const CXXRecordDecl *Class) {
7438      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7439    }
7440  };
7441
7442  UserData Data;
7443
7444  // Returns false if we find a dependent base.
7445  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7446    return false;
7447
7448  // Returns false if the class has a dependent base or if it or one
7449  // of its bases is present in the base set of the current context.
7450  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7451    return false;
7452
7453  Diag(SS.getRange().getBegin(),
7454       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7455    << (NestedNameSpecifier*) SS.getScopeRep()
7456    << cast<CXXRecordDecl>(CurContext)
7457    << SS.getRange();
7458
7459  return true;
7460}
7461
7462Decl *Sema::ActOnAliasDeclaration(Scope *S,
7463                                  AccessSpecifier AS,
7464                                  MultiTemplateParamsArg TemplateParamLists,
7465                                  SourceLocation UsingLoc,
7466                                  UnqualifiedId &Name,
7467                                  AttributeList *AttrList,
7468                                  TypeResult Type) {
7469  // Skip up to the relevant declaration scope.
7470  while (S->getFlags() & Scope::TemplateParamScope)
7471    S = S->getParent();
7472  assert((S->getFlags() & Scope::DeclScope) &&
7473         "got alias-declaration outside of declaration scope");
7474
7475  if (Type.isInvalid())
7476    return 0;
7477
7478  bool Invalid = false;
7479  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7480  TypeSourceInfo *TInfo = 0;
7481  GetTypeFromParser(Type.get(), &TInfo);
7482
7483  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7484    return 0;
7485
7486  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7487                                      UPPC_DeclarationType)) {
7488    Invalid = true;
7489    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7490                                             TInfo->getTypeLoc().getBeginLoc());
7491  }
7492
7493  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7494  LookupName(Previous, S);
7495
7496  // Warn about shadowing the name of a template parameter.
7497  if (Previous.isSingleResult() &&
7498      Previous.getFoundDecl()->isTemplateParameter()) {
7499    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7500    Previous.clear();
7501  }
7502
7503  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7504         "name in alias declaration must be an identifier");
7505  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7506                                               Name.StartLocation,
7507                                               Name.Identifier, TInfo);
7508
7509  NewTD->setAccess(AS);
7510
7511  if (Invalid)
7512    NewTD->setInvalidDecl();
7513
7514  ProcessDeclAttributeList(S, NewTD, AttrList);
7515
7516  CheckTypedefForVariablyModifiedType(S, NewTD);
7517  Invalid |= NewTD->isInvalidDecl();
7518
7519  bool Redeclaration = false;
7520
7521  NamedDecl *NewND;
7522  if (TemplateParamLists.size()) {
7523    TypeAliasTemplateDecl *OldDecl = 0;
7524    TemplateParameterList *OldTemplateParams = 0;
7525
7526    if (TemplateParamLists.size() != 1) {
7527      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7528        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7529         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7530    }
7531    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7532
7533    // Only consider previous declarations in the same scope.
7534    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7535                         /*ExplicitInstantiationOrSpecialization*/false);
7536    if (!Previous.empty()) {
7537      Redeclaration = true;
7538
7539      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7540      if (!OldDecl && !Invalid) {
7541        Diag(UsingLoc, diag::err_redefinition_different_kind)
7542          << Name.Identifier;
7543
7544        NamedDecl *OldD = Previous.getRepresentativeDecl();
7545        if (OldD->getLocation().isValid())
7546          Diag(OldD->getLocation(), diag::note_previous_definition);
7547
7548        Invalid = true;
7549      }
7550
7551      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7552        if (TemplateParameterListsAreEqual(TemplateParams,
7553                                           OldDecl->getTemplateParameters(),
7554                                           /*Complain=*/true,
7555                                           TPL_TemplateMatch))
7556          OldTemplateParams = OldDecl->getTemplateParameters();
7557        else
7558          Invalid = true;
7559
7560        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7561        if (!Invalid &&
7562            !Context.hasSameType(OldTD->getUnderlyingType(),
7563                                 NewTD->getUnderlyingType())) {
7564          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7565          // but we can't reasonably accept it.
7566          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7567            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7568          if (OldTD->getLocation().isValid())
7569            Diag(OldTD->getLocation(), diag::note_previous_definition);
7570          Invalid = true;
7571        }
7572      }
7573    }
7574
7575    // Merge any previous default template arguments into our parameters,
7576    // and check the parameter list.
7577    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7578                                   TPC_TypeAliasTemplate))
7579      return 0;
7580
7581    TypeAliasTemplateDecl *NewDecl =
7582      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7583                                    Name.Identifier, TemplateParams,
7584                                    NewTD);
7585
7586    NewDecl->setAccess(AS);
7587
7588    if (Invalid)
7589      NewDecl->setInvalidDecl();
7590    else if (OldDecl)
7591      NewDecl->setPreviousDeclaration(OldDecl);
7592
7593    NewND = NewDecl;
7594  } else {
7595    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7596    NewND = NewTD;
7597  }
7598
7599  if (!Redeclaration)
7600    PushOnScopeChains(NewND, S);
7601
7602  ActOnDocumentableDecl(NewND);
7603  return NewND;
7604}
7605
7606Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7607                                             SourceLocation NamespaceLoc,
7608                                             SourceLocation AliasLoc,
7609                                             IdentifierInfo *Alias,
7610                                             CXXScopeSpec &SS,
7611                                             SourceLocation IdentLoc,
7612                                             IdentifierInfo *Ident) {
7613
7614  // Lookup the namespace name.
7615  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7616  LookupParsedName(R, S, &SS);
7617
7618  // Check if we have a previous declaration with the same name.
7619  NamedDecl *PrevDecl
7620    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7621                       ForRedeclaration);
7622  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7623    PrevDecl = 0;
7624
7625  if (PrevDecl) {
7626    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7627      // We already have an alias with the same name that points to the same
7628      // namespace, so don't create a new one.
7629      // FIXME: At some point, we'll want to create the (redundant)
7630      // declaration to maintain better source information.
7631      if (!R.isAmbiguous() && !R.empty() &&
7632          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7633        return 0;
7634    }
7635
7636    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7637      diag::err_redefinition_different_kind;
7638    Diag(AliasLoc, DiagID) << Alias;
7639    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7640    return 0;
7641  }
7642
7643  if (R.isAmbiguous())
7644    return 0;
7645
7646  if (R.empty()) {
7647    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7648      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7649      return 0;
7650    }
7651  }
7652
7653  NamespaceAliasDecl *AliasDecl =
7654    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7655                               Alias, SS.getWithLocInContext(Context),
7656                               IdentLoc, R.getFoundDecl());
7657
7658  PushOnScopeChains(AliasDecl, S);
7659  return AliasDecl;
7660}
7661
7662Sema::ImplicitExceptionSpecification
7663Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7664                                               CXXMethodDecl *MD) {
7665  CXXRecordDecl *ClassDecl = MD->getParent();
7666
7667  // C++ [except.spec]p14:
7668  //   An implicitly declared special member function (Clause 12) shall have an
7669  //   exception-specification. [...]
7670  ImplicitExceptionSpecification ExceptSpec(*this);
7671  if (ClassDecl->isInvalidDecl())
7672    return ExceptSpec;
7673
7674  // Direct base-class constructors.
7675  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7676                                       BEnd = ClassDecl->bases_end();
7677       B != BEnd; ++B) {
7678    if (B->isVirtual()) // Handled below.
7679      continue;
7680
7681    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7682      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7683      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7684      // If this is a deleted function, add it anyway. This might be conformant
7685      // with the standard. This might not. I'm not sure. It might not matter.
7686      if (Constructor)
7687        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7688    }
7689  }
7690
7691  // Virtual base-class constructors.
7692  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7693                                       BEnd = ClassDecl->vbases_end();
7694       B != BEnd; ++B) {
7695    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7696      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7697      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7698      // If this is a deleted function, add it anyway. This might be conformant
7699      // with the standard. This might not. I'm not sure. It might not matter.
7700      if (Constructor)
7701        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7702    }
7703  }
7704
7705  // Field constructors.
7706  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7707                               FEnd = ClassDecl->field_end();
7708       F != FEnd; ++F) {
7709    if (F->hasInClassInitializer()) {
7710      if (Expr *E = F->getInClassInitializer())
7711        ExceptSpec.CalledExpr(E);
7712      else if (!F->isInvalidDecl())
7713        // DR1351:
7714        //   If the brace-or-equal-initializer of a non-static data member
7715        //   invokes a defaulted default constructor of its class or of an
7716        //   enclosing class in a potentially evaluated subexpression, the
7717        //   program is ill-formed.
7718        //
7719        // This resolution is unworkable: the exception specification of the
7720        // default constructor can be needed in an unevaluated context, in
7721        // particular, in the operand of a noexcept-expression, and we can be
7722        // unable to compute an exception specification for an enclosed class.
7723        //
7724        // We do not allow an in-class initializer to require the evaluation
7725        // of the exception specification for any in-class initializer whose
7726        // definition is not lexically complete.
7727        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7728    } else if (const RecordType *RecordTy
7729              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7730      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7731      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7732      // If this is a deleted function, add it anyway. This might be conformant
7733      // with the standard. This might not. I'm not sure. It might not matter.
7734      // In particular, the problem is that this function never gets called. It
7735      // might just be ill-formed because this function attempts to refer to
7736      // a deleted function here.
7737      if (Constructor)
7738        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7739    }
7740  }
7741
7742  return ExceptSpec;
7743}
7744
7745Sema::ImplicitExceptionSpecification
7746Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7747  CXXRecordDecl *ClassDecl = CD->getParent();
7748
7749  // C++ [except.spec]p14:
7750  //   An inheriting constructor [...] shall have an exception-specification. [...]
7751  ImplicitExceptionSpecification ExceptSpec(*this);
7752  if (ClassDecl->isInvalidDecl())
7753    return ExceptSpec;
7754
7755  // Inherited constructor.
7756  const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7757  const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7758  // FIXME: Copying or moving the parameters could add extra exceptions to the
7759  // set, as could the default arguments for the inherited constructor. This
7760  // will be addressed when we implement the resolution of core issue 1351.
7761  ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7762
7763  // Direct base-class constructors.
7764  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7765                                       BEnd = ClassDecl->bases_end();
7766       B != BEnd; ++B) {
7767    if (B->isVirtual()) // Handled below.
7768      continue;
7769
7770    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7771      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7772      if (BaseClassDecl == InheritedDecl)
7773        continue;
7774      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7775      if (Constructor)
7776        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7777    }
7778  }
7779
7780  // Virtual base-class constructors.
7781  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7782                                       BEnd = ClassDecl->vbases_end();
7783       B != BEnd; ++B) {
7784    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7785      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7786      if (BaseClassDecl == InheritedDecl)
7787        continue;
7788      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7789      if (Constructor)
7790        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7791    }
7792  }
7793
7794  // Field constructors.
7795  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7796                               FEnd = ClassDecl->field_end();
7797       F != FEnd; ++F) {
7798    if (F->hasInClassInitializer()) {
7799      if (Expr *E = F->getInClassInitializer())
7800        ExceptSpec.CalledExpr(E);
7801      else if (!F->isInvalidDecl())
7802        Diag(CD->getLocation(),
7803             diag::err_in_class_initializer_references_def_ctor) << CD;
7804    } else if (const RecordType *RecordTy
7805              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7806      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7807      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7808      if (Constructor)
7809        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7810    }
7811  }
7812
7813  return ExceptSpec;
7814}
7815
7816namespace {
7817/// RAII object to register a special member as being currently declared.
7818struct DeclaringSpecialMember {
7819  Sema &S;
7820  Sema::SpecialMemberDecl D;
7821  bool WasAlreadyBeingDeclared;
7822
7823  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
7824    : S(S), D(RD, CSM) {
7825    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
7826    if (WasAlreadyBeingDeclared)
7827      // This almost never happens, but if it does, ensure that our cache
7828      // doesn't contain a stale result.
7829      S.SpecialMemberCache.clear();
7830
7831    // FIXME: Register a note to be produced if we encounter an error while
7832    // declaring the special member.
7833  }
7834  ~DeclaringSpecialMember() {
7835    if (!WasAlreadyBeingDeclared)
7836      S.SpecialMembersBeingDeclared.erase(D);
7837  }
7838
7839  /// \brief Are we already trying to declare this special member?
7840  bool isAlreadyBeingDeclared() const {
7841    return WasAlreadyBeingDeclared;
7842  }
7843};
7844}
7845
7846CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7847                                                     CXXRecordDecl *ClassDecl) {
7848  // C++ [class.ctor]p5:
7849  //   A default constructor for a class X is a constructor of class X
7850  //   that can be called without an argument. If there is no
7851  //   user-declared constructor for class X, a default constructor is
7852  //   implicitly declared. An implicitly-declared default constructor
7853  //   is an inline public member of its class.
7854  assert(ClassDecl->needsImplicitDefaultConstructor() &&
7855         "Should not build implicit default constructor!");
7856
7857  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
7858  if (DSM.isAlreadyBeingDeclared())
7859    return 0;
7860
7861  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
7862                                                     CXXDefaultConstructor,
7863                                                     false);
7864
7865  // Create the actual constructor declaration.
7866  CanQualType ClassType
7867    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7868  SourceLocation ClassLoc = ClassDecl->getLocation();
7869  DeclarationName Name
7870    = Context.DeclarationNames.getCXXConstructorName(ClassType);
7871  DeclarationNameInfo NameInfo(Name, ClassLoc);
7872  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7873      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
7874      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7875      Constexpr);
7876  DefaultCon->setAccess(AS_public);
7877  DefaultCon->setDefaulted();
7878  DefaultCon->setImplicit();
7879
7880  // Build an exception specification pointing back at this constructor.
7881  FunctionProtoType::ExtProtoInfo EPI;
7882  EPI.ExceptionSpecType = EST_Unevaluated;
7883  EPI.ExceptionSpecDecl = DefaultCon;
7884  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
7885
7886  // We don't need to use SpecialMemberIsTrivial here; triviality for default
7887  // constructors is easy to compute.
7888  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
7889
7890  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
7891    SetDeclDeleted(DefaultCon, ClassLoc);
7892
7893  // Note that we have declared this constructor.
7894  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7895
7896  if (Scope *S = getScopeForContext(ClassDecl))
7897    PushOnScopeChains(DefaultCon, S, false);
7898  ClassDecl->addDecl(DefaultCon);
7899
7900  return DefaultCon;
7901}
7902
7903void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7904                                            CXXConstructorDecl *Constructor) {
7905  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
7906          !Constructor->doesThisDeclarationHaveABody() &&
7907          !Constructor->isDeleted()) &&
7908    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
7909
7910  CXXRecordDecl *ClassDecl = Constructor->getParent();
7911  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
7912
7913  SynthesizedFunctionScope Scope(*this, Constructor);
7914  DiagnosticErrorTrap Trap(Diags);
7915  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
7916      Trap.hasErrorOccurred()) {
7917    Diag(CurrentLocation, diag::note_member_synthesized_at)
7918      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
7919    Constructor->setInvalidDecl();
7920    return;
7921  }
7922
7923  SourceLocation Loc = Constructor->getLocation();
7924  Constructor->setBody(new (Context) CompoundStmt(Loc));
7925
7926  Constructor->setUsed();
7927  MarkVTableUsed(CurrentLocation, ClassDecl);
7928
7929  if (ASTMutationListener *L = getASTMutationListener()) {
7930    L->CompletedImplicitDefinition(Constructor);
7931  }
7932}
7933
7934void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7935  // Check that any explicitly-defaulted methods have exception specifications
7936  // compatible with their implicit exception specifications.
7937  CheckDelayedExplicitlyDefaultedMemberExceptionSpecs();
7938}
7939
7940namespace {
7941/// Information on inheriting constructors to declare.
7942class InheritingConstructorInfo {
7943public:
7944  InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
7945      : SemaRef(SemaRef), Derived(Derived) {
7946    // Mark the constructors that we already have in the derived class.
7947    //
7948    // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7949    //   unless there is a user-declared constructor with the same signature in
7950    //   the class where the using-declaration appears.
7951    visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
7952  }
7953
7954  void inheritAll(CXXRecordDecl *RD) {
7955    visitAll(RD, &InheritingConstructorInfo::inherit);
7956  }
7957
7958private:
7959  /// Information about an inheriting constructor.
7960  struct InheritingConstructor {
7961    InheritingConstructor()
7962      : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
7963
7964    /// If \c true, a constructor with this signature is already declared
7965    /// in the derived class.
7966    bool DeclaredInDerived;
7967
7968    /// The constructor which is inherited.
7969    const CXXConstructorDecl *BaseCtor;
7970
7971    /// The derived constructor we declared.
7972    CXXConstructorDecl *DerivedCtor;
7973  };
7974
7975  /// Inheriting constructors with a given canonical type. There can be at
7976  /// most one such non-template constructor, and any number of templated
7977  /// constructors.
7978  struct InheritingConstructorsForType {
7979    InheritingConstructor NonTemplate;
7980    llvm::SmallVector<
7981      std::pair<TemplateParameterList*, InheritingConstructor>, 4> Templates;
7982
7983    InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
7984      if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
7985        TemplateParameterList *ParamList = FTD->getTemplateParameters();
7986        for (unsigned I = 0, N = Templates.size(); I != N; ++I)
7987          if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
7988                                               false, S.TPL_TemplateMatch))
7989            return Templates[I].second;
7990        Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
7991        return Templates.back().second;
7992      }
7993
7994      return NonTemplate;
7995    }
7996  };
7997
7998  /// Get or create the inheriting constructor record for a constructor.
7999  InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8000                                  QualType CtorType) {
8001    return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8002        .getEntry(SemaRef, Ctor);
8003  }
8004
8005  typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8006
8007  /// Process all constructors for a class.
8008  void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8009    for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8010                                      CtorE = RD->ctor_end();
8011         CtorIt != CtorE; ++CtorIt)
8012      (this->*Callback)(*CtorIt);
8013    for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8014             I(RD->decls_begin()), E(RD->decls_end());
8015         I != E; ++I) {
8016      const FunctionDecl *FD = (*I)->getTemplatedDecl();
8017      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8018        (this->*Callback)(CD);
8019    }
8020  }
8021
8022  /// Note that a constructor (or constructor template) was declared in Derived.
8023  void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8024    getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8025  }
8026
8027  /// Inherit a single constructor.
8028  void inherit(const CXXConstructorDecl *Ctor) {
8029    const FunctionProtoType *CtorType =
8030        Ctor->getType()->castAs<FunctionProtoType>();
8031    ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8032    FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8033
8034    SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8035
8036    // Core issue (no number yet): the ellipsis is always discarded.
8037    if (EPI.Variadic) {
8038      SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8039      SemaRef.Diag(Ctor->getLocation(),
8040                   diag::note_using_decl_constructor_ellipsis);
8041      EPI.Variadic = false;
8042    }
8043
8044    // Declare a constructor for each number of parameters.
8045    //
8046    // C++11 [class.inhctor]p1:
8047    //   The candidate set of inherited constructors from the class X named in
8048    //   the using-declaration consists of [... modulo defects ...] for each
8049    //   constructor or constructor template of X, the set of constructors or
8050    //   constructor templates that results from omitting any ellipsis parameter
8051    //   specification and successively omitting parameters with a default
8052    //   argument from the end of the parameter-type-list
8053    unsigned MinParams = minParamsToInherit(Ctor);
8054    unsigned Params = Ctor->getNumParams();
8055    if (Params >= MinParams) {
8056      do
8057        declareCtor(UsingLoc, Ctor,
8058                    SemaRef.Context.getFunctionType(
8059                        Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8060      while (Params > MinParams &&
8061             Ctor->getParamDecl(--Params)->hasDefaultArg());
8062    }
8063  }
8064
8065  /// Find the using-declaration which specified that we should inherit the
8066  /// constructors of \p Base.
8067  SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8068    // No fancy lookup required; just look for the base constructor name
8069    // directly within the derived class.
8070    ASTContext &Context = SemaRef.Context;
8071    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8072        Context.getCanonicalType(Context.getRecordType(Base)));
8073    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8074    return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8075  }
8076
8077  unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8078    // C++11 [class.inhctor]p3:
8079    //   [F]or each constructor template in the candidate set of inherited
8080    //   constructors, a constructor template is implicitly declared
8081    if (Ctor->getDescribedFunctionTemplate())
8082      return 0;
8083
8084    //   For each non-template constructor in the candidate set of inherited
8085    //   constructors other than a constructor having no parameters or a
8086    //   copy/move constructor having a single parameter, a constructor is
8087    //   implicitly declared [...]
8088    if (Ctor->getNumParams() == 0)
8089      return 1;
8090    if (Ctor->isCopyOrMoveConstructor())
8091      return 2;
8092
8093    // Per discussion on core reflector, never inherit a constructor which
8094    // would become a default, copy, or move constructor of Derived either.
8095    const ParmVarDecl *PD = Ctor->getParamDecl(0);
8096    const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8097    return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8098  }
8099
8100  /// Declare a single inheriting constructor, inheriting the specified
8101  /// constructor, with the given type.
8102  void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8103                   QualType DerivedType) {
8104    InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8105
8106    // C++11 [class.inhctor]p3:
8107    //   ... a constructor is implicitly declared with the same constructor
8108    //   characteristics unless there is a user-declared constructor with
8109    //   the same signature in the class where the using-declaration appears
8110    if (Entry.DeclaredInDerived)
8111      return;
8112
8113    // C++11 [class.inhctor]p7:
8114    //   If two using-declarations declare inheriting constructors with the
8115    //   same signature, the program is ill-formed
8116    if (Entry.DerivedCtor) {
8117      if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8118        // Only diagnose this once per constructor.
8119        if (Entry.DerivedCtor->isInvalidDecl())
8120          return;
8121        Entry.DerivedCtor->setInvalidDecl();
8122
8123        SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8124        SemaRef.Diag(BaseCtor->getLocation(),
8125                     diag::note_using_decl_constructor_conflict_current_ctor);
8126        SemaRef.Diag(Entry.BaseCtor->getLocation(),
8127                     diag::note_using_decl_constructor_conflict_previous_ctor);
8128        SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8129                     diag::note_using_decl_constructor_conflict_previous_using);
8130      } else {
8131        // Core issue (no number): if the same inheriting constructor is
8132        // produced by multiple base class constructors from the same base
8133        // class, the inheriting constructor is defined as deleted.
8134        SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8135      }
8136
8137      return;
8138    }
8139
8140    ASTContext &Context = SemaRef.Context;
8141    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8142        Context.getCanonicalType(Context.getRecordType(Derived)));
8143    DeclarationNameInfo NameInfo(Name, UsingLoc);
8144
8145    TemplateParameterList *TemplateParams = 0;
8146    if (const FunctionTemplateDecl *FTD =
8147            BaseCtor->getDescribedFunctionTemplate()) {
8148      TemplateParams = FTD->getTemplateParameters();
8149      // We're reusing template parameters from a different DeclContext. This
8150      // is questionable at best, but works out because the template depth in
8151      // both places is guaranteed to be 0.
8152      // FIXME: Rebuild the template parameters in the new context, and
8153      // transform the function type to refer to them.
8154    }
8155
8156    // Build type source info pointing at the using-declaration. This is
8157    // required by template instantiation.
8158    TypeSourceInfo *TInfo =
8159        Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8160    FunctionProtoTypeLoc ProtoLoc =
8161        TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8162
8163    CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8164        Context, Derived, UsingLoc, NameInfo, DerivedType,
8165        TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8166        /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8167
8168    // Build an unevaluated exception specification for this constructor.
8169    const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8170    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8171    EPI.ExceptionSpecType = EST_Unevaluated;
8172    EPI.ExceptionSpecDecl = DerivedCtor;
8173    DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8174                                                 FPT->getArgTypes(), EPI));
8175
8176    // Build the parameter declarations.
8177    SmallVector<ParmVarDecl *, 16> ParamDecls;
8178    for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8179      TypeSourceInfo *TInfo =
8180          Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8181      ParmVarDecl *PD = ParmVarDecl::Create(
8182          Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8183          FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8184      PD->setScopeInfo(0, I);
8185      PD->setImplicit();
8186      ParamDecls.push_back(PD);
8187      ProtoLoc.setArg(I, PD);
8188    }
8189
8190    // Set up the new constructor.
8191    DerivedCtor->setAccess(BaseCtor->getAccess());
8192    DerivedCtor->setParams(ParamDecls);
8193    DerivedCtor->setInheritedConstructor(BaseCtor);
8194    if (BaseCtor->isDeleted())
8195      SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8196
8197    // If this is a constructor template, build the template declaration.
8198    if (TemplateParams) {
8199      FunctionTemplateDecl *DerivedTemplate =
8200          FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8201                                       TemplateParams, DerivedCtor);
8202      DerivedTemplate->setAccess(BaseCtor->getAccess());
8203      DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8204      Derived->addDecl(DerivedTemplate);
8205    } else {
8206      Derived->addDecl(DerivedCtor);
8207    }
8208
8209    Entry.BaseCtor = BaseCtor;
8210    Entry.DerivedCtor = DerivedCtor;
8211  }
8212
8213  Sema &SemaRef;
8214  CXXRecordDecl *Derived;
8215  typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8216  MapType Map;
8217};
8218}
8219
8220void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8221  // Defer declaring the inheriting constructors until the class is
8222  // instantiated.
8223  if (ClassDecl->isDependentContext())
8224    return;
8225
8226  // Find base classes from which we might inherit constructors.
8227  SmallVector<CXXRecordDecl*, 4> InheritedBases;
8228  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8229                                          BaseE = ClassDecl->bases_end();
8230       BaseIt != BaseE; ++BaseIt)
8231    if (BaseIt->getInheritConstructors())
8232      InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8233
8234  // Go no further if we're not inheriting any constructors.
8235  if (InheritedBases.empty())
8236    return;
8237
8238  // Declare the inherited constructors.
8239  InheritingConstructorInfo ICI(*this, ClassDecl);
8240  for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8241    ICI.inheritAll(InheritedBases[I]);
8242}
8243
8244void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8245                                       CXXConstructorDecl *Constructor) {
8246  CXXRecordDecl *ClassDecl = Constructor->getParent();
8247  assert(Constructor->getInheritedConstructor() &&
8248         !Constructor->doesThisDeclarationHaveABody() &&
8249         !Constructor->isDeleted());
8250
8251  SynthesizedFunctionScope Scope(*this, Constructor);
8252  DiagnosticErrorTrap Trap(Diags);
8253  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8254      Trap.hasErrorOccurred()) {
8255    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8256      << Context.getTagDeclType(ClassDecl);
8257    Constructor->setInvalidDecl();
8258    return;
8259  }
8260
8261  SourceLocation Loc = Constructor->getLocation();
8262  Constructor->setBody(new (Context) CompoundStmt(Loc));
8263
8264  Constructor->setUsed();
8265  MarkVTableUsed(CurrentLocation, ClassDecl);
8266
8267  if (ASTMutationListener *L = getASTMutationListener()) {
8268    L->CompletedImplicitDefinition(Constructor);
8269  }
8270}
8271
8272
8273Sema::ImplicitExceptionSpecification
8274Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8275  CXXRecordDecl *ClassDecl = MD->getParent();
8276
8277  // C++ [except.spec]p14:
8278  //   An implicitly declared special member function (Clause 12) shall have
8279  //   an exception-specification.
8280  ImplicitExceptionSpecification ExceptSpec(*this);
8281  if (ClassDecl->isInvalidDecl())
8282    return ExceptSpec;
8283
8284  // Direct base-class destructors.
8285  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8286                                       BEnd = ClassDecl->bases_end();
8287       B != BEnd; ++B) {
8288    if (B->isVirtual()) // Handled below.
8289      continue;
8290
8291    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8292      ExceptSpec.CalledDecl(B->getLocStart(),
8293                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8294  }
8295
8296  // Virtual base-class destructors.
8297  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8298                                       BEnd = ClassDecl->vbases_end();
8299       B != BEnd; ++B) {
8300    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8301      ExceptSpec.CalledDecl(B->getLocStart(),
8302                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8303  }
8304
8305  // Field destructors.
8306  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8307                               FEnd = ClassDecl->field_end();
8308       F != FEnd; ++F) {
8309    if (const RecordType *RecordTy
8310        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8311      ExceptSpec.CalledDecl(F->getLocation(),
8312                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8313  }
8314
8315  return ExceptSpec;
8316}
8317
8318CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8319  // C++ [class.dtor]p2:
8320  //   If a class has no user-declared destructor, a destructor is
8321  //   declared implicitly. An implicitly-declared destructor is an
8322  //   inline public member of its class.
8323  assert(ClassDecl->needsImplicitDestructor());
8324
8325  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8326  if (DSM.isAlreadyBeingDeclared())
8327    return 0;
8328
8329  // Create the actual destructor declaration.
8330  CanQualType ClassType
8331    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8332  SourceLocation ClassLoc = ClassDecl->getLocation();
8333  DeclarationName Name
8334    = Context.DeclarationNames.getCXXDestructorName(ClassType);
8335  DeclarationNameInfo NameInfo(Name, ClassLoc);
8336  CXXDestructorDecl *Destructor
8337      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8338                                  QualType(), 0, /*isInline=*/true,
8339                                  /*isImplicitlyDeclared=*/true);
8340  Destructor->setAccess(AS_public);
8341  Destructor->setDefaulted();
8342  Destructor->setImplicit();
8343
8344  // Build an exception specification pointing back at this destructor.
8345  FunctionProtoType::ExtProtoInfo EPI;
8346  EPI.ExceptionSpecType = EST_Unevaluated;
8347  EPI.ExceptionSpecDecl = Destructor;
8348  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8349
8350  AddOverriddenMethods(ClassDecl, Destructor);
8351
8352  // We don't need to use SpecialMemberIsTrivial here; triviality for
8353  // destructors is easy to compute.
8354  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8355
8356  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8357    SetDeclDeleted(Destructor, ClassLoc);
8358
8359  // Note that we have declared this destructor.
8360  ++ASTContext::NumImplicitDestructorsDeclared;
8361
8362  // Introduce this destructor into its scope.
8363  if (Scope *S = getScopeForContext(ClassDecl))
8364    PushOnScopeChains(Destructor, S, false);
8365  ClassDecl->addDecl(Destructor);
8366
8367  return Destructor;
8368}
8369
8370void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8371                                    CXXDestructorDecl *Destructor) {
8372  assert((Destructor->isDefaulted() &&
8373          !Destructor->doesThisDeclarationHaveABody() &&
8374          !Destructor->isDeleted()) &&
8375         "DefineImplicitDestructor - call it for implicit default dtor");
8376  CXXRecordDecl *ClassDecl = Destructor->getParent();
8377  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8378
8379  if (Destructor->isInvalidDecl())
8380    return;
8381
8382  SynthesizedFunctionScope Scope(*this, Destructor);
8383
8384  DiagnosticErrorTrap Trap(Diags);
8385  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8386                                         Destructor->getParent());
8387
8388  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8389    Diag(CurrentLocation, diag::note_member_synthesized_at)
8390      << CXXDestructor << Context.getTagDeclType(ClassDecl);
8391
8392    Destructor->setInvalidDecl();
8393    return;
8394  }
8395
8396  SourceLocation Loc = Destructor->getLocation();
8397  Destructor->setBody(new (Context) CompoundStmt(Loc));
8398  Destructor->setImplicitlyDefined(true);
8399  Destructor->setUsed();
8400  MarkVTableUsed(CurrentLocation, ClassDecl);
8401
8402  if (ASTMutationListener *L = getASTMutationListener()) {
8403    L->CompletedImplicitDefinition(Destructor);
8404  }
8405}
8406
8407/// \brief Perform any semantic analysis which needs to be delayed until all
8408/// pending class member declarations have been parsed.
8409void Sema::ActOnFinishCXXMemberDecls() {
8410  // If the context is an invalid C++ class, just suppress these checks.
8411  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8412    if (Record->isInvalidDecl()) {
8413      DelayedDestructorExceptionSpecChecks.clear();
8414      return;
8415    }
8416  }
8417
8418  // Perform any deferred checking of exception specifications for virtual
8419  // destructors.
8420  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
8421       i != e; ++i) {
8422    const CXXDestructorDecl *Dtor =
8423        DelayedDestructorExceptionSpecChecks[i].first;
8424    assert(!Dtor->getParent()->isDependentType() &&
8425           "Should not ever add destructors of templates into the list.");
8426    CheckOverridingFunctionExceptionSpec(Dtor,
8427        DelayedDestructorExceptionSpecChecks[i].second);
8428  }
8429  DelayedDestructorExceptionSpecChecks.clear();
8430}
8431
8432void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8433                                         CXXDestructorDecl *Destructor) {
8434  assert(getLangOpts().CPlusPlus11 &&
8435         "adjusting dtor exception specs was introduced in c++11");
8436
8437  // C++11 [class.dtor]p3:
8438  //   A declaration of a destructor that does not have an exception-
8439  //   specification is implicitly considered to have the same exception-
8440  //   specification as an implicit declaration.
8441  const FunctionProtoType *DtorType = Destructor->getType()->
8442                                        getAs<FunctionProtoType>();
8443  if (DtorType->hasExceptionSpec())
8444    return;
8445
8446  // Replace the destructor's type, building off the existing one. Fortunately,
8447  // the only thing of interest in the destructor type is its extended info.
8448  // The return and arguments are fixed.
8449  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8450  EPI.ExceptionSpecType = EST_Unevaluated;
8451  EPI.ExceptionSpecDecl = Destructor;
8452  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8453
8454  // FIXME: If the destructor has a body that could throw, and the newly created
8455  // spec doesn't allow exceptions, we should emit a warning, because this
8456  // change in behavior can break conforming C++03 programs at runtime.
8457  // However, we don't have a body or an exception specification yet, so it
8458  // needs to be done somewhere else.
8459}
8460
8461/// When generating a defaulted copy or move assignment operator, if a field
8462/// should be copied with __builtin_memcpy rather than via explicit assignments,
8463/// do so. This optimization only applies for arrays of scalars, and for arrays
8464/// of class type where the selected copy/move-assignment operator is trivial.
8465static StmtResult
8466buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8467                           Expr *To, Expr *From) {
8468  // Compute the size of the memory buffer to be copied.
8469  QualType SizeType = S.Context.getSizeType();
8470  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8471                   S.Context.getTypeSizeInChars(T).getQuantity());
8472
8473  // Take the address of the field references for "from" and "to". We
8474  // directly construct UnaryOperators here because semantic analysis
8475  // does not permit us to take the address of an xvalue.
8476  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8477                         S.Context.getPointerType(From->getType()),
8478                         VK_RValue, OK_Ordinary, Loc);
8479  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8480                       S.Context.getPointerType(To->getType()),
8481                       VK_RValue, OK_Ordinary, Loc);
8482
8483  const Type *E = T->getBaseElementTypeUnsafe();
8484  bool NeedsCollectableMemCpy =
8485    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8486
8487  // Create a reference to the __builtin_objc_memmove_collectable function
8488  StringRef MemCpyName = NeedsCollectableMemCpy ?
8489    "__builtin_objc_memmove_collectable" :
8490    "__builtin_memcpy";
8491  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8492                 Sema::LookupOrdinaryName);
8493  S.LookupName(R, S.TUScope, true);
8494
8495  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8496  if (!MemCpy)
8497    // Something went horribly wrong earlier, and we will have complained
8498    // about it.
8499    return StmtError();
8500
8501  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8502                                            VK_RValue, Loc, 0);
8503  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8504
8505  Expr *CallArgs[] = {
8506    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8507  };
8508  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8509                                    Loc, CallArgs, Loc);
8510
8511  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8512  return S.Owned(Call.takeAs<Stmt>());
8513}
8514
8515/// \brief Builds a statement that copies/moves the given entity from \p From to
8516/// \c To.
8517///
8518/// This routine is used to copy/move the members of a class with an
8519/// implicitly-declared copy/move assignment operator. When the entities being
8520/// copied are arrays, this routine builds for loops to copy them.
8521///
8522/// \param S The Sema object used for type-checking.
8523///
8524/// \param Loc The location where the implicit copy/move is being generated.
8525///
8526/// \param T The type of the expressions being copied/moved. Both expressions
8527/// must have this type.
8528///
8529/// \param To The expression we are copying/moving to.
8530///
8531/// \param From The expression we are copying/moving from.
8532///
8533/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8534/// Otherwise, it's a non-static member subobject.
8535///
8536/// \param Copying Whether we're copying or moving.
8537///
8538/// \param Depth Internal parameter recording the depth of the recursion.
8539///
8540/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8541/// if a memcpy should be used instead.
8542static StmtResult
8543buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8544                                 Expr *To, Expr *From,
8545                                 bool CopyingBaseSubobject, bool Copying,
8546                                 unsigned Depth = 0) {
8547  // C++11 [class.copy]p28:
8548  //   Each subobject is assigned in the manner appropriate to its type:
8549  //
8550  //     - if the subobject is of class type, as if by a call to operator= with
8551  //       the subobject as the object expression and the corresponding
8552  //       subobject of x as a single function argument (as if by explicit
8553  //       qualification; that is, ignoring any possible virtual overriding
8554  //       functions in more derived classes);
8555  //
8556  // C++03 [class.copy]p13:
8557  //     - if the subobject is of class type, the copy assignment operator for
8558  //       the class is used (as if by explicit qualification; that is,
8559  //       ignoring any possible virtual overriding functions in more derived
8560  //       classes);
8561  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8562    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8563
8564    // Look for operator=.
8565    DeclarationName Name
8566      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8567    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8568    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8569
8570    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8571    // operator.
8572    if (!S.getLangOpts().CPlusPlus11) {
8573      LookupResult::Filter F = OpLookup.makeFilter();
8574      while (F.hasNext()) {
8575        NamedDecl *D = F.next();
8576        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8577          if (Method->isCopyAssignmentOperator() ||
8578              (!Copying && Method->isMoveAssignmentOperator()))
8579            continue;
8580
8581        F.erase();
8582      }
8583      F.done();
8584    }
8585
8586    // Suppress the protected check (C++ [class.protected]) for each of the
8587    // assignment operators we found. This strange dance is required when
8588    // we're assigning via a base classes's copy-assignment operator. To
8589    // ensure that we're getting the right base class subobject (without
8590    // ambiguities), we need to cast "this" to that subobject type; to
8591    // ensure that we don't go through the virtual call mechanism, we need
8592    // to qualify the operator= name with the base class (see below). However,
8593    // this means that if the base class has a protected copy assignment
8594    // operator, the protected member access check will fail. So, we
8595    // rewrite "protected" access to "public" access in this case, since we
8596    // know by construction that we're calling from a derived class.
8597    if (CopyingBaseSubobject) {
8598      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8599           L != LEnd; ++L) {
8600        if (L.getAccess() == AS_protected)
8601          L.setAccess(AS_public);
8602      }
8603    }
8604
8605    // Create the nested-name-specifier that will be used to qualify the
8606    // reference to operator=; this is required to suppress the virtual
8607    // call mechanism.
8608    CXXScopeSpec SS;
8609    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8610    SS.MakeTrivial(S.Context,
8611                   NestedNameSpecifier::Create(S.Context, 0, false,
8612                                               CanonicalT),
8613                   Loc);
8614
8615    // Create the reference to operator=.
8616    ExprResult OpEqualRef
8617      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
8618                                   /*TemplateKWLoc=*/SourceLocation(),
8619                                   /*FirstQualifierInScope=*/0,
8620                                   OpLookup,
8621                                   /*TemplateArgs=*/0,
8622                                   /*SuppressQualifierCheck=*/true);
8623    if (OpEqualRef.isInvalid())
8624      return StmtError();
8625
8626    // Build the call to the assignment operator.
8627
8628    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8629                                                  OpEqualRef.takeAs<Expr>(),
8630                                                  Loc, From, Loc);
8631    if (Call.isInvalid())
8632      return StmtError();
8633
8634    // If we built a call to a trivial 'operator=' while copying an array,
8635    // bail out. We'll replace the whole shebang with a memcpy.
8636    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8637    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8638      return StmtResult((Stmt*)0);
8639
8640    // Convert to an expression-statement, and clean up any produced
8641    // temporaries.
8642    return S.ActOnExprStmt(Call);
8643  }
8644
8645  //     - if the subobject is of scalar type, the built-in assignment
8646  //       operator is used.
8647  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
8648  if (!ArrayTy) {
8649    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
8650    if (Assignment.isInvalid())
8651      return StmtError();
8652    return S.ActOnExprStmt(Assignment);
8653  }
8654
8655  //     - if the subobject is an array, each element is assigned, in the
8656  //       manner appropriate to the element type;
8657
8658  // Construct a loop over the array bounds, e.g.,
8659  //
8660  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
8661  //
8662  // that will copy each of the array elements.
8663  QualType SizeType = S.Context.getSizeType();
8664
8665  // Create the iteration variable.
8666  IdentifierInfo *IterationVarName = 0;
8667  {
8668    SmallString<8> Str;
8669    llvm::raw_svector_ostream OS(Str);
8670    OS << "__i" << Depth;
8671    IterationVarName = &S.Context.Idents.get(OS.str());
8672  }
8673  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
8674                                          IterationVarName, SizeType,
8675                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
8676                                          SC_None);
8677
8678  // Initialize the iteration variable to zero.
8679  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8680  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8681
8682  // Create a reference to the iteration variable; we'll use this several
8683  // times throughout.
8684  Expr *IterationVarRef
8685    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
8686  assert(IterationVarRef && "Reference to invented variable cannot fail!");
8687  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
8688  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
8689
8690  // Create the DeclStmt that holds the iteration variable.
8691  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
8692
8693  // Subscript the "from" and "to" expressions with the iteration variable.
8694  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
8695                                                         IterationVarRefRVal,
8696                                                         Loc));
8697  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
8698                                                       IterationVarRefRVal,
8699                                                       Loc));
8700  if (!Copying) // Cast to rvalue
8701    From = CastForMoving(S, From);
8702
8703  // Build the copy/move for an individual element of the array.
8704  StmtResult Copy =
8705    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
8706                                     To, From, CopyingBaseSubobject,
8707                                     Copying, Depth + 1);
8708  // Bail out if copying fails or if we determined that we should use memcpy.
8709  if (Copy.isInvalid() || !Copy.get())
8710    return Copy;
8711
8712  // Create the comparison against the array bound.
8713  llvm::APInt Upper
8714    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
8715  Expr *Comparison
8716    = new (S.Context) BinaryOperator(IterationVarRefRVal,
8717                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
8718                                     BO_NE, S.Context.BoolTy,
8719                                     VK_RValue, OK_Ordinary, Loc, false);
8720
8721  // Create the pre-increment of the iteration variable.
8722  Expr *Increment
8723    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
8724                                    VK_LValue, OK_Ordinary, Loc);
8725
8726  // Construct the loop that copies all elements of this array.
8727  return S.ActOnForStmt(Loc, Loc, InitStmt,
8728                        S.MakeFullExpr(Comparison),
8729                        0, S.MakeFullDiscardedValueExpr(Increment),
8730                        Loc, Copy.take());
8731}
8732
8733static StmtResult
8734buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
8735                      Expr *To, Expr *From,
8736                      bool CopyingBaseSubobject, bool Copying) {
8737  // Maybe we should use a memcpy?
8738  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
8739      T.isTriviallyCopyableType(S.Context))
8740    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8741
8742  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
8743                                                     CopyingBaseSubobject,
8744                                                     Copying, 0));
8745
8746  // If we ended up picking a trivial assignment operator for an array of a
8747  // non-trivially-copyable class type, just emit a memcpy.
8748  if (!Result.isInvalid() && !Result.get())
8749    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
8750
8751  return Result;
8752}
8753
8754Sema::ImplicitExceptionSpecification
8755Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
8756  CXXRecordDecl *ClassDecl = MD->getParent();
8757
8758  ImplicitExceptionSpecification ExceptSpec(*this);
8759  if (ClassDecl->isInvalidDecl())
8760    return ExceptSpec;
8761
8762  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
8763  assert(T->getNumArgs() == 1 && "not a copy assignment op");
8764  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
8765
8766  // C++ [except.spec]p14:
8767  //   An implicitly declared special member function (Clause 12) shall have an
8768  //   exception-specification. [...]
8769
8770  // It is unspecified whether or not an implicit copy assignment operator
8771  // attempts to deduplicate calls to assignment operators of virtual bases are
8772  // made. As such, this exception specification is effectively unspecified.
8773  // Based on a similar decision made for constness in C++0x, we're erring on
8774  // the side of assuming such calls to be made regardless of whether they
8775  // actually happen.
8776  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8777                                       BaseEnd = ClassDecl->bases_end();
8778       Base != BaseEnd; ++Base) {
8779    if (Base->isVirtual())
8780      continue;
8781
8782    CXXRecordDecl *BaseClassDecl
8783      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8784    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8785                                                            ArgQuals, false, 0))
8786      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8787  }
8788
8789  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8790                                       BaseEnd = ClassDecl->vbases_end();
8791       Base != BaseEnd; ++Base) {
8792    CXXRecordDecl *BaseClassDecl
8793      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8794    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
8795                                                            ArgQuals, false, 0))
8796      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
8797  }
8798
8799  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8800                                  FieldEnd = ClassDecl->field_end();
8801       Field != FieldEnd;
8802       ++Field) {
8803    QualType FieldType = Context.getBaseElementType(Field->getType());
8804    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8805      if (CXXMethodDecl *CopyAssign =
8806          LookupCopyingAssignment(FieldClassDecl,
8807                                  ArgQuals | FieldType.getCVRQualifiers(),
8808                                  false, 0))
8809        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
8810    }
8811  }
8812
8813  return ExceptSpec;
8814}
8815
8816CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
8817  // Note: The following rules are largely analoguous to the copy
8818  // constructor rules. Note that virtual bases are not taken into account
8819  // for determining the argument type of the operator. Note also that
8820  // operators taking an object instead of a reference are allowed.
8821  assert(ClassDecl->needsImplicitCopyAssignment());
8822
8823  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
8824  if (DSM.isAlreadyBeingDeclared())
8825    return 0;
8826
8827  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8828  QualType RetType = Context.getLValueReferenceType(ArgType);
8829  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
8830  if (Const)
8831    ArgType = ArgType.withConst();
8832  ArgType = Context.getLValueReferenceType(ArgType);
8833
8834  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8835                                                     CXXCopyAssignment,
8836                                                     Const);
8837
8838  //   An implicitly-declared copy assignment operator is an inline public
8839  //   member of its class.
8840  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8841  SourceLocation ClassLoc = ClassDecl->getLocation();
8842  DeclarationNameInfo NameInfo(Name, ClassLoc);
8843  CXXMethodDecl *CopyAssignment =
8844      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
8845                            /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
8846                            /*isInline=*/ true, Constexpr, SourceLocation());
8847  CopyAssignment->setAccess(AS_public);
8848  CopyAssignment->setDefaulted();
8849  CopyAssignment->setImplicit();
8850
8851  // Build an exception specification pointing back at this member.
8852  FunctionProtoType::ExtProtoInfo EPI;
8853  EPI.ExceptionSpecType = EST_Unevaluated;
8854  EPI.ExceptionSpecDecl = CopyAssignment;
8855  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
8856
8857  // Add the parameter to the operator.
8858  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
8859                                               ClassLoc, ClassLoc, /*Id=*/0,
8860                                               ArgType, /*TInfo=*/0,
8861                                               SC_None, 0);
8862  CopyAssignment->setParams(FromParam);
8863
8864  AddOverriddenMethods(ClassDecl, CopyAssignment);
8865
8866  CopyAssignment->setTrivial(
8867    ClassDecl->needsOverloadResolutionForCopyAssignment()
8868      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
8869      : ClassDecl->hasTrivialCopyAssignment());
8870
8871  // C++11 [class.copy]p19:
8872  //   ....  If the class definition does not explicitly declare a copy
8873  //   assignment operator, there is no user-declared move constructor, and
8874  //   there is no user-declared move assignment operator, a copy assignment
8875  //   operator is implicitly declared as defaulted.
8876  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
8877    SetDeclDeleted(CopyAssignment, ClassLoc);
8878
8879  // Note that we have added this copy-assignment operator.
8880  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
8881
8882  if (Scope *S = getScopeForContext(ClassDecl))
8883    PushOnScopeChains(CopyAssignment, S, false);
8884  ClassDecl->addDecl(CopyAssignment);
8885
8886  return CopyAssignment;
8887}
8888
8889/// Diagnose an implicit copy operation for a class which is odr-used, but
8890/// which is deprecated because the class has a user-declared copy constructor,
8891/// copy assignment operator, or destructor.
8892static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
8893                                            SourceLocation UseLoc) {
8894  assert(CopyOp->isImplicit());
8895
8896  CXXRecordDecl *RD = CopyOp->getParent();
8897  CXXMethodDecl *UserDeclaredOperation = 0;
8898
8899  // In Microsoft mode, assignment operations don't affect constructors and
8900  // vice versa.
8901  if (RD->hasUserDeclaredDestructor()) {
8902    UserDeclaredOperation = RD->getDestructor();
8903  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
8904             RD->hasUserDeclaredCopyConstructor() &&
8905             !S.getLangOpts().MicrosoftMode) {
8906    // Find any user-declared copy constructor.
8907    for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
8908                                      E = RD->ctor_end(); I != E; ++I) {
8909      if (I->isCopyConstructor()) {
8910        UserDeclaredOperation = *I;
8911        break;
8912      }
8913    }
8914    assert(UserDeclaredOperation);
8915  } else if (isa<CXXConstructorDecl>(CopyOp) &&
8916             RD->hasUserDeclaredCopyAssignment() &&
8917             !S.getLangOpts().MicrosoftMode) {
8918    // Find any user-declared move assignment operator.
8919    for (CXXRecordDecl::method_iterator I = RD->method_begin(),
8920                                        E = RD->method_end(); I != E; ++I) {
8921      if (I->isCopyAssignmentOperator()) {
8922        UserDeclaredOperation = *I;
8923        break;
8924      }
8925    }
8926    assert(UserDeclaredOperation);
8927  }
8928
8929  if (UserDeclaredOperation) {
8930    S.Diag(UserDeclaredOperation->getLocation(),
8931         diag::warn_deprecated_copy_operation)
8932      << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
8933      << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
8934    S.Diag(UseLoc, diag::note_member_synthesized_at)
8935      << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
8936                                          : Sema::CXXCopyAssignment)
8937      << RD;
8938  }
8939}
8940
8941void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
8942                                        CXXMethodDecl *CopyAssignOperator) {
8943  assert((CopyAssignOperator->isDefaulted() &&
8944          CopyAssignOperator->isOverloadedOperator() &&
8945          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
8946          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
8947          !CopyAssignOperator->isDeleted()) &&
8948         "DefineImplicitCopyAssignment called for wrong function");
8949
8950  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
8951
8952  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
8953    CopyAssignOperator->setInvalidDecl();
8954    return;
8955  }
8956
8957  // C++11 [class.copy]p18:
8958  //   The [definition of an implicitly declared copy assignment operator] is
8959  //   deprecated if the class has a user-declared copy constructor or a
8960  //   user-declared destructor.
8961  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
8962    diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
8963
8964  CopyAssignOperator->setUsed();
8965
8966  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
8967  DiagnosticErrorTrap Trap(Diags);
8968
8969  // C++0x [class.copy]p30:
8970  //   The implicitly-defined or explicitly-defaulted copy assignment operator
8971  //   for a non-union class X performs memberwise copy assignment of its
8972  //   subobjects. The direct base classes of X are assigned first, in the
8973  //   order of their declaration in the base-specifier-list, and then the
8974  //   immediate non-static data members of X are assigned, in the order in
8975  //   which they were declared in the class definition.
8976
8977  // The statements that form the synthesized function body.
8978  SmallVector<Stmt*, 8> Statements;
8979
8980  // The parameter for the "other" object, which we are copying from.
8981  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
8982  Qualifiers OtherQuals = Other->getType().getQualifiers();
8983  QualType OtherRefType = Other->getType();
8984  if (const LValueReferenceType *OtherRef
8985                                = OtherRefType->getAs<LValueReferenceType>()) {
8986    OtherRefType = OtherRef->getPointeeType();
8987    OtherQuals = OtherRefType.getQualifiers();
8988  }
8989
8990  // Our location for everything implicitly-generated.
8991  SourceLocation Loc = CopyAssignOperator->getLocation();
8992
8993  // Construct a reference to the "other" object. We'll be using this
8994  // throughout the generated ASTs.
8995  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8996  assert(OtherRef && "Reference to parameter cannot fail!");
8997
8998  // Construct the "this" pointer. We'll be using this throughout the generated
8999  // ASTs.
9000  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9001  assert(This && "Reference to this cannot fail!");
9002
9003  // Assign base classes.
9004  bool Invalid = false;
9005  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9006       E = ClassDecl->bases_end(); Base != E; ++Base) {
9007    // Form the assignment:
9008    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9009    QualType BaseType = Base->getType().getUnqualifiedType();
9010    if (!BaseType->isRecordType()) {
9011      Invalid = true;
9012      continue;
9013    }
9014
9015    CXXCastPath BasePath;
9016    BasePath.push_back(Base);
9017
9018    // Construct the "from" expression, which is an implicit cast to the
9019    // appropriately-qualified base type.
9020    Expr *From = OtherRef;
9021    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
9022                             CK_UncheckedDerivedToBase,
9023                             VK_LValue, &BasePath).take();
9024
9025    // Dereference "this".
9026    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9027
9028    // Implicitly cast "this" to the appropriately-qualified base type.
9029    To = ImpCastExprToType(To.take(),
9030                           Context.getCVRQualifiedType(BaseType,
9031                                     CopyAssignOperator->getTypeQualifiers()),
9032                           CK_UncheckedDerivedToBase,
9033                           VK_LValue, &BasePath);
9034
9035    // Build the copy.
9036    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9037                                            To.get(), From,
9038                                            /*CopyingBaseSubobject=*/true,
9039                                            /*Copying=*/true);
9040    if (Copy.isInvalid()) {
9041      Diag(CurrentLocation, diag::note_member_synthesized_at)
9042        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9043      CopyAssignOperator->setInvalidDecl();
9044      return;
9045    }
9046
9047    // Success! Record the copy.
9048    Statements.push_back(Copy.takeAs<Expr>());
9049  }
9050
9051  // Assign non-static members.
9052  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9053                                  FieldEnd = ClassDecl->field_end();
9054       Field != FieldEnd; ++Field) {
9055    if (Field->isUnnamedBitfield())
9056      continue;
9057
9058    if (Field->isInvalidDecl()) {
9059      Invalid = true;
9060      continue;
9061    }
9062
9063    // Check for members of reference type; we can't copy those.
9064    if (Field->getType()->isReferenceType()) {
9065      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9066        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9067      Diag(Field->getLocation(), diag::note_declared_at);
9068      Diag(CurrentLocation, diag::note_member_synthesized_at)
9069        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9070      Invalid = true;
9071      continue;
9072    }
9073
9074    // Check for members of const-qualified, non-class type.
9075    QualType BaseType = Context.getBaseElementType(Field->getType());
9076    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9077      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9078        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9079      Diag(Field->getLocation(), diag::note_declared_at);
9080      Diag(CurrentLocation, diag::note_member_synthesized_at)
9081        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9082      Invalid = true;
9083      continue;
9084    }
9085
9086    // Suppress assigning zero-width bitfields.
9087    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9088      continue;
9089
9090    QualType FieldType = Field->getType().getNonReferenceType();
9091    if (FieldType->isIncompleteArrayType()) {
9092      assert(ClassDecl->hasFlexibleArrayMember() &&
9093             "Incomplete array type is not valid");
9094      continue;
9095    }
9096
9097    // Build references to the field in the object we're copying from and to.
9098    CXXScopeSpec SS; // Intentionally empty
9099    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9100                              LookupMemberName);
9101    MemberLookup.addDecl(*Field);
9102    MemberLookup.resolveKind();
9103    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9104                                               Loc, /*IsArrow=*/false,
9105                                               SS, SourceLocation(), 0,
9106                                               MemberLookup, 0);
9107    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9108                                             Loc, /*IsArrow=*/true,
9109                                             SS, SourceLocation(), 0,
9110                                             MemberLookup, 0);
9111    assert(!From.isInvalid() && "Implicit field reference cannot fail");
9112    assert(!To.isInvalid() && "Implicit field reference cannot fail");
9113
9114    // Build the copy of this field.
9115    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9116                                            To.get(), From.get(),
9117                                            /*CopyingBaseSubobject=*/false,
9118                                            /*Copying=*/true);
9119    if (Copy.isInvalid()) {
9120      Diag(CurrentLocation, diag::note_member_synthesized_at)
9121        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9122      CopyAssignOperator->setInvalidDecl();
9123      return;
9124    }
9125
9126    // Success! Record the copy.
9127    Statements.push_back(Copy.takeAs<Stmt>());
9128  }
9129
9130  if (!Invalid) {
9131    // Add a "return *this;"
9132    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9133
9134    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9135    if (Return.isInvalid())
9136      Invalid = true;
9137    else {
9138      Statements.push_back(Return.takeAs<Stmt>());
9139
9140      if (Trap.hasErrorOccurred()) {
9141        Diag(CurrentLocation, diag::note_member_synthesized_at)
9142          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9143        Invalid = true;
9144      }
9145    }
9146  }
9147
9148  if (Invalid) {
9149    CopyAssignOperator->setInvalidDecl();
9150    return;
9151  }
9152
9153  StmtResult Body;
9154  {
9155    CompoundScopeRAII CompoundScope(*this);
9156    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9157                             /*isStmtExpr=*/false);
9158    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9159  }
9160  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9161
9162  if (ASTMutationListener *L = getASTMutationListener()) {
9163    L->CompletedImplicitDefinition(CopyAssignOperator);
9164  }
9165}
9166
9167Sema::ImplicitExceptionSpecification
9168Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9169  CXXRecordDecl *ClassDecl = MD->getParent();
9170
9171  ImplicitExceptionSpecification ExceptSpec(*this);
9172  if (ClassDecl->isInvalidDecl())
9173    return ExceptSpec;
9174
9175  // C++0x [except.spec]p14:
9176  //   An implicitly declared special member function (Clause 12) shall have an
9177  //   exception-specification. [...]
9178
9179  // It is unspecified whether or not an implicit move assignment operator
9180  // attempts to deduplicate calls to assignment operators of virtual bases are
9181  // made. As such, this exception specification is effectively unspecified.
9182  // Based on a similar decision made for constness in C++0x, we're erring on
9183  // the side of assuming such calls to be made regardless of whether they
9184  // actually happen.
9185  // Note that a move constructor is not implicitly declared when there are
9186  // virtual bases, but it can still be user-declared and explicitly defaulted.
9187  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9188                                       BaseEnd = ClassDecl->bases_end();
9189       Base != BaseEnd; ++Base) {
9190    if (Base->isVirtual())
9191      continue;
9192
9193    CXXRecordDecl *BaseClassDecl
9194      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9195    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9196                                                           0, false, 0))
9197      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9198  }
9199
9200  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9201                                       BaseEnd = ClassDecl->vbases_end();
9202       Base != BaseEnd; ++Base) {
9203    CXXRecordDecl *BaseClassDecl
9204      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9205    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9206                                                           0, false, 0))
9207      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9208  }
9209
9210  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9211                                  FieldEnd = ClassDecl->field_end();
9212       Field != FieldEnd;
9213       ++Field) {
9214    QualType FieldType = Context.getBaseElementType(Field->getType());
9215    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9216      if (CXXMethodDecl *MoveAssign =
9217              LookupMovingAssignment(FieldClassDecl,
9218                                     FieldType.getCVRQualifiers(),
9219                                     false, 0))
9220        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9221    }
9222  }
9223
9224  return ExceptSpec;
9225}
9226
9227/// Determine whether the class type has any direct or indirect virtual base
9228/// classes which have a non-trivial move assignment operator.
9229static bool
9230hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9231  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9232                                          BaseEnd = ClassDecl->vbases_end();
9233       Base != BaseEnd; ++Base) {
9234    CXXRecordDecl *BaseClass =
9235        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9236
9237    // Try to declare the move assignment. If it would be deleted, then the
9238    // class does not have a non-trivial move assignment.
9239    if (BaseClass->needsImplicitMoveAssignment())
9240      S.DeclareImplicitMoveAssignment(BaseClass);
9241
9242    if (BaseClass->hasNonTrivialMoveAssignment())
9243      return true;
9244  }
9245
9246  return false;
9247}
9248
9249/// Determine whether the given type either has a move constructor or is
9250/// trivially copyable.
9251static bool
9252hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9253  Type = S.Context.getBaseElementType(Type);
9254
9255  // FIXME: Technically, non-trivially-copyable non-class types, such as
9256  // reference types, are supposed to return false here, but that appears
9257  // to be a standard defect.
9258  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
9259  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
9260    return true;
9261
9262  if (Type.isTriviallyCopyableType(S.Context))
9263    return true;
9264
9265  if (IsConstructor) {
9266    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9267    // give the right answer.
9268    if (ClassDecl->needsImplicitMoveConstructor())
9269      S.DeclareImplicitMoveConstructor(ClassDecl);
9270    return ClassDecl->hasMoveConstructor();
9271  }
9272
9273  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9274  // give the right answer.
9275  if (ClassDecl->needsImplicitMoveAssignment())
9276    S.DeclareImplicitMoveAssignment(ClassDecl);
9277  return ClassDecl->hasMoveAssignment();
9278}
9279
9280/// Determine whether all non-static data members and direct or virtual bases
9281/// of class \p ClassDecl have either a move operation, or are trivially
9282/// copyable.
9283static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9284                                            bool IsConstructor) {
9285  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9286                                          BaseEnd = ClassDecl->bases_end();
9287       Base != BaseEnd; ++Base) {
9288    if (Base->isVirtual())
9289      continue;
9290
9291    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9292      return false;
9293  }
9294
9295  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9296                                          BaseEnd = ClassDecl->vbases_end();
9297       Base != BaseEnd; ++Base) {
9298    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9299      return false;
9300  }
9301
9302  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9303                                     FieldEnd = ClassDecl->field_end();
9304       Field != FieldEnd; ++Field) {
9305    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9306      return false;
9307  }
9308
9309  return true;
9310}
9311
9312CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9313  // C++11 [class.copy]p20:
9314  //   If the definition of a class X does not explicitly declare a move
9315  //   assignment operator, one will be implicitly declared as defaulted
9316  //   if and only if:
9317  //
9318  //   - [first 4 bullets]
9319  assert(ClassDecl->needsImplicitMoveAssignment());
9320
9321  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9322  if (DSM.isAlreadyBeingDeclared())
9323    return 0;
9324
9325  // [Checked after we build the declaration]
9326  //   - the move assignment operator would not be implicitly defined as
9327  //     deleted,
9328
9329  // [DR1402]:
9330  //   - X has no direct or indirect virtual base class with a non-trivial
9331  //     move assignment operator, and
9332  //   - each of X's non-static data members and direct or virtual base classes
9333  //     has a type that either has a move assignment operator or is trivially
9334  //     copyable.
9335  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9336      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9337    ClassDecl->setFailedImplicitMoveAssignment();
9338    return 0;
9339  }
9340
9341  // Note: The following rules are largely analoguous to the move
9342  // constructor rules.
9343
9344  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9345  QualType RetType = Context.getLValueReferenceType(ArgType);
9346  ArgType = Context.getRValueReferenceType(ArgType);
9347
9348  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9349                                                     CXXMoveAssignment,
9350                                                     false);
9351
9352  //   An implicitly-declared move assignment operator is an inline public
9353  //   member of its class.
9354  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9355  SourceLocation ClassLoc = ClassDecl->getLocation();
9356  DeclarationNameInfo NameInfo(Name, ClassLoc);
9357  CXXMethodDecl *MoveAssignment =
9358      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9359                            /*TInfo=*/0, /*StorageClass=*/SC_None,
9360                            /*isInline=*/true, Constexpr, SourceLocation());
9361  MoveAssignment->setAccess(AS_public);
9362  MoveAssignment->setDefaulted();
9363  MoveAssignment->setImplicit();
9364
9365  // Build an exception specification pointing back at this member.
9366  FunctionProtoType::ExtProtoInfo EPI;
9367  EPI.ExceptionSpecType = EST_Unevaluated;
9368  EPI.ExceptionSpecDecl = MoveAssignment;
9369  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9370
9371  // Add the parameter to the operator.
9372  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9373                                               ClassLoc, ClassLoc, /*Id=*/0,
9374                                               ArgType, /*TInfo=*/0,
9375                                               SC_None, 0);
9376  MoveAssignment->setParams(FromParam);
9377
9378  AddOverriddenMethods(ClassDecl, MoveAssignment);
9379
9380  MoveAssignment->setTrivial(
9381    ClassDecl->needsOverloadResolutionForMoveAssignment()
9382      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9383      : ClassDecl->hasTrivialMoveAssignment());
9384
9385  // C++0x [class.copy]p9:
9386  //   If the definition of a class X does not explicitly declare a move
9387  //   assignment operator, one will be implicitly declared as defaulted if and
9388  //   only if:
9389  //   [...]
9390  //   - the move assignment operator would not be implicitly defined as
9391  //     deleted.
9392  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9393    // Cache this result so that we don't try to generate this over and over
9394    // on every lookup, leaking memory and wasting time.
9395    ClassDecl->setFailedImplicitMoveAssignment();
9396    return 0;
9397  }
9398
9399  // Note that we have added this copy-assignment operator.
9400  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9401
9402  if (Scope *S = getScopeForContext(ClassDecl))
9403    PushOnScopeChains(MoveAssignment, S, false);
9404  ClassDecl->addDecl(MoveAssignment);
9405
9406  return MoveAssignment;
9407}
9408
9409void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9410                                        CXXMethodDecl *MoveAssignOperator) {
9411  assert((MoveAssignOperator->isDefaulted() &&
9412          MoveAssignOperator->isOverloadedOperator() &&
9413          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9414          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9415          !MoveAssignOperator->isDeleted()) &&
9416         "DefineImplicitMoveAssignment called for wrong function");
9417
9418  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9419
9420  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9421    MoveAssignOperator->setInvalidDecl();
9422    return;
9423  }
9424
9425  MoveAssignOperator->setUsed();
9426
9427  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9428  DiagnosticErrorTrap Trap(Diags);
9429
9430  // C++0x [class.copy]p28:
9431  //   The implicitly-defined or move assignment operator for a non-union class
9432  //   X performs memberwise move assignment of its subobjects. The direct base
9433  //   classes of X are assigned first, in the order of their declaration in the
9434  //   base-specifier-list, and then the immediate non-static data members of X
9435  //   are assigned, in the order in which they were declared in the class
9436  //   definition.
9437
9438  // The statements that form the synthesized function body.
9439  SmallVector<Stmt*, 8> Statements;
9440
9441  // The parameter for the "other" object, which we are move from.
9442  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9443  QualType OtherRefType = Other->getType()->
9444      getAs<RValueReferenceType>()->getPointeeType();
9445  assert(!OtherRefType.getQualifiers() &&
9446         "Bad argument type of defaulted move assignment");
9447
9448  // Our location for everything implicitly-generated.
9449  SourceLocation Loc = MoveAssignOperator->getLocation();
9450
9451  // Construct a reference to the "other" object. We'll be using this
9452  // throughout the generated ASTs.
9453  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
9454  assert(OtherRef && "Reference to parameter cannot fail!");
9455  // Cast to rvalue.
9456  OtherRef = CastForMoving(*this, OtherRef);
9457
9458  // Construct the "this" pointer. We'll be using this throughout the generated
9459  // ASTs.
9460  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
9461  assert(This && "Reference to this cannot fail!");
9462
9463  // Assign base classes.
9464  bool Invalid = false;
9465  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9466       E = ClassDecl->bases_end(); Base != E; ++Base) {
9467    // Form the assignment:
9468    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9469    QualType BaseType = Base->getType().getUnqualifiedType();
9470    if (!BaseType->isRecordType()) {
9471      Invalid = true;
9472      continue;
9473    }
9474
9475    CXXCastPath BasePath;
9476    BasePath.push_back(Base);
9477
9478    // Construct the "from" expression, which is an implicit cast to the
9479    // appropriately-qualified base type.
9480    Expr *From = OtherRef;
9481    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
9482                             VK_XValue, &BasePath).take();
9483
9484    // Dereference "this".
9485    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9486
9487    // Implicitly cast "this" to the appropriately-qualified base type.
9488    To = ImpCastExprToType(To.take(),
9489                           Context.getCVRQualifiedType(BaseType,
9490                                     MoveAssignOperator->getTypeQualifiers()),
9491                           CK_UncheckedDerivedToBase,
9492                           VK_LValue, &BasePath);
9493
9494    // Build the move.
9495    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9496                                            To.get(), From,
9497                                            /*CopyingBaseSubobject=*/true,
9498                                            /*Copying=*/false);
9499    if (Move.isInvalid()) {
9500      Diag(CurrentLocation, diag::note_member_synthesized_at)
9501        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9502      MoveAssignOperator->setInvalidDecl();
9503      return;
9504    }
9505
9506    // Success! Record the move.
9507    Statements.push_back(Move.takeAs<Expr>());
9508  }
9509
9510  // Assign non-static members.
9511  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9512                                  FieldEnd = ClassDecl->field_end();
9513       Field != FieldEnd; ++Field) {
9514    if (Field->isUnnamedBitfield())
9515      continue;
9516
9517    if (Field->isInvalidDecl()) {
9518      Invalid = true;
9519      continue;
9520    }
9521
9522    // Check for members of reference type; we can't move those.
9523    if (Field->getType()->isReferenceType()) {
9524      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9525        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9526      Diag(Field->getLocation(), diag::note_declared_at);
9527      Diag(CurrentLocation, diag::note_member_synthesized_at)
9528        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9529      Invalid = true;
9530      continue;
9531    }
9532
9533    // Check for members of const-qualified, non-class type.
9534    QualType BaseType = Context.getBaseElementType(Field->getType());
9535    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9536      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9537        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9538      Diag(Field->getLocation(), diag::note_declared_at);
9539      Diag(CurrentLocation, diag::note_member_synthesized_at)
9540        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9541      Invalid = true;
9542      continue;
9543    }
9544
9545    // Suppress assigning zero-width bitfields.
9546    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9547      continue;
9548
9549    QualType FieldType = Field->getType().getNonReferenceType();
9550    if (FieldType->isIncompleteArrayType()) {
9551      assert(ClassDecl->hasFlexibleArrayMember() &&
9552             "Incomplete array type is not valid");
9553      continue;
9554    }
9555
9556    // Build references to the field in the object we're copying from and to.
9557    CXXScopeSpec SS; // Intentionally empty
9558    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9559                              LookupMemberName);
9560    MemberLookup.addDecl(*Field);
9561    MemberLookup.resolveKind();
9562    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
9563                                               Loc, /*IsArrow=*/false,
9564                                               SS, SourceLocation(), 0,
9565                                               MemberLookup, 0);
9566    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
9567                                             Loc, /*IsArrow=*/true,
9568                                             SS, SourceLocation(), 0,
9569                                             MemberLookup, 0);
9570    assert(!From.isInvalid() && "Implicit field reference cannot fail");
9571    assert(!To.isInvalid() && "Implicit field reference cannot fail");
9572
9573    assert(!From.get()->isLValue() && // could be xvalue or prvalue
9574        "Member reference with rvalue base must be rvalue except for reference "
9575        "members, which aren't allowed for move assignment.");
9576
9577    // Build the move of this field.
9578    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9579                                            To.get(), From.get(),
9580                                            /*CopyingBaseSubobject=*/false,
9581                                            /*Copying=*/false);
9582    if (Move.isInvalid()) {
9583      Diag(CurrentLocation, diag::note_member_synthesized_at)
9584        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9585      MoveAssignOperator->setInvalidDecl();
9586      return;
9587    }
9588
9589    // Success! Record the copy.
9590    Statements.push_back(Move.takeAs<Stmt>());
9591  }
9592
9593  if (!Invalid) {
9594    // Add a "return *this;"
9595    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
9596
9597    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9598    if (Return.isInvalid())
9599      Invalid = true;
9600    else {
9601      Statements.push_back(Return.takeAs<Stmt>());
9602
9603      if (Trap.hasErrorOccurred()) {
9604        Diag(CurrentLocation, diag::note_member_synthesized_at)
9605          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9606        Invalid = true;
9607      }
9608    }
9609  }
9610
9611  if (Invalid) {
9612    MoveAssignOperator->setInvalidDecl();
9613    return;
9614  }
9615
9616  StmtResult Body;
9617  {
9618    CompoundScopeRAII CompoundScope(*this);
9619    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9620                             /*isStmtExpr=*/false);
9621    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9622  }
9623  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9624
9625  if (ASTMutationListener *L = getASTMutationListener()) {
9626    L->CompletedImplicitDefinition(MoveAssignOperator);
9627  }
9628}
9629
9630Sema::ImplicitExceptionSpecification
9631Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9632  CXXRecordDecl *ClassDecl = MD->getParent();
9633
9634  ImplicitExceptionSpecification ExceptSpec(*this);
9635  if (ClassDecl->isInvalidDecl())
9636    return ExceptSpec;
9637
9638  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9639  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9640  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9641
9642  // C++ [except.spec]p14:
9643  //   An implicitly declared special member function (Clause 12) shall have an
9644  //   exception-specification. [...]
9645  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9646                                       BaseEnd = ClassDecl->bases_end();
9647       Base != BaseEnd;
9648       ++Base) {
9649    // Virtual bases are handled below.
9650    if (Base->isVirtual())
9651      continue;
9652
9653    CXXRecordDecl *BaseClassDecl
9654      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9655    if (CXXConstructorDecl *CopyConstructor =
9656          LookupCopyingConstructor(BaseClassDecl, Quals))
9657      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9658  }
9659  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9660                                       BaseEnd = ClassDecl->vbases_end();
9661       Base != BaseEnd;
9662       ++Base) {
9663    CXXRecordDecl *BaseClassDecl
9664      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9665    if (CXXConstructorDecl *CopyConstructor =
9666          LookupCopyingConstructor(BaseClassDecl, Quals))
9667      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9668  }
9669  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9670                                  FieldEnd = ClassDecl->field_end();
9671       Field != FieldEnd;
9672       ++Field) {
9673    QualType FieldType = Context.getBaseElementType(Field->getType());
9674    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9675      if (CXXConstructorDecl *CopyConstructor =
9676              LookupCopyingConstructor(FieldClassDecl,
9677                                       Quals | FieldType.getCVRQualifiers()))
9678      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
9679    }
9680  }
9681
9682  return ExceptSpec;
9683}
9684
9685CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
9686                                                    CXXRecordDecl *ClassDecl) {
9687  // C++ [class.copy]p4:
9688  //   If the class definition does not explicitly declare a copy
9689  //   constructor, one is declared implicitly.
9690  assert(ClassDecl->needsImplicitCopyConstructor());
9691
9692  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
9693  if (DSM.isAlreadyBeingDeclared())
9694    return 0;
9695
9696  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9697  QualType ArgType = ClassType;
9698  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
9699  if (Const)
9700    ArgType = ArgType.withConst();
9701  ArgType = Context.getLValueReferenceType(ArgType);
9702
9703  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9704                                                     CXXCopyConstructor,
9705                                                     Const);
9706
9707  DeclarationName Name
9708    = Context.DeclarationNames.getCXXConstructorName(
9709                                           Context.getCanonicalType(ClassType));
9710  SourceLocation ClassLoc = ClassDecl->getLocation();
9711  DeclarationNameInfo NameInfo(Name, ClassLoc);
9712
9713  //   An implicitly-declared copy constructor is an inline public
9714  //   member of its class.
9715  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
9716      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9717      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9718      Constexpr);
9719  CopyConstructor->setAccess(AS_public);
9720  CopyConstructor->setDefaulted();
9721
9722  // Build an exception specification pointing back at this member.
9723  FunctionProtoType::ExtProtoInfo EPI;
9724  EPI.ExceptionSpecType = EST_Unevaluated;
9725  EPI.ExceptionSpecDecl = CopyConstructor;
9726  CopyConstructor->setType(
9727      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9728
9729  // Add the parameter to the constructor.
9730  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
9731                                               ClassLoc, ClassLoc,
9732                                               /*IdentifierInfo=*/0,
9733                                               ArgType, /*TInfo=*/0,
9734                                               SC_None, 0);
9735  CopyConstructor->setParams(FromParam);
9736
9737  CopyConstructor->setTrivial(
9738    ClassDecl->needsOverloadResolutionForCopyConstructor()
9739      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
9740      : ClassDecl->hasTrivialCopyConstructor());
9741
9742  // C++11 [class.copy]p8:
9743  //   ... If the class definition does not explicitly declare a copy
9744  //   constructor, there is no user-declared move constructor, and there is no
9745  //   user-declared move assignment operator, a copy constructor is implicitly
9746  //   declared as defaulted.
9747  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
9748    SetDeclDeleted(CopyConstructor, ClassLoc);
9749
9750  // Note that we have declared this constructor.
9751  ++ASTContext::NumImplicitCopyConstructorsDeclared;
9752
9753  if (Scope *S = getScopeForContext(ClassDecl))
9754    PushOnScopeChains(CopyConstructor, S, false);
9755  ClassDecl->addDecl(CopyConstructor);
9756
9757  return CopyConstructor;
9758}
9759
9760void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
9761                                   CXXConstructorDecl *CopyConstructor) {
9762  assert((CopyConstructor->isDefaulted() &&
9763          CopyConstructor->isCopyConstructor() &&
9764          !CopyConstructor->doesThisDeclarationHaveABody() &&
9765          !CopyConstructor->isDeleted()) &&
9766         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
9767
9768  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
9769  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
9770
9771  // C++11 [class.copy]p7:
9772  //   The [definition of an implicitly declared copy constructro] is
9773  //   deprecated if the class has a user-declared copy assignment operator
9774  //   or a user-declared destructor.
9775  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
9776    diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
9777
9778  SynthesizedFunctionScope Scope(*this, CopyConstructor);
9779  DiagnosticErrorTrap Trap(Diags);
9780
9781  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
9782      Trap.hasErrorOccurred()) {
9783    Diag(CurrentLocation, diag::note_member_synthesized_at)
9784      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
9785    CopyConstructor->setInvalidDecl();
9786  }  else {
9787    Sema::CompoundScopeRAII CompoundScope(*this);
9788    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
9789                                               CopyConstructor->getLocation(),
9790                                               MultiStmtArg(),
9791                                               /*isStmtExpr=*/false)
9792                                                              .takeAs<Stmt>());
9793    CopyConstructor->setImplicitlyDefined(true);
9794  }
9795
9796  CopyConstructor->setUsed();
9797  if (ASTMutationListener *L = getASTMutationListener()) {
9798    L->CompletedImplicitDefinition(CopyConstructor);
9799  }
9800}
9801
9802Sema::ImplicitExceptionSpecification
9803Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
9804  CXXRecordDecl *ClassDecl = MD->getParent();
9805
9806  // C++ [except.spec]p14:
9807  //   An implicitly declared special member function (Clause 12) shall have an
9808  //   exception-specification. [...]
9809  ImplicitExceptionSpecification ExceptSpec(*this);
9810  if (ClassDecl->isInvalidDecl())
9811    return ExceptSpec;
9812
9813  // Direct base-class constructors.
9814  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
9815                                       BEnd = ClassDecl->bases_end();
9816       B != BEnd; ++B) {
9817    if (B->isVirtual()) // Handled below.
9818      continue;
9819
9820    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9821      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9822      CXXConstructorDecl *Constructor =
9823          LookupMovingConstructor(BaseClassDecl, 0);
9824      // If this is a deleted function, add it anyway. This might be conformant
9825      // with the standard. This might not. I'm not sure. It might not matter.
9826      if (Constructor)
9827        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9828    }
9829  }
9830
9831  // Virtual base-class constructors.
9832  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
9833                                       BEnd = ClassDecl->vbases_end();
9834       B != BEnd; ++B) {
9835    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
9836      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
9837      CXXConstructorDecl *Constructor =
9838          LookupMovingConstructor(BaseClassDecl, 0);
9839      // If this is a deleted function, add it anyway. This might be conformant
9840      // with the standard. This might not. I'm not sure. It might not matter.
9841      if (Constructor)
9842        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
9843    }
9844  }
9845
9846  // Field constructors.
9847  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
9848                               FEnd = ClassDecl->field_end();
9849       F != FEnd; ++F) {
9850    QualType FieldType = Context.getBaseElementType(F->getType());
9851    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
9852      CXXConstructorDecl *Constructor =
9853          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
9854      // If this is a deleted function, add it anyway. This might be conformant
9855      // with the standard. This might not. I'm not sure. It might not matter.
9856      // In particular, the problem is that this function never gets called. It
9857      // might just be ill-formed because this function attempts to refer to
9858      // a deleted function here.
9859      if (Constructor)
9860        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
9861    }
9862  }
9863
9864  return ExceptSpec;
9865}
9866
9867CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
9868                                                    CXXRecordDecl *ClassDecl) {
9869  // C++11 [class.copy]p9:
9870  //   If the definition of a class X does not explicitly declare a move
9871  //   constructor, one will be implicitly declared as defaulted if and only if:
9872  //
9873  //   - [first 4 bullets]
9874  assert(ClassDecl->needsImplicitMoveConstructor());
9875
9876  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
9877  if (DSM.isAlreadyBeingDeclared())
9878    return 0;
9879
9880  // [Checked after we build the declaration]
9881  //   - the move assignment operator would not be implicitly defined as
9882  //     deleted,
9883
9884  // [DR1402]:
9885  //   - each of X's non-static data members and direct or virtual base classes
9886  //     has a type that either has a move constructor or is trivially copyable.
9887  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
9888    ClassDecl->setFailedImplicitMoveConstructor();
9889    return 0;
9890  }
9891
9892  QualType ClassType = Context.getTypeDeclType(ClassDecl);
9893  QualType ArgType = Context.getRValueReferenceType(ClassType);
9894
9895  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9896                                                     CXXMoveConstructor,
9897                                                     false);
9898
9899  DeclarationName Name
9900    = Context.DeclarationNames.getCXXConstructorName(
9901                                           Context.getCanonicalType(ClassType));
9902  SourceLocation ClassLoc = ClassDecl->getLocation();
9903  DeclarationNameInfo NameInfo(Name, ClassLoc);
9904
9905  // C++11 [class.copy]p11:
9906  //   An implicitly-declared copy/move constructor is an inline public
9907  //   member of its class.
9908  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
9909      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
9910      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
9911      Constexpr);
9912  MoveConstructor->setAccess(AS_public);
9913  MoveConstructor->setDefaulted();
9914
9915  // Build an exception specification pointing back at this member.
9916  FunctionProtoType::ExtProtoInfo EPI;
9917  EPI.ExceptionSpecType = EST_Unevaluated;
9918  EPI.ExceptionSpecDecl = MoveConstructor;
9919  MoveConstructor->setType(
9920      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
9921
9922  // Add the parameter to the constructor.
9923  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
9924                                               ClassLoc, ClassLoc,
9925                                               /*IdentifierInfo=*/0,
9926                                               ArgType, /*TInfo=*/0,
9927                                               SC_None, 0);
9928  MoveConstructor->setParams(FromParam);
9929
9930  MoveConstructor->setTrivial(
9931    ClassDecl->needsOverloadResolutionForMoveConstructor()
9932      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
9933      : ClassDecl->hasTrivialMoveConstructor());
9934
9935  // C++0x [class.copy]p9:
9936  //   If the definition of a class X does not explicitly declare a move
9937  //   constructor, one will be implicitly declared as defaulted if and only if:
9938  //   [...]
9939  //   - the move constructor would not be implicitly defined as deleted.
9940  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
9941    // Cache this result so that we don't try to generate this over and over
9942    // on every lookup, leaking memory and wasting time.
9943    ClassDecl->setFailedImplicitMoveConstructor();
9944    return 0;
9945  }
9946
9947  // Note that we have declared this constructor.
9948  ++ASTContext::NumImplicitMoveConstructorsDeclared;
9949
9950  if (Scope *S = getScopeForContext(ClassDecl))
9951    PushOnScopeChains(MoveConstructor, S, false);
9952  ClassDecl->addDecl(MoveConstructor);
9953
9954  return MoveConstructor;
9955}
9956
9957void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
9958                                   CXXConstructorDecl *MoveConstructor) {
9959  assert((MoveConstructor->isDefaulted() &&
9960          MoveConstructor->isMoveConstructor() &&
9961          !MoveConstructor->doesThisDeclarationHaveABody() &&
9962          !MoveConstructor->isDeleted()) &&
9963         "DefineImplicitMoveConstructor - call it for implicit move ctor");
9964
9965  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
9966  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
9967
9968  SynthesizedFunctionScope Scope(*this, MoveConstructor);
9969  DiagnosticErrorTrap Trap(Diags);
9970
9971  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
9972      Trap.hasErrorOccurred()) {
9973    Diag(CurrentLocation, diag::note_member_synthesized_at)
9974      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
9975    MoveConstructor->setInvalidDecl();
9976  }  else {
9977    Sema::CompoundScopeRAII CompoundScope(*this);
9978    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
9979                                               MoveConstructor->getLocation(),
9980                                               MultiStmtArg(),
9981                                               /*isStmtExpr=*/false)
9982                                                              .takeAs<Stmt>());
9983    MoveConstructor->setImplicitlyDefined(true);
9984  }
9985
9986  MoveConstructor->setUsed();
9987
9988  if (ASTMutationListener *L = getASTMutationListener()) {
9989    L->CompletedImplicitDefinition(MoveConstructor);
9990  }
9991}
9992
9993bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
9994  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
9995}
9996
9997/// \brief Mark the call operator of the given lambda closure type as "used".
9998static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
9999  CXXMethodDecl *CallOperator
10000    = cast<CXXMethodDecl>(
10001        Lambda->lookup(
10002          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
10003  CallOperator->setReferenced();
10004  CallOperator->setUsed();
10005}
10006
10007void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10008       SourceLocation CurrentLocation,
10009       CXXConversionDecl *Conv)
10010{
10011  CXXRecordDecl *Lambda = Conv->getParent();
10012
10013  // Make sure that the lambda call operator is marked used.
10014  markLambdaCallOperatorUsed(*this, Lambda);
10015
10016  Conv->setUsed();
10017
10018  SynthesizedFunctionScope Scope(*this, Conv);
10019  DiagnosticErrorTrap Trap(Diags);
10020
10021  // Return the address of the __invoke function.
10022  DeclarationName InvokeName = &Context.Idents.get("__invoke");
10023  CXXMethodDecl *Invoke
10024    = cast<CXXMethodDecl>(Lambda->lookup(InvokeName).front());
10025  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
10026                                       VK_LValue, Conv->getLocation()).take();
10027  assert(FunctionRef && "Can't refer to __invoke function?");
10028  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10029  Conv->setBody(new (Context) CompoundStmt(Context, Return,
10030                                           Conv->getLocation(),
10031                                           Conv->getLocation()));
10032
10033  // Fill in the __invoke function with a dummy implementation. IR generation
10034  // will fill in the actual details.
10035  Invoke->setUsed();
10036  Invoke->setReferenced();
10037  Invoke->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10038
10039  if (ASTMutationListener *L = getASTMutationListener()) {
10040    L->CompletedImplicitDefinition(Conv);
10041    L->CompletedImplicitDefinition(Invoke);
10042  }
10043}
10044
10045void Sema::DefineImplicitLambdaToBlockPointerConversion(
10046       SourceLocation CurrentLocation,
10047       CXXConversionDecl *Conv)
10048{
10049  Conv->setUsed();
10050
10051  SynthesizedFunctionScope Scope(*this, Conv);
10052  DiagnosticErrorTrap Trap(Diags);
10053
10054  // Copy-initialize the lambda object as needed to capture it.
10055  Expr *This = ActOnCXXThis(CurrentLocation).take();
10056  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10057
10058  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10059                                                        Conv->getLocation(),
10060                                                        Conv, DerefThis);
10061
10062  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10063  // behavior.  Note that only the general conversion function does this
10064  // (since it's unusable otherwise); in the case where we inline the
10065  // block literal, it has block literal lifetime semantics.
10066  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10067    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10068                                          CK_CopyAndAutoreleaseBlockObject,
10069                                          BuildBlock.get(), 0, VK_RValue);
10070
10071  if (BuildBlock.isInvalid()) {
10072    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10073    Conv->setInvalidDecl();
10074    return;
10075  }
10076
10077  // Create the return statement that returns the block from the conversion
10078  // function.
10079  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10080  if (Return.isInvalid()) {
10081    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10082    Conv->setInvalidDecl();
10083    return;
10084  }
10085
10086  // Set the body of the conversion function.
10087  Stmt *ReturnS = Return.take();
10088  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10089                                           Conv->getLocation(),
10090                                           Conv->getLocation()));
10091
10092  // We're done; notify the mutation listener, if any.
10093  if (ASTMutationListener *L = getASTMutationListener()) {
10094    L->CompletedImplicitDefinition(Conv);
10095  }
10096}
10097
10098/// \brief Determine whether the given list arguments contains exactly one
10099/// "real" (non-default) argument.
10100static bool hasOneRealArgument(MultiExprArg Args) {
10101  switch (Args.size()) {
10102  case 0:
10103    return false;
10104
10105  default:
10106    if (!Args[1]->isDefaultArgument())
10107      return false;
10108
10109    // fall through
10110  case 1:
10111    return !Args[0]->isDefaultArgument();
10112  }
10113
10114  return false;
10115}
10116
10117ExprResult
10118Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10119                            CXXConstructorDecl *Constructor,
10120                            MultiExprArg ExprArgs,
10121                            bool HadMultipleCandidates,
10122                            bool IsListInitialization,
10123                            bool RequiresZeroInit,
10124                            unsigned ConstructKind,
10125                            SourceRange ParenRange) {
10126  bool Elidable = false;
10127
10128  // C++0x [class.copy]p34:
10129  //   When certain criteria are met, an implementation is allowed to
10130  //   omit the copy/move construction of a class object, even if the
10131  //   copy/move constructor and/or destructor for the object have
10132  //   side effects. [...]
10133  //     - when a temporary class object that has not been bound to a
10134  //       reference (12.2) would be copied/moved to a class object
10135  //       with the same cv-unqualified type, the copy/move operation
10136  //       can be omitted by constructing the temporary object
10137  //       directly into the target of the omitted copy/move
10138  if (ConstructKind == CXXConstructExpr::CK_Complete &&
10139      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10140    Expr *SubExpr = ExprArgs[0];
10141    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10142  }
10143
10144  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10145                               Elidable, ExprArgs, HadMultipleCandidates,
10146                               IsListInitialization, RequiresZeroInit,
10147                               ConstructKind, ParenRange);
10148}
10149
10150/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10151/// including handling of its default argument expressions.
10152ExprResult
10153Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10154                            CXXConstructorDecl *Constructor, bool Elidable,
10155                            MultiExprArg ExprArgs,
10156                            bool HadMultipleCandidates,
10157                            bool IsListInitialization,
10158                            bool RequiresZeroInit,
10159                            unsigned ConstructKind,
10160                            SourceRange ParenRange) {
10161  MarkFunctionReferenced(ConstructLoc, Constructor);
10162  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10163                                        Constructor, Elidable, ExprArgs,
10164                                        HadMultipleCandidates,
10165                                        IsListInitialization, RequiresZeroInit,
10166              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10167                                        ParenRange));
10168}
10169
10170void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10171  if (VD->isInvalidDecl()) return;
10172
10173  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10174  if (ClassDecl->isInvalidDecl()) return;
10175  if (ClassDecl->hasIrrelevantDestructor()) return;
10176  if (ClassDecl->isDependentContext()) return;
10177
10178  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10179  MarkFunctionReferenced(VD->getLocation(), Destructor);
10180  CheckDestructorAccess(VD->getLocation(), Destructor,
10181                        PDiag(diag::err_access_dtor_var)
10182                        << VD->getDeclName()
10183                        << VD->getType());
10184  DiagnoseUseOfDecl(Destructor, VD->getLocation());
10185
10186  if (!VD->hasGlobalStorage()) return;
10187
10188  // Emit warning for non-trivial dtor in global scope (a real global,
10189  // class-static, function-static).
10190  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10191
10192  // TODO: this should be re-enabled for static locals by !CXAAtExit
10193  if (!VD->isStaticLocal())
10194    Diag(VD->getLocation(), diag::warn_global_destructor);
10195}
10196
10197/// \brief Given a constructor and the set of arguments provided for the
10198/// constructor, convert the arguments and add any required default arguments
10199/// to form a proper call to this constructor.
10200///
10201/// \returns true if an error occurred, false otherwise.
10202bool
10203Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10204                              MultiExprArg ArgsPtr,
10205                              SourceLocation Loc,
10206                              SmallVectorImpl<Expr*> &ConvertedArgs,
10207                              bool AllowExplicit,
10208                              bool IsListInitialization) {
10209  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10210  unsigned NumArgs = ArgsPtr.size();
10211  Expr **Args = ArgsPtr.data();
10212
10213  const FunctionProtoType *Proto
10214    = Constructor->getType()->getAs<FunctionProtoType>();
10215  assert(Proto && "Constructor without a prototype?");
10216  unsigned NumArgsInProto = Proto->getNumArgs();
10217
10218  // If too few arguments are available, we'll fill in the rest with defaults.
10219  if (NumArgs < NumArgsInProto)
10220    ConvertedArgs.reserve(NumArgsInProto);
10221  else
10222    ConvertedArgs.reserve(NumArgs);
10223
10224  VariadicCallType CallType =
10225    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10226  SmallVector<Expr *, 8> AllArgs;
10227  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10228                                        Proto, 0,
10229                                        llvm::makeArrayRef(Args, NumArgs),
10230                                        AllArgs,
10231                                        CallType, AllowExplicit,
10232                                        IsListInitialization);
10233  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10234
10235  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10236
10237  CheckConstructorCall(Constructor,
10238                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10239                                                        AllArgs.size()),
10240                       Proto, Loc);
10241
10242  return Invalid;
10243}
10244
10245static inline bool
10246CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10247                                       const FunctionDecl *FnDecl) {
10248  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10249  if (isa<NamespaceDecl>(DC)) {
10250    return SemaRef.Diag(FnDecl->getLocation(),
10251                        diag::err_operator_new_delete_declared_in_namespace)
10252      << FnDecl->getDeclName();
10253  }
10254
10255  if (isa<TranslationUnitDecl>(DC) &&
10256      FnDecl->getStorageClass() == SC_Static) {
10257    return SemaRef.Diag(FnDecl->getLocation(),
10258                        diag::err_operator_new_delete_declared_static)
10259      << FnDecl->getDeclName();
10260  }
10261
10262  return false;
10263}
10264
10265static inline bool
10266CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10267                            CanQualType ExpectedResultType,
10268                            CanQualType ExpectedFirstParamType,
10269                            unsigned DependentParamTypeDiag,
10270                            unsigned InvalidParamTypeDiag) {
10271  QualType ResultType =
10272    FnDecl->getType()->getAs<FunctionType>()->getResultType();
10273
10274  // Check that the result type is not dependent.
10275  if (ResultType->isDependentType())
10276    return SemaRef.Diag(FnDecl->getLocation(),
10277                        diag::err_operator_new_delete_dependent_result_type)
10278    << FnDecl->getDeclName() << ExpectedResultType;
10279
10280  // Check that the result type is what we expect.
10281  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10282    return SemaRef.Diag(FnDecl->getLocation(),
10283                        diag::err_operator_new_delete_invalid_result_type)
10284    << FnDecl->getDeclName() << ExpectedResultType;
10285
10286  // A function template must have at least 2 parameters.
10287  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10288    return SemaRef.Diag(FnDecl->getLocation(),
10289                      diag::err_operator_new_delete_template_too_few_parameters)
10290        << FnDecl->getDeclName();
10291
10292  // The function decl must have at least 1 parameter.
10293  if (FnDecl->getNumParams() == 0)
10294    return SemaRef.Diag(FnDecl->getLocation(),
10295                        diag::err_operator_new_delete_too_few_parameters)
10296      << FnDecl->getDeclName();
10297
10298  // Check the first parameter type is not dependent.
10299  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10300  if (FirstParamType->isDependentType())
10301    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10302      << FnDecl->getDeclName() << ExpectedFirstParamType;
10303
10304  // Check that the first parameter type is what we expect.
10305  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10306      ExpectedFirstParamType)
10307    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10308    << FnDecl->getDeclName() << ExpectedFirstParamType;
10309
10310  return false;
10311}
10312
10313static bool
10314CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10315  // C++ [basic.stc.dynamic.allocation]p1:
10316  //   A program is ill-formed if an allocation function is declared in a
10317  //   namespace scope other than global scope or declared static in global
10318  //   scope.
10319  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10320    return true;
10321
10322  CanQualType SizeTy =
10323    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10324
10325  // C++ [basic.stc.dynamic.allocation]p1:
10326  //  The return type shall be void*. The first parameter shall have type
10327  //  std::size_t.
10328  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10329                                  SizeTy,
10330                                  diag::err_operator_new_dependent_param_type,
10331                                  diag::err_operator_new_param_type))
10332    return true;
10333
10334  // C++ [basic.stc.dynamic.allocation]p1:
10335  //  The first parameter shall not have an associated default argument.
10336  if (FnDecl->getParamDecl(0)->hasDefaultArg())
10337    return SemaRef.Diag(FnDecl->getLocation(),
10338                        diag::err_operator_new_default_arg)
10339      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10340
10341  return false;
10342}
10343
10344static bool
10345CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10346  // C++ [basic.stc.dynamic.deallocation]p1:
10347  //   A program is ill-formed if deallocation functions are declared in a
10348  //   namespace scope other than global scope or declared static in global
10349  //   scope.
10350  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10351    return true;
10352
10353  // C++ [basic.stc.dynamic.deallocation]p2:
10354  //   Each deallocation function shall return void and its first parameter
10355  //   shall be void*.
10356  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10357                                  SemaRef.Context.VoidPtrTy,
10358                                 diag::err_operator_delete_dependent_param_type,
10359                                 diag::err_operator_delete_param_type))
10360    return true;
10361
10362  return false;
10363}
10364
10365/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10366/// of this overloaded operator is well-formed. If so, returns false;
10367/// otherwise, emits appropriate diagnostics and returns true.
10368bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10369  assert(FnDecl && FnDecl->isOverloadedOperator() &&
10370         "Expected an overloaded operator declaration");
10371
10372  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10373
10374  // C++ [over.oper]p5:
10375  //   The allocation and deallocation functions, operator new,
10376  //   operator new[], operator delete and operator delete[], are
10377  //   described completely in 3.7.3. The attributes and restrictions
10378  //   found in the rest of this subclause do not apply to them unless
10379  //   explicitly stated in 3.7.3.
10380  if (Op == OO_Delete || Op == OO_Array_Delete)
10381    return CheckOperatorDeleteDeclaration(*this, FnDecl);
10382
10383  if (Op == OO_New || Op == OO_Array_New)
10384    return CheckOperatorNewDeclaration(*this, FnDecl);
10385
10386  // C++ [over.oper]p6:
10387  //   An operator function shall either be a non-static member
10388  //   function or be a non-member function and have at least one
10389  //   parameter whose type is a class, a reference to a class, an
10390  //   enumeration, or a reference to an enumeration.
10391  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10392    if (MethodDecl->isStatic())
10393      return Diag(FnDecl->getLocation(),
10394                  diag::err_operator_overload_static) << FnDecl->getDeclName();
10395  } else {
10396    bool ClassOrEnumParam = false;
10397    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10398                                   ParamEnd = FnDecl->param_end();
10399         Param != ParamEnd; ++Param) {
10400      QualType ParamType = (*Param)->getType().getNonReferenceType();
10401      if (ParamType->isDependentType() || ParamType->isRecordType() ||
10402          ParamType->isEnumeralType()) {
10403        ClassOrEnumParam = true;
10404        break;
10405      }
10406    }
10407
10408    if (!ClassOrEnumParam)
10409      return Diag(FnDecl->getLocation(),
10410                  diag::err_operator_overload_needs_class_or_enum)
10411        << FnDecl->getDeclName();
10412  }
10413
10414  // C++ [over.oper]p8:
10415  //   An operator function cannot have default arguments (8.3.6),
10416  //   except where explicitly stated below.
10417  //
10418  // Only the function-call operator allows default arguments
10419  // (C++ [over.call]p1).
10420  if (Op != OO_Call) {
10421    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10422         Param != FnDecl->param_end(); ++Param) {
10423      if ((*Param)->hasDefaultArg())
10424        return Diag((*Param)->getLocation(),
10425                    diag::err_operator_overload_default_arg)
10426          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10427    }
10428  }
10429
10430  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10431    { false, false, false }
10432#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10433    , { Unary, Binary, MemberOnly }
10434#include "clang/Basic/OperatorKinds.def"
10435  };
10436
10437  bool CanBeUnaryOperator = OperatorUses[Op][0];
10438  bool CanBeBinaryOperator = OperatorUses[Op][1];
10439  bool MustBeMemberOperator = OperatorUses[Op][2];
10440
10441  // C++ [over.oper]p8:
10442  //   [...] Operator functions cannot have more or fewer parameters
10443  //   than the number required for the corresponding operator, as
10444  //   described in the rest of this subclause.
10445  unsigned NumParams = FnDecl->getNumParams()
10446                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10447  if (Op != OO_Call &&
10448      ((NumParams == 1 && !CanBeUnaryOperator) ||
10449       (NumParams == 2 && !CanBeBinaryOperator) ||
10450       (NumParams < 1) || (NumParams > 2))) {
10451    // We have the wrong number of parameters.
10452    unsigned ErrorKind;
10453    if (CanBeUnaryOperator && CanBeBinaryOperator) {
10454      ErrorKind = 2;  // 2 -> unary or binary.
10455    } else if (CanBeUnaryOperator) {
10456      ErrorKind = 0;  // 0 -> unary
10457    } else {
10458      assert(CanBeBinaryOperator &&
10459             "All non-call overloaded operators are unary or binary!");
10460      ErrorKind = 1;  // 1 -> binary
10461    }
10462
10463    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10464      << FnDecl->getDeclName() << NumParams << ErrorKind;
10465  }
10466
10467  // Overloaded operators other than operator() cannot be variadic.
10468  if (Op != OO_Call &&
10469      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10470    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10471      << FnDecl->getDeclName();
10472  }
10473
10474  // Some operators must be non-static member functions.
10475  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10476    return Diag(FnDecl->getLocation(),
10477                diag::err_operator_overload_must_be_member)
10478      << FnDecl->getDeclName();
10479  }
10480
10481  // C++ [over.inc]p1:
10482  //   The user-defined function called operator++ implements the
10483  //   prefix and postfix ++ operator. If this function is a member
10484  //   function with no parameters, or a non-member function with one
10485  //   parameter of class or enumeration type, it defines the prefix
10486  //   increment operator ++ for objects of that type. If the function
10487  //   is a member function with one parameter (which shall be of type
10488  //   int) or a non-member function with two parameters (the second
10489  //   of which shall be of type int), it defines the postfix
10490  //   increment operator ++ for objects of that type.
10491  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10492    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10493    bool ParamIsInt = false;
10494    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10495      ParamIsInt = BT->getKind() == BuiltinType::Int;
10496
10497    if (!ParamIsInt)
10498      return Diag(LastParam->getLocation(),
10499                  diag::err_operator_overload_post_incdec_must_be_int)
10500        << LastParam->getType() << (Op == OO_MinusMinus);
10501  }
10502
10503  return false;
10504}
10505
10506/// CheckLiteralOperatorDeclaration - Check whether the declaration
10507/// of this literal operator function is well-formed. If so, returns
10508/// false; otherwise, emits appropriate diagnostics and returns true.
10509bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10510  if (isa<CXXMethodDecl>(FnDecl)) {
10511    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10512      << FnDecl->getDeclName();
10513    return true;
10514  }
10515
10516  if (FnDecl->isExternC()) {
10517    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10518    return true;
10519  }
10520
10521  bool Valid = false;
10522
10523  // This might be the definition of a literal operator template.
10524  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10525  // This might be a specialization of a literal operator template.
10526  if (!TpDecl)
10527    TpDecl = FnDecl->getPrimaryTemplate();
10528
10529  // template <char...> type operator "" name() is the only valid template
10530  // signature, and the only valid signature with no parameters.
10531  if (TpDecl) {
10532    if (FnDecl->param_size() == 0) {
10533      // Must have only one template parameter
10534      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10535      if (Params->size() == 1) {
10536        NonTypeTemplateParmDecl *PmDecl =
10537          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10538
10539        // The template parameter must be a char parameter pack.
10540        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10541            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10542          Valid = true;
10543      }
10544    }
10545  } else if (FnDecl->param_size()) {
10546    // Check the first parameter
10547    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10548
10549    QualType T = (*Param)->getType().getUnqualifiedType();
10550
10551    // unsigned long long int, long double, and any character type are allowed
10552    // as the only parameters.
10553    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10554        Context.hasSameType(T, Context.LongDoubleTy) ||
10555        Context.hasSameType(T, Context.CharTy) ||
10556        Context.hasSameType(T, Context.WideCharTy) ||
10557        Context.hasSameType(T, Context.Char16Ty) ||
10558        Context.hasSameType(T, Context.Char32Ty)) {
10559      if (++Param == FnDecl->param_end())
10560        Valid = true;
10561      goto FinishedParams;
10562    }
10563
10564    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10565    const PointerType *PT = T->getAs<PointerType>();
10566    if (!PT)
10567      goto FinishedParams;
10568    T = PT->getPointeeType();
10569    if (!T.isConstQualified() || T.isVolatileQualified())
10570      goto FinishedParams;
10571    T = T.getUnqualifiedType();
10572
10573    // Move on to the second parameter;
10574    ++Param;
10575
10576    // If there is no second parameter, the first must be a const char *
10577    if (Param == FnDecl->param_end()) {
10578      if (Context.hasSameType(T, Context.CharTy))
10579        Valid = true;
10580      goto FinishedParams;
10581    }
10582
10583    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10584    // are allowed as the first parameter to a two-parameter function
10585    if (!(Context.hasSameType(T, Context.CharTy) ||
10586          Context.hasSameType(T, Context.WideCharTy) ||
10587          Context.hasSameType(T, Context.Char16Ty) ||
10588          Context.hasSameType(T, Context.Char32Ty)))
10589      goto FinishedParams;
10590
10591    // The second and final parameter must be an std::size_t
10592    T = (*Param)->getType().getUnqualifiedType();
10593    if (Context.hasSameType(T, Context.getSizeType()) &&
10594        ++Param == FnDecl->param_end())
10595      Valid = true;
10596  }
10597
10598  // FIXME: This diagnostic is absolutely terrible.
10599FinishedParams:
10600  if (!Valid) {
10601    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10602      << FnDecl->getDeclName();
10603    return true;
10604  }
10605
10606  // A parameter-declaration-clause containing a default argument is not
10607  // equivalent to any of the permitted forms.
10608  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10609                                    ParamEnd = FnDecl->param_end();
10610       Param != ParamEnd; ++Param) {
10611    if ((*Param)->hasDefaultArg()) {
10612      Diag((*Param)->getDefaultArgRange().getBegin(),
10613           diag::err_literal_operator_default_argument)
10614        << (*Param)->getDefaultArgRange();
10615      break;
10616    }
10617  }
10618
10619  StringRef LiteralName
10620    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10621  if (LiteralName[0] != '_') {
10622    // C++11 [usrlit.suffix]p1:
10623    //   Literal suffix identifiers that do not start with an underscore
10624    //   are reserved for future standardization.
10625    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
10626  }
10627
10628  return false;
10629}
10630
10631/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
10632/// linkage specification, including the language and (if present)
10633/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
10634/// the location of the language string literal, which is provided
10635/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
10636/// the '{' brace. Otherwise, this linkage specification does not
10637/// have any braces.
10638Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
10639                                           SourceLocation LangLoc,
10640                                           StringRef Lang,
10641                                           SourceLocation LBraceLoc) {
10642  LinkageSpecDecl::LanguageIDs Language;
10643  if (Lang == "\"C\"")
10644    Language = LinkageSpecDecl::lang_c;
10645  else if (Lang == "\"C++\"")
10646    Language = LinkageSpecDecl::lang_cxx;
10647  else {
10648    Diag(LangLoc, diag::err_bad_language);
10649    return 0;
10650  }
10651
10652  // FIXME: Add all the various semantics of linkage specifications
10653
10654  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
10655                                               ExternLoc, LangLoc, Language,
10656                                               LBraceLoc.isValid());
10657  CurContext->addDecl(D);
10658  PushDeclContext(S, D);
10659  return D;
10660}
10661
10662/// ActOnFinishLinkageSpecification - Complete the definition of
10663/// the C++ linkage specification LinkageSpec. If RBraceLoc is
10664/// valid, it's the position of the closing '}' brace in a linkage
10665/// specification that uses braces.
10666Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
10667                                            Decl *LinkageSpec,
10668                                            SourceLocation RBraceLoc) {
10669  if (LinkageSpec) {
10670    if (RBraceLoc.isValid()) {
10671      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
10672      LSDecl->setRBraceLoc(RBraceLoc);
10673    }
10674    PopDeclContext();
10675  }
10676  return LinkageSpec;
10677}
10678
10679Decl *Sema::ActOnEmptyDeclaration(Scope *S,
10680                                  AttributeList *AttrList,
10681                                  SourceLocation SemiLoc) {
10682  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
10683  // Attribute declarations appertain to empty declaration so we handle
10684  // them here.
10685  if (AttrList)
10686    ProcessDeclAttributeList(S, ED, AttrList);
10687
10688  CurContext->addDecl(ED);
10689  return ED;
10690}
10691
10692/// \brief Perform semantic analysis for the variable declaration that
10693/// occurs within a C++ catch clause, returning the newly-created
10694/// variable.
10695VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
10696                                         TypeSourceInfo *TInfo,
10697                                         SourceLocation StartLoc,
10698                                         SourceLocation Loc,
10699                                         IdentifierInfo *Name) {
10700  bool Invalid = false;
10701  QualType ExDeclType = TInfo->getType();
10702
10703  // Arrays and functions decay.
10704  if (ExDeclType->isArrayType())
10705    ExDeclType = Context.getArrayDecayedType(ExDeclType);
10706  else if (ExDeclType->isFunctionType())
10707    ExDeclType = Context.getPointerType(ExDeclType);
10708
10709  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
10710  // The exception-declaration shall not denote a pointer or reference to an
10711  // incomplete type, other than [cv] void*.
10712  // N2844 forbids rvalue references.
10713  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
10714    Diag(Loc, diag::err_catch_rvalue_ref);
10715    Invalid = true;
10716  }
10717
10718  QualType BaseType = ExDeclType;
10719  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
10720  unsigned DK = diag::err_catch_incomplete;
10721  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
10722    BaseType = Ptr->getPointeeType();
10723    Mode = 1;
10724    DK = diag::err_catch_incomplete_ptr;
10725  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
10726    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
10727    BaseType = Ref->getPointeeType();
10728    Mode = 2;
10729    DK = diag::err_catch_incomplete_ref;
10730  }
10731  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
10732      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
10733    Invalid = true;
10734
10735  if (!Invalid && !ExDeclType->isDependentType() &&
10736      RequireNonAbstractType(Loc, ExDeclType,
10737                             diag::err_abstract_type_in_decl,
10738                             AbstractVariableType))
10739    Invalid = true;
10740
10741  // Only the non-fragile NeXT runtime currently supports C++ catches
10742  // of ObjC types, and no runtime supports catching ObjC types by value.
10743  if (!Invalid && getLangOpts().ObjC1) {
10744    QualType T = ExDeclType;
10745    if (const ReferenceType *RT = T->getAs<ReferenceType>())
10746      T = RT->getPointeeType();
10747
10748    if (T->isObjCObjectType()) {
10749      Diag(Loc, diag::err_objc_object_catch);
10750      Invalid = true;
10751    } else if (T->isObjCObjectPointerType()) {
10752      // FIXME: should this be a test for macosx-fragile specifically?
10753      if (getLangOpts().ObjCRuntime.isFragile())
10754        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
10755    }
10756  }
10757
10758  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
10759                                    ExDeclType, TInfo, SC_None);
10760  ExDecl->setExceptionVariable(true);
10761
10762  // In ARC, infer 'retaining' for variables of retainable type.
10763  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
10764    Invalid = true;
10765
10766  if (!Invalid && !ExDeclType->isDependentType()) {
10767    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
10768      // Insulate this from anything else we might currently be parsing.
10769      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10770
10771      // C++ [except.handle]p16:
10772      //   The object declared in an exception-declaration or, if the
10773      //   exception-declaration does not specify a name, a temporary (12.2) is
10774      //   copy-initialized (8.5) from the exception object. [...]
10775      //   The object is destroyed when the handler exits, after the destruction
10776      //   of any automatic objects initialized within the handler.
10777      //
10778      // We just pretend to initialize the object with itself, then make sure
10779      // it can be destroyed later.
10780      QualType initType = ExDeclType;
10781
10782      InitializedEntity entity =
10783        InitializedEntity::InitializeVariable(ExDecl);
10784      InitializationKind initKind =
10785        InitializationKind::CreateCopy(Loc, SourceLocation());
10786
10787      Expr *opaqueValue =
10788        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
10789      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
10790      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
10791      if (result.isInvalid())
10792        Invalid = true;
10793      else {
10794        // If the constructor used was non-trivial, set this as the
10795        // "initializer".
10796        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
10797        if (!construct->getConstructor()->isTrivial()) {
10798          Expr *init = MaybeCreateExprWithCleanups(construct);
10799          ExDecl->setInit(init);
10800        }
10801
10802        // And make sure it's destructable.
10803        FinalizeVarWithDestructor(ExDecl, recordType);
10804      }
10805    }
10806  }
10807
10808  if (Invalid)
10809    ExDecl->setInvalidDecl();
10810
10811  return ExDecl;
10812}
10813
10814/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
10815/// handler.
10816Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
10817  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10818  bool Invalid = D.isInvalidType();
10819
10820  // Check for unexpanded parameter packs.
10821  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
10822                                      UPPC_ExceptionType)) {
10823    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10824                                             D.getIdentifierLoc());
10825    Invalid = true;
10826  }
10827
10828  IdentifierInfo *II = D.getIdentifier();
10829  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
10830                                             LookupOrdinaryName,
10831                                             ForRedeclaration)) {
10832    // The scope should be freshly made just for us. There is just no way
10833    // it contains any previous declaration.
10834    assert(!S->isDeclScope(PrevDecl));
10835    if (PrevDecl->isTemplateParameter()) {
10836      // Maybe we will complain about the shadowed template parameter.
10837      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10838      PrevDecl = 0;
10839    }
10840  }
10841
10842  if (D.getCXXScopeSpec().isSet() && !Invalid) {
10843    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
10844      << D.getCXXScopeSpec().getRange();
10845    Invalid = true;
10846  }
10847
10848  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
10849                                              D.getLocStart(),
10850                                              D.getIdentifierLoc(),
10851                                              D.getIdentifier());
10852  if (Invalid)
10853    ExDecl->setInvalidDecl();
10854
10855  // Add the exception declaration into this scope.
10856  if (II)
10857    PushOnScopeChains(ExDecl, S);
10858  else
10859    CurContext->addDecl(ExDecl);
10860
10861  ProcessDeclAttributes(S, ExDecl, D);
10862  return ExDecl;
10863}
10864
10865Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10866                                         Expr *AssertExpr,
10867                                         Expr *AssertMessageExpr,
10868                                         SourceLocation RParenLoc) {
10869  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
10870
10871  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
10872    return 0;
10873
10874  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
10875                                      AssertMessage, RParenLoc, false);
10876}
10877
10878Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
10879                                         Expr *AssertExpr,
10880                                         StringLiteral *AssertMessage,
10881                                         SourceLocation RParenLoc,
10882                                         bool Failed) {
10883  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
10884      !Failed) {
10885    // In a static_assert-declaration, the constant-expression shall be a
10886    // constant expression that can be contextually converted to bool.
10887    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
10888    if (Converted.isInvalid())
10889      Failed = true;
10890
10891    llvm::APSInt Cond;
10892    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
10893          diag::err_static_assert_expression_is_not_constant,
10894          /*AllowFold=*/false).isInvalid())
10895      Failed = true;
10896
10897    if (!Failed && !Cond) {
10898      SmallString<256> MsgBuffer;
10899      llvm::raw_svector_ostream Msg(MsgBuffer);
10900      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
10901      Diag(StaticAssertLoc, diag::err_static_assert_failed)
10902        << Msg.str() << AssertExpr->getSourceRange();
10903      Failed = true;
10904    }
10905  }
10906
10907  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
10908                                        AssertExpr, AssertMessage, RParenLoc,
10909                                        Failed);
10910
10911  CurContext->addDecl(Decl);
10912  return Decl;
10913}
10914
10915/// \brief Perform semantic analysis of the given friend type declaration.
10916///
10917/// \returns A friend declaration that.
10918FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
10919                                      SourceLocation FriendLoc,
10920                                      TypeSourceInfo *TSInfo) {
10921  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
10922
10923  QualType T = TSInfo->getType();
10924  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
10925
10926  // C++03 [class.friend]p2:
10927  //   An elaborated-type-specifier shall be used in a friend declaration
10928  //   for a class.*
10929  //
10930  //   * The class-key of the elaborated-type-specifier is required.
10931  if (!ActiveTemplateInstantiations.empty()) {
10932    // Do not complain about the form of friend template types during
10933    // template instantiation; we will already have complained when the
10934    // template was declared.
10935  } else {
10936    if (!T->isElaboratedTypeSpecifier()) {
10937      // If we evaluated the type to a record type, suggest putting
10938      // a tag in front.
10939      if (const RecordType *RT = T->getAs<RecordType>()) {
10940        RecordDecl *RD = RT->getDecl();
10941
10942        std::string InsertionText = std::string(" ") + RD->getKindName();
10943
10944        Diag(TypeRange.getBegin(),
10945             getLangOpts().CPlusPlus11 ?
10946               diag::warn_cxx98_compat_unelaborated_friend_type :
10947               diag::ext_unelaborated_friend_type)
10948          << (unsigned) RD->getTagKind()
10949          << T
10950          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
10951                                        InsertionText);
10952      } else {
10953        Diag(FriendLoc,
10954             getLangOpts().CPlusPlus11 ?
10955               diag::warn_cxx98_compat_nonclass_type_friend :
10956               diag::ext_nonclass_type_friend)
10957          << T
10958          << TypeRange;
10959      }
10960    } else if (T->getAs<EnumType>()) {
10961      Diag(FriendLoc,
10962           getLangOpts().CPlusPlus11 ?
10963             diag::warn_cxx98_compat_enum_friend :
10964             diag::ext_enum_friend)
10965        << T
10966        << TypeRange;
10967    }
10968
10969    // C++11 [class.friend]p3:
10970    //   A friend declaration that does not declare a function shall have one
10971    //   of the following forms:
10972    //     friend elaborated-type-specifier ;
10973    //     friend simple-type-specifier ;
10974    //     friend typename-specifier ;
10975    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
10976      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
10977  }
10978
10979  //   If the type specifier in a friend declaration designates a (possibly
10980  //   cv-qualified) class type, that class is declared as a friend; otherwise,
10981  //   the friend declaration is ignored.
10982  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
10983}
10984
10985/// Handle a friend tag declaration where the scope specifier was
10986/// templated.
10987Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10988                                    unsigned TagSpec, SourceLocation TagLoc,
10989                                    CXXScopeSpec &SS,
10990                                    IdentifierInfo *Name,
10991                                    SourceLocation NameLoc,
10992                                    AttributeList *Attr,
10993                                    MultiTemplateParamsArg TempParamLists) {
10994  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10995
10996  bool isExplicitSpecialization = false;
10997  bool Invalid = false;
10998
10999  if (TemplateParameterList *TemplateParams
11000        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
11001                                                  TempParamLists.data(),
11002                                                  TempParamLists.size(),
11003                                                  /*friend*/ true,
11004                                                  isExplicitSpecialization,
11005                                                  Invalid)) {
11006    if (TemplateParams->size() > 0) {
11007      // This is a declaration of a class template.
11008      if (Invalid)
11009        return 0;
11010
11011      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11012                                SS, Name, NameLoc, Attr,
11013                                TemplateParams, AS_public,
11014                                /*ModulePrivateLoc=*/SourceLocation(),
11015                                TempParamLists.size() - 1,
11016                                TempParamLists.data()).take();
11017    } else {
11018      // The "template<>" header is extraneous.
11019      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11020        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11021      isExplicitSpecialization = true;
11022    }
11023  }
11024
11025  if (Invalid) return 0;
11026
11027  bool isAllExplicitSpecializations = true;
11028  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11029    if (TempParamLists[I]->size()) {
11030      isAllExplicitSpecializations = false;
11031      break;
11032    }
11033  }
11034
11035  // FIXME: don't ignore attributes.
11036
11037  // If it's explicit specializations all the way down, just forget
11038  // about the template header and build an appropriate non-templated
11039  // friend.  TODO: for source fidelity, remember the headers.
11040  if (isAllExplicitSpecializations) {
11041    if (SS.isEmpty()) {
11042      bool Owned = false;
11043      bool IsDependent = false;
11044      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11045                      Attr, AS_public,
11046                      /*ModulePrivateLoc=*/SourceLocation(),
11047                      MultiTemplateParamsArg(), Owned, IsDependent,
11048                      /*ScopedEnumKWLoc=*/SourceLocation(),
11049                      /*ScopedEnumUsesClassTag=*/false,
11050                      /*UnderlyingType=*/TypeResult());
11051    }
11052
11053    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11054    ElaboratedTypeKeyword Keyword
11055      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11056    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11057                                   *Name, NameLoc);
11058    if (T.isNull())
11059      return 0;
11060
11061    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11062    if (isa<DependentNameType>(T)) {
11063      DependentNameTypeLoc TL =
11064          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11065      TL.setElaboratedKeywordLoc(TagLoc);
11066      TL.setQualifierLoc(QualifierLoc);
11067      TL.setNameLoc(NameLoc);
11068    } else {
11069      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11070      TL.setElaboratedKeywordLoc(TagLoc);
11071      TL.setQualifierLoc(QualifierLoc);
11072      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11073    }
11074
11075    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11076                                            TSI, FriendLoc, TempParamLists);
11077    Friend->setAccess(AS_public);
11078    CurContext->addDecl(Friend);
11079    return Friend;
11080  }
11081
11082  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11083
11084
11085
11086  // Handle the case of a templated-scope friend class.  e.g.
11087  //   template <class T> class A<T>::B;
11088  // FIXME: we don't support these right now.
11089  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11090  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11091  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11092  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11093  TL.setElaboratedKeywordLoc(TagLoc);
11094  TL.setQualifierLoc(SS.getWithLocInContext(Context));
11095  TL.setNameLoc(NameLoc);
11096
11097  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11098                                          TSI, FriendLoc, TempParamLists);
11099  Friend->setAccess(AS_public);
11100  Friend->setUnsupportedFriend(true);
11101  CurContext->addDecl(Friend);
11102  return Friend;
11103}
11104
11105
11106/// Handle a friend type declaration.  This works in tandem with
11107/// ActOnTag.
11108///
11109/// Notes on friend class templates:
11110///
11111/// We generally treat friend class declarations as if they were
11112/// declaring a class.  So, for example, the elaborated type specifier
11113/// in a friend declaration is required to obey the restrictions of a
11114/// class-head (i.e. no typedefs in the scope chain), template
11115/// parameters are required to match up with simple template-ids, &c.
11116/// However, unlike when declaring a template specialization, it's
11117/// okay to refer to a template specialization without an empty
11118/// template parameter declaration, e.g.
11119///   friend class A<T>::B<unsigned>;
11120/// We permit this as a special case; if there are any template
11121/// parameters present at all, require proper matching, i.e.
11122///   template <> template \<class T> friend class A<int>::B;
11123Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11124                                MultiTemplateParamsArg TempParams) {
11125  SourceLocation Loc = DS.getLocStart();
11126
11127  assert(DS.isFriendSpecified());
11128  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11129
11130  // Try to convert the decl specifier to a type.  This works for
11131  // friend templates because ActOnTag never produces a ClassTemplateDecl
11132  // for a TUK_Friend.
11133  Declarator TheDeclarator(DS, Declarator::MemberContext);
11134  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11135  QualType T = TSI->getType();
11136  if (TheDeclarator.isInvalidType())
11137    return 0;
11138
11139  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11140    return 0;
11141
11142  // This is definitely an error in C++98.  It's probably meant to
11143  // be forbidden in C++0x, too, but the specification is just
11144  // poorly written.
11145  //
11146  // The problem is with declarations like the following:
11147  //   template <T> friend A<T>::foo;
11148  // where deciding whether a class C is a friend or not now hinges
11149  // on whether there exists an instantiation of A that causes
11150  // 'foo' to equal C.  There are restrictions on class-heads
11151  // (which we declare (by fiat) elaborated friend declarations to
11152  // be) that makes this tractable.
11153  //
11154  // FIXME: handle "template <> friend class A<T>;", which
11155  // is possibly well-formed?  Who even knows?
11156  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11157    Diag(Loc, diag::err_tagless_friend_type_template)
11158      << DS.getSourceRange();
11159    return 0;
11160  }
11161
11162  // C++98 [class.friend]p1: A friend of a class is a function
11163  //   or class that is not a member of the class . . .
11164  // This is fixed in DR77, which just barely didn't make the C++03
11165  // deadline.  It's also a very silly restriction that seriously
11166  // affects inner classes and which nobody else seems to implement;
11167  // thus we never diagnose it, not even in -pedantic.
11168  //
11169  // But note that we could warn about it: it's always useless to
11170  // friend one of your own members (it's not, however, worthless to
11171  // friend a member of an arbitrary specialization of your template).
11172
11173  Decl *D;
11174  if (unsigned NumTempParamLists = TempParams.size())
11175    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11176                                   NumTempParamLists,
11177                                   TempParams.data(),
11178                                   TSI,
11179                                   DS.getFriendSpecLoc());
11180  else
11181    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11182
11183  if (!D)
11184    return 0;
11185
11186  D->setAccess(AS_public);
11187  CurContext->addDecl(D);
11188
11189  return D;
11190}
11191
11192NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11193                                        MultiTemplateParamsArg TemplateParams) {
11194  const DeclSpec &DS = D.getDeclSpec();
11195
11196  assert(DS.isFriendSpecified());
11197  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11198
11199  SourceLocation Loc = D.getIdentifierLoc();
11200  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11201
11202  // C++ [class.friend]p1
11203  //   A friend of a class is a function or class....
11204  // Note that this sees through typedefs, which is intended.
11205  // It *doesn't* see through dependent types, which is correct
11206  // according to [temp.arg.type]p3:
11207  //   If a declaration acquires a function type through a
11208  //   type dependent on a template-parameter and this causes
11209  //   a declaration that does not use the syntactic form of a
11210  //   function declarator to have a function type, the program
11211  //   is ill-formed.
11212  if (!TInfo->getType()->isFunctionType()) {
11213    Diag(Loc, diag::err_unexpected_friend);
11214
11215    // It might be worthwhile to try to recover by creating an
11216    // appropriate declaration.
11217    return 0;
11218  }
11219
11220  // C++ [namespace.memdef]p3
11221  //  - If a friend declaration in a non-local class first declares a
11222  //    class or function, the friend class or function is a member
11223  //    of the innermost enclosing namespace.
11224  //  - The name of the friend is not found by simple name lookup
11225  //    until a matching declaration is provided in that namespace
11226  //    scope (either before or after the class declaration granting
11227  //    friendship).
11228  //  - If a friend function is called, its name may be found by the
11229  //    name lookup that considers functions from namespaces and
11230  //    classes associated with the types of the function arguments.
11231  //  - When looking for a prior declaration of a class or a function
11232  //    declared as a friend, scopes outside the innermost enclosing
11233  //    namespace scope are not considered.
11234
11235  CXXScopeSpec &SS = D.getCXXScopeSpec();
11236  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11237  DeclarationName Name = NameInfo.getName();
11238  assert(Name);
11239
11240  // Check for unexpanded parameter packs.
11241  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11242      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11243      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11244    return 0;
11245
11246  // The context we found the declaration in, or in which we should
11247  // create the declaration.
11248  DeclContext *DC;
11249  Scope *DCScope = S;
11250  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11251                        ForRedeclaration);
11252
11253  // FIXME: there are different rules in local classes
11254
11255  // There are four cases here.
11256  //   - There's no scope specifier, in which case we just go to the
11257  //     appropriate scope and look for a function or function template
11258  //     there as appropriate.
11259  // Recover from invalid scope qualifiers as if they just weren't there.
11260  if (SS.isInvalid() || !SS.isSet()) {
11261    // C++0x [namespace.memdef]p3:
11262    //   If the name in a friend declaration is neither qualified nor
11263    //   a template-id and the declaration is a function or an
11264    //   elaborated-type-specifier, the lookup to determine whether
11265    //   the entity has been previously declared shall not consider
11266    //   any scopes outside the innermost enclosing namespace.
11267    // C++0x [class.friend]p11:
11268    //   If a friend declaration appears in a local class and the name
11269    //   specified is an unqualified name, a prior declaration is
11270    //   looked up without considering scopes that are outside the
11271    //   innermost enclosing non-class scope. For a friend function
11272    //   declaration, if there is no prior declaration, the program is
11273    //   ill-formed.
11274    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
11275    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11276
11277    // Find the appropriate context according to the above.
11278    DC = CurContext;
11279
11280    // Skip class contexts.  If someone can cite chapter and verse
11281    // for this behavior, that would be nice --- it's what GCC and
11282    // EDG do, and it seems like a reasonable intent, but the spec
11283    // really only says that checks for unqualified existing
11284    // declarations should stop at the nearest enclosing namespace,
11285    // not that they should only consider the nearest enclosing
11286    // namespace.
11287    while (DC->isRecord())
11288      DC = DC->getParent();
11289
11290    DeclContext *LookupDC = DC;
11291    while (LookupDC->isTransparentContext())
11292      LookupDC = LookupDC->getParent();
11293
11294    while (true) {
11295      LookupQualifiedName(Previous, LookupDC);
11296
11297      // TODO: decide what we think about using declarations.
11298      if (isLocal)
11299        break;
11300
11301      if (!Previous.empty()) {
11302        DC = LookupDC;
11303        break;
11304      }
11305
11306      if (isTemplateId) {
11307        if (isa<TranslationUnitDecl>(LookupDC)) break;
11308      } else {
11309        if (LookupDC->isFileContext()) break;
11310      }
11311      LookupDC = LookupDC->getParent();
11312    }
11313
11314    DCScope = getScopeForDeclContext(S, DC);
11315
11316    // C++ [class.friend]p6:
11317    //   A function can be defined in a friend declaration of a class if and
11318    //   only if the class is a non-local class (9.8), the function name is
11319    //   unqualified, and the function has namespace scope.
11320    if (isLocal && D.isFunctionDefinition()) {
11321      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11322    }
11323
11324  //   - There's a non-dependent scope specifier, in which case we
11325  //     compute it and do a previous lookup there for a function
11326  //     or function template.
11327  } else if (!SS.getScopeRep()->isDependent()) {
11328    DC = computeDeclContext(SS);
11329    if (!DC) return 0;
11330
11331    if (RequireCompleteDeclContext(SS, DC)) return 0;
11332
11333    LookupQualifiedName(Previous, DC);
11334
11335    // Ignore things found implicitly in the wrong scope.
11336    // TODO: better diagnostics for this case.  Suggesting the right
11337    // qualified scope would be nice...
11338    LookupResult::Filter F = Previous.makeFilter();
11339    while (F.hasNext()) {
11340      NamedDecl *D = F.next();
11341      if (!DC->InEnclosingNamespaceSetOf(
11342              D->getDeclContext()->getRedeclContext()))
11343        F.erase();
11344    }
11345    F.done();
11346
11347    if (Previous.empty()) {
11348      D.setInvalidType();
11349      Diag(Loc, diag::err_qualified_friend_not_found)
11350          << Name << TInfo->getType();
11351      return 0;
11352    }
11353
11354    // C++ [class.friend]p1: A friend of a class is a function or
11355    //   class that is not a member of the class . . .
11356    if (DC->Equals(CurContext))
11357      Diag(DS.getFriendSpecLoc(),
11358           getLangOpts().CPlusPlus11 ?
11359             diag::warn_cxx98_compat_friend_is_member :
11360             diag::err_friend_is_member);
11361
11362    if (D.isFunctionDefinition()) {
11363      // C++ [class.friend]p6:
11364      //   A function can be defined in a friend declaration of a class if and
11365      //   only if the class is a non-local class (9.8), the function name is
11366      //   unqualified, and the function has namespace scope.
11367      SemaDiagnosticBuilder DB
11368        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11369
11370      DB << SS.getScopeRep();
11371      if (DC->isFileContext())
11372        DB << FixItHint::CreateRemoval(SS.getRange());
11373      SS.clear();
11374    }
11375
11376  //   - There's a scope specifier that does not match any template
11377  //     parameter lists, in which case we use some arbitrary context,
11378  //     create a method or method template, and wait for instantiation.
11379  //   - There's a scope specifier that does match some template
11380  //     parameter lists, which we don't handle right now.
11381  } else {
11382    if (D.isFunctionDefinition()) {
11383      // C++ [class.friend]p6:
11384      //   A function can be defined in a friend declaration of a class if and
11385      //   only if the class is a non-local class (9.8), the function name is
11386      //   unqualified, and the function has namespace scope.
11387      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11388        << SS.getScopeRep();
11389    }
11390
11391    DC = CurContext;
11392    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11393  }
11394
11395  if (!DC->isRecord()) {
11396    // This implies that it has to be an operator or function.
11397    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11398        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11399        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11400      Diag(Loc, diag::err_introducing_special_friend) <<
11401        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11402         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11403      return 0;
11404    }
11405  }
11406
11407  // FIXME: This is an egregious hack to cope with cases where the scope stack
11408  // does not contain the declaration context, i.e., in an out-of-line
11409  // definition of a class.
11410  Scope FakeDCScope(S, Scope::DeclScope, Diags);
11411  if (!DCScope) {
11412    FakeDCScope.setEntity(DC);
11413    DCScope = &FakeDCScope;
11414  }
11415
11416  bool AddToScope = true;
11417  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11418                                          TemplateParams, AddToScope);
11419  if (!ND) return 0;
11420
11421  assert(ND->getDeclContext() == DC);
11422  assert(ND->getLexicalDeclContext() == CurContext);
11423
11424  // Add the function declaration to the appropriate lookup tables,
11425  // adjusting the redeclarations list as necessary.  We don't
11426  // want to do this yet if the friending class is dependent.
11427  //
11428  // Also update the scope-based lookup if the target context's
11429  // lookup context is in lexical scope.
11430  if (!CurContext->isDependentContext()) {
11431    DC = DC->getRedeclContext();
11432    DC->makeDeclVisibleInContext(ND);
11433    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11434      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11435  }
11436
11437  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11438                                       D.getIdentifierLoc(), ND,
11439                                       DS.getFriendSpecLoc());
11440  FrD->setAccess(AS_public);
11441  CurContext->addDecl(FrD);
11442
11443  if (ND->isInvalidDecl()) {
11444    FrD->setInvalidDecl();
11445  } else {
11446    if (DC->isRecord()) CheckFriendAccess(ND);
11447
11448    FunctionDecl *FD;
11449    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11450      FD = FTD->getTemplatedDecl();
11451    else
11452      FD = cast<FunctionDecl>(ND);
11453
11454    // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11455    // default argument expression, that declaration shall be a definition
11456    // and shall be the only declaration of the function or function
11457    // template in the translation unit.
11458    if (functionDeclHasDefaultArgument(FD)) {
11459      if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11460        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11461        Diag(OldFD->getLocation(), diag::note_previous_declaration);
11462      } else if (!D.isFunctionDefinition())
11463        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11464    }
11465
11466    // Mark templated-scope function declarations as unsupported.
11467    if (FD->getNumTemplateParameterLists())
11468      FrD->setUnsupportedFriend(true);
11469  }
11470
11471  return ND;
11472}
11473
11474void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11475  AdjustDeclIfTemplate(Dcl);
11476
11477  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11478  if (!Fn) {
11479    Diag(DelLoc, diag::err_deleted_non_function);
11480    return;
11481  }
11482
11483  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11484    // Don't consider the implicit declaration we generate for explicit
11485    // specializations. FIXME: Do not generate these implicit declarations.
11486    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11487        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11488      Diag(DelLoc, diag::err_deleted_decl_not_first);
11489      Diag(Prev->getLocation(), diag::note_previous_declaration);
11490    }
11491    // If the declaration wasn't the first, we delete the function anyway for
11492    // recovery.
11493    Fn = Fn->getCanonicalDecl();
11494  }
11495
11496  if (Fn->isDeleted())
11497    return;
11498
11499  // See if we're deleting a function which is already known to override a
11500  // non-deleted virtual function.
11501  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11502    bool IssuedDiagnostic = false;
11503    for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11504                                        E = MD->end_overridden_methods();
11505         I != E; ++I) {
11506      if (!(*MD->begin_overridden_methods())->isDeleted()) {
11507        if (!IssuedDiagnostic) {
11508          Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11509          IssuedDiagnostic = true;
11510        }
11511        Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11512      }
11513    }
11514  }
11515
11516  Fn->setDeletedAsWritten();
11517}
11518
11519void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11520  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11521
11522  if (MD) {
11523    if (MD->getParent()->isDependentType()) {
11524      MD->setDefaulted();
11525      MD->setExplicitlyDefaulted();
11526      return;
11527    }
11528
11529    CXXSpecialMember Member = getSpecialMember(MD);
11530    if (Member == CXXInvalid) {
11531      if (!MD->isInvalidDecl())
11532        Diag(DefaultLoc, diag::err_default_special_members);
11533      return;
11534    }
11535
11536    MD->setDefaulted();
11537    MD->setExplicitlyDefaulted();
11538
11539    // If this definition appears within the record, do the checking when
11540    // the record is complete.
11541    const FunctionDecl *Primary = MD;
11542    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11543      // Find the uninstantiated declaration that actually had the '= default'
11544      // on it.
11545      Pattern->isDefined(Primary);
11546
11547    // If the method was defaulted on its first declaration, we will have
11548    // already performed the checking in CheckCompletedCXXClass. Such a
11549    // declaration doesn't trigger an implicit definition.
11550    if (Primary == Primary->getCanonicalDecl())
11551      return;
11552
11553    CheckExplicitlyDefaultedSpecialMember(MD);
11554
11555    // The exception specification is needed because we are defining the
11556    // function.
11557    ResolveExceptionSpec(DefaultLoc,
11558                         MD->getType()->castAs<FunctionProtoType>());
11559
11560    switch (Member) {
11561    case CXXDefaultConstructor: {
11562      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11563      if (!CD->isInvalidDecl())
11564        DefineImplicitDefaultConstructor(DefaultLoc, CD);
11565      break;
11566    }
11567
11568    case CXXCopyConstructor: {
11569      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11570      if (!CD->isInvalidDecl())
11571        DefineImplicitCopyConstructor(DefaultLoc, CD);
11572      break;
11573    }
11574
11575    case CXXCopyAssignment: {
11576      if (!MD->isInvalidDecl())
11577        DefineImplicitCopyAssignment(DefaultLoc, MD);
11578      break;
11579    }
11580
11581    case CXXDestructor: {
11582      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
11583      if (!DD->isInvalidDecl())
11584        DefineImplicitDestructor(DefaultLoc, DD);
11585      break;
11586    }
11587
11588    case CXXMoveConstructor: {
11589      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
11590      if (!CD->isInvalidDecl())
11591        DefineImplicitMoveConstructor(DefaultLoc, CD);
11592      break;
11593    }
11594
11595    case CXXMoveAssignment: {
11596      if (!MD->isInvalidDecl())
11597        DefineImplicitMoveAssignment(DefaultLoc, MD);
11598      break;
11599    }
11600
11601    case CXXInvalid:
11602      llvm_unreachable("Invalid special member.");
11603    }
11604  } else {
11605    Diag(DefaultLoc, diag::err_default_special_members);
11606  }
11607}
11608
11609static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11610  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11611    Stmt *SubStmt = *CI;
11612    if (!SubStmt)
11613      continue;
11614    if (isa<ReturnStmt>(SubStmt))
11615      Self.Diag(SubStmt->getLocStart(),
11616           diag::err_return_in_constructor_handler);
11617    if (!isa<Expr>(SubStmt))
11618      SearchForReturnInStmt(Self, SubStmt);
11619  }
11620}
11621
11622void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11623  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11624    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11625    SearchForReturnInStmt(*this, Handler);
11626  }
11627}
11628
11629bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
11630                                             const CXXMethodDecl *Old) {
11631  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
11632  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
11633
11634  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
11635
11636  // If the calling conventions match, everything is fine
11637  if (NewCC == OldCC)
11638    return false;
11639
11640  // If either of the calling conventions are set to "default", we need to pick
11641  // something more sensible based on the target. This supports code where the
11642  // one method explicitly sets thiscall, and another has no explicit calling
11643  // convention.
11644  CallingConv Default =
11645    Context.getTargetInfo().getDefaultCallingConv(TargetInfo::CCMT_Member);
11646  if (NewCC == CC_Default)
11647    NewCC = Default;
11648  if (OldCC == CC_Default)
11649    OldCC = Default;
11650
11651  // If the calling conventions still don't match, then report the error
11652  if (NewCC != OldCC) {
11653    Diag(New->getLocation(),
11654         diag::err_conflicting_overriding_cc_attributes)
11655      << New->getDeclName() << New->getType() << Old->getType();
11656    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11657    return true;
11658  }
11659
11660  return false;
11661}
11662
11663bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
11664                                             const CXXMethodDecl *Old) {
11665  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
11666  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
11667
11668  if (Context.hasSameType(NewTy, OldTy) ||
11669      NewTy->isDependentType() || OldTy->isDependentType())
11670    return false;
11671
11672  // Check if the return types are covariant
11673  QualType NewClassTy, OldClassTy;
11674
11675  /// Both types must be pointers or references to classes.
11676  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
11677    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
11678      NewClassTy = NewPT->getPointeeType();
11679      OldClassTy = OldPT->getPointeeType();
11680    }
11681  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
11682    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
11683      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
11684        NewClassTy = NewRT->getPointeeType();
11685        OldClassTy = OldRT->getPointeeType();
11686      }
11687    }
11688  }
11689
11690  // The return types aren't either both pointers or references to a class type.
11691  if (NewClassTy.isNull()) {
11692    Diag(New->getLocation(),
11693         diag::err_different_return_type_for_overriding_virtual_function)
11694      << New->getDeclName() << NewTy << OldTy;
11695    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11696
11697    return true;
11698  }
11699
11700  // C++ [class.virtual]p6:
11701  //   If the return type of D::f differs from the return type of B::f, the
11702  //   class type in the return type of D::f shall be complete at the point of
11703  //   declaration of D::f or shall be the class type D.
11704  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
11705    if (!RT->isBeingDefined() &&
11706        RequireCompleteType(New->getLocation(), NewClassTy,
11707                            diag::err_covariant_return_incomplete,
11708                            New->getDeclName()))
11709    return true;
11710  }
11711
11712  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
11713    // Check if the new class derives from the old class.
11714    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
11715      Diag(New->getLocation(),
11716           diag::err_covariant_return_not_derived)
11717      << New->getDeclName() << NewTy << OldTy;
11718      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11719      return true;
11720    }
11721
11722    // Check if we the conversion from derived to base is valid.
11723    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
11724                    diag::err_covariant_return_inaccessible_base,
11725                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
11726                    // FIXME: Should this point to the return type?
11727                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
11728      // FIXME: this note won't trigger for delayed access control
11729      // diagnostics, and it's impossible to get an undelayed error
11730      // here from access control during the original parse because
11731      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
11732      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11733      return true;
11734    }
11735  }
11736
11737  // The qualifiers of the return types must be the same.
11738  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
11739    Diag(New->getLocation(),
11740         diag::err_covariant_return_type_different_qualifications)
11741    << New->getDeclName() << NewTy << OldTy;
11742    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11743    return true;
11744  };
11745
11746
11747  // The new class type must have the same or less qualifiers as the old type.
11748  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
11749    Diag(New->getLocation(),
11750         diag::err_covariant_return_type_class_type_more_qualified)
11751    << New->getDeclName() << NewTy << OldTy;
11752    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
11753    return true;
11754  };
11755
11756  return false;
11757}
11758
11759/// \brief Mark the given method pure.
11760///
11761/// \param Method the method to be marked pure.
11762///
11763/// \param InitRange the source range that covers the "0" initializer.
11764bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
11765  SourceLocation EndLoc = InitRange.getEnd();
11766  if (EndLoc.isValid())
11767    Method->setRangeEnd(EndLoc);
11768
11769  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
11770    Method->setPure();
11771    return false;
11772  }
11773
11774  if (!Method->isInvalidDecl())
11775    Diag(Method->getLocation(), diag::err_non_virtual_pure)
11776      << Method->getDeclName() << InitRange;
11777  return true;
11778}
11779
11780/// \brief Determine whether the given declaration is a static data member.
11781static bool isStaticDataMember(Decl *D) {
11782  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
11783  if (!Var)
11784    return false;
11785
11786  return Var->isStaticDataMember();
11787}
11788/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
11789/// an initializer for the out-of-line declaration 'Dcl'.  The scope
11790/// is a fresh scope pushed for just this purpose.
11791///
11792/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
11793/// static data member of class X, names should be looked up in the scope of
11794/// class X.
11795void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
11796  // If there is no declaration, there was an error parsing it.
11797  if (D == 0 || D->isInvalidDecl()) return;
11798
11799  // We should only get called for declarations with scope specifiers, like:
11800  //   int foo::bar;
11801  assert(D->isOutOfLine());
11802  EnterDeclaratorContext(S, D->getDeclContext());
11803
11804  // If we are parsing the initializer for a static data member, push a
11805  // new expression evaluation context that is associated with this static
11806  // data member.
11807  if (isStaticDataMember(D))
11808    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
11809}
11810
11811/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
11812/// initializer for the out-of-line declaration 'D'.
11813void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
11814  // If there is no declaration, there was an error parsing it.
11815  if (D == 0 || D->isInvalidDecl()) return;
11816
11817  if (isStaticDataMember(D))
11818    PopExpressionEvaluationContext();
11819
11820  assert(D->isOutOfLine());
11821  ExitDeclaratorContext(S);
11822}
11823
11824/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
11825/// C++ if/switch/while/for statement.
11826/// e.g: "if (int x = f()) {...}"
11827DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
11828  // C++ 6.4p2:
11829  // The declarator shall not specify a function or an array.
11830  // The type-specifier-seq shall not contain typedef and shall not declare a
11831  // new class or enumeration.
11832  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
11833         "Parser allowed 'typedef' as storage class of condition decl.");
11834
11835  Decl *Dcl = ActOnDeclarator(S, D);
11836  if (!Dcl)
11837    return true;
11838
11839  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
11840    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
11841      << D.getSourceRange();
11842    return true;
11843  }
11844
11845  return Dcl;
11846}
11847
11848void Sema::LoadExternalVTableUses() {
11849  if (!ExternalSource)
11850    return;
11851
11852  SmallVector<ExternalVTableUse, 4> VTables;
11853  ExternalSource->ReadUsedVTables(VTables);
11854  SmallVector<VTableUse, 4> NewUses;
11855  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
11856    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
11857      = VTablesUsed.find(VTables[I].Record);
11858    // Even if a definition wasn't required before, it may be required now.
11859    if (Pos != VTablesUsed.end()) {
11860      if (!Pos->second && VTables[I].DefinitionRequired)
11861        Pos->second = true;
11862      continue;
11863    }
11864
11865    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
11866    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
11867  }
11868
11869  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
11870}
11871
11872void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
11873                          bool DefinitionRequired) {
11874  // Ignore any vtable uses in unevaluated operands or for classes that do
11875  // not have a vtable.
11876  if (!Class->isDynamicClass() || Class->isDependentContext() ||
11877      CurContext->isDependentContext() || isUnevaluatedContext())
11878    return;
11879
11880  // Try to insert this class into the map.
11881  LoadExternalVTableUses();
11882  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11883  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
11884    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
11885  if (!Pos.second) {
11886    // If we already had an entry, check to see if we are promoting this vtable
11887    // to required a definition. If so, we need to reappend to the VTableUses
11888    // list, since we may have already processed the first entry.
11889    if (DefinitionRequired && !Pos.first->second) {
11890      Pos.first->second = true;
11891    } else {
11892      // Otherwise, we can early exit.
11893      return;
11894    }
11895  }
11896
11897  // Local classes need to have their virtual members marked
11898  // immediately. For all other classes, we mark their virtual members
11899  // at the end of the translation unit.
11900  if (Class->isLocalClass())
11901    MarkVirtualMembersReferenced(Loc, Class);
11902  else
11903    VTableUses.push_back(std::make_pair(Class, Loc));
11904}
11905
11906bool Sema::DefineUsedVTables() {
11907  LoadExternalVTableUses();
11908  if (VTableUses.empty())
11909    return false;
11910
11911  // Note: The VTableUses vector could grow as a result of marking
11912  // the members of a class as "used", so we check the size each
11913  // time through the loop and prefer indices (which are stable) to
11914  // iterators (which are not).
11915  bool DefinedAnything = false;
11916  for (unsigned I = 0; I != VTableUses.size(); ++I) {
11917    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
11918    if (!Class)
11919      continue;
11920
11921    SourceLocation Loc = VTableUses[I].second;
11922
11923    bool DefineVTable = true;
11924
11925    // If this class has a key function, but that key function is
11926    // defined in another translation unit, we don't need to emit the
11927    // vtable even though we're using it.
11928    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
11929    if (KeyFunction && !KeyFunction->hasBody()) {
11930      switch (KeyFunction->getTemplateSpecializationKind()) {
11931      case TSK_Undeclared:
11932      case TSK_ExplicitSpecialization:
11933      case TSK_ExplicitInstantiationDeclaration:
11934        // The key function is in another translation unit.
11935        DefineVTable = false;
11936        break;
11937
11938      case TSK_ExplicitInstantiationDefinition:
11939      case TSK_ImplicitInstantiation:
11940        // We will be instantiating the key function.
11941        break;
11942      }
11943    } else if (!KeyFunction) {
11944      // If we have a class with no key function that is the subject
11945      // of an explicit instantiation declaration, suppress the
11946      // vtable; it will live with the explicit instantiation
11947      // definition.
11948      bool IsExplicitInstantiationDeclaration
11949        = Class->getTemplateSpecializationKind()
11950                                      == TSK_ExplicitInstantiationDeclaration;
11951      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
11952                                 REnd = Class->redecls_end();
11953           R != REnd; ++R) {
11954        TemplateSpecializationKind TSK
11955          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
11956        if (TSK == TSK_ExplicitInstantiationDeclaration)
11957          IsExplicitInstantiationDeclaration = true;
11958        else if (TSK == TSK_ExplicitInstantiationDefinition) {
11959          IsExplicitInstantiationDeclaration = false;
11960          break;
11961        }
11962      }
11963
11964      if (IsExplicitInstantiationDeclaration)
11965        DefineVTable = false;
11966    }
11967
11968    // The exception specifications for all virtual members may be needed even
11969    // if we are not providing an authoritative form of the vtable in this TU.
11970    // We may choose to emit it available_externally anyway.
11971    if (!DefineVTable) {
11972      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
11973      continue;
11974    }
11975
11976    // Mark all of the virtual members of this class as referenced, so
11977    // that we can build a vtable. Then, tell the AST consumer that a
11978    // vtable for this class is required.
11979    DefinedAnything = true;
11980    MarkVirtualMembersReferenced(Loc, Class);
11981    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
11982    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
11983
11984    // Optionally warn if we're emitting a weak vtable.
11985    if (Class->isExternallyVisible() &&
11986        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
11987      const FunctionDecl *KeyFunctionDef = 0;
11988      if (!KeyFunction ||
11989          (KeyFunction->hasBody(KeyFunctionDef) &&
11990           KeyFunctionDef->isInlined()))
11991        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
11992             TSK_ExplicitInstantiationDefinition
11993             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
11994          << Class;
11995    }
11996  }
11997  VTableUses.clear();
11998
11999  return DefinedAnything;
12000}
12001
12002void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12003                                                 const CXXRecordDecl *RD) {
12004  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12005                                      E = RD->method_end(); I != E; ++I)
12006    if ((*I)->isVirtual() && !(*I)->isPure())
12007      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12008}
12009
12010void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12011                                        const CXXRecordDecl *RD) {
12012  // Mark all functions which will appear in RD's vtable as used.
12013  CXXFinalOverriderMap FinalOverriders;
12014  RD->getFinalOverriders(FinalOverriders);
12015  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12016                                            E = FinalOverriders.end();
12017       I != E; ++I) {
12018    for (OverridingMethods::const_iterator OI = I->second.begin(),
12019                                           OE = I->second.end();
12020         OI != OE; ++OI) {
12021      assert(OI->second.size() > 0 && "no final overrider");
12022      CXXMethodDecl *Overrider = OI->second.front().Method;
12023
12024      // C++ [basic.def.odr]p2:
12025      //   [...] A virtual member function is used if it is not pure. [...]
12026      if (!Overrider->isPure())
12027        MarkFunctionReferenced(Loc, Overrider);
12028    }
12029  }
12030
12031  // Only classes that have virtual bases need a VTT.
12032  if (RD->getNumVBases() == 0)
12033    return;
12034
12035  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12036           e = RD->bases_end(); i != e; ++i) {
12037    const CXXRecordDecl *Base =
12038        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
12039    if (Base->getNumVBases() == 0)
12040      continue;
12041    MarkVirtualMembersReferenced(Loc, Base);
12042  }
12043}
12044
12045/// SetIvarInitializers - This routine builds initialization ASTs for the
12046/// Objective-C implementation whose ivars need be initialized.
12047void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12048  if (!getLangOpts().CPlusPlus)
12049    return;
12050  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12051    SmallVector<ObjCIvarDecl*, 8> ivars;
12052    CollectIvarsToConstructOrDestruct(OID, ivars);
12053    if (ivars.empty())
12054      return;
12055    SmallVector<CXXCtorInitializer*, 32> AllToInit;
12056    for (unsigned i = 0; i < ivars.size(); i++) {
12057      FieldDecl *Field = ivars[i];
12058      if (Field->isInvalidDecl())
12059        continue;
12060
12061      CXXCtorInitializer *Member;
12062      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12063      InitializationKind InitKind =
12064        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12065
12066      InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12067      ExprResult MemberInit =
12068        InitSeq.Perform(*this, InitEntity, InitKind, None);
12069      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12070      // Note, MemberInit could actually come back empty if no initialization
12071      // is required (e.g., because it would call a trivial default constructor)
12072      if (!MemberInit.get() || MemberInit.isInvalid())
12073        continue;
12074
12075      Member =
12076        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12077                                         SourceLocation(),
12078                                         MemberInit.takeAs<Expr>(),
12079                                         SourceLocation());
12080      AllToInit.push_back(Member);
12081
12082      // Be sure that the destructor is accessible and is marked as referenced.
12083      if (const RecordType *RecordTy
12084                  = Context.getBaseElementType(Field->getType())
12085                                                        ->getAs<RecordType>()) {
12086                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12087        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12088          MarkFunctionReferenced(Field->getLocation(), Destructor);
12089          CheckDestructorAccess(Field->getLocation(), Destructor,
12090                            PDiag(diag::err_access_dtor_ivar)
12091                              << Context.getBaseElementType(Field->getType()));
12092        }
12093      }
12094    }
12095    ObjCImplementation->setIvarInitializers(Context,
12096                                            AllToInit.data(), AllToInit.size());
12097  }
12098}
12099
12100static
12101void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12102                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12103                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12104                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12105                           Sema &S) {
12106  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12107                                                   CE = Current.end();
12108  if (Ctor->isInvalidDecl())
12109    return;
12110
12111  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12112
12113  // Target may not be determinable yet, for instance if this is a dependent
12114  // call in an uninstantiated template.
12115  if (Target) {
12116    const FunctionDecl *FNTarget = 0;
12117    (void)Target->hasBody(FNTarget);
12118    Target = const_cast<CXXConstructorDecl*>(
12119      cast_or_null<CXXConstructorDecl>(FNTarget));
12120  }
12121
12122  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12123                     // Avoid dereferencing a null pointer here.
12124                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12125
12126  if (!Current.insert(Canonical))
12127    return;
12128
12129  // We know that beyond here, we aren't chaining into a cycle.
12130  if (!Target || !Target->isDelegatingConstructor() ||
12131      Target->isInvalidDecl() || Valid.count(TCanonical)) {
12132    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12133      Valid.insert(*CI);
12134    Current.clear();
12135  // We've hit a cycle.
12136  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12137             Current.count(TCanonical)) {
12138    // If we haven't diagnosed this cycle yet, do so now.
12139    if (!Invalid.count(TCanonical)) {
12140      S.Diag((*Ctor->init_begin())->getSourceLocation(),
12141             diag::warn_delegating_ctor_cycle)
12142        << Ctor;
12143
12144      // Don't add a note for a function delegating directly to itself.
12145      if (TCanonical != Canonical)
12146        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12147
12148      CXXConstructorDecl *C = Target;
12149      while (C->getCanonicalDecl() != Canonical) {
12150        const FunctionDecl *FNTarget = 0;
12151        (void)C->getTargetConstructor()->hasBody(FNTarget);
12152        assert(FNTarget && "Ctor cycle through bodiless function");
12153
12154        C = const_cast<CXXConstructorDecl*>(
12155          cast<CXXConstructorDecl>(FNTarget));
12156        S.Diag(C->getLocation(), diag::note_which_delegates_to);
12157      }
12158    }
12159
12160    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
12161      Invalid.insert(*CI);
12162    Current.clear();
12163  } else {
12164    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12165  }
12166}
12167
12168
12169void Sema::CheckDelegatingCtorCycles() {
12170  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12171
12172  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
12173                                                   CE = Current.end();
12174
12175  for (DelegatingCtorDeclsType::iterator
12176         I = DelegatingCtorDecls.begin(ExternalSource),
12177         E = DelegatingCtorDecls.end();
12178       I != E; ++I)
12179    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12180
12181  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
12182    (*CI)->setInvalidDecl();
12183}
12184
12185namespace {
12186  /// \brief AST visitor that finds references to the 'this' expression.
12187  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12188    Sema &S;
12189
12190  public:
12191    explicit FindCXXThisExpr(Sema &S) : S(S) { }
12192
12193    bool VisitCXXThisExpr(CXXThisExpr *E) {
12194      S.Diag(E->getLocation(), diag::err_this_static_member_func)
12195        << E->isImplicit();
12196      return false;
12197    }
12198  };
12199}
12200
12201bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12202  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12203  if (!TSInfo)
12204    return false;
12205
12206  TypeLoc TL = TSInfo->getTypeLoc();
12207  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12208  if (!ProtoTL)
12209    return false;
12210
12211  // C++11 [expr.prim.general]p3:
12212  //   [The expression this] shall not appear before the optional
12213  //   cv-qualifier-seq and it shall not appear within the declaration of a
12214  //   static member function (although its type and value category are defined
12215  //   within a static member function as they are within a non-static member
12216  //   function). [ Note: this is because declaration matching does not occur
12217  //  until the complete declarator is known. - end note ]
12218  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12219  FindCXXThisExpr Finder(*this);
12220
12221  // If the return type came after the cv-qualifier-seq, check it now.
12222  if (Proto->hasTrailingReturn() &&
12223      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12224    return true;
12225
12226  // Check the exception specification.
12227  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12228    return true;
12229
12230  return checkThisInStaticMemberFunctionAttributes(Method);
12231}
12232
12233bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12234  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12235  if (!TSInfo)
12236    return false;
12237
12238  TypeLoc TL = TSInfo->getTypeLoc();
12239  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12240  if (!ProtoTL)
12241    return false;
12242
12243  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12244  FindCXXThisExpr Finder(*this);
12245
12246  switch (Proto->getExceptionSpecType()) {
12247  case EST_Uninstantiated:
12248  case EST_Unevaluated:
12249  case EST_BasicNoexcept:
12250  case EST_DynamicNone:
12251  case EST_MSAny:
12252  case EST_None:
12253    break;
12254
12255  case EST_ComputedNoexcept:
12256    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12257      return true;
12258
12259  case EST_Dynamic:
12260    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12261         EEnd = Proto->exception_end();
12262         E != EEnd; ++E) {
12263      if (!Finder.TraverseType(*E))
12264        return true;
12265    }
12266    break;
12267  }
12268
12269  return false;
12270}
12271
12272bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12273  FindCXXThisExpr Finder(*this);
12274
12275  // Check attributes.
12276  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12277       A != AEnd; ++A) {
12278    // FIXME: This should be emitted by tblgen.
12279    Expr *Arg = 0;
12280    ArrayRef<Expr *> Args;
12281    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12282      Arg = G->getArg();
12283    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12284      Arg = G->getArg();
12285    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12286      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12287    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12288      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12289    else if (ExclusiveLockFunctionAttr *ELF
12290               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12291      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12292    else if (SharedLockFunctionAttr *SLF
12293               = dyn_cast<SharedLockFunctionAttr>(*A))
12294      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12295    else if (ExclusiveTrylockFunctionAttr *ETLF
12296               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12297      Arg = ETLF->getSuccessValue();
12298      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12299    } else if (SharedTrylockFunctionAttr *STLF
12300                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12301      Arg = STLF->getSuccessValue();
12302      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12303    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12304      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12305    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12306      Arg = LR->getArg();
12307    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12308      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12309    else if (ExclusiveLocksRequiredAttr *ELR
12310               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12311      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12312    else if (SharedLocksRequiredAttr *SLR
12313               = dyn_cast<SharedLocksRequiredAttr>(*A))
12314      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12315
12316    if (Arg && !Finder.TraverseStmt(Arg))
12317      return true;
12318
12319    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12320      if (!Finder.TraverseStmt(Args[I]))
12321        return true;
12322    }
12323  }
12324
12325  return false;
12326}
12327
12328void
12329Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12330                                  ArrayRef<ParsedType> DynamicExceptions,
12331                                  ArrayRef<SourceRange> DynamicExceptionRanges,
12332                                  Expr *NoexceptExpr,
12333                                  SmallVectorImpl<QualType> &Exceptions,
12334                                  FunctionProtoType::ExtProtoInfo &EPI) {
12335  Exceptions.clear();
12336  EPI.ExceptionSpecType = EST;
12337  if (EST == EST_Dynamic) {
12338    Exceptions.reserve(DynamicExceptions.size());
12339    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12340      // FIXME: Preserve type source info.
12341      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12342
12343      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12344      collectUnexpandedParameterPacks(ET, Unexpanded);
12345      if (!Unexpanded.empty()) {
12346        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12347                                         UPPC_ExceptionType,
12348                                         Unexpanded);
12349        continue;
12350      }
12351
12352      // Check that the type is valid for an exception spec, and
12353      // drop it if not.
12354      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12355        Exceptions.push_back(ET);
12356    }
12357    EPI.NumExceptions = Exceptions.size();
12358    EPI.Exceptions = Exceptions.data();
12359    return;
12360  }
12361
12362  if (EST == EST_ComputedNoexcept) {
12363    // If an error occurred, there's no expression here.
12364    if (NoexceptExpr) {
12365      assert((NoexceptExpr->isTypeDependent() ||
12366              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12367              Context.BoolTy) &&
12368             "Parser should have made sure that the expression is boolean");
12369      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12370        EPI.ExceptionSpecType = EST_BasicNoexcept;
12371        return;
12372      }
12373
12374      if (!NoexceptExpr->isValueDependent())
12375        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12376                         diag::err_noexcept_needs_constant_expression,
12377                         /*AllowFold*/ false).take();
12378      EPI.NoexceptExpr = NoexceptExpr;
12379    }
12380    return;
12381  }
12382}
12383
12384/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12385Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12386  // Implicitly declared functions (e.g. copy constructors) are
12387  // __host__ __device__
12388  if (D->isImplicit())
12389    return CFT_HostDevice;
12390
12391  if (D->hasAttr<CUDAGlobalAttr>())
12392    return CFT_Global;
12393
12394  if (D->hasAttr<CUDADeviceAttr>()) {
12395    if (D->hasAttr<CUDAHostAttr>())
12396      return CFT_HostDevice;
12397    else
12398      return CFT_Device;
12399  }
12400
12401  return CFT_Host;
12402}
12403
12404bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12405                           CUDAFunctionTarget CalleeTarget) {
12406  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12407  // Callable from the device only."
12408  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12409    return true;
12410
12411  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12412  // Callable from the host only."
12413  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12414  // Callable from the host only."
12415  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12416      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12417    return true;
12418
12419  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12420    return true;
12421
12422  return false;
12423}
12424
12425/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12426///
12427MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12428                                       SourceLocation DeclStart,
12429                                       Declarator &D, Expr *BitWidth,
12430                                       InClassInitStyle InitStyle,
12431                                       AccessSpecifier AS,
12432                                       AttributeList *MSPropertyAttr) {
12433  IdentifierInfo *II = D.getIdentifier();
12434  if (!II) {
12435    Diag(DeclStart, diag::err_anonymous_property);
12436    return NULL;
12437  }
12438  SourceLocation Loc = D.getIdentifierLoc();
12439
12440  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12441  QualType T = TInfo->getType();
12442  if (getLangOpts().CPlusPlus) {
12443    CheckExtraCXXDefaultArguments(D);
12444
12445    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12446                                        UPPC_DataMemberType)) {
12447      D.setInvalidType();
12448      T = Context.IntTy;
12449      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12450    }
12451  }
12452
12453  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12454
12455  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12456    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12457         diag::err_invalid_thread)
12458      << DeclSpec::getSpecifierName(TSCS);
12459
12460  // Check to see if this name was declared as a member previously
12461  NamedDecl *PrevDecl = 0;
12462  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12463  LookupName(Previous, S);
12464  switch (Previous.getResultKind()) {
12465  case LookupResult::Found:
12466  case LookupResult::FoundUnresolvedValue:
12467    PrevDecl = Previous.getAsSingle<NamedDecl>();
12468    break;
12469
12470  case LookupResult::FoundOverloaded:
12471    PrevDecl = Previous.getRepresentativeDecl();
12472    break;
12473
12474  case LookupResult::NotFound:
12475  case LookupResult::NotFoundInCurrentInstantiation:
12476  case LookupResult::Ambiguous:
12477    break;
12478  }
12479
12480  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12481    // Maybe we will complain about the shadowed template parameter.
12482    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12483    // Just pretend that we didn't see the previous declaration.
12484    PrevDecl = 0;
12485  }
12486
12487  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12488    PrevDecl = 0;
12489
12490  SourceLocation TSSL = D.getLocStart();
12491  MSPropertyDecl *NewPD;
12492  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12493  NewPD = new (Context) MSPropertyDecl(Record, Loc,
12494                                       II, T, TInfo, TSSL,
12495                                       Data.GetterId, Data.SetterId);
12496  ProcessDeclAttributes(TUScope, NewPD, D);
12497  NewPD->setAccess(AS);
12498
12499  if (NewPD->isInvalidDecl())
12500    Record->setInvalidDecl();
12501
12502  if (D.getDeclSpec().isModulePrivateSpecified())
12503    NewPD->setModulePrivate();
12504
12505  if (NewPD->isInvalidDecl() && PrevDecl) {
12506    // Don't introduce NewFD into scope; there's already something
12507    // with the same name in the same scope.
12508  } else if (II) {
12509    PushOnScopeChains(NewPD, S);
12510  } else
12511    Record->addDecl(NewPD);
12512
12513  return NewPD;
12514}
12515