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