SemaDeclCXX.cpp revision 6960587df0bd1b421c11715807a4d2302a3aae3c
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
3349    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3350    DiagnoseUseOfDecl(Dtor, Location);
3351  }
3352
3353  // Virtual bases.
3354  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3355       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3356
3357    // Bases are always records in a well-formed non-dependent class.
3358    const RecordType *RT = VBase->getType()->getAs<RecordType>();
3359
3360    // Ignore direct virtual bases.
3361    if (DirectVirtualBases.count(RT))
3362      continue;
3363
3364    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3365    // If our base class is invalid, we probably can't get its dtor anyway.
3366    if (BaseClassDecl->isInvalidDecl())
3367      continue;
3368    if (BaseClassDecl->hasIrrelevantDestructor())
3369      continue;
3370
3371    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3372    assert(Dtor && "No dtor found for BaseClassDecl!");
3373    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3374                          PDiag(diag::err_access_dtor_vbase)
3375                            << VBase->getType());
3376
3377    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3378    DiagnoseUseOfDecl(Dtor, Location);
3379  }
3380}
3381
3382void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3383  if (!CDtorDecl)
3384    return;
3385
3386  if (CXXConstructorDecl *Constructor
3387      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3388    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3389}
3390
3391bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3392                                  unsigned DiagID, AbstractDiagSelID SelID) {
3393  if (SelID == -1)
3394    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
3395  else
3396    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
3397}
3398
3399bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3400                                  const PartialDiagnostic &PD) {
3401  if (!getLangOpts().CPlusPlus)
3402    return false;
3403
3404  if (const ArrayType *AT = Context.getAsArrayType(T))
3405    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3406
3407  if (const PointerType *PT = T->getAs<PointerType>()) {
3408    // Find the innermost pointer type.
3409    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3410      PT = T;
3411
3412    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3413      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3414  }
3415
3416  const RecordType *RT = T->getAs<RecordType>();
3417  if (!RT)
3418    return false;
3419
3420  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3421
3422  // We can't answer whether something is abstract until it has a
3423  // definition.  If it's currently being defined, we'll walk back
3424  // over all the declarations when we have a full definition.
3425  const CXXRecordDecl *Def = RD->getDefinition();
3426  if (!Def || Def->isBeingDefined())
3427    return false;
3428
3429  if (!RD->isAbstract())
3430    return false;
3431
3432  Diag(Loc, PD) << RD->getDeclName();
3433  DiagnoseAbstractType(RD);
3434
3435  return true;
3436}
3437
3438void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3439  // Check if we've already emitted the list of pure virtual functions
3440  // for this class.
3441  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3442    return;
3443
3444  CXXFinalOverriderMap FinalOverriders;
3445  RD->getFinalOverriders(FinalOverriders);
3446
3447  // Keep a set of seen pure methods so we won't diagnose the same method
3448  // more than once.
3449  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3450
3451  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3452                                   MEnd = FinalOverriders.end();
3453       M != MEnd;
3454       ++M) {
3455    for (OverridingMethods::iterator SO = M->second.begin(),
3456                                  SOEnd = M->second.end();
3457         SO != SOEnd; ++SO) {
3458      // C++ [class.abstract]p4:
3459      //   A class is abstract if it contains or inherits at least one
3460      //   pure virtual function for which the final overrider is pure
3461      //   virtual.
3462
3463      //
3464      if (SO->second.size() != 1)
3465        continue;
3466
3467      if (!SO->second.front().Method->isPure())
3468        continue;
3469
3470      if (!SeenPureMethods.insert(SO->second.front().Method))
3471        continue;
3472
3473      Diag(SO->second.front().Method->getLocation(),
3474           diag::note_pure_virtual_function)
3475        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3476    }
3477  }
3478
3479  if (!PureVirtualClassDiagSet)
3480    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3481  PureVirtualClassDiagSet->insert(RD);
3482}
3483
3484namespace {
3485struct AbstractUsageInfo {
3486  Sema &S;
3487  CXXRecordDecl *Record;
3488  CanQualType AbstractType;
3489  bool Invalid;
3490
3491  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3492    : S(S), Record(Record),
3493      AbstractType(S.Context.getCanonicalType(
3494                   S.Context.getTypeDeclType(Record))),
3495      Invalid(false) {}
3496
3497  void DiagnoseAbstractType() {
3498    if (Invalid) return;
3499    S.DiagnoseAbstractType(Record);
3500    Invalid = true;
3501  }
3502
3503  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3504};
3505
3506struct CheckAbstractUsage {
3507  AbstractUsageInfo &Info;
3508  const NamedDecl *Ctx;
3509
3510  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3511    : Info(Info), Ctx(Ctx) {}
3512
3513  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3514    switch (TL.getTypeLocClass()) {
3515#define ABSTRACT_TYPELOC(CLASS, PARENT)
3516#define TYPELOC(CLASS, PARENT) \
3517    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3518#include "clang/AST/TypeLocNodes.def"
3519    }
3520  }
3521
3522  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3523    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3524    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3525      if (!TL.getArg(I))
3526        continue;
3527
3528      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3529      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3530    }
3531  }
3532
3533  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3534    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3535  }
3536
3537  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3538    // Visit the type parameters from a permissive context.
3539    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3540      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3541      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3542        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3543          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3544      // TODO: other template argument types?
3545    }
3546  }
3547
3548  // Visit pointee types from a permissive context.
3549#define CheckPolymorphic(Type) \
3550  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3551    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3552  }
3553  CheckPolymorphic(PointerTypeLoc)
3554  CheckPolymorphic(ReferenceTypeLoc)
3555  CheckPolymorphic(MemberPointerTypeLoc)
3556  CheckPolymorphic(BlockPointerTypeLoc)
3557  CheckPolymorphic(AtomicTypeLoc)
3558
3559  /// Handle all the types we haven't given a more specific
3560  /// implementation for above.
3561  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3562    // Every other kind of type that we haven't called out already
3563    // that has an inner type is either (1) sugar or (2) contains that
3564    // inner type in some way as a subobject.
3565    if (TypeLoc Next = TL.getNextTypeLoc())
3566      return Visit(Next, Sel);
3567
3568    // If there's no inner type and we're in a permissive context,
3569    // don't diagnose.
3570    if (Sel == Sema::AbstractNone) return;
3571
3572    // Check whether the type matches the abstract type.
3573    QualType T = TL.getType();
3574    if (T->isArrayType()) {
3575      Sel = Sema::AbstractArrayType;
3576      T = Info.S.Context.getBaseElementType(T);
3577    }
3578    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3579    if (CT != Info.AbstractType) return;
3580
3581    // It matched; do some magic.
3582    if (Sel == Sema::AbstractArrayType) {
3583      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3584        << T << TL.getSourceRange();
3585    } else {
3586      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3587        << Sel << T << TL.getSourceRange();
3588    }
3589    Info.DiagnoseAbstractType();
3590  }
3591};
3592
3593void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3594                                  Sema::AbstractDiagSelID Sel) {
3595  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3596}
3597
3598}
3599
3600/// Check for invalid uses of an abstract type in a method declaration.
3601static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3602                                    CXXMethodDecl *MD) {
3603  // No need to do the check on definitions, which require that
3604  // the return/param types be complete.
3605  if (MD->doesThisDeclarationHaveABody())
3606    return;
3607
3608  // For safety's sake, just ignore it if we don't have type source
3609  // information.  This should never happen for non-implicit methods,
3610  // but...
3611  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3612    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3613}
3614
3615/// Check for invalid uses of an abstract type within a class definition.
3616static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3617                                    CXXRecordDecl *RD) {
3618  for (CXXRecordDecl::decl_iterator
3619         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3620    Decl *D = *I;
3621    if (D->isImplicit()) continue;
3622
3623    // Methods and method templates.
3624    if (isa<CXXMethodDecl>(D)) {
3625      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3626    } else if (isa<FunctionTemplateDecl>(D)) {
3627      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3628      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3629
3630    // Fields and static variables.
3631    } else if (isa<FieldDecl>(D)) {
3632      FieldDecl *FD = cast<FieldDecl>(D);
3633      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3634        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3635    } else if (isa<VarDecl>(D)) {
3636      VarDecl *VD = cast<VarDecl>(D);
3637      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3638        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3639
3640    // Nested classes and class templates.
3641    } else if (isa<CXXRecordDecl>(D)) {
3642      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3643    } else if (isa<ClassTemplateDecl>(D)) {
3644      CheckAbstractClassUsage(Info,
3645                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3646    }
3647  }
3648}
3649
3650/// \brief Perform semantic checks on a class definition that has been
3651/// completing, introducing implicitly-declared members, checking for
3652/// abstract types, etc.
3653void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3654  if (!Record)
3655    return;
3656
3657  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3658    AbstractUsageInfo Info(*this, Record);
3659    CheckAbstractClassUsage(Info, Record);
3660  }
3661
3662  // If this is not an aggregate type and has no user-declared constructor,
3663  // complain about any non-static data members of reference or const scalar
3664  // type, since they will never get initializers.
3665  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3666      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3667      !Record->isLambda()) {
3668    bool Complained = false;
3669    for (RecordDecl::field_iterator F = Record->field_begin(),
3670                                 FEnd = Record->field_end();
3671         F != FEnd; ++F) {
3672      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3673        continue;
3674
3675      if (F->getType()->isReferenceType() ||
3676          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3677        if (!Complained) {
3678          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3679            << Record->getTagKind() << Record;
3680          Complained = true;
3681        }
3682
3683        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3684          << F->getType()->isReferenceType()
3685          << F->getDeclName();
3686      }
3687    }
3688  }
3689
3690  if (Record->isDynamicClass() && !Record->isDependentType())
3691    DynamicClasses.push_back(Record);
3692
3693  if (Record->getIdentifier()) {
3694    // C++ [class.mem]p13:
3695    //   If T is the name of a class, then each of the following shall have a
3696    //   name different from T:
3697    //     - every member of every anonymous union that is a member of class T.
3698    //
3699    // C++ [class.mem]p14:
3700    //   In addition, if class T has a user-declared constructor (12.1), every
3701    //   non-static data member of class T shall have a name different from T.
3702    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3703         R.first != R.second; ++R.first) {
3704      NamedDecl *D = *R.first;
3705      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3706          isa<IndirectFieldDecl>(D)) {
3707        Diag(D->getLocation(), diag::err_member_name_of_class)
3708          << D->getDeclName();
3709        break;
3710      }
3711    }
3712  }
3713
3714  // Warn if the class has virtual methods but non-virtual public destructor.
3715  if (Record->isPolymorphic() && !Record->isDependentType()) {
3716    CXXDestructorDecl *dtor = Record->getDestructor();
3717    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3718      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3719           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3720  }
3721
3722  // See if a method overloads virtual methods in a base
3723  /// class without overriding any.
3724  if (!Record->isDependentType()) {
3725    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3726                                     MEnd = Record->method_end();
3727         M != MEnd; ++M) {
3728      if (!(*M)->isStatic())
3729        DiagnoseHiddenVirtualMethods(Record, *M);
3730    }
3731  }
3732
3733  // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3734  // function that is not a constructor declares that member function to be
3735  // const. [...] The class of which that function is a member shall be
3736  // a literal type.
3737  //
3738  // If the class has virtual bases, any constexpr members will already have
3739  // been diagnosed by the checks performed on the member declaration, so
3740  // suppress this (less useful) diagnostic.
3741  if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3742      !Record->isLiteral() && !Record->getNumVBases()) {
3743    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3744                                     MEnd = Record->method_end();
3745         M != MEnd; ++M) {
3746      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3747        switch (Record->getTemplateSpecializationKind()) {
3748        case TSK_ImplicitInstantiation:
3749        case TSK_ExplicitInstantiationDeclaration:
3750        case TSK_ExplicitInstantiationDefinition:
3751          // If a template instantiates to a non-literal type, but its members
3752          // instantiate to constexpr functions, the template is technically
3753          // ill-formed, but we allow it for sanity.
3754          continue;
3755
3756        case TSK_Undeclared:
3757        case TSK_ExplicitSpecialization:
3758          RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3759                             PDiag(diag::err_constexpr_method_non_literal));
3760          break;
3761        }
3762
3763        // Only produce one error per class.
3764        break;
3765      }
3766    }
3767  }
3768
3769  // Declare inherited constructors. We do this eagerly here because:
3770  // - The standard requires an eager diagnostic for conflicting inherited
3771  //   constructors from different classes.
3772  // - The lazy declaration of the other implicit constructors is so as to not
3773  //   waste space and performance on classes that are not meant to be
3774  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3775  //   have inherited constructors.
3776  DeclareInheritedConstructors(Record);
3777
3778  if (!Record->isDependentType())
3779    CheckExplicitlyDefaultedMethods(Record);
3780}
3781
3782void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3783  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3784                                      ME = Record->method_end();
3785       MI != ME; ++MI) {
3786    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3787      switch (getSpecialMember(*MI)) {
3788      case CXXDefaultConstructor:
3789        CheckExplicitlyDefaultedDefaultConstructor(
3790                                                  cast<CXXConstructorDecl>(*MI));
3791        break;
3792
3793      case CXXDestructor:
3794        CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3795        break;
3796
3797      case CXXCopyConstructor:
3798        CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3799        break;
3800
3801      case CXXCopyAssignment:
3802        CheckExplicitlyDefaultedCopyAssignment(*MI);
3803        break;
3804
3805      case CXXMoveConstructor:
3806        CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
3807        break;
3808
3809      case CXXMoveAssignment:
3810        CheckExplicitlyDefaultedMoveAssignment(*MI);
3811        break;
3812
3813      case CXXInvalid:
3814        llvm_unreachable("non-special member explicitly defaulted!");
3815      }
3816    }
3817  }
3818
3819}
3820
3821void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3822  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3823
3824  // Whether this was the first-declared instance of the constructor.
3825  // This affects whether we implicitly add an exception spec (and, eventually,
3826  // constexpr). It is also ill-formed to explicitly default a constructor such
3827  // that it would be deleted. (C++0x [decl.fct.def.default])
3828  bool First = CD == CD->getCanonicalDecl();
3829
3830  bool HadError = false;
3831  if (CD->getNumParams() != 0) {
3832    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3833      << CD->getSourceRange();
3834    HadError = true;
3835  }
3836
3837  ImplicitExceptionSpecification Spec
3838    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3839  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3840  if (EPI.ExceptionSpecType == EST_Delayed) {
3841    // Exception specification depends on some deferred part of the class. We'll
3842    // try again when the class's definition has been fully processed.
3843    return;
3844  }
3845  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3846                          *ExceptionType = Context.getFunctionType(
3847                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3848
3849  // C++11 [dcl.fct.def.default]p2:
3850  //   An explicitly-defaulted function may be declared constexpr only if it
3851  //   would have been implicitly declared as constexpr,
3852  // Do not apply this rule to templates, since core issue 1358 makes such
3853  // functions always instantiate to constexpr functions.
3854  if (CD->isConstexpr() &&
3855      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
3856    if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3857      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3858        << CXXDefaultConstructor;
3859      HadError = true;
3860    }
3861  }
3862  //   and may have an explicit exception-specification only if it is compatible
3863  //   with the exception-specification on the implicit declaration.
3864  if (CtorType->hasExceptionSpec()) {
3865    if (CheckEquivalentExceptionSpec(
3866          PDiag(diag::err_incorrect_defaulted_exception_spec)
3867            << CXXDefaultConstructor,
3868          PDiag(),
3869          ExceptionType, SourceLocation(),
3870          CtorType, CD->getLocation())) {
3871      HadError = true;
3872    }
3873  }
3874
3875  //   If a function is explicitly defaulted on its first declaration,
3876  if (First) {
3877    //  -- it is implicitly considered to be constexpr if the implicit
3878    //     definition would be,
3879    CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3880
3881    //  -- it is implicitly considered to have the same
3882    //     exception-specification as if it had been implicitly declared
3883    //
3884    // FIXME: a compatible, but different, explicit exception specification
3885    // will be silently overridden. We should issue a warning if this happens.
3886    EPI.ExtInfo = CtorType->getExtInfo();
3887
3888    // Such a function is also trivial if the implicitly-declared function
3889    // would have been.
3890    CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
3891  }
3892
3893  if (HadError) {
3894    CD->setInvalidDecl();
3895    return;
3896  }
3897
3898  if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
3899    if (First) {
3900      CD->setDeletedAsWritten();
3901    } else {
3902      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3903        << CXXDefaultConstructor;
3904      CD->setInvalidDecl();
3905    }
3906  }
3907}
3908
3909void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3910  assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3911
3912  // Whether this was the first-declared instance of the constructor.
3913  bool First = CD == CD->getCanonicalDecl();
3914
3915  bool HadError = false;
3916  if (CD->getNumParams() != 1) {
3917    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3918      << CD->getSourceRange();
3919    HadError = true;
3920  }
3921
3922  ImplicitExceptionSpecification Spec(Context);
3923  bool Const;
3924  llvm::tie(Spec, Const) =
3925    ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3926
3927  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3928  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3929                          *ExceptionType = Context.getFunctionType(
3930                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3931
3932  // Check for parameter type matching.
3933  // This is a copy ctor so we know it's a cv-qualified reference to T.
3934  QualType ArgType = CtorType->getArgType(0);
3935  if (ArgType->getPointeeType().isVolatileQualified()) {
3936    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3937    HadError = true;
3938  }
3939  if (ArgType->getPointeeType().isConstQualified() && !Const) {
3940    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3941    HadError = true;
3942  }
3943
3944  // C++11 [dcl.fct.def.default]p2:
3945  //   An explicitly-defaulted function may be declared constexpr only if it
3946  //   would have been implicitly declared as constexpr,
3947  // Do not apply this rule to templates, since core issue 1358 makes such
3948  // functions always instantiate to constexpr functions.
3949  if (CD->isConstexpr() &&
3950      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
3951    if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3952      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3953        << CXXCopyConstructor;
3954      HadError = true;
3955    }
3956  }
3957  //   and may have an explicit exception-specification only if it is compatible
3958  //   with the exception-specification on the implicit declaration.
3959  if (CtorType->hasExceptionSpec()) {
3960    if (CheckEquivalentExceptionSpec(
3961          PDiag(diag::err_incorrect_defaulted_exception_spec)
3962            << CXXCopyConstructor,
3963          PDiag(),
3964          ExceptionType, SourceLocation(),
3965          CtorType, CD->getLocation())) {
3966      HadError = true;
3967    }
3968  }
3969
3970  //   If a function is explicitly defaulted on its first declaration,
3971  if (First) {
3972    //  -- it is implicitly considered to be constexpr if the implicit
3973    //     definition would be,
3974    CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3975
3976    //  -- it is implicitly considered to have the same
3977    //     exception-specification as if it had been implicitly declared, and
3978    //
3979    // FIXME: a compatible, but different, explicit exception specification
3980    // will be silently overridden. We should issue a warning if this happens.
3981    EPI.ExtInfo = CtorType->getExtInfo();
3982
3983    //  -- [...] it shall have the same parameter type as if it had been
3984    //     implicitly declared.
3985    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3986
3987    // Such a function is also trivial if the implicitly-declared function
3988    // would have been.
3989    CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
3990  }
3991
3992  if (HadError) {
3993    CD->setInvalidDecl();
3994    return;
3995  }
3996
3997  if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
3998    if (First) {
3999      CD->setDeletedAsWritten();
4000    } else {
4001      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4002        << CXXCopyConstructor;
4003      CD->setInvalidDecl();
4004    }
4005  }
4006}
4007
4008void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4009  assert(MD->isExplicitlyDefaulted());
4010
4011  // Whether this was the first-declared instance of the operator
4012  bool First = MD == MD->getCanonicalDecl();
4013
4014  bool HadError = false;
4015  if (MD->getNumParams() != 1) {
4016    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4017      << MD->getSourceRange();
4018    HadError = true;
4019  }
4020
4021  QualType ReturnType =
4022    MD->getType()->getAs<FunctionType>()->getResultType();
4023  if (!ReturnType->isLValueReferenceType() ||
4024      !Context.hasSameType(
4025        Context.getCanonicalType(ReturnType->getPointeeType()),
4026        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4027    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4028    HadError = true;
4029  }
4030
4031  ImplicitExceptionSpecification Spec(Context);
4032  bool Const;
4033  llvm::tie(Spec, Const) =
4034    ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4035
4036  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4037  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4038                          *ExceptionType = Context.getFunctionType(
4039                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4040
4041  QualType ArgType = OperType->getArgType(0);
4042  if (!ArgType->isLValueReferenceType()) {
4043    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4044    HadError = true;
4045  } else {
4046    if (ArgType->getPointeeType().isVolatileQualified()) {
4047      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4048      HadError = true;
4049    }
4050    if (ArgType->getPointeeType().isConstQualified() && !Const) {
4051      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4052      HadError = true;
4053    }
4054  }
4055
4056  if (OperType->getTypeQuals()) {
4057    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4058    HadError = true;
4059  }
4060
4061  if (OperType->hasExceptionSpec()) {
4062    if (CheckEquivalentExceptionSpec(
4063          PDiag(diag::err_incorrect_defaulted_exception_spec)
4064            << CXXCopyAssignment,
4065          PDiag(),
4066          ExceptionType, SourceLocation(),
4067          OperType, MD->getLocation())) {
4068      HadError = true;
4069    }
4070  }
4071  if (First) {
4072    // We set the declaration to have the computed exception spec here.
4073    // We duplicate the one parameter type.
4074    EPI.RefQualifier = OperType->getRefQualifier();
4075    EPI.ExtInfo = OperType->getExtInfo();
4076    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4077
4078    // Such a function is also trivial if the implicitly-declared function
4079    // would have been.
4080    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
4081  }
4082
4083  if (HadError) {
4084    MD->setInvalidDecl();
4085    return;
4086  }
4087
4088  if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
4089    if (First) {
4090      MD->setDeletedAsWritten();
4091    } else {
4092      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4093        << CXXCopyAssignment;
4094      MD->setInvalidDecl();
4095    }
4096  }
4097}
4098
4099void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4100  assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4101
4102  // Whether this was the first-declared instance of the constructor.
4103  bool First = CD == CD->getCanonicalDecl();
4104
4105  bool HadError = false;
4106  if (CD->getNumParams() != 1) {
4107    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4108      << CD->getSourceRange();
4109    HadError = true;
4110  }
4111
4112  ImplicitExceptionSpecification Spec(
4113      ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4114
4115  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4116  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4117                          *ExceptionType = Context.getFunctionType(
4118                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4119
4120  // Check for parameter type matching.
4121  // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4122  QualType ArgType = CtorType->getArgType(0);
4123  if (ArgType->getPointeeType().isVolatileQualified()) {
4124    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4125    HadError = true;
4126  }
4127  if (ArgType->getPointeeType().isConstQualified()) {
4128    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4129    HadError = true;
4130  }
4131
4132  // C++11 [dcl.fct.def.default]p2:
4133  //   An explicitly-defaulted function may be declared constexpr only if it
4134  //   would have been implicitly declared as constexpr,
4135  // Do not apply this rule to templates, since core issue 1358 makes such
4136  // functions always instantiate to constexpr functions.
4137  if (CD->isConstexpr() &&
4138      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4139    if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4140      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4141        << CXXMoveConstructor;
4142      HadError = true;
4143    }
4144  }
4145  //   and may have an explicit exception-specification only if it is compatible
4146  //   with the exception-specification on the implicit declaration.
4147  if (CtorType->hasExceptionSpec()) {
4148    if (CheckEquivalentExceptionSpec(
4149          PDiag(diag::err_incorrect_defaulted_exception_spec)
4150            << CXXMoveConstructor,
4151          PDiag(),
4152          ExceptionType, SourceLocation(),
4153          CtorType, CD->getLocation())) {
4154      HadError = true;
4155    }
4156  }
4157
4158  //   If a function is explicitly defaulted on its first declaration,
4159  if (First) {
4160    //  -- it is implicitly considered to be constexpr if the implicit
4161    //     definition would be,
4162    CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4163
4164    //  -- it is implicitly considered to have the same
4165    //     exception-specification as if it had been implicitly declared, and
4166    //
4167    // FIXME: a compatible, but different, explicit exception specification
4168    // will be silently overridden. We should issue a warning if this happens.
4169    EPI.ExtInfo = CtorType->getExtInfo();
4170
4171    //  -- [...] it shall have the same parameter type as if it had been
4172    //     implicitly declared.
4173    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4174
4175    // Such a function is also trivial if the implicitly-declared function
4176    // would have been.
4177    CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
4178  }
4179
4180  if (HadError) {
4181    CD->setInvalidDecl();
4182    return;
4183  }
4184
4185  if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
4186    if (First) {
4187      CD->setDeletedAsWritten();
4188    } else {
4189      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4190        << CXXMoveConstructor;
4191      CD->setInvalidDecl();
4192    }
4193  }
4194}
4195
4196void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4197  assert(MD->isExplicitlyDefaulted());
4198
4199  // Whether this was the first-declared instance of the operator
4200  bool First = MD == MD->getCanonicalDecl();
4201
4202  bool HadError = false;
4203  if (MD->getNumParams() != 1) {
4204    Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4205      << MD->getSourceRange();
4206    HadError = true;
4207  }
4208
4209  QualType ReturnType =
4210    MD->getType()->getAs<FunctionType>()->getResultType();
4211  if (!ReturnType->isLValueReferenceType() ||
4212      !Context.hasSameType(
4213        Context.getCanonicalType(ReturnType->getPointeeType()),
4214        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4215    Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4216    HadError = true;
4217  }
4218
4219  ImplicitExceptionSpecification Spec(
4220      ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4221
4222  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4223  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4224                          *ExceptionType = Context.getFunctionType(
4225                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4226
4227  QualType ArgType = OperType->getArgType(0);
4228  if (!ArgType->isRValueReferenceType()) {
4229    Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4230    HadError = true;
4231  } else {
4232    if (ArgType->getPointeeType().isVolatileQualified()) {
4233      Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4234      HadError = true;
4235    }
4236    if (ArgType->getPointeeType().isConstQualified()) {
4237      Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4238      HadError = true;
4239    }
4240  }
4241
4242  if (OperType->getTypeQuals()) {
4243    Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4244    HadError = true;
4245  }
4246
4247  if (OperType->hasExceptionSpec()) {
4248    if (CheckEquivalentExceptionSpec(
4249          PDiag(diag::err_incorrect_defaulted_exception_spec)
4250            << CXXMoveAssignment,
4251          PDiag(),
4252          ExceptionType, SourceLocation(),
4253          OperType, MD->getLocation())) {
4254      HadError = true;
4255    }
4256  }
4257  if (First) {
4258    // We set the declaration to have the computed exception spec here.
4259    // We duplicate the one parameter type.
4260    EPI.RefQualifier = OperType->getRefQualifier();
4261    EPI.ExtInfo = OperType->getExtInfo();
4262    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4263
4264    // Such a function is also trivial if the implicitly-declared function
4265    // would have been.
4266    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
4267  }
4268
4269  if (HadError) {
4270    MD->setInvalidDecl();
4271    return;
4272  }
4273
4274  if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
4275    if (First) {
4276      MD->setDeletedAsWritten();
4277    } else {
4278      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4279        << CXXMoveAssignment;
4280      MD->setInvalidDecl();
4281    }
4282  }
4283}
4284
4285void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4286  assert(DD->isExplicitlyDefaulted());
4287
4288  // Whether this was the first-declared instance of the destructor.
4289  bool First = DD == DD->getCanonicalDecl();
4290
4291  ImplicitExceptionSpecification Spec
4292    = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4293  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4294  const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4295                          *ExceptionType = Context.getFunctionType(
4296                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4297
4298  if (DtorType->hasExceptionSpec()) {
4299    if (CheckEquivalentExceptionSpec(
4300          PDiag(diag::err_incorrect_defaulted_exception_spec)
4301            << CXXDestructor,
4302          PDiag(),
4303          ExceptionType, SourceLocation(),
4304          DtorType, DD->getLocation())) {
4305      DD->setInvalidDecl();
4306      return;
4307    }
4308  }
4309  if (First) {
4310    // We set the declaration to have the computed exception spec here.
4311    // There are no parameters.
4312    EPI.ExtInfo = DtorType->getExtInfo();
4313    DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4314
4315    // Such a function is also trivial if the implicitly-declared function
4316    // would have been.
4317    DD->setTrivial(DD->getParent()->hasTrivialDestructor());
4318  }
4319
4320  if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
4321    if (First) {
4322      DD->setDeletedAsWritten();
4323    } else {
4324      Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
4325        << CXXDestructor;
4326      DD->setInvalidDecl();
4327    }
4328  }
4329}
4330
4331namespace {
4332struct SpecialMemberDeletionInfo {
4333  Sema &S;
4334  CXXMethodDecl *MD;
4335  Sema::CXXSpecialMember CSM;
4336
4337  // Properties of the special member, computed for convenience.
4338  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4339  SourceLocation Loc;
4340
4341  bool AllFieldsAreConst;
4342
4343  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4344                            Sema::CXXSpecialMember CSM)
4345    : S(S), MD(MD), CSM(CSM),
4346      IsConstructor(false), IsAssignment(false), IsMove(false),
4347      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4348      AllFieldsAreConst(true) {
4349    switch (CSM) {
4350      case Sema::CXXDefaultConstructor:
4351      case Sema::CXXCopyConstructor:
4352        IsConstructor = true;
4353        break;
4354      case Sema::CXXMoveConstructor:
4355        IsConstructor = true;
4356        IsMove = true;
4357        break;
4358      case Sema::CXXCopyAssignment:
4359        IsAssignment = true;
4360        break;
4361      case Sema::CXXMoveAssignment:
4362        IsAssignment = true;
4363        IsMove = true;
4364        break;
4365      case Sema::CXXDestructor:
4366        break;
4367      case Sema::CXXInvalid:
4368        llvm_unreachable("invalid special member kind");
4369    }
4370
4371    if (MD->getNumParams()) {
4372      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4373      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4374    }
4375  }
4376
4377  bool inUnion() const { return MD->getParent()->isUnion(); }
4378
4379  /// Look up the corresponding special member in the given class.
4380  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4381    unsigned TQ = MD->getTypeQualifiers();
4382    return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4383                                 MD->getRefQualifier() == RQ_RValue,
4384                                 TQ & Qualifiers::Const,
4385                                 TQ & Qualifiers::Volatile);
4386  }
4387
4388  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, FieldDecl *Field);
4389
4390  bool shouldDeleteForBase(CXXRecordDecl *BaseDecl, bool IsVirtualBase);
4391  bool shouldDeleteForField(FieldDecl *FD);
4392  bool shouldDeleteForAllConstMembers();
4393};
4394}
4395
4396/// Check whether we should delete a special member function due to having a
4397/// direct or virtual base class or static data member of class type M.
4398bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4399    CXXRecordDecl *Class, FieldDecl *Field) {
4400  // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
4401  // -- any direct or virtual base class [...] has a type with a destructor
4402  //    that is deleted or inaccessible
4403  if (!IsAssignment) {
4404    CXXDestructorDecl *Dtor = S.LookupDestructor(Class);
4405    if (Dtor->isDeleted())
4406      return true;
4407    if (S.CheckDestructorAccess(Loc, Dtor, S.PDiag()) != Sema::AR_accessible)
4408      return true;
4409
4410    // C++11 [class.dtor]p5:
4411    // -- X is a union-like class that has a variant member with a non-trivial
4412    //    destructor
4413    if (CSM == Sema::CXXDestructor && Field && Field->getParent()->isUnion() &&
4414        !Dtor->isTrivial())
4415      return true;
4416  }
4417
4418  // C++11 [class.ctor]p5:
4419  // -- any direct or virtual base class [...] has class type M [...] and
4420  //    either M has no default constructor or overload resolution as applied
4421  //    to M's default constructor results in an ambiguity or in a function
4422  //    that is deleted or inaccessible
4423  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4424  // -- a direct or virtual base class B that cannot be copied/moved because
4425  //    overload resolution, as applied to B's corresponding special member,
4426  //    results in an ambiguity or a function that is deleted or inaccessible
4427  //    from the defaulted special member
4428  // FIXME: in-class initializers should be handled here
4429  if (CSM != Sema::CXXDestructor) {
4430    Sema::SpecialMemberOverloadResult *SMOR = lookupIn(Class);
4431    if (!SMOR->hasSuccess())
4432      return true;
4433
4434    CXXMethodDecl *Member = SMOR->getMethod();
4435    // A member of a union must have a trivial corresponding special member.
4436    if (Field && Field->getParent()->isUnion() && !Member->isTrivial())
4437      return true;
4438
4439    if (IsConstructor) {
4440      CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Member);
4441      if (S.CheckConstructorAccess(Loc, Ctor, Ctor->getAccess(), S.PDiag())
4442            != Sema::AR_accessible)
4443        return true;
4444
4445      // -- for the move constructor, a [...] direct or virtual base class with
4446      //    a type that does not have a move constructor and is not trivially
4447      //    copyable.
4448      if (IsMove && !Ctor->isMoveConstructor() && !Class->isTriviallyCopyable())
4449        return true;
4450    } else {
4451      assert(IsAssignment && "unexpected kind of special member");
4452      if (S.CheckDirectMemberAccess(Loc, Member, S.PDiag())
4453            != Sema::AR_accessible)
4454        return true;
4455
4456      // -- for the move assignment operator, a direct base class with a type
4457      //    that does not have a move assignment operator and is not trivially
4458      //    copyable.
4459      if (IsMove && !Member->isMoveAssignmentOperator() &&
4460          !Class->isTriviallyCopyable())
4461        return true;
4462    }
4463  }
4464
4465  return false;
4466}
4467
4468/// Check whether we should delete a special member function due to the class
4469/// having a particular direct or virtual base class.
4470bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXRecordDecl *BaseDecl,
4471                                                    bool IsVirtualBase) {
4472  // C++11 [class.copy]p23:
4473  // -- for the move assignment operator, any direct or indirect virtual
4474  //    base class.
4475  if (CSM == Sema::CXXMoveAssignment && IsVirtualBase)
4476    return true;
4477
4478  if (shouldDeleteForClassSubobject(BaseDecl, 0))
4479    return true;
4480
4481  return false;
4482}
4483
4484/// Check whether we should delete a special member function due to the class
4485/// having a particular non-static data member.
4486bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4487  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4488  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4489
4490  if (CSM == Sema::CXXDefaultConstructor) {
4491    // For a default constructor, all references must be initialized in-class
4492    // and, if a union, it must have a non-const member.
4493    if (FieldType->isReferenceType() && !FD->hasInClassInitializer())
4494      return true;
4495
4496    if (inUnion() && !FieldType.isConstQualified())
4497      AllFieldsAreConst = false;
4498
4499    // C++11 [class.ctor]p5: any non-variant non-static data member of
4500    // const-qualified type (or array thereof) with no
4501    // brace-or-equal-initializer does not have a user-provided default
4502    // constructor.
4503    if (!inUnion() && FieldType.isConstQualified() &&
4504        !FD->hasInClassInitializer() &&
4505        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor()))
4506      return true;
4507  } else if (CSM == Sema::CXXCopyConstructor) {
4508    // For a copy constructor, data members must not be of rvalue reference
4509    // type.
4510    if (FieldType->isRValueReferenceType())
4511      return true;
4512  } else if (IsAssignment) {
4513    // For an assignment operator, data members must not be of reference type.
4514    if (FieldType->isReferenceType())
4515      return true;
4516  }
4517
4518  if (FieldRecord) {
4519    // Some additional restrictions exist on the variant members.
4520    if (!inUnion() && FieldRecord->isUnion() &&
4521        FieldRecord->isAnonymousStructOrUnion()) {
4522      bool AllVariantFieldsAreConst = true;
4523
4524      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4525                                         UE = FieldRecord->field_end();
4526           UI != UE; ++UI) {
4527        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4528
4529        if (!UnionFieldType.isConstQualified())
4530          AllVariantFieldsAreConst = false;
4531
4532        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4533        if (UnionFieldRecord &&
4534            shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4535          return true;
4536      }
4537
4538      // At least one member in each anonymous union must be non-const
4539      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4540          FieldRecord->field_begin() != FieldRecord->field_end())
4541        return true;
4542
4543      // Don't try to initialize the anonymous union
4544      // This is technically non-conformant, but sanity demands it.
4545      return false;
4546    }
4547
4548    // When checking a constructor, the field's destructor must be accessible
4549    // and not deleted.
4550    if (IsConstructor) {
4551      CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4552      if (FieldDtor->isDeleted())
4553        return true;
4554      if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4555          Sema::AR_accessible)
4556        return true;
4557    }
4558
4559    // Check that the corresponding member of the field is accessible,
4560    // unique, and non-deleted. We don't do this if it has an explicit
4561    // initialization when default-constructing.
4562    if (!(CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())) {
4563      Sema::SpecialMemberOverloadResult *SMOR = lookupIn(FieldRecord);
4564      if (!SMOR->hasSuccess())
4565        return true;
4566
4567      CXXMethodDecl *FieldMember = SMOR->getMethod();
4568
4569      // We need the corresponding member of a union to be trivial so that
4570      // we can safely process all members simultaneously.
4571      if (inUnion() && !FieldMember->isTrivial())
4572        return true;
4573
4574      if (IsConstructor) {
4575        CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4576        if (S.CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4577                                     S.PDiag()) != Sema::AR_accessible)
4578        return true;
4579
4580        // For a move operation, the corresponding operation must actually
4581        // be a move operation (and not a copy selected by overload
4582        // resolution) unless we are working on a trivially copyable class.
4583        if (IsMove && !FieldCtor->isMoveConstructor() &&
4584            !FieldRecord->isTriviallyCopyable())
4585          return true;
4586      } else if (CSM == Sema::CXXDestructor) {
4587        CXXDestructorDecl *FieldDtor = S.LookupDestructor(FieldRecord);
4588        if (FieldDtor->isDeleted())
4589          return true;
4590        if (S.CheckDestructorAccess(Loc, FieldDtor, S.PDiag()) !=
4591            Sema::AR_accessible)
4592          return true;
4593      } else {
4594        assert(IsAssignment && "unexpected kind of special member");
4595        if (S.CheckDirectMemberAccess(Loc, FieldMember, S.PDiag())
4596              != Sema::AR_accessible)
4597          return true;
4598
4599        // -- for the move assignment operator, a non-static data member with a
4600        //    type that does not have a move assignment operator and is not
4601        //    trivially copyable.
4602        if (IsMove && !FieldMember->isMoveAssignmentOperator() &&
4603            !FieldRecord->isTriviallyCopyable())
4604          return true;
4605      }
4606    }
4607  } else if (IsAssignment && FieldType.isConstQualified()) {
4608    // C++11 [class.copy]p23:
4609    // -- a non-static data member of const non-class type (or array thereof)
4610    return true;
4611  }
4612
4613  return false;
4614}
4615
4616/// C++11 [class.ctor] p5:
4617///   A defaulted default constructor for a class X is defined as deleted if
4618/// X is a union and all of its variant members are of const-qualified type.
4619bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4620  // This is a silly definition, because it gives an empty union a deleted
4621  // default constructor. Don't do that.
4622  return CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4623    (MD->getParent()->field_begin() != MD->getParent()->field_end());
4624}
4625
4626/// Determine whether a defaulted special member function should be defined as
4627/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4628/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4629bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4630  assert(!MD->isInvalidDecl());
4631  CXXRecordDecl *RD = MD->getParent();
4632  assert(!RD->isDependentType() && "do deletion after instantiation");
4633  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4634    return false;
4635
4636  // FIXME: Provide the ability to diagnose why a special member was deleted.
4637
4638  // C++11 [expr.lambda.prim]p19:
4639  //   The closure type associated with a lambda-expression has a
4640  //   deleted (8.4.3) default constructor and a deleted copy
4641  //   assignment operator.
4642  if (RD->isLambda() &&
4643      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment))
4644    return true;
4645
4646  // C++11 [class.dtor]p5:
4647  // -- for a virtual destructor, lookup of the non-array deallocation function
4648  //    results in an ambiguity or in a function that is deleted or inaccessible
4649  if (CSM == Sema::CXXDestructor && MD->isVirtual()) {
4650    FunctionDecl *OperatorDelete = 0;
4651    DeclarationName Name =
4652      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4653    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4654                                 OperatorDelete, false))
4655      return true;
4656  }
4657
4658  // For an anonymous struct or union, the copy and assignment special members
4659  // will never be used, so skip the check. For an anonymous union declared at
4660  // namespace scope, the constructor and destructor are used.
4661  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4662      RD->isAnonymousStructOrUnion())
4663    return false;
4664
4665  // Do access control from the special member function
4666  ContextRAII MethodContext(*this, MD);
4667
4668  SpecialMemberDeletionInfo SMI(*this, MD, CSM);
4669
4670  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4671                                          BE = RD->bases_end(); BI != BE; ++BI)
4672    if (!BI->isVirtual() &&
4673        SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), false))
4674      return true;
4675
4676  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4677                                          BE = RD->vbases_end(); BI != BE; ++BI)
4678    if (SMI.shouldDeleteForBase(BI->getType()->getAsCXXRecordDecl(), true))
4679      return true;
4680
4681  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4682                                     FE = RD->field_end(); FI != FE; ++FI)
4683    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4684        SMI.shouldDeleteForField(*FI))
4685      return true;
4686
4687  if (SMI.shouldDeleteForAllConstMembers())
4688    return true;
4689
4690  return false;
4691}
4692
4693/// \brief Data used with FindHiddenVirtualMethod
4694namespace {
4695  struct FindHiddenVirtualMethodData {
4696    Sema *S;
4697    CXXMethodDecl *Method;
4698    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4699    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4700  };
4701}
4702
4703/// \brief Member lookup function that determines whether a given C++
4704/// method overloads virtual methods in a base class without overriding any,
4705/// to be used with CXXRecordDecl::lookupInBases().
4706static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4707                                    CXXBasePath &Path,
4708                                    void *UserData) {
4709  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4710
4711  FindHiddenVirtualMethodData &Data
4712    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4713
4714  DeclarationName Name = Data.Method->getDeclName();
4715  assert(Name.getNameKind() == DeclarationName::Identifier);
4716
4717  bool foundSameNameMethod = false;
4718  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4719  for (Path.Decls = BaseRecord->lookup(Name);
4720       Path.Decls.first != Path.Decls.second;
4721       ++Path.Decls.first) {
4722    NamedDecl *D = *Path.Decls.first;
4723    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4724      MD = MD->getCanonicalDecl();
4725      foundSameNameMethod = true;
4726      // Interested only in hidden virtual methods.
4727      if (!MD->isVirtual())
4728        continue;
4729      // If the method we are checking overrides a method from its base
4730      // don't warn about the other overloaded methods.
4731      if (!Data.S->IsOverload(Data.Method, MD, false))
4732        return true;
4733      // Collect the overload only if its hidden.
4734      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4735        overloadedMethods.push_back(MD);
4736    }
4737  }
4738
4739  if (foundSameNameMethod)
4740    Data.OverloadedMethods.append(overloadedMethods.begin(),
4741                                   overloadedMethods.end());
4742  return foundSameNameMethod;
4743}
4744
4745/// \brief See if a method overloads virtual methods in a base class without
4746/// overriding any.
4747void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4748  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4749                               MD->getLocation()) == DiagnosticsEngine::Ignored)
4750    return;
4751  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4752    return;
4753
4754  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4755                     /*bool RecordPaths=*/false,
4756                     /*bool DetectVirtual=*/false);
4757  FindHiddenVirtualMethodData Data;
4758  Data.Method = MD;
4759  Data.S = this;
4760
4761  // Keep the base methods that were overriden or introduced in the subclass
4762  // by 'using' in a set. A base method not in this set is hidden.
4763  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4764       res.first != res.second; ++res.first) {
4765    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4766      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4767                                          E = MD->end_overridden_methods();
4768           I != E; ++I)
4769        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4770    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4771      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4772        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4773  }
4774
4775  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4776      !Data.OverloadedMethods.empty()) {
4777    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4778      << MD << (Data.OverloadedMethods.size() > 1);
4779
4780    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4781      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4782      Diag(overloadedMD->getLocation(),
4783           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4784    }
4785  }
4786}
4787
4788void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4789                                             Decl *TagDecl,
4790                                             SourceLocation LBrac,
4791                                             SourceLocation RBrac,
4792                                             AttributeList *AttrList) {
4793  if (!TagDecl)
4794    return;
4795
4796  AdjustDeclIfTemplate(TagDecl);
4797
4798  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4799              // strict aliasing violation!
4800              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4801              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4802
4803  CheckCompletedCXXClass(
4804                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4805}
4806
4807/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4808/// special functions, such as the default constructor, copy
4809/// constructor, or destructor, to the given C++ class (C++
4810/// [special]p1).  This routine can only be executed just before the
4811/// definition of the class is complete.
4812void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4813  if (!ClassDecl->hasUserDeclaredConstructor())
4814    ++ASTContext::NumImplicitDefaultConstructors;
4815
4816  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4817    ++ASTContext::NumImplicitCopyConstructors;
4818
4819  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4820    ++ASTContext::NumImplicitMoveConstructors;
4821
4822  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4823    ++ASTContext::NumImplicitCopyAssignmentOperators;
4824
4825    // If we have a dynamic class, then the copy assignment operator may be
4826    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4827    // it shows up in the right place in the vtable and that we diagnose
4828    // problems with the implicit exception specification.
4829    if (ClassDecl->isDynamicClass())
4830      DeclareImplicitCopyAssignment(ClassDecl);
4831  }
4832
4833  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
4834    ++ASTContext::NumImplicitMoveAssignmentOperators;
4835
4836    // Likewise for the move assignment operator.
4837    if (ClassDecl->isDynamicClass())
4838      DeclareImplicitMoveAssignment(ClassDecl);
4839  }
4840
4841  if (!ClassDecl->hasUserDeclaredDestructor()) {
4842    ++ASTContext::NumImplicitDestructors;
4843
4844    // If we have a dynamic class, then the destructor may be virtual, so we
4845    // have to declare the destructor immediately. This ensures that, e.g., it
4846    // shows up in the right place in the vtable and that we diagnose problems
4847    // with the implicit exception specification.
4848    if (ClassDecl->isDynamicClass())
4849      DeclareImplicitDestructor(ClassDecl);
4850  }
4851}
4852
4853void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4854  if (!D)
4855    return;
4856
4857  int NumParamList = D->getNumTemplateParameterLists();
4858  for (int i = 0; i < NumParamList; i++) {
4859    TemplateParameterList* Params = D->getTemplateParameterList(i);
4860    for (TemplateParameterList::iterator Param = Params->begin(),
4861                                      ParamEnd = Params->end();
4862          Param != ParamEnd; ++Param) {
4863      NamedDecl *Named = cast<NamedDecl>(*Param);
4864      if (Named->getDeclName()) {
4865        S->AddDecl(Named);
4866        IdResolver.AddDecl(Named);
4867      }
4868    }
4869  }
4870}
4871
4872void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4873  if (!D)
4874    return;
4875
4876  TemplateParameterList *Params = 0;
4877  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4878    Params = Template->getTemplateParameters();
4879  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4880           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4881    Params = PartialSpec->getTemplateParameters();
4882  else
4883    return;
4884
4885  for (TemplateParameterList::iterator Param = Params->begin(),
4886                                    ParamEnd = Params->end();
4887       Param != ParamEnd; ++Param) {
4888    NamedDecl *Named = cast<NamedDecl>(*Param);
4889    if (Named->getDeclName()) {
4890      S->AddDecl(Named);
4891      IdResolver.AddDecl(Named);
4892    }
4893  }
4894}
4895
4896void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4897  if (!RecordD) return;
4898  AdjustDeclIfTemplate(RecordD);
4899  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4900  PushDeclContext(S, Record);
4901}
4902
4903void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4904  if (!RecordD) return;
4905  PopDeclContext();
4906}
4907
4908/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4909/// parsing a top-level (non-nested) C++ class, and we are now
4910/// parsing those parts of the given Method declaration that could
4911/// not be parsed earlier (C++ [class.mem]p2), such as default
4912/// arguments. This action should enter the scope of the given
4913/// Method declaration as if we had just parsed the qualified method
4914/// name. However, it should not bring the parameters into scope;
4915/// that will be performed by ActOnDelayedCXXMethodParameter.
4916void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4917}
4918
4919/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4920/// C++ method declaration. We're (re-)introducing the given
4921/// function parameter into scope for use in parsing later parts of
4922/// the method declaration. For example, we could see an
4923/// ActOnParamDefaultArgument event for this parameter.
4924void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4925  if (!ParamD)
4926    return;
4927
4928  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4929
4930  // If this parameter has an unparsed default argument, clear it out
4931  // to make way for the parsed default argument.
4932  if (Param->hasUnparsedDefaultArg())
4933    Param->setDefaultArg(0);
4934
4935  S->AddDecl(Param);
4936  if (Param->getDeclName())
4937    IdResolver.AddDecl(Param);
4938}
4939
4940/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4941/// processing the delayed method declaration for Method. The method
4942/// declaration is now considered finished. There may be a separate
4943/// ActOnStartOfFunctionDef action later (not necessarily
4944/// immediately!) for this method, if it was also defined inside the
4945/// class body.
4946void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4947  if (!MethodD)
4948    return;
4949
4950  AdjustDeclIfTemplate(MethodD);
4951
4952  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4953
4954  // Now that we have our default arguments, check the constructor
4955  // again. It could produce additional diagnostics or affect whether
4956  // the class has implicitly-declared destructors, among other
4957  // things.
4958  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4959    CheckConstructor(Constructor);
4960
4961  // Check the default arguments, which we may have added.
4962  if (!Method->isInvalidDecl())
4963    CheckCXXDefaultArguments(Method);
4964}
4965
4966/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4967/// the well-formedness of the constructor declarator @p D with type @p
4968/// R. If there are any errors in the declarator, this routine will
4969/// emit diagnostics and set the invalid bit to true.  In any case, the type
4970/// will be updated to reflect a well-formed type for the constructor and
4971/// returned.
4972QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4973                                          StorageClass &SC) {
4974  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4975
4976  // C++ [class.ctor]p3:
4977  //   A constructor shall not be virtual (10.3) or static (9.4). A
4978  //   constructor can be invoked for a const, volatile or const
4979  //   volatile object. A constructor shall not be declared const,
4980  //   volatile, or const volatile (9.3.2).
4981  if (isVirtual) {
4982    if (!D.isInvalidType())
4983      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4984        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4985        << SourceRange(D.getIdentifierLoc());
4986    D.setInvalidType();
4987  }
4988  if (SC == SC_Static) {
4989    if (!D.isInvalidType())
4990      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4991        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4992        << SourceRange(D.getIdentifierLoc());
4993    D.setInvalidType();
4994    SC = SC_None;
4995  }
4996
4997  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4998  if (FTI.TypeQuals != 0) {
4999    if (FTI.TypeQuals & Qualifiers::Const)
5000      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5001        << "const" << SourceRange(D.getIdentifierLoc());
5002    if (FTI.TypeQuals & Qualifiers::Volatile)
5003      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5004        << "volatile" << SourceRange(D.getIdentifierLoc());
5005    if (FTI.TypeQuals & Qualifiers::Restrict)
5006      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5007        << "restrict" << SourceRange(D.getIdentifierLoc());
5008    D.setInvalidType();
5009  }
5010
5011  // C++0x [class.ctor]p4:
5012  //   A constructor shall not be declared with a ref-qualifier.
5013  if (FTI.hasRefQualifier()) {
5014    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5015      << FTI.RefQualifierIsLValueRef
5016      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5017    D.setInvalidType();
5018  }
5019
5020  // Rebuild the function type "R" without any type qualifiers (in
5021  // case any of the errors above fired) and with "void" as the
5022  // return type, since constructors don't have return types.
5023  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5024  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5025    return R;
5026
5027  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5028  EPI.TypeQuals = 0;
5029  EPI.RefQualifier = RQ_None;
5030
5031  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5032                                 Proto->getNumArgs(), EPI);
5033}
5034
5035/// CheckConstructor - Checks a fully-formed constructor for
5036/// well-formedness, issuing any diagnostics required. Returns true if
5037/// the constructor declarator is invalid.
5038void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5039  CXXRecordDecl *ClassDecl
5040    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5041  if (!ClassDecl)
5042    return Constructor->setInvalidDecl();
5043
5044  // C++ [class.copy]p3:
5045  //   A declaration of a constructor for a class X is ill-formed if
5046  //   its first parameter is of type (optionally cv-qualified) X and
5047  //   either there are no other parameters or else all other
5048  //   parameters have default arguments.
5049  if (!Constructor->isInvalidDecl() &&
5050      ((Constructor->getNumParams() == 1) ||
5051       (Constructor->getNumParams() > 1 &&
5052        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5053      Constructor->getTemplateSpecializationKind()
5054                                              != TSK_ImplicitInstantiation) {
5055    QualType ParamType = Constructor->getParamDecl(0)->getType();
5056    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5057    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5058      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5059      const char *ConstRef
5060        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5061                                                        : " const &";
5062      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5063        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5064
5065      // FIXME: Rather that making the constructor invalid, we should endeavor
5066      // to fix the type.
5067      Constructor->setInvalidDecl();
5068    }
5069  }
5070}
5071
5072/// CheckDestructor - Checks a fully-formed destructor definition for
5073/// well-formedness, issuing any diagnostics required.  Returns true
5074/// on error.
5075bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5076  CXXRecordDecl *RD = Destructor->getParent();
5077
5078  if (Destructor->isVirtual()) {
5079    SourceLocation Loc;
5080
5081    if (!Destructor->isImplicit())
5082      Loc = Destructor->getLocation();
5083    else
5084      Loc = RD->getLocation();
5085
5086    // If we have a virtual destructor, look up the deallocation function
5087    FunctionDecl *OperatorDelete = 0;
5088    DeclarationName Name =
5089    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5090    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5091      return true;
5092
5093    MarkFunctionReferenced(Loc, OperatorDelete);
5094
5095    Destructor->setOperatorDelete(OperatorDelete);
5096  }
5097
5098  return false;
5099}
5100
5101static inline bool
5102FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5103  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5104          FTI.ArgInfo[0].Param &&
5105          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5106}
5107
5108/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5109/// the well-formednes of the destructor declarator @p D with type @p
5110/// R. If there are any errors in the declarator, this routine will
5111/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5112/// will be updated to reflect a well-formed type for the destructor and
5113/// returned.
5114QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5115                                         StorageClass& SC) {
5116  // C++ [class.dtor]p1:
5117  //   [...] A typedef-name that names a class is a class-name
5118  //   (7.1.3); however, a typedef-name that names a class shall not
5119  //   be used as the identifier in the declarator for a destructor
5120  //   declaration.
5121  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5122  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5123    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5124      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5125  else if (const TemplateSpecializationType *TST =
5126             DeclaratorType->getAs<TemplateSpecializationType>())
5127    if (TST->isTypeAlias())
5128      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5129        << DeclaratorType << 1;
5130
5131  // C++ [class.dtor]p2:
5132  //   A destructor is used to destroy objects of its class type. A
5133  //   destructor takes no parameters, and no return type can be
5134  //   specified for it (not even void). The address of a destructor
5135  //   shall not be taken. A destructor shall not be static. A
5136  //   destructor can be invoked for a const, volatile or const
5137  //   volatile object. A destructor shall not be declared const,
5138  //   volatile or const volatile (9.3.2).
5139  if (SC == SC_Static) {
5140    if (!D.isInvalidType())
5141      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5142        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5143        << SourceRange(D.getIdentifierLoc())
5144        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5145
5146    SC = SC_None;
5147  }
5148  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5149    // Destructors don't have return types, but the parser will
5150    // happily parse something like:
5151    //
5152    //   class X {
5153    //     float ~X();
5154    //   };
5155    //
5156    // The return type will be eliminated later.
5157    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5158      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5159      << SourceRange(D.getIdentifierLoc());
5160  }
5161
5162  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5163  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5164    if (FTI.TypeQuals & Qualifiers::Const)
5165      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5166        << "const" << SourceRange(D.getIdentifierLoc());
5167    if (FTI.TypeQuals & Qualifiers::Volatile)
5168      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5169        << "volatile" << SourceRange(D.getIdentifierLoc());
5170    if (FTI.TypeQuals & Qualifiers::Restrict)
5171      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5172        << "restrict" << SourceRange(D.getIdentifierLoc());
5173    D.setInvalidType();
5174  }
5175
5176  // C++0x [class.dtor]p2:
5177  //   A destructor shall not be declared with a ref-qualifier.
5178  if (FTI.hasRefQualifier()) {
5179    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5180      << FTI.RefQualifierIsLValueRef
5181      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5182    D.setInvalidType();
5183  }
5184
5185  // Make sure we don't have any parameters.
5186  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5187    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5188
5189    // Delete the parameters.
5190    FTI.freeArgs();
5191    D.setInvalidType();
5192  }
5193
5194  // Make sure the destructor isn't variadic.
5195  if (FTI.isVariadic) {
5196    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5197    D.setInvalidType();
5198  }
5199
5200  // Rebuild the function type "R" without any type qualifiers or
5201  // parameters (in case any of the errors above fired) and with
5202  // "void" as the return type, since destructors don't have return
5203  // types.
5204  if (!D.isInvalidType())
5205    return R;
5206
5207  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5208  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5209  EPI.Variadic = false;
5210  EPI.TypeQuals = 0;
5211  EPI.RefQualifier = RQ_None;
5212  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5213}
5214
5215/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5216/// well-formednes of the conversion function declarator @p D with
5217/// type @p R. If there are any errors in the declarator, this routine
5218/// will emit diagnostics and return true. Otherwise, it will return
5219/// false. Either way, the type @p R will be updated to reflect a
5220/// well-formed type for the conversion operator.
5221void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5222                                     StorageClass& SC) {
5223  // C++ [class.conv.fct]p1:
5224  //   Neither parameter types nor return type can be specified. The
5225  //   type of a conversion function (8.3.5) is "function taking no
5226  //   parameter returning conversion-type-id."
5227  if (SC == SC_Static) {
5228    if (!D.isInvalidType())
5229      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5230        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5231        << SourceRange(D.getIdentifierLoc());
5232    D.setInvalidType();
5233    SC = SC_None;
5234  }
5235
5236  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5237
5238  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5239    // Conversion functions don't have return types, but the parser will
5240    // happily parse something like:
5241    //
5242    //   class X {
5243    //     float operator bool();
5244    //   };
5245    //
5246    // The return type will be changed later anyway.
5247    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5248      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5249      << SourceRange(D.getIdentifierLoc());
5250    D.setInvalidType();
5251  }
5252
5253  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5254
5255  // Make sure we don't have any parameters.
5256  if (Proto->getNumArgs() > 0) {
5257    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5258
5259    // Delete the parameters.
5260    D.getFunctionTypeInfo().freeArgs();
5261    D.setInvalidType();
5262  } else if (Proto->isVariadic()) {
5263    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5264    D.setInvalidType();
5265  }
5266
5267  // Diagnose "&operator bool()" and other such nonsense.  This
5268  // is actually a gcc extension which we don't support.
5269  if (Proto->getResultType() != ConvType) {
5270    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5271      << Proto->getResultType();
5272    D.setInvalidType();
5273    ConvType = Proto->getResultType();
5274  }
5275
5276  // C++ [class.conv.fct]p4:
5277  //   The conversion-type-id shall not represent a function type nor
5278  //   an array type.
5279  if (ConvType->isArrayType()) {
5280    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5281    ConvType = Context.getPointerType(ConvType);
5282    D.setInvalidType();
5283  } else if (ConvType->isFunctionType()) {
5284    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5285    ConvType = Context.getPointerType(ConvType);
5286    D.setInvalidType();
5287  }
5288
5289  // Rebuild the function type "R" without any parameters (in case any
5290  // of the errors above fired) and with the conversion type as the
5291  // return type.
5292  if (D.isInvalidType())
5293    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5294
5295  // C++0x explicit conversion operators.
5296  if (D.getDeclSpec().isExplicitSpecified())
5297    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5298         getLangOpts().CPlusPlus0x ?
5299           diag::warn_cxx98_compat_explicit_conversion_functions :
5300           diag::ext_explicit_conversion_functions)
5301      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5302}
5303
5304/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5305/// the declaration of the given C++ conversion function. This routine
5306/// is responsible for recording the conversion function in the C++
5307/// class, if possible.
5308Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5309  assert(Conversion && "Expected to receive a conversion function declaration");
5310
5311  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5312
5313  // Make sure we aren't redeclaring the conversion function.
5314  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5315
5316  // C++ [class.conv.fct]p1:
5317  //   [...] A conversion function is never used to convert a
5318  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5319  //   same object type (or a reference to it), to a (possibly
5320  //   cv-qualified) base class of that type (or a reference to it),
5321  //   or to (possibly cv-qualified) void.
5322  // FIXME: Suppress this warning if the conversion function ends up being a
5323  // virtual function that overrides a virtual function in a base class.
5324  QualType ClassType
5325    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5326  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5327    ConvType = ConvTypeRef->getPointeeType();
5328  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5329      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5330    /* Suppress diagnostics for instantiations. */;
5331  else if (ConvType->isRecordType()) {
5332    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5333    if (ConvType == ClassType)
5334      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5335        << ClassType;
5336    else if (IsDerivedFrom(ClassType, ConvType))
5337      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5338        <<  ClassType << ConvType;
5339  } else if (ConvType->isVoidType()) {
5340    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5341      << ClassType << ConvType;
5342  }
5343
5344  if (FunctionTemplateDecl *ConversionTemplate
5345                                = Conversion->getDescribedFunctionTemplate())
5346    return ConversionTemplate;
5347
5348  return Conversion;
5349}
5350
5351//===----------------------------------------------------------------------===//
5352// Namespace Handling
5353//===----------------------------------------------------------------------===//
5354
5355
5356
5357/// ActOnStartNamespaceDef - This is called at the start of a namespace
5358/// definition.
5359Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5360                                   SourceLocation InlineLoc,
5361                                   SourceLocation NamespaceLoc,
5362                                   SourceLocation IdentLoc,
5363                                   IdentifierInfo *II,
5364                                   SourceLocation LBrace,
5365                                   AttributeList *AttrList) {
5366  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5367  // For anonymous namespace, take the location of the left brace.
5368  SourceLocation Loc = II ? IdentLoc : LBrace;
5369  bool IsInline = InlineLoc.isValid();
5370  bool IsInvalid = false;
5371  bool IsStd = false;
5372  bool AddToKnown = false;
5373  Scope *DeclRegionScope = NamespcScope->getParent();
5374
5375  NamespaceDecl *PrevNS = 0;
5376  if (II) {
5377    // C++ [namespace.def]p2:
5378    //   The identifier in an original-namespace-definition shall not
5379    //   have been previously defined in the declarative region in
5380    //   which the original-namespace-definition appears. The
5381    //   identifier in an original-namespace-definition is the name of
5382    //   the namespace. Subsequently in that declarative region, it is
5383    //   treated as an original-namespace-name.
5384    //
5385    // Since namespace names are unique in their scope, and we don't
5386    // look through using directives, just look for any ordinary names.
5387
5388    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5389    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5390    Decl::IDNS_Namespace;
5391    NamedDecl *PrevDecl = 0;
5392    for (DeclContext::lookup_result R
5393         = CurContext->getRedeclContext()->lookup(II);
5394         R.first != R.second; ++R.first) {
5395      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5396        PrevDecl = *R.first;
5397        break;
5398      }
5399    }
5400
5401    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5402
5403    if (PrevNS) {
5404      // This is an extended namespace definition.
5405      if (IsInline != PrevNS->isInline()) {
5406        // inline-ness must match
5407        if (PrevNS->isInline()) {
5408          // The user probably just forgot the 'inline', so suggest that it
5409          // be added back.
5410          Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5411            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5412        } else {
5413          Diag(Loc, diag::err_inline_namespace_mismatch)
5414            << IsInline;
5415        }
5416        Diag(PrevNS->getLocation(), diag::note_previous_definition);
5417
5418        IsInline = PrevNS->isInline();
5419      }
5420    } else if (PrevDecl) {
5421      // This is an invalid name redefinition.
5422      Diag(Loc, diag::err_redefinition_different_kind)
5423        << II;
5424      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5425      IsInvalid = true;
5426      // Continue on to push Namespc as current DeclContext and return it.
5427    } else if (II->isStr("std") &&
5428               CurContext->getRedeclContext()->isTranslationUnit()) {
5429      // This is the first "real" definition of the namespace "std", so update
5430      // our cache of the "std" namespace to point at this definition.
5431      PrevNS = getStdNamespace();
5432      IsStd = true;
5433      AddToKnown = !IsInline;
5434    } else {
5435      // We've seen this namespace for the first time.
5436      AddToKnown = !IsInline;
5437    }
5438  } else {
5439    // Anonymous namespaces.
5440
5441    // Determine whether the parent already has an anonymous namespace.
5442    DeclContext *Parent = CurContext->getRedeclContext();
5443    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5444      PrevNS = TU->getAnonymousNamespace();
5445    } else {
5446      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5447      PrevNS = ND->getAnonymousNamespace();
5448    }
5449
5450    if (PrevNS && IsInline != PrevNS->isInline()) {
5451      // inline-ness must match
5452      Diag(Loc, diag::err_inline_namespace_mismatch)
5453        << IsInline;
5454      Diag(PrevNS->getLocation(), diag::note_previous_definition);
5455
5456      // Recover by ignoring the new namespace's inline status.
5457      IsInline = PrevNS->isInline();
5458    }
5459  }
5460
5461  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5462                                                 StartLoc, Loc, II, PrevNS);
5463  if (IsInvalid)
5464    Namespc->setInvalidDecl();
5465
5466  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5467
5468  // FIXME: Should we be merging attributes?
5469  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5470    PushNamespaceVisibilityAttr(Attr, Loc);
5471
5472  if (IsStd)
5473    StdNamespace = Namespc;
5474  if (AddToKnown)
5475    KnownNamespaces[Namespc] = false;
5476
5477  if (II) {
5478    PushOnScopeChains(Namespc, DeclRegionScope);
5479  } else {
5480    // Link the anonymous namespace into its parent.
5481    DeclContext *Parent = CurContext->getRedeclContext();
5482    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5483      TU->setAnonymousNamespace(Namespc);
5484    } else {
5485      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5486    }
5487
5488    CurContext->addDecl(Namespc);
5489
5490    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5491    //   behaves as if it were replaced by
5492    //     namespace unique { /* empty body */ }
5493    //     using namespace unique;
5494    //     namespace unique { namespace-body }
5495    //   where all occurrences of 'unique' in a translation unit are
5496    //   replaced by the same identifier and this identifier differs
5497    //   from all other identifiers in the entire program.
5498
5499    // We just create the namespace with an empty name and then add an
5500    // implicit using declaration, just like the standard suggests.
5501    //
5502    // CodeGen enforces the "universally unique" aspect by giving all
5503    // declarations semantically contained within an anonymous
5504    // namespace internal linkage.
5505
5506    if (!PrevNS) {
5507      UsingDirectiveDecl* UD
5508        = UsingDirectiveDecl::Create(Context, CurContext,
5509                                     /* 'using' */ LBrace,
5510                                     /* 'namespace' */ SourceLocation(),
5511                                     /* qualifier */ NestedNameSpecifierLoc(),
5512                                     /* identifier */ SourceLocation(),
5513                                     Namespc,
5514                                     /* Ancestor */ CurContext);
5515      UD->setImplicit();
5516      CurContext->addDecl(UD);
5517    }
5518  }
5519
5520  // Although we could have an invalid decl (i.e. the namespace name is a
5521  // redefinition), push it as current DeclContext and try to continue parsing.
5522  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5523  // for the namespace has the declarations that showed up in that particular
5524  // namespace definition.
5525  PushDeclContext(NamespcScope, Namespc);
5526  return Namespc;
5527}
5528
5529/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5530/// is a namespace alias, returns the namespace it points to.
5531static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5532  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5533    return AD->getNamespace();
5534  return dyn_cast_or_null<NamespaceDecl>(D);
5535}
5536
5537/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5538/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5539void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5540  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5541  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5542  Namespc->setRBraceLoc(RBrace);
5543  PopDeclContext();
5544  if (Namespc->hasAttr<VisibilityAttr>())
5545    PopPragmaVisibility(true, RBrace);
5546}
5547
5548CXXRecordDecl *Sema::getStdBadAlloc() const {
5549  return cast_or_null<CXXRecordDecl>(
5550                                  StdBadAlloc.get(Context.getExternalSource()));
5551}
5552
5553NamespaceDecl *Sema::getStdNamespace() const {
5554  return cast_or_null<NamespaceDecl>(
5555                                 StdNamespace.get(Context.getExternalSource()));
5556}
5557
5558/// \brief Retrieve the special "std" namespace, which may require us to
5559/// implicitly define the namespace.
5560NamespaceDecl *Sema::getOrCreateStdNamespace() {
5561  if (!StdNamespace) {
5562    // The "std" namespace has not yet been defined, so build one implicitly.
5563    StdNamespace = NamespaceDecl::Create(Context,
5564                                         Context.getTranslationUnitDecl(),
5565                                         /*Inline=*/false,
5566                                         SourceLocation(), SourceLocation(),
5567                                         &PP.getIdentifierTable().get("std"),
5568                                         /*PrevDecl=*/0);
5569    getStdNamespace()->setImplicit(true);
5570  }
5571
5572  return getStdNamespace();
5573}
5574
5575bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5576  assert(getLangOpts().CPlusPlus &&
5577         "Looking for std::initializer_list outside of C++.");
5578
5579  // We're looking for implicit instantiations of
5580  // template <typename E> class std::initializer_list.
5581
5582  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5583    return false;
5584
5585  ClassTemplateDecl *Template = 0;
5586  const TemplateArgument *Arguments = 0;
5587
5588  if (const RecordType *RT = Ty->getAs<RecordType>()) {
5589
5590    ClassTemplateSpecializationDecl *Specialization =
5591        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5592    if (!Specialization)
5593      return false;
5594
5595    Template = Specialization->getSpecializedTemplate();
5596    Arguments = Specialization->getTemplateArgs().data();
5597  } else if (const TemplateSpecializationType *TST =
5598                 Ty->getAs<TemplateSpecializationType>()) {
5599    Template = dyn_cast_or_null<ClassTemplateDecl>(
5600        TST->getTemplateName().getAsTemplateDecl());
5601    Arguments = TST->getArgs();
5602  }
5603  if (!Template)
5604    return false;
5605
5606  if (!StdInitializerList) {
5607    // Haven't recognized std::initializer_list yet, maybe this is it.
5608    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5609    if (TemplateClass->getIdentifier() !=
5610            &PP.getIdentifierTable().get("initializer_list") ||
5611        !getStdNamespace()->InEnclosingNamespaceSetOf(
5612            TemplateClass->getDeclContext()))
5613      return false;
5614    // This is a template called std::initializer_list, but is it the right
5615    // template?
5616    TemplateParameterList *Params = Template->getTemplateParameters();
5617    if (Params->getMinRequiredArguments() != 1)
5618      return false;
5619    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5620      return false;
5621
5622    // It's the right template.
5623    StdInitializerList = Template;
5624  }
5625
5626  if (Template != StdInitializerList)
5627    return false;
5628
5629  // This is an instance of std::initializer_list. Find the argument type.
5630  if (Element)
5631    *Element = Arguments[0].getAsType();
5632  return true;
5633}
5634
5635static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5636  NamespaceDecl *Std = S.getStdNamespace();
5637  if (!Std) {
5638    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5639    return 0;
5640  }
5641
5642  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5643                      Loc, Sema::LookupOrdinaryName);
5644  if (!S.LookupQualifiedName(Result, Std)) {
5645    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5646    return 0;
5647  }
5648  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5649  if (!Template) {
5650    Result.suppressDiagnostics();
5651    // We found something weird. Complain about the first thing we found.
5652    NamedDecl *Found = *Result.begin();
5653    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5654    return 0;
5655  }
5656
5657  // We found some template called std::initializer_list. Now verify that it's
5658  // correct.
5659  TemplateParameterList *Params = Template->getTemplateParameters();
5660  if (Params->getMinRequiredArguments() != 1 ||
5661      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5662    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5663    return 0;
5664  }
5665
5666  return Template;
5667}
5668
5669QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5670  if (!StdInitializerList) {
5671    StdInitializerList = LookupStdInitializerList(*this, Loc);
5672    if (!StdInitializerList)
5673      return QualType();
5674  }
5675
5676  TemplateArgumentListInfo Args(Loc, Loc);
5677  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5678                                       Context.getTrivialTypeSourceInfo(Element,
5679                                                                        Loc)));
5680  return Context.getCanonicalType(
5681      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5682}
5683
5684bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5685  // C++ [dcl.init.list]p2:
5686  //   A constructor is an initializer-list constructor if its first parameter
5687  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5688  //   std::initializer_list<E> for some type E, and either there are no other
5689  //   parameters or else all other parameters have default arguments.
5690  if (Ctor->getNumParams() < 1 ||
5691      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5692    return false;
5693
5694  QualType ArgType = Ctor->getParamDecl(0)->getType();
5695  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5696    ArgType = RT->getPointeeType().getUnqualifiedType();
5697
5698  return isStdInitializerList(ArgType, 0);
5699}
5700
5701/// \brief Determine whether a using statement is in a context where it will be
5702/// apply in all contexts.
5703static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5704  switch (CurContext->getDeclKind()) {
5705    case Decl::TranslationUnit:
5706      return true;
5707    case Decl::LinkageSpec:
5708      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5709    default:
5710      return false;
5711  }
5712}
5713
5714namespace {
5715
5716// Callback to only accept typo corrections that are namespaces.
5717class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5718 public:
5719  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5720    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5721      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5722    }
5723    return false;
5724  }
5725};
5726
5727}
5728
5729static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5730                                       CXXScopeSpec &SS,
5731                                       SourceLocation IdentLoc,
5732                                       IdentifierInfo *Ident) {
5733  NamespaceValidatorCCC Validator;
5734  R.clear();
5735  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5736                                               R.getLookupKind(), Sc, &SS,
5737                                               Validator)) {
5738    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5739    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5740    if (DeclContext *DC = S.computeDeclContext(SS, false))
5741      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5742        << Ident << DC << CorrectedQuotedStr << SS.getRange()
5743        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5744    else
5745      S.Diag(IdentLoc, diag::err_using_directive_suggest)
5746        << Ident << CorrectedQuotedStr
5747        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5748
5749    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5750         diag::note_namespace_defined_here) << CorrectedQuotedStr;
5751
5752    Ident = Corrected.getCorrectionAsIdentifierInfo();
5753    R.addDecl(Corrected.getCorrectionDecl());
5754    return true;
5755  }
5756  return false;
5757}
5758
5759Decl *Sema::ActOnUsingDirective(Scope *S,
5760                                          SourceLocation UsingLoc,
5761                                          SourceLocation NamespcLoc,
5762                                          CXXScopeSpec &SS,
5763                                          SourceLocation IdentLoc,
5764                                          IdentifierInfo *NamespcName,
5765                                          AttributeList *AttrList) {
5766  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5767  assert(NamespcName && "Invalid NamespcName.");
5768  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5769
5770  // This can only happen along a recovery path.
5771  while (S->getFlags() & Scope::TemplateParamScope)
5772    S = S->getParent();
5773  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5774
5775  UsingDirectiveDecl *UDir = 0;
5776  NestedNameSpecifier *Qualifier = 0;
5777  if (SS.isSet())
5778    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5779
5780  // Lookup namespace name.
5781  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5782  LookupParsedName(R, S, &SS);
5783  if (R.isAmbiguous())
5784    return 0;
5785
5786  if (R.empty()) {
5787    R.clear();
5788    // Allow "using namespace std;" or "using namespace ::std;" even if
5789    // "std" hasn't been defined yet, for GCC compatibility.
5790    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5791        NamespcName->isStr("std")) {
5792      Diag(IdentLoc, diag::ext_using_undefined_std);
5793      R.addDecl(getOrCreateStdNamespace());
5794      R.resolveKind();
5795    }
5796    // Otherwise, attempt typo correction.
5797    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5798  }
5799
5800  if (!R.empty()) {
5801    NamedDecl *Named = R.getFoundDecl();
5802    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5803        && "expected namespace decl");
5804    // C++ [namespace.udir]p1:
5805    //   A using-directive specifies that the names in the nominated
5806    //   namespace can be used in the scope in which the
5807    //   using-directive appears after the using-directive. During
5808    //   unqualified name lookup (3.4.1), the names appear as if they
5809    //   were declared in the nearest enclosing namespace which
5810    //   contains both the using-directive and the nominated
5811    //   namespace. [Note: in this context, "contains" means "contains
5812    //   directly or indirectly". ]
5813
5814    // Find enclosing context containing both using-directive and
5815    // nominated namespace.
5816    NamespaceDecl *NS = getNamespaceDecl(Named);
5817    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5818    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5819      CommonAncestor = CommonAncestor->getParent();
5820
5821    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5822                                      SS.getWithLocInContext(Context),
5823                                      IdentLoc, Named, CommonAncestor);
5824
5825    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5826        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5827      Diag(IdentLoc, diag::warn_using_directive_in_header);
5828    }
5829
5830    PushUsingDirective(S, UDir);
5831  } else {
5832    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5833  }
5834
5835  // FIXME: We ignore attributes for now.
5836  return UDir;
5837}
5838
5839void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5840  // If the scope has an associated entity and the using directive is at
5841  // namespace or translation unit scope, add the UsingDirectiveDecl into
5842  // its lookup structure so qualified name lookup can find it.
5843  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5844  if (Ctx && !Ctx->isFunctionOrMethod())
5845    Ctx->addDecl(UDir);
5846  else
5847    // Otherwise, it is at block sope. The using-directives will affect lookup
5848    // only to the end of the scope.
5849    S->PushUsingDirective(UDir);
5850}
5851
5852
5853Decl *Sema::ActOnUsingDeclaration(Scope *S,
5854                                  AccessSpecifier AS,
5855                                  bool HasUsingKeyword,
5856                                  SourceLocation UsingLoc,
5857                                  CXXScopeSpec &SS,
5858                                  UnqualifiedId &Name,
5859                                  AttributeList *AttrList,
5860                                  bool IsTypeName,
5861                                  SourceLocation TypenameLoc) {
5862  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5863
5864  switch (Name.getKind()) {
5865  case UnqualifiedId::IK_ImplicitSelfParam:
5866  case UnqualifiedId::IK_Identifier:
5867  case UnqualifiedId::IK_OperatorFunctionId:
5868  case UnqualifiedId::IK_LiteralOperatorId:
5869  case UnqualifiedId::IK_ConversionFunctionId:
5870    break;
5871
5872  case UnqualifiedId::IK_ConstructorName:
5873  case UnqualifiedId::IK_ConstructorTemplateId:
5874    // C++0x inherited constructors.
5875    Diag(Name.getLocStart(),
5876         getLangOpts().CPlusPlus0x ?
5877           diag::warn_cxx98_compat_using_decl_constructor :
5878           diag::err_using_decl_constructor)
5879      << SS.getRange();
5880
5881    if (getLangOpts().CPlusPlus0x) break;
5882
5883    return 0;
5884
5885  case UnqualifiedId::IK_DestructorName:
5886    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5887      << SS.getRange();
5888    return 0;
5889
5890  case UnqualifiedId::IK_TemplateId:
5891    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5892      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5893    return 0;
5894  }
5895
5896  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5897  DeclarationName TargetName = TargetNameInfo.getName();
5898  if (!TargetName)
5899    return 0;
5900
5901  // Warn about using declarations.
5902  // TODO: store that the declaration was written without 'using' and
5903  // talk about access decls instead of using decls in the
5904  // diagnostics.
5905  if (!HasUsingKeyword) {
5906    UsingLoc = Name.getLocStart();
5907
5908    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5909      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5910  }
5911
5912  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5913      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5914    return 0;
5915
5916  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5917                                        TargetNameInfo, AttrList,
5918                                        /* IsInstantiation */ false,
5919                                        IsTypeName, TypenameLoc);
5920  if (UD)
5921    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5922
5923  return UD;
5924}
5925
5926/// \brief Determine whether a using declaration considers the given
5927/// declarations as "equivalent", e.g., if they are redeclarations of
5928/// the same entity or are both typedefs of the same type.
5929static bool
5930IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5931                         bool &SuppressRedeclaration) {
5932  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5933    SuppressRedeclaration = false;
5934    return true;
5935  }
5936
5937  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5938    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5939      SuppressRedeclaration = true;
5940      return Context.hasSameType(TD1->getUnderlyingType(),
5941                                 TD2->getUnderlyingType());
5942    }
5943
5944  return false;
5945}
5946
5947
5948/// Determines whether to create a using shadow decl for a particular
5949/// decl, given the set of decls existing prior to this using lookup.
5950bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5951                                const LookupResult &Previous) {
5952  // Diagnose finding a decl which is not from a base class of the
5953  // current class.  We do this now because there are cases where this
5954  // function will silently decide not to build a shadow decl, which
5955  // will pre-empt further diagnostics.
5956  //
5957  // We don't need to do this in C++0x because we do the check once on
5958  // the qualifier.
5959  //
5960  // FIXME: diagnose the following if we care enough:
5961  //   struct A { int foo; };
5962  //   struct B : A { using A::foo; };
5963  //   template <class T> struct C : A {};
5964  //   template <class T> struct D : C<T> { using B::foo; } // <---
5965  // This is invalid (during instantiation) in C++03 because B::foo
5966  // resolves to the using decl in B, which is not a base class of D<T>.
5967  // We can't diagnose it immediately because C<T> is an unknown
5968  // specialization.  The UsingShadowDecl in D<T> then points directly
5969  // to A::foo, which will look well-formed when we instantiate.
5970  // The right solution is to not collapse the shadow-decl chain.
5971  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
5972    DeclContext *OrigDC = Orig->getDeclContext();
5973
5974    // Handle enums and anonymous structs.
5975    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5976    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5977    while (OrigRec->isAnonymousStructOrUnion())
5978      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5979
5980    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5981      if (OrigDC == CurContext) {
5982        Diag(Using->getLocation(),
5983             diag::err_using_decl_nested_name_specifier_is_current_class)
5984          << Using->getQualifierLoc().getSourceRange();
5985        Diag(Orig->getLocation(), diag::note_using_decl_target);
5986        return true;
5987      }
5988
5989      Diag(Using->getQualifierLoc().getBeginLoc(),
5990           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5991        << Using->getQualifier()
5992        << cast<CXXRecordDecl>(CurContext)
5993        << Using->getQualifierLoc().getSourceRange();
5994      Diag(Orig->getLocation(), diag::note_using_decl_target);
5995      return true;
5996    }
5997  }
5998
5999  if (Previous.empty()) return false;
6000
6001  NamedDecl *Target = Orig;
6002  if (isa<UsingShadowDecl>(Target))
6003    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6004
6005  // If the target happens to be one of the previous declarations, we
6006  // don't have a conflict.
6007  //
6008  // FIXME: but we might be increasing its access, in which case we
6009  // should redeclare it.
6010  NamedDecl *NonTag = 0, *Tag = 0;
6011  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6012         I != E; ++I) {
6013    NamedDecl *D = (*I)->getUnderlyingDecl();
6014    bool Result;
6015    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6016      return Result;
6017
6018    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6019  }
6020
6021  if (Target->isFunctionOrFunctionTemplate()) {
6022    FunctionDecl *FD;
6023    if (isa<FunctionTemplateDecl>(Target))
6024      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6025    else
6026      FD = cast<FunctionDecl>(Target);
6027
6028    NamedDecl *OldDecl = 0;
6029    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6030    case Ovl_Overload:
6031      return false;
6032
6033    case Ovl_NonFunction:
6034      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6035      break;
6036
6037    // We found a decl with the exact signature.
6038    case Ovl_Match:
6039      // If we're in a record, we want to hide the target, so we
6040      // return true (without a diagnostic) to tell the caller not to
6041      // build a shadow decl.
6042      if (CurContext->isRecord())
6043        return true;
6044
6045      // If we're not in a record, this is an error.
6046      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6047      break;
6048    }
6049
6050    Diag(Target->getLocation(), diag::note_using_decl_target);
6051    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6052    return true;
6053  }
6054
6055  // Target is not a function.
6056
6057  if (isa<TagDecl>(Target)) {
6058    // No conflict between a tag and a non-tag.
6059    if (!Tag) return false;
6060
6061    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6062    Diag(Target->getLocation(), diag::note_using_decl_target);
6063    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6064    return true;
6065  }
6066
6067  // No conflict between a tag and a non-tag.
6068  if (!NonTag) return false;
6069
6070  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6071  Diag(Target->getLocation(), diag::note_using_decl_target);
6072  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6073  return true;
6074}
6075
6076/// Builds a shadow declaration corresponding to a 'using' declaration.
6077UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6078                                            UsingDecl *UD,
6079                                            NamedDecl *Orig) {
6080
6081  // If we resolved to another shadow declaration, just coalesce them.
6082  NamedDecl *Target = Orig;
6083  if (isa<UsingShadowDecl>(Target)) {
6084    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6085    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6086  }
6087
6088  UsingShadowDecl *Shadow
6089    = UsingShadowDecl::Create(Context, CurContext,
6090                              UD->getLocation(), UD, Target);
6091  UD->addShadowDecl(Shadow);
6092
6093  Shadow->setAccess(UD->getAccess());
6094  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6095    Shadow->setInvalidDecl();
6096
6097  if (S)
6098    PushOnScopeChains(Shadow, S);
6099  else
6100    CurContext->addDecl(Shadow);
6101
6102
6103  return Shadow;
6104}
6105
6106/// Hides a using shadow declaration.  This is required by the current
6107/// using-decl implementation when a resolvable using declaration in a
6108/// class is followed by a declaration which would hide or override
6109/// one or more of the using decl's targets; for example:
6110///
6111///   struct Base { void foo(int); };
6112///   struct Derived : Base {
6113///     using Base::foo;
6114///     void foo(int);
6115///   };
6116///
6117/// The governing language is C++03 [namespace.udecl]p12:
6118///
6119///   When a using-declaration brings names from a base class into a
6120///   derived class scope, member functions in the derived class
6121///   override and/or hide member functions with the same name and
6122///   parameter types in a base class (rather than conflicting).
6123///
6124/// There are two ways to implement this:
6125///   (1) optimistically create shadow decls when they're not hidden
6126///       by existing declarations, or
6127///   (2) don't create any shadow decls (or at least don't make them
6128///       visible) until we've fully parsed/instantiated the class.
6129/// The problem with (1) is that we might have to retroactively remove
6130/// a shadow decl, which requires several O(n) operations because the
6131/// decl structures are (very reasonably) not designed for removal.
6132/// (2) avoids this but is very fiddly and phase-dependent.
6133void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6134  if (Shadow->getDeclName().getNameKind() ==
6135        DeclarationName::CXXConversionFunctionName)
6136    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6137
6138  // Remove it from the DeclContext...
6139  Shadow->getDeclContext()->removeDecl(Shadow);
6140
6141  // ...and the scope, if applicable...
6142  if (S) {
6143    S->RemoveDecl(Shadow);
6144    IdResolver.RemoveDecl(Shadow);
6145  }
6146
6147  // ...and the using decl.
6148  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6149
6150  // TODO: complain somehow if Shadow was used.  It shouldn't
6151  // be possible for this to happen, because...?
6152}
6153
6154/// Builds a using declaration.
6155///
6156/// \param IsInstantiation - Whether this call arises from an
6157///   instantiation of an unresolved using declaration.  We treat
6158///   the lookup differently for these declarations.
6159NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6160                                       SourceLocation UsingLoc,
6161                                       CXXScopeSpec &SS,
6162                                       const DeclarationNameInfo &NameInfo,
6163                                       AttributeList *AttrList,
6164                                       bool IsInstantiation,
6165                                       bool IsTypeName,
6166                                       SourceLocation TypenameLoc) {
6167  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6168  SourceLocation IdentLoc = NameInfo.getLoc();
6169  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6170
6171  // FIXME: We ignore attributes for now.
6172
6173  if (SS.isEmpty()) {
6174    Diag(IdentLoc, diag::err_using_requires_qualname);
6175    return 0;
6176  }
6177
6178  // Do the redeclaration lookup in the current scope.
6179  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6180                        ForRedeclaration);
6181  Previous.setHideTags(false);
6182  if (S) {
6183    LookupName(Previous, S);
6184
6185    // It is really dumb that we have to do this.
6186    LookupResult::Filter F = Previous.makeFilter();
6187    while (F.hasNext()) {
6188      NamedDecl *D = F.next();
6189      if (!isDeclInScope(D, CurContext, S))
6190        F.erase();
6191    }
6192    F.done();
6193  } else {
6194    assert(IsInstantiation && "no scope in non-instantiation");
6195    assert(CurContext->isRecord() && "scope not record in instantiation");
6196    LookupQualifiedName(Previous, CurContext);
6197  }
6198
6199  // Check for invalid redeclarations.
6200  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6201    return 0;
6202
6203  // Check for bad qualifiers.
6204  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6205    return 0;
6206
6207  DeclContext *LookupContext = computeDeclContext(SS);
6208  NamedDecl *D;
6209  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6210  if (!LookupContext) {
6211    if (IsTypeName) {
6212      // FIXME: not all declaration name kinds are legal here
6213      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6214                                              UsingLoc, TypenameLoc,
6215                                              QualifierLoc,
6216                                              IdentLoc, NameInfo.getName());
6217    } else {
6218      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6219                                           QualifierLoc, NameInfo);
6220    }
6221  } else {
6222    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6223                          NameInfo, IsTypeName);
6224  }
6225  D->setAccess(AS);
6226  CurContext->addDecl(D);
6227
6228  if (!LookupContext) return D;
6229  UsingDecl *UD = cast<UsingDecl>(D);
6230
6231  if (RequireCompleteDeclContext(SS, LookupContext)) {
6232    UD->setInvalidDecl();
6233    return UD;
6234  }
6235
6236  // Constructor inheriting using decls get special treatment.
6237  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6238    if (CheckInheritedConstructorUsingDecl(UD))
6239      UD->setInvalidDecl();
6240    return UD;
6241  }
6242
6243  // Otherwise, look up the target name.
6244
6245  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6246
6247  // Unlike most lookups, we don't always want to hide tag
6248  // declarations: tag names are visible through the using declaration
6249  // even if hidden by ordinary names, *except* in a dependent context
6250  // where it's important for the sanity of two-phase lookup.
6251  if (!IsInstantiation)
6252    R.setHideTags(false);
6253
6254  LookupQualifiedName(R, LookupContext);
6255
6256  if (R.empty()) {
6257    Diag(IdentLoc, diag::err_no_member)
6258      << NameInfo.getName() << LookupContext << SS.getRange();
6259    UD->setInvalidDecl();
6260    return UD;
6261  }
6262
6263  if (R.isAmbiguous()) {
6264    UD->setInvalidDecl();
6265    return UD;
6266  }
6267
6268  if (IsTypeName) {
6269    // If we asked for a typename and got a non-type decl, error out.
6270    if (!R.getAsSingle<TypeDecl>()) {
6271      Diag(IdentLoc, diag::err_using_typename_non_type);
6272      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6273        Diag((*I)->getUnderlyingDecl()->getLocation(),
6274             diag::note_using_decl_target);
6275      UD->setInvalidDecl();
6276      return UD;
6277    }
6278  } else {
6279    // If we asked for a non-typename and we got a type, error out,
6280    // but only if this is an instantiation of an unresolved using
6281    // decl.  Otherwise just silently find the type name.
6282    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6283      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6284      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6285      UD->setInvalidDecl();
6286      return UD;
6287    }
6288  }
6289
6290  // C++0x N2914 [namespace.udecl]p6:
6291  // A using-declaration shall not name a namespace.
6292  if (R.getAsSingle<NamespaceDecl>()) {
6293    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6294      << SS.getRange();
6295    UD->setInvalidDecl();
6296    return UD;
6297  }
6298
6299  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6300    if (!CheckUsingShadowDecl(UD, *I, Previous))
6301      BuildUsingShadowDecl(S, UD, *I);
6302  }
6303
6304  return UD;
6305}
6306
6307/// Additional checks for a using declaration referring to a constructor name.
6308bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6309  if (UD->isTypeName()) {
6310    // FIXME: Cannot specify typename when specifying constructor
6311    return true;
6312  }
6313
6314  const Type *SourceType = UD->getQualifier()->getAsType();
6315  assert(SourceType &&
6316         "Using decl naming constructor doesn't have type in scope spec.");
6317  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6318
6319  // Check whether the named type is a direct base class.
6320  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6321  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6322  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6323       BaseIt != BaseE; ++BaseIt) {
6324    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6325    if (CanonicalSourceType == BaseType)
6326      break;
6327  }
6328
6329  if (BaseIt == BaseE) {
6330    // Did not find SourceType in the bases.
6331    Diag(UD->getUsingLocation(),
6332         diag::err_using_decl_constructor_not_in_direct_base)
6333      << UD->getNameInfo().getSourceRange()
6334      << QualType(SourceType, 0) << TargetClass;
6335    return true;
6336  }
6337
6338  BaseIt->setInheritConstructors();
6339
6340  return false;
6341}
6342
6343/// Checks that the given using declaration is not an invalid
6344/// redeclaration.  Note that this is checking only for the using decl
6345/// itself, not for any ill-formedness among the UsingShadowDecls.
6346bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6347                                       bool isTypeName,
6348                                       const CXXScopeSpec &SS,
6349                                       SourceLocation NameLoc,
6350                                       const LookupResult &Prev) {
6351  // C++03 [namespace.udecl]p8:
6352  // C++0x [namespace.udecl]p10:
6353  //   A using-declaration is a declaration and can therefore be used
6354  //   repeatedly where (and only where) multiple declarations are
6355  //   allowed.
6356  //
6357  // That's in non-member contexts.
6358  if (!CurContext->getRedeclContext()->isRecord())
6359    return false;
6360
6361  NestedNameSpecifier *Qual
6362    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6363
6364  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6365    NamedDecl *D = *I;
6366
6367    bool DTypename;
6368    NestedNameSpecifier *DQual;
6369    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6370      DTypename = UD->isTypeName();
6371      DQual = UD->getQualifier();
6372    } else if (UnresolvedUsingValueDecl *UD
6373                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6374      DTypename = false;
6375      DQual = UD->getQualifier();
6376    } else if (UnresolvedUsingTypenameDecl *UD
6377                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6378      DTypename = true;
6379      DQual = UD->getQualifier();
6380    } else continue;
6381
6382    // using decls differ if one says 'typename' and the other doesn't.
6383    // FIXME: non-dependent using decls?
6384    if (isTypeName != DTypename) continue;
6385
6386    // using decls differ if they name different scopes (but note that
6387    // template instantiation can cause this check to trigger when it
6388    // didn't before instantiation).
6389    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6390        Context.getCanonicalNestedNameSpecifier(DQual))
6391      continue;
6392
6393    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6394    Diag(D->getLocation(), diag::note_using_decl) << 1;
6395    return true;
6396  }
6397
6398  return false;
6399}
6400
6401
6402/// Checks that the given nested-name qualifier used in a using decl
6403/// in the current context is appropriately related to the current
6404/// scope.  If an error is found, diagnoses it and returns true.
6405bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6406                                   const CXXScopeSpec &SS,
6407                                   SourceLocation NameLoc) {
6408  DeclContext *NamedContext = computeDeclContext(SS);
6409
6410  if (!CurContext->isRecord()) {
6411    // C++03 [namespace.udecl]p3:
6412    // C++0x [namespace.udecl]p8:
6413    //   A using-declaration for a class member shall be a member-declaration.
6414
6415    // If we weren't able to compute a valid scope, it must be a
6416    // dependent class scope.
6417    if (!NamedContext || NamedContext->isRecord()) {
6418      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6419        << SS.getRange();
6420      return true;
6421    }
6422
6423    // Otherwise, everything is known to be fine.
6424    return false;
6425  }
6426
6427  // The current scope is a record.
6428
6429  // If the named context is dependent, we can't decide much.
6430  if (!NamedContext) {
6431    // FIXME: in C++0x, we can diagnose if we can prove that the
6432    // nested-name-specifier does not refer to a base class, which is
6433    // still possible in some cases.
6434
6435    // Otherwise we have to conservatively report that things might be
6436    // okay.
6437    return false;
6438  }
6439
6440  if (!NamedContext->isRecord()) {
6441    // Ideally this would point at the last name in the specifier,
6442    // but we don't have that level of source info.
6443    Diag(SS.getRange().getBegin(),
6444         diag::err_using_decl_nested_name_specifier_is_not_class)
6445      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6446    return true;
6447  }
6448
6449  if (!NamedContext->isDependentContext() &&
6450      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6451    return true;
6452
6453  if (getLangOpts().CPlusPlus0x) {
6454    // C++0x [namespace.udecl]p3:
6455    //   In a using-declaration used as a member-declaration, the
6456    //   nested-name-specifier shall name a base class of the class
6457    //   being defined.
6458
6459    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6460                                 cast<CXXRecordDecl>(NamedContext))) {
6461      if (CurContext == NamedContext) {
6462        Diag(NameLoc,
6463             diag::err_using_decl_nested_name_specifier_is_current_class)
6464          << SS.getRange();
6465        return true;
6466      }
6467
6468      Diag(SS.getRange().getBegin(),
6469           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6470        << (NestedNameSpecifier*) SS.getScopeRep()
6471        << cast<CXXRecordDecl>(CurContext)
6472        << SS.getRange();
6473      return true;
6474    }
6475
6476    return false;
6477  }
6478
6479  // C++03 [namespace.udecl]p4:
6480  //   A using-declaration used as a member-declaration shall refer
6481  //   to a member of a base class of the class being defined [etc.].
6482
6483  // Salient point: SS doesn't have to name a base class as long as
6484  // lookup only finds members from base classes.  Therefore we can
6485  // diagnose here only if we can prove that that can't happen,
6486  // i.e. if the class hierarchies provably don't intersect.
6487
6488  // TODO: it would be nice if "definitely valid" results were cached
6489  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6490  // need to be repeated.
6491
6492  struct UserData {
6493    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6494
6495    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6496      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6497      Data->Bases.insert(Base);
6498      return true;
6499    }
6500
6501    bool hasDependentBases(const CXXRecordDecl *Class) {
6502      return !Class->forallBases(collect, this);
6503    }
6504
6505    /// Returns true if the base is dependent or is one of the
6506    /// accumulated base classes.
6507    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6508      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6509      return !Data->Bases.count(Base);
6510    }
6511
6512    bool mightShareBases(const CXXRecordDecl *Class) {
6513      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6514    }
6515  };
6516
6517  UserData Data;
6518
6519  // Returns false if we find a dependent base.
6520  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6521    return false;
6522
6523  // Returns false if the class has a dependent base or if it or one
6524  // of its bases is present in the base set of the current context.
6525  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6526    return false;
6527
6528  Diag(SS.getRange().getBegin(),
6529       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6530    << (NestedNameSpecifier*) SS.getScopeRep()
6531    << cast<CXXRecordDecl>(CurContext)
6532    << SS.getRange();
6533
6534  return true;
6535}
6536
6537Decl *Sema::ActOnAliasDeclaration(Scope *S,
6538                                  AccessSpecifier AS,
6539                                  MultiTemplateParamsArg TemplateParamLists,
6540                                  SourceLocation UsingLoc,
6541                                  UnqualifiedId &Name,
6542                                  TypeResult Type) {
6543  // Skip up to the relevant declaration scope.
6544  while (S->getFlags() & Scope::TemplateParamScope)
6545    S = S->getParent();
6546  assert((S->getFlags() & Scope::DeclScope) &&
6547         "got alias-declaration outside of declaration scope");
6548
6549  if (Type.isInvalid())
6550    return 0;
6551
6552  bool Invalid = false;
6553  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6554  TypeSourceInfo *TInfo = 0;
6555  GetTypeFromParser(Type.get(), &TInfo);
6556
6557  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6558    return 0;
6559
6560  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6561                                      UPPC_DeclarationType)) {
6562    Invalid = true;
6563    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6564                                             TInfo->getTypeLoc().getBeginLoc());
6565  }
6566
6567  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6568  LookupName(Previous, S);
6569
6570  // Warn about shadowing the name of a template parameter.
6571  if (Previous.isSingleResult() &&
6572      Previous.getFoundDecl()->isTemplateParameter()) {
6573    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6574    Previous.clear();
6575  }
6576
6577  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6578         "name in alias declaration must be an identifier");
6579  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6580                                               Name.StartLocation,
6581                                               Name.Identifier, TInfo);
6582
6583  NewTD->setAccess(AS);
6584
6585  if (Invalid)
6586    NewTD->setInvalidDecl();
6587
6588  CheckTypedefForVariablyModifiedType(S, NewTD);
6589  Invalid |= NewTD->isInvalidDecl();
6590
6591  bool Redeclaration = false;
6592
6593  NamedDecl *NewND;
6594  if (TemplateParamLists.size()) {
6595    TypeAliasTemplateDecl *OldDecl = 0;
6596    TemplateParameterList *OldTemplateParams = 0;
6597
6598    if (TemplateParamLists.size() != 1) {
6599      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6600        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6601         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6602    }
6603    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6604
6605    // Only consider previous declarations in the same scope.
6606    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6607                         /*ExplicitInstantiationOrSpecialization*/false);
6608    if (!Previous.empty()) {
6609      Redeclaration = true;
6610
6611      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6612      if (!OldDecl && !Invalid) {
6613        Diag(UsingLoc, diag::err_redefinition_different_kind)
6614          << Name.Identifier;
6615
6616        NamedDecl *OldD = Previous.getRepresentativeDecl();
6617        if (OldD->getLocation().isValid())
6618          Diag(OldD->getLocation(), diag::note_previous_definition);
6619
6620        Invalid = true;
6621      }
6622
6623      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6624        if (TemplateParameterListsAreEqual(TemplateParams,
6625                                           OldDecl->getTemplateParameters(),
6626                                           /*Complain=*/true,
6627                                           TPL_TemplateMatch))
6628          OldTemplateParams = OldDecl->getTemplateParameters();
6629        else
6630          Invalid = true;
6631
6632        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6633        if (!Invalid &&
6634            !Context.hasSameType(OldTD->getUnderlyingType(),
6635                                 NewTD->getUnderlyingType())) {
6636          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6637          // but we can't reasonably accept it.
6638          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6639            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6640          if (OldTD->getLocation().isValid())
6641            Diag(OldTD->getLocation(), diag::note_previous_definition);
6642          Invalid = true;
6643        }
6644      }
6645    }
6646
6647    // Merge any previous default template arguments into our parameters,
6648    // and check the parameter list.
6649    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6650                                   TPC_TypeAliasTemplate))
6651      return 0;
6652
6653    TypeAliasTemplateDecl *NewDecl =
6654      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6655                                    Name.Identifier, TemplateParams,
6656                                    NewTD);
6657
6658    NewDecl->setAccess(AS);
6659
6660    if (Invalid)
6661      NewDecl->setInvalidDecl();
6662    else if (OldDecl)
6663      NewDecl->setPreviousDeclaration(OldDecl);
6664
6665    NewND = NewDecl;
6666  } else {
6667    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6668    NewND = NewTD;
6669  }
6670
6671  if (!Redeclaration)
6672    PushOnScopeChains(NewND, S);
6673
6674  return NewND;
6675}
6676
6677Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6678                                             SourceLocation NamespaceLoc,
6679                                             SourceLocation AliasLoc,
6680                                             IdentifierInfo *Alias,
6681                                             CXXScopeSpec &SS,
6682                                             SourceLocation IdentLoc,
6683                                             IdentifierInfo *Ident) {
6684
6685  // Lookup the namespace name.
6686  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6687  LookupParsedName(R, S, &SS);
6688
6689  // Check if we have a previous declaration with the same name.
6690  NamedDecl *PrevDecl
6691    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6692                       ForRedeclaration);
6693  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6694    PrevDecl = 0;
6695
6696  if (PrevDecl) {
6697    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6698      // We already have an alias with the same name that points to the same
6699      // namespace, so don't create a new one.
6700      // FIXME: At some point, we'll want to create the (redundant)
6701      // declaration to maintain better source information.
6702      if (!R.isAmbiguous() && !R.empty() &&
6703          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6704        return 0;
6705    }
6706
6707    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6708      diag::err_redefinition_different_kind;
6709    Diag(AliasLoc, DiagID) << Alias;
6710    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6711    return 0;
6712  }
6713
6714  if (R.isAmbiguous())
6715    return 0;
6716
6717  if (R.empty()) {
6718    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6719      Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
6720      return 0;
6721    }
6722  }
6723
6724  NamespaceAliasDecl *AliasDecl =
6725    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6726                               Alias, SS.getWithLocInContext(Context),
6727                               IdentLoc, R.getFoundDecl());
6728
6729  PushOnScopeChains(AliasDecl, S);
6730  return AliasDecl;
6731}
6732
6733namespace {
6734  /// \brief Scoped object used to handle the state changes required in Sema
6735  /// to implicitly define the body of a C++ member function;
6736  class ImplicitlyDefinedFunctionScope {
6737    Sema &S;
6738    Sema::ContextRAII SavedContext;
6739
6740  public:
6741    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6742      : S(S), SavedContext(S, Method)
6743    {
6744      S.PushFunctionScope();
6745      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6746    }
6747
6748    ~ImplicitlyDefinedFunctionScope() {
6749      S.PopExpressionEvaluationContext();
6750      S.PopFunctionScopeInfo();
6751    }
6752  };
6753}
6754
6755Sema::ImplicitExceptionSpecification
6756Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6757  // C++ [except.spec]p14:
6758  //   An implicitly declared special member function (Clause 12) shall have an
6759  //   exception-specification. [...]
6760  ImplicitExceptionSpecification ExceptSpec(Context);
6761  if (ClassDecl->isInvalidDecl())
6762    return ExceptSpec;
6763
6764  // Direct base-class constructors.
6765  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6766                                       BEnd = ClassDecl->bases_end();
6767       B != BEnd; ++B) {
6768    if (B->isVirtual()) // Handled below.
6769      continue;
6770
6771    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6772      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6773      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6774      // If this is a deleted function, add it anyway. This might be conformant
6775      // with the standard. This might not. I'm not sure. It might not matter.
6776      if (Constructor)
6777        ExceptSpec.CalledDecl(Constructor);
6778    }
6779  }
6780
6781  // Virtual base-class constructors.
6782  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6783                                       BEnd = ClassDecl->vbases_end();
6784       B != BEnd; ++B) {
6785    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6786      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6787      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6788      // If this is a deleted function, add it anyway. This might be conformant
6789      // with the standard. This might not. I'm not sure. It might not matter.
6790      if (Constructor)
6791        ExceptSpec.CalledDecl(Constructor);
6792    }
6793  }
6794
6795  // Field constructors.
6796  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6797                               FEnd = ClassDecl->field_end();
6798       F != FEnd; ++F) {
6799    if (F->hasInClassInitializer()) {
6800      if (Expr *E = F->getInClassInitializer())
6801        ExceptSpec.CalledExpr(E);
6802      else if (!F->isInvalidDecl())
6803        ExceptSpec.SetDelayed();
6804    } else if (const RecordType *RecordTy
6805              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6806      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6807      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
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      // In particular, the problem is that this function never gets called. It
6811      // might just be ill-formed because this function attempts to refer to
6812      // a deleted function here.
6813      if (Constructor)
6814        ExceptSpec.CalledDecl(Constructor);
6815    }
6816  }
6817
6818  return ExceptSpec;
6819}
6820
6821CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6822                                                     CXXRecordDecl *ClassDecl) {
6823  // C++ [class.ctor]p5:
6824  //   A default constructor for a class X is a constructor of class X
6825  //   that can be called without an argument. If there is no
6826  //   user-declared constructor for class X, a default constructor is
6827  //   implicitly declared. An implicitly-declared default constructor
6828  //   is an inline public member of its class.
6829  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6830         "Should not build implicit default constructor!");
6831
6832  ImplicitExceptionSpecification Spec =
6833    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6834  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6835
6836  // Create the actual constructor declaration.
6837  CanQualType ClassType
6838    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6839  SourceLocation ClassLoc = ClassDecl->getLocation();
6840  DeclarationName Name
6841    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6842  DeclarationNameInfo NameInfo(Name, ClassLoc);
6843  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6844      Context, ClassDecl, ClassLoc, NameInfo,
6845      Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6846      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6847      /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
6848        getLangOpts().CPlusPlus0x);
6849  DefaultCon->setAccess(AS_public);
6850  DefaultCon->setDefaulted();
6851  DefaultCon->setImplicit();
6852  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6853
6854  // Note that we have declared this constructor.
6855  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6856
6857  if (Scope *S = getScopeForContext(ClassDecl))
6858    PushOnScopeChains(DefaultCon, S, false);
6859  ClassDecl->addDecl(DefaultCon);
6860
6861  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6862    DefaultCon->setDeletedAsWritten();
6863
6864  return DefaultCon;
6865}
6866
6867void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6868                                            CXXConstructorDecl *Constructor) {
6869  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6870          !Constructor->doesThisDeclarationHaveABody() &&
6871          !Constructor->isDeleted()) &&
6872    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6873
6874  CXXRecordDecl *ClassDecl = Constructor->getParent();
6875  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6876
6877  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6878  DiagnosticErrorTrap Trap(Diags);
6879  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6880      Trap.hasErrorOccurred()) {
6881    Diag(CurrentLocation, diag::note_member_synthesized_at)
6882      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6883    Constructor->setInvalidDecl();
6884    return;
6885  }
6886
6887  SourceLocation Loc = Constructor->getLocation();
6888  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6889
6890  Constructor->setUsed();
6891  MarkVTableUsed(CurrentLocation, ClassDecl);
6892
6893  if (ASTMutationListener *L = getASTMutationListener()) {
6894    L->CompletedImplicitDefinition(Constructor);
6895  }
6896}
6897
6898/// Get any existing defaulted default constructor for the given class. Do not
6899/// implicitly define one if it does not exist.
6900static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6901                                                             CXXRecordDecl *D) {
6902  ASTContext &Context = Self.Context;
6903  QualType ClassType = Context.getTypeDeclType(D);
6904  DeclarationName ConstructorName
6905    = Context.DeclarationNames.getCXXConstructorName(
6906                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6907
6908  DeclContext::lookup_const_iterator Con, ConEnd;
6909  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6910       Con != ConEnd; ++Con) {
6911    // A function template cannot be defaulted.
6912    if (isa<FunctionTemplateDecl>(*Con))
6913      continue;
6914
6915    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6916    if (Constructor->isDefaultConstructor())
6917      return Constructor->isDefaulted() ? Constructor : 0;
6918  }
6919  return 0;
6920}
6921
6922void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6923  if (!D) return;
6924  AdjustDeclIfTemplate(D);
6925
6926  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6927  CXXConstructorDecl *CtorDecl
6928    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6929
6930  if (!CtorDecl) return;
6931
6932  // Compute the exception specification for the default constructor.
6933  const FunctionProtoType *CtorTy =
6934    CtorDecl->getType()->castAs<FunctionProtoType>();
6935  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6936    ImplicitExceptionSpecification Spec =
6937      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6938    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6939    assert(EPI.ExceptionSpecType != EST_Delayed);
6940
6941    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6942  }
6943
6944  // If the default constructor is explicitly defaulted, checking the exception
6945  // specification is deferred until now.
6946  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6947      !ClassDecl->isDependentType())
6948    CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6949}
6950
6951void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6952  // We start with an initial pass over the base classes to collect those that
6953  // inherit constructors from. If there are none, we can forgo all further
6954  // processing.
6955  typedef SmallVector<const RecordType *, 4> BasesVector;
6956  BasesVector BasesToInheritFrom;
6957  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6958                                          BaseE = ClassDecl->bases_end();
6959         BaseIt != BaseE; ++BaseIt) {
6960    if (BaseIt->getInheritConstructors()) {
6961      QualType Base = BaseIt->getType();
6962      if (Base->isDependentType()) {
6963        // If we inherit constructors from anything that is dependent, just
6964        // abort processing altogether. We'll get another chance for the
6965        // instantiations.
6966        return;
6967      }
6968      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6969    }
6970  }
6971  if (BasesToInheritFrom.empty())
6972    return;
6973
6974  // Now collect the constructors that we already have in the current class.
6975  // Those take precedence over inherited constructors.
6976  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6977  //   unless there is a user-declared constructor with the same signature in
6978  //   the class where the using-declaration appears.
6979  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6980  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6981                                    CtorE = ClassDecl->ctor_end();
6982       CtorIt != CtorE; ++CtorIt) {
6983    ExistingConstructors.insert(
6984        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6985  }
6986
6987  Scope *S = getScopeForContext(ClassDecl);
6988  DeclarationName CreatedCtorName =
6989      Context.DeclarationNames.getCXXConstructorName(
6990          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6991
6992  // Now comes the true work.
6993  // First, we keep a map from constructor types to the base that introduced
6994  // them. Needed for finding conflicting constructors. We also keep the
6995  // actually inserted declarations in there, for pretty diagnostics.
6996  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6997  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6998  ConstructorToSourceMap InheritedConstructors;
6999  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7000                             BaseE = BasesToInheritFrom.end();
7001       BaseIt != BaseE; ++BaseIt) {
7002    const RecordType *Base = *BaseIt;
7003    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7004    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7005    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7006                                      CtorE = BaseDecl->ctor_end();
7007         CtorIt != CtorE; ++CtorIt) {
7008      // Find the using declaration for inheriting this base's constructors.
7009      DeclarationName Name =
7010          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7011      UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7012          LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7013      SourceLocation UsingLoc = UD ? UD->getLocation() :
7014                                     ClassDecl->getLocation();
7015
7016      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7017      //   from the class X named in the using-declaration consists of actual
7018      //   constructors and notional constructors that result from the
7019      //   transformation of defaulted parameters as follows:
7020      //   - all non-template default constructors of X, and
7021      //   - for each non-template constructor of X that has at least one
7022      //     parameter with a default argument, the set of constructors that
7023      //     results from omitting any ellipsis parameter specification and
7024      //     successively omitting parameters with a default argument from the
7025      //     end of the parameter-type-list.
7026      CXXConstructorDecl *BaseCtor = *CtorIt;
7027      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7028      const FunctionProtoType *BaseCtorType =
7029          BaseCtor->getType()->getAs<FunctionProtoType>();
7030
7031      for (unsigned params = BaseCtor->getMinRequiredArguments(),
7032                    maxParams = BaseCtor->getNumParams();
7033           params <= maxParams; ++params) {
7034        // Skip default constructors. They're never inherited.
7035        if (params == 0)
7036          continue;
7037        // Skip copy and move constructors for the same reason.
7038        if (CanBeCopyOrMove && params == 1)
7039          continue;
7040
7041        // Build up a function type for this particular constructor.
7042        // FIXME: The working paper does not consider that the exception spec
7043        // for the inheriting constructor might be larger than that of the
7044        // source. This code doesn't yet, either. When it does, this code will
7045        // need to be delayed until after exception specifications and in-class
7046        // member initializers are attached.
7047        const Type *NewCtorType;
7048        if (params == maxParams)
7049          NewCtorType = BaseCtorType;
7050        else {
7051          SmallVector<QualType, 16> Args;
7052          for (unsigned i = 0; i < params; ++i) {
7053            Args.push_back(BaseCtorType->getArgType(i));
7054          }
7055          FunctionProtoType::ExtProtoInfo ExtInfo =
7056              BaseCtorType->getExtProtoInfo();
7057          ExtInfo.Variadic = false;
7058          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7059                                                Args.data(), params, ExtInfo)
7060                       .getTypePtr();
7061        }
7062        const Type *CanonicalNewCtorType =
7063            Context.getCanonicalType(NewCtorType);
7064
7065        // Now that we have the type, first check if the class already has a
7066        // constructor with this signature.
7067        if (ExistingConstructors.count(CanonicalNewCtorType))
7068          continue;
7069
7070        // Then we check if we have already declared an inherited constructor
7071        // with this signature.
7072        std::pair<ConstructorToSourceMap::iterator, bool> result =
7073            InheritedConstructors.insert(std::make_pair(
7074                CanonicalNewCtorType,
7075                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7076        if (!result.second) {
7077          // Already in the map. If it came from a different class, that's an
7078          // error. Not if it's from the same.
7079          CanQualType PreviousBase = result.first->second.first;
7080          if (CanonicalBase != PreviousBase) {
7081            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7082            const CXXConstructorDecl *PrevBaseCtor =
7083                PrevCtor->getInheritedConstructor();
7084            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7085
7086            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7087            Diag(BaseCtor->getLocation(),
7088                 diag::note_using_decl_constructor_conflict_current_ctor);
7089            Diag(PrevBaseCtor->getLocation(),
7090                 diag::note_using_decl_constructor_conflict_previous_ctor);
7091            Diag(PrevCtor->getLocation(),
7092                 diag::note_using_decl_constructor_conflict_previous_using);
7093          }
7094          continue;
7095        }
7096
7097        // OK, we're there, now add the constructor.
7098        // C++0x [class.inhctor]p8: [...] that would be performed by a
7099        //   user-written inline constructor [...]
7100        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7101        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7102            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7103            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7104            /*ImplicitlyDeclared=*/true,
7105            // FIXME: Due to a defect in the standard, we treat inherited
7106            // constructors as constexpr even if that makes them ill-formed.
7107            /*Constexpr=*/BaseCtor->isConstexpr());
7108        NewCtor->setAccess(BaseCtor->getAccess());
7109
7110        // Build up the parameter decls and add them.
7111        SmallVector<ParmVarDecl *, 16> ParamDecls;
7112        for (unsigned i = 0; i < params; ++i) {
7113          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7114                                                   UsingLoc, UsingLoc,
7115                                                   /*IdentifierInfo=*/0,
7116                                                   BaseCtorType->getArgType(i),
7117                                                   /*TInfo=*/0, SC_None,
7118                                                   SC_None, /*DefaultArg=*/0));
7119        }
7120        NewCtor->setParams(ParamDecls);
7121        NewCtor->setInheritedConstructor(BaseCtor);
7122
7123        PushOnScopeChains(NewCtor, S, false);
7124        ClassDecl->addDecl(NewCtor);
7125        result.first->second.second = NewCtor;
7126      }
7127    }
7128  }
7129}
7130
7131Sema::ImplicitExceptionSpecification
7132Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
7133  // C++ [except.spec]p14:
7134  //   An implicitly declared special member function (Clause 12) shall have
7135  //   an exception-specification.
7136  ImplicitExceptionSpecification ExceptSpec(Context);
7137  if (ClassDecl->isInvalidDecl())
7138    return ExceptSpec;
7139
7140  // Direct base-class destructors.
7141  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7142                                       BEnd = ClassDecl->bases_end();
7143       B != BEnd; ++B) {
7144    if (B->isVirtual()) // Handled below.
7145      continue;
7146
7147    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7148      ExceptSpec.CalledDecl(
7149                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7150  }
7151
7152  // Virtual base-class destructors.
7153  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7154                                       BEnd = ClassDecl->vbases_end();
7155       B != BEnd; ++B) {
7156    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7157      ExceptSpec.CalledDecl(
7158                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7159  }
7160
7161  // Field destructors.
7162  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7163                               FEnd = ClassDecl->field_end();
7164       F != FEnd; ++F) {
7165    if (const RecordType *RecordTy
7166        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7167      ExceptSpec.CalledDecl(
7168                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7169  }
7170
7171  return ExceptSpec;
7172}
7173
7174CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7175  // C++ [class.dtor]p2:
7176  //   If a class has no user-declared destructor, a destructor is
7177  //   declared implicitly. An implicitly-declared destructor is an
7178  //   inline public member of its class.
7179
7180  ImplicitExceptionSpecification Spec =
7181      ComputeDefaultedDtorExceptionSpec(ClassDecl);
7182  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7183
7184  // Create the actual destructor declaration.
7185  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
7186
7187  CanQualType ClassType
7188    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7189  SourceLocation ClassLoc = ClassDecl->getLocation();
7190  DeclarationName Name
7191    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7192  DeclarationNameInfo NameInfo(Name, ClassLoc);
7193  CXXDestructorDecl *Destructor
7194      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7195                                  /*isInline=*/true,
7196                                  /*isImplicitlyDeclared=*/true);
7197  Destructor->setAccess(AS_public);
7198  Destructor->setDefaulted();
7199  Destructor->setImplicit();
7200  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7201
7202  // Note that we have declared this destructor.
7203  ++ASTContext::NumImplicitDestructorsDeclared;
7204
7205  // Introduce this destructor into its scope.
7206  if (Scope *S = getScopeForContext(ClassDecl))
7207    PushOnScopeChains(Destructor, S, false);
7208  ClassDecl->addDecl(Destructor);
7209
7210  // This could be uniqued if it ever proves significant.
7211  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
7212
7213  AddOverriddenMethods(ClassDecl, Destructor);
7214
7215  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7216    Destructor->setDeletedAsWritten();
7217
7218  return Destructor;
7219}
7220
7221void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7222                                    CXXDestructorDecl *Destructor) {
7223  assert((Destructor->isDefaulted() &&
7224          !Destructor->doesThisDeclarationHaveABody() &&
7225          !Destructor->isDeleted()) &&
7226         "DefineImplicitDestructor - call it for implicit default dtor");
7227  CXXRecordDecl *ClassDecl = Destructor->getParent();
7228  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7229
7230  if (Destructor->isInvalidDecl())
7231    return;
7232
7233  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7234
7235  DiagnosticErrorTrap Trap(Diags);
7236  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7237                                         Destructor->getParent());
7238
7239  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7240    Diag(CurrentLocation, diag::note_member_synthesized_at)
7241      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7242
7243    Destructor->setInvalidDecl();
7244    return;
7245  }
7246
7247  SourceLocation Loc = Destructor->getLocation();
7248  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7249  Destructor->setImplicitlyDefined(true);
7250  Destructor->setUsed();
7251  MarkVTableUsed(CurrentLocation, ClassDecl);
7252
7253  if (ASTMutationListener *L = getASTMutationListener()) {
7254    L->CompletedImplicitDefinition(Destructor);
7255  }
7256}
7257
7258void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7259                                         CXXDestructorDecl *destructor) {
7260  // C++11 [class.dtor]p3:
7261  //   A declaration of a destructor that does not have an exception-
7262  //   specification is implicitly considered to have the same exception-
7263  //   specification as an implicit declaration.
7264  const FunctionProtoType *dtorType = destructor->getType()->
7265                                        getAs<FunctionProtoType>();
7266  if (dtorType->hasExceptionSpec())
7267    return;
7268
7269  ImplicitExceptionSpecification exceptSpec =
7270      ComputeDefaultedDtorExceptionSpec(classDecl);
7271
7272  // Replace the destructor's type, building off the existing one. Fortunately,
7273  // the only thing of interest in the destructor type is its extended info.
7274  // The return and arguments are fixed.
7275  FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
7276  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7277  epi.NumExceptions = exceptSpec.size();
7278  epi.Exceptions = exceptSpec.data();
7279  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7280
7281  destructor->setType(ty);
7282
7283  // FIXME: If the destructor has a body that could throw, and the newly created
7284  // spec doesn't allow exceptions, we should emit a warning, because this
7285  // change in behavior can break conforming C++03 programs at runtime.
7286  // However, we don't have a body yet, so it needs to be done somewhere else.
7287}
7288
7289/// \brief Builds a statement that copies/moves the given entity from \p From to
7290/// \c To.
7291///
7292/// This routine is used to copy/move the members of a class with an
7293/// implicitly-declared copy/move assignment operator. When the entities being
7294/// copied are arrays, this routine builds for loops to copy them.
7295///
7296/// \param S The Sema object used for type-checking.
7297///
7298/// \param Loc The location where the implicit copy/move is being generated.
7299///
7300/// \param T The type of the expressions being copied/moved. Both expressions
7301/// must have this type.
7302///
7303/// \param To The expression we are copying/moving to.
7304///
7305/// \param From The expression we are copying/moving from.
7306///
7307/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7308/// Otherwise, it's a non-static member subobject.
7309///
7310/// \param Copying Whether we're copying or moving.
7311///
7312/// \param Depth Internal parameter recording the depth of the recursion.
7313///
7314/// \returns A statement or a loop that copies the expressions.
7315static StmtResult
7316BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7317                      Expr *To, Expr *From,
7318                      bool CopyingBaseSubobject, bool Copying,
7319                      unsigned Depth = 0) {
7320  // C++0x [class.copy]p28:
7321  //   Each subobject is assigned in the manner appropriate to its type:
7322  //
7323  //     - if the subobject is of class type, as if by a call to operator= with
7324  //       the subobject as the object expression and the corresponding
7325  //       subobject of x as a single function argument (as if by explicit
7326  //       qualification; that is, ignoring any possible virtual overriding
7327  //       functions in more derived classes);
7328  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7329    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7330
7331    // Look for operator=.
7332    DeclarationName Name
7333      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7334    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7335    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7336
7337    // Filter out any result that isn't a copy/move-assignment operator.
7338    LookupResult::Filter F = OpLookup.makeFilter();
7339    while (F.hasNext()) {
7340      NamedDecl *D = F.next();
7341      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7342        if (Copying ? Method->isCopyAssignmentOperator() :
7343                      Method->isMoveAssignmentOperator())
7344          continue;
7345
7346      F.erase();
7347    }
7348    F.done();
7349
7350    // Suppress the protected check (C++ [class.protected]) for each of the
7351    // assignment operators we found. This strange dance is required when
7352    // we're assigning via a base classes's copy-assignment operator. To
7353    // ensure that we're getting the right base class subobject (without
7354    // ambiguities), we need to cast "this" to that subobject type; to
7355    // ensure that we don't go through the virtual call mechanism, we need
7356    // to qualify the operator= name with the base class (see below). However,
7357    // this means that if the base class has a protected copy assignment
7358    // operator, the protected member access check will fail. So, we
7359    // rewrite "protected" access to "public" access in this case, since we
7360    // know by construction that we're calling from a derived class.
7361    if (CopyingBaseSubobject) {
7362      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7363           L != LEnd; ++L) {
7364        if (L.getAccess() == AS_protected)
7365          L.setAccess(AS_public);
7366      }
7367    }
7368
7369    // Create the nested-name-specifier that will be used to qualify the
7370    // reference to operator=; this is required to suppress the virtual
7371    // call mechanism.
7372    CXXScopeSpec SS;
7373    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7374    SS.MakeTrivial(S.Context,
7375                   NestedNameSpecifier::Create(S.Context, 0, false,
7376                                               CanonicalT),
7377                   Loc);
7378
7379    // Create the reference to operator=.
7380    ExprResult OpEqualRef
7381      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7382                                   /*TemplateKWLoc=*/SourceLocation(),
7383                                   /*FirstQualifierInScope=*/0,
7384                                   OpLookup,
7385                                   /*TemplateArgs=*/0,
7386                                   /*SuppressQualifierCheck=*/true);
7387    if (OpEqualRef.isInvalid())
7388      return StmtError();
7389
7390    // Build the call to the assignment operator.
7391
7392    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7393                                                  OpEqualRef.takeAs<Expr>(),
7394                                                  Loc, &From, 1, Loc);
7395    if (Call.isInvalid())
7396      return StmtError();
7397
7398    return S.Owned(Call.takeAs<Stmt>());
7399  }
7400
7401  //     - if the subobject is of scalar type, the built-in assignment
7402  //       operator is used.
7403  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7404  if (!ArrayTy) {
7405    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7406    if (Assignment.isInvalid())
7407      return StmtError();
7408
7409    return S.Owned(Assignment.takeAs<Stmt>());
7410  }
7411
7412  //     - if the subobject is an array, each element is assigned, in the
7413  //       manner appropriate to the element type;
7414
7415  // Construct a loop over the array bounds, e.g.,
7416  //
7417  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7418  //
7419  // that will copy each of the array elements.
7420  QualType SizeType = S.Context.getSizeType();
7421
7422  // Create the iteration variable.
7423  IdentifierInfo *IterationVarName = 0;
7424  {
7425    SmallString<8> Str;
7426    llvm::raw_svector_ostream OS(Str);
7427    OS << "__i" << Depth;
7428    IterationVarName = &S.Context.Idents.get(OS.str());
7429  }
7430  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7431                                          IterationVarName, SizeType,
7432                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7433                                          SC_None, SC_None);
7434
7435  // Initialize the iteration variable to zero.
7436  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7437  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7438
7439  // Create a reference to the iteration variable; we'll use this several
7440  // times throughout.
7441  Expr *IterationVarRef
7442    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7443  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7444  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7445  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7446
7447  // Create the DeclStmt that holds the iteration variable.
7448  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7449
7450  // Create the comparison against the array bound.
7451  llvm::APInt Upper
7452    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7453  Expr *Comparison
7454    = new (S.Context) BinaryOperator(IterationVarRefRVal,
7455                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7456                                     BO_NE, S.Context.BoolTy,
7457                                     VK_RValue, OK_Ordinary, Loc);
7458
7459  // Create the pre-increment of the iteration variable.
7460  Expr *Increment
7461    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7462                                    VK_LValue, OK_Ordinary, Loc);
7463
7464  // Subscript the "from" and "to" expressions with the iteration variable.
7465  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7466                                                         IterationVarRefRVal,
7467                                                         Loc));
7468  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7469                                                       IterationVarRefRVal,
7470                                                       Loc));
7471  if (!Copying) // Cast to rvalue
7472    From = CastForMoving(S, From);
7473
7474  // Build the copy/move for an individual element of the array.
7475  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7476                                          To, From, CopyingBaseSubobject,
7477                                          Copying, Depth + 1);
7478  if (Copy.isInvalid())
7479    return StmtError();
7480
7481  // Construct the loop that copies all elements of this array.
7482  return S.ActOnForStmt(Loc, Loc, InitStmt,
7483                        S.MakeFullExpr(Comparison),
7484                        0, S.MakeFullExpr(Increment),
7485                        Loc, Copy.take());
7486}
7487
7488std::pair<Sema::ImplicitExceptionSpecification, bool>
7489Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7490                                                   CXXRecordDecl *ClassDecl) {
7491  if (ClassDecl->isInvalidDecl())
7492    return std::make_pair(ImplicitExceptionSpecification(Context), false);
7493
7494  // C++ [class.copy]p10:
7495  //   If the class definition does not explicitly declare a copy
7496  //   assignment operator, one is declared implicitly.
7497  //   The implicitly-defined copy assignment operator for a class X
7498  //   will have the form
7499  //
7500  //       X& X::operator=(const X&)
7501  //
7502  //   if
7503  bool HasConstCopyAssignment = true;
7504
7505  //       -- each direct base class B of X has a copy assignment operator
7506  //          whose parameter is of type const B&, const volatile B& or B,
7507  //          and
7508  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7509                                       BaseEnd = ClassDecl->bases_end();
7510       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7511    // We'll handle this below
7512    if (LangOpts.CPlusPlus0x && Base->isVirtual())
7513      continue;
7514
7515    assert(!Base->getType()->isDependentType() &&
7516           "Cannot generate implicit members for class with dependent bases.");
7517    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7518    LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7519                            &HasConstCopyAssignment);
7520  }
7521
7522  // In C++11, the above citation has "or virtual" added
7523  if (LangOpts.CPlusPlus0x) {
7524    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7525                                         BaseEnd = ClassDecl->vbases_end();
7526         HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7527      assert(!Base->getType()->isDependentType() &&
7528             "Cannot generate implicit members for class with dependent bases.");
7529      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7530      LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7531                              &HasConstCopyAssignment);
7532    }
7533  }
7534
7535  //       -- for all the nonstatic data members of X that are of a class
7536  //          type M (or array thereof), each such class type has a copy
7537  //          assignment operator whose parameter is of type const M&,
7538  //          const volatile M& or M.
7539  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7540                                  FieldEnd = ClassDecl->field_end();
7541       HasConstCopyAssignment && Field != FieldEnd;
7542       ++Field) {
7543    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7544    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7545      LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7546                              &HasConstCopyAssignment);
7547    }
7548  }
7549
7550  //   Otherwise, the implicitly declared copy assignment operator will
7551  //   have the form
7552  //
7553  //       X& X::operator=(X&)
7554
7555  // C++ [except.spec]p14:
7556  //   An implicitly declared special member function (Clause 12) shall have an
7557  //   exception-specification. [...]
7558
7559  // It is unspecified whether or not an implicit copy assignment operator
7560  // attempts to deduplicate calls to assignment operators of virtual bases are
7561  // made. As such, this exception specification is effectively unspecified.
7562  // Based on a similar decision made for constness in C++0x, we're erring on
7563  // the side of assuming such calls to be made regardless of whether they
7564  // actually happen.
7565  ImplicitExceptionSpecification ExceptSpec(Context);
7566  unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
7567  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7568                                       BaseEnd = ClassDecl->bases_end();
7569       Base != BaseEnd; ++Base) {
7570    if (Base->isVirtual())
7571      continue;
7572
7573    CXXRecordDecl *BaseClassDecl
7574      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7575    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7576                                                            ArgQuals, false, 0))
7577      ExceptSpec.CalledDecl(CopyAssign);
7578  }
7579
7580  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7581                                       BaseEnd = ClassDecl->vbases_end();
7582       Base != BaseEnd; ++Base) {
7583    CXXRecordDecl *BaseClassDecl
7584      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7585    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7586                                                            ArgQuals, false, 0))
7587      ExceptSpec.CalledDecl(CopyAssign);
7588  }
7589
7590  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7591                                  FieldEnd = ClassDecl->field_end();
7592       Field != FieldEnd;
7593       ++Field) {
7594    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7595    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7596      if (CXXMethodDecl *CopyAssign =
7597          LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7598        ExceptSpec.CalledDecl(CopyAssign);
7599    }
7600  }
7601
7602  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7603}
7604
7605CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7606  // Note: The following rules are largely analoguous to the copy
7607  // constructor rules. Note that virtual bases are not taken into account
7608  // for determining the argument type of the operator. Note also that
7609  // operators taking an object instead of a reference are allowed.
7610
7611  ImplicitExceptionSpecification Spec(Context);
7612  bool Const;
7613  llvm::tie(Spec, Const) =
7614    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7615
7616  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7617  QualType RetType = Context.getLValueReferenceType(ArgType);
7618  if (Const)
7619    ArgType = ArgType.withConst();
7620  ArgType = Context.getLValueReferenceType(ArgType);
7621
7622  //   An implicitly-declared copy assignment operator is an inline public
7623  //   member of its class.
7624  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7625  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7626  SourceLocation ClassLoc = ClassDecl->getLocation();
7627  DeclarationNameInfo NameInfo(Name, ClassLoc);
7628  CXXMethodDecl *CopyAssignment
7629    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7630                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7631                            /*TInfo=*/0, /*isStatic=*/false,
7632                            /*StorageClassAsWritten=*/SC_None,
7633                            /*isInline=*/true, /*isConstexpr=*/false,
7634                            SourceLocation());
7635  CopyAssignment->setAccess(AS_public);
7636  CopyAssignment->setDefaulted();
7637  CopyAssignment->setImplicit();
7638  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7639
7640  // Add the parameter to the operator.
7641  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7642                                               ClassLoc, ClassLoc, /*Id=*/0,
7643                                               ArgType, /*TInfo=*/0,
7644                                               SC_None,
7645                                               SC_None, 0);
7646  CopyAssignment->setParams(FromParam);
7647
7648  // Note that we have added this copy-assignment operator.
7649  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7650
7651  if (Scope *S = getScopeForContext(ClassDecl))
7652    PushOnScopeChains(CopyAssignment, S, false);
7653  ClassDecl->addDecl(CopyAssignment);
7654
7655  // C++0x [class.copy]p19:
7656  //   ....  If the class definition does not explicitly declare a copy
7657  //   assignment operator, there is no user-declared move constructor, and
7658  //   there is no user-declared move assignment operator, a copy assignment
7659  //   operator is implicitly declared as defaulted.
7660  if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
7661          !getLangOpts().MicrosoftMode) ||
7662      ClassDecl->hasUserDeclaredMoveAssignment() ||
7663      ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7664    CopyAssignment->setDeletedAsWritten();
7665
7666  AddOverriddenMethods(ClassDecl, CopyAssignment);
7667  return CopyAssignment;
7668}
7669
7670void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7671                                        CXXMethodDecl *CopyAssignOperator) {
7672  assert((CopyAssignOperator->isDefaulted() &&
7673          CopyAssignOperator->isOverloadedOperator() &&
7674          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7675          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7676          !CopyAssignOperator->isDeleted()) &&
7677         "DefineImplicitCopyAssignment called for wrong function");
7678
7679  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7680
7681  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7682    CopyAssignOperator->setInvalidDecl();
7683    return;
7684  }
7685
7686  CopyAssignOperator->setUsed();
7687
7688  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7689  DiagnosticErrorTrap Trap(Diags);
7690
7691  // C++0x [class.copy]p30:
7692  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7693  //   for a non-union class X performs memberwise copy assignment of its
7694  //   subobjects. The direct base classes of X are assigned first, in the
7695  //   order of their declaration in the base-specifier-list, and then the
7696  //   immediate non-static data members of X are assigned, in the order in
7697  //   which they were declared in the class definition.
7698
7699  // The statements that form the synthesized function body.
7700  ASTOwningVector<Stmt*> Statements(*this);
7701
7702  // The parameter for the "other" object, which we are copying from.
7703  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7704  Qualifiers OtherQuals = Other->getType().getQualifiers();
7705  QualType OtherRefType = Other->getType();
7706  if (const LValueReferenceType *OtherRef
7707                                = OtherRefType->getAs<LValueReferenceType>()) {
7708    OtherRefType = OtherRef->getPointeeType();
7709    OtherQuals = OtherRefType.getQualifiers();
7710  }
7711
7712  // Our location for everything implicitly-generated.
7713  SourceLocation Loc = CopyAssignOperator->getLocation();
7714
7715  // Construct a reference to the "other" object. We'll be using this
7716  // throughout the generated ASTs.
7717  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7718  assert(OtherRef && "Reference to parameter cannot fail!");
7719
7720  // Construct the "this" pointer. We'll be using this throughout the generated
7721  // ASTs.
7722  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7723  assert(This && "Reference to this cannot fail!");
7724
7725  // Assign base classes.
7726  bool Invalid = false;
7727  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7728       E = ClassDecl->bases_end(); Base != E; ++Base) {
7729    // Form the assignment:
7730    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7731    QualType BaseType = Base->getType().getUnqualifiedType();
7732    if (!BaseType->isRecordType()) {
7733      Invalid = true;
7734      continue;
7735    }
7736
7737    CXXCastPath BasePath;
7738    BasePath.push_back(Base);
7739
7740    // Construct the "from" expression, which is an implicit cast to the
7741    // appropriately-qualified base type.
7742    Expr *From = OtherRef;
7743    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7744                             CK_UncheckedDerivedToBase,
7745                             VK_LValue, &BasePath).take();
7746
7747    // Dereference "this".
7748    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7749
7750    // Implicitly cast "this" to the appropriately-qualified base type.
7751    To = ImpCastExprToType(To.take(),
7752                           Context.getCVRQualifiedType(BaseType,
7753                                     CopyAssignOperator->getTypeQualifiers()),
7754                           CK_UncheckedDerivedToBase,
7755                           VK_LValue, &BasePath);
7756
7757    // Build the copy.
7758    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7759                                            To.get(), From,
7760                                            /*CopyingBaseSubobject=*/true,
7761                                            /*Copying=*/true);
7762    if (Copy.isInvalid()) {
7763      Diag(CurrentLocation, diag::note_member_synthesized_at)
7764        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7765      CopyAssignOperator->setInvalidDecl();
7766      return;
7767    }
7768
7769    // Success! Record the copy.
7770    Statements.push_back(Copy.takeAs<Expr>());
7771  }
7772
7773  // \brief Reference to the __builtin_memcpy function.
7774  Expr *BuiltinMemCpyRef = 0;
7775  // \brief Reference to the __builtin_objc_memmove_collectable function.
7776  Expr *CollectableMemCpyRef = 0;
7777
7778  // Assign non-static members.
7779  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7780                                  FieldEnd = ClassDecl->field_end();
7781       Field != FieldEnd; ++Field) {
7782    if (Field->isUnnamedBitfield())
7783      continue;
7784
7785    // Check for members of reference type; we can't copy those.
7786    if (Field->getType()->isReferenceType()) {
7787      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7788        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7789      Diag(Field->getLocation(), diag::note_declared_at);
7790      Diag(CurrentLocation, diag::note_member_synthesized_at)
7791        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7792      Invalid = true;
7793      continue;
7794    }
7795
7796    // Check for members of const-qualified, non-class type.
7797    QualType BaseType = Context.getBaseElementType(Field->getType());
7798    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7799      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7800        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7801      Diag(Field->getLocation(), diag::note_declared_at);
7802      Diag(CurrentLocation, diag::note_member_synthesized_at)
7803        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7804      Invalid = true;
7805      continue;
7806    }
7807
7808    // Suppress assigning zero-width bitfields.
7809    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7810      continue;
7811
7812    QualType FieldType = Field->getType().getNonReferenceType();
7813    if (FieldType->isIncompleteArrayType()) {
7814      assert(ClassDecl->hasFlexibleArrayMember() &&
7815             "Incomplete array type is not valid");
7816      continue;
7817    }
7818
7819    // Build references to the field in the object we're copying from and to.
7820    CXXScopeSpec SS; // Intentionally empty
7821    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7822                              LookupMemberName);
7823    MemberLookup.addDecl(*Field);
7824    MemberLookup.resolveKind();
7825    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7826                                               Loc, /*IsArrow=*/false,
7827                                               SS, SourceLocation(), 0,
7828                                               MemberLookup, 0);
7829    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7830                                             Loc, /*IsArrow=*/true,
7831                                             SS, SourceLocation(), 0,
7832                                             MemberLookup, 0);
7833    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7834    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7835
7836    // If the field should be copied with __builtin_memcpy rather than via
7837    // explicit assignments, do so. This optimization only applies for arrays
7838    // of scalars and arrays of class type with trivial copy-assignment
7839    // operators.
7840    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7841        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7842      // Compute the size of the memory buffer to be copied.
7843      QualType SizeType = Context.getSizeType();
7844      llvm::APInt Size(Context.getTypeSize(SizeType),
7845                       Context.getTypeSizeInChars(BaseType).getQuantity());
7846      for (const ConstantArrayType *Array
7847              = Context.getAsConstantArrayType(FieldType);
7848           Array;
7849           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7850        llvm::APInt ArraySize
7851          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7852        Size *= ArraySize;
7853      }
7854
7855      // Take the address of the field references for "from" and "to".
7856      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7857      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7858
7859      bool NeedsCollectableMemCpy =
7860          (BaseType->isRecordType() &&
7861           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7862
7863      if (NeedsCollectableMemCpy) {
7864        if (!CollectableMemCpyRef) {
7865          // Create a reference to the __builtin_objc_memmove_collectable function.
7866          LookupResult R(*this,
7867                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7868                         Loc, LookupOrdinaryName);
7869          LookupName(R, TUScope, true);
7870
7871          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7872          if (!CollectableMemCpy) {
7873            // Something went horribly wrong earlier, and we will have
7874            // complained about it.
7875            Invalid = true;
7876            continue;
7877          }
7878
7879          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7880                                                  CollectableMemCpy->getType(),
7881                                                  VK_LValue, Loc, 0).take();
7882          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7883        }
7884      }
7885      // Create a reference to the __builtin_memcpy builtin function.
7886      else if (!BuiltinMemCpyRef) {
7887        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7888                       LookupOrdinaryName);
7889        LookupName(R, TUScope, true);
7890
7891        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7892        if (!BuiltinMemCpy) {
7893          // Something went horribly wrong earlier, and we will have complained
7894          // about it.
7895          Invalid = true;
7896          continue;
7897        }
7898
7899        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7900                                            BuiltinMemCpy->getType(),
7901                                            VK_LValue, Loc, 0).take();
7902        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7903      }
7904
7905      ASTOwningVector<Expr*> CallArgs(*this);
7906      CallArgs.push_back(To.takeAs<Expr>());
7907      CallArgs.push_back(From.takeAs<Expr>());
7908      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7909      ExprResult Call = ExprError();
7910      if (NeedsCollectableMemCpy)
7911        Call = ActOnCallExpr(/*Scope=*/0,
7912                             CollectableMemCpyRef,
7913                             Loc, move_arg(CallArgs),
7914                             Loc);
7915      else
7916        Call = ActOnCallExpr(/*Scope=*/0,
7917                             BuiltinMemCpyRef,
7918                             Loc, move_arg(CallArgs),
7919                             Loc);
7920
7921      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7922      Statements.push_back(Call.takeAs<Expr>());
7923      continue;
7924    }
7925
7926    // Build the copy of this field.
7927    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7928                                            To.get(), From.get(),
7929                                            /*CopyingBaseSubobject=*/false,
7930                                            /*Copying=*/true);
7931    if (Copy.isInvalid()) {
7932      Diag(CurrentLocation, diag::note_member_synthesized_at)
7933        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7934      CopyAssignOperator->setInvalidDecl();
7935      return;
7936    }
7937
7938    // Success! Record the copy.
7939    Statements.push_back(Copy.takeAs<Stmt>());
7940  }
7941
7942  if (!Invalid) {
7943    // Add a "return *this;"
7944    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7945
7946    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7947    if (Return.isInvalid())
7948      Invalid = true;
7949    else {
7950      Statements.push_back(Return.takeAs<Stmt>());
7951
7952      if (Trap.hasErrorOccurred()) {
7953        Diag(CurrentLocation, diag::note_member_synthesized_at)
7954          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7955        Invalid = true;
7956      }
7957    }
7958  }
7959
7960  if (Invalid) {
7961    CopyAssignOperator->setInvalidDecl();
7962    return;
7963  }
7964
7965  StmtResult Body;
7966  {
7967    CompoundScopeRAII CompoundScope(*this);
7968    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7969                             /*isStmtExpr=*/false);
7970    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7971  }
7972  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7973
7974  if (ASTMutationListener *L = getASTMutationListener()) {
7975    L->CompletedImplicitDefinition(CopyAssignOperator);
7976  }
7977}
7978
7979Sema::ImplicitExceptionSpecification
7980Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7981  ImplicitExceptionSpecification ExceptSpec(Context);
7982
7983  if (ClassDecl->isInvalidDecl())
7984    return ExceptSpec;
7985
7986  // C++0x [except.spec]p14:
7987  //   An implicitly declared special member function (Clause 12) shall have an
7988  //   exception-specification. [...]
7989
7990  // It is unspecified whether or not an implicit move assignment operator
7991  // attempts to deduplicate calls to assignment operators of virtual bases are
7992  // made. As such, this exception specification is effectively unspecified.
7993  // Based on a similar decision made for constness in C++0x, we're erring on
7994  // the side of assuming such calls to be made regardless of whether they
7995  // actually happen.
7996  // Note that a move constructor is not implicitly declared when there are
7997  // virtual bases, but it can still be user-declared and explicitly defaulted.
7998  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7999                                       BaseEnd = ClassDecl->bases_end();
8000       Base != BaseEnd; ++Base) {
8001    if (Base->isVirtual())
8002      continue;
8003
8004    CXXRecordDecl *BaseClassDecl
8005      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8006    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8007                                                           false, 0))
8008      ExceptSpec.CalledDecl(MoveAssign);
8009  }
8010
8011  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8012                                       BaseEnd = ClassDecl->vbases_end();
8013       Base != BaseEnd; ++Base) {
8014    CXXRecordDecl *BaseClassDecl
8015      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8016    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8017                                                           false, 0))
8018      ExceptSpec.CalledDecl(MoveAssign);
8019  }
8020
8021  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8022                                  FieldEnd = ClassDecl->field_end();
8023       Field != FieldEnd;
8024       ++Field) {
8025    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8026    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8027      if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8028                                                             false, 0))
8029        ExceptSpec.CalledDecl(MoveAssign);
8030    }
8031  }
8032
8033  return ExceptSpec;
8034}
8035
8036CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8037  // Note: The following rules are largely analoguous to the move
8038  // constructor rules.
8039
8040  ImplicitExceptionSpecification Spec(
8041      ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8042
8043  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8044  QualType RetType = Context.getLValueReferenceType(ArgType);
8045  ArgType = Context.getRValueReferenceType(ArgType);
8046
8047  //   An implicitly-declared move assignment operator is an inline public
8048  //   member of its class.
8049  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8050  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8051  SourceLocation ClassLoc = ClassDecl->getLocation();
8052  DeclarationNameInfo NameInfo(Name, ClassLoc);
8053  CXXMethodDecl *MoveAssignment
8054    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8055                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
8056                            /*TInfo=*/0, /*isStatic=*/false,
8057                            /*StorageClassAsWritten=*/SC_None,
8058                            /*isInline=*/true,
8059                            /*isConstexpr=*/false,
8060                            SourceLocation());
8061  MoveAssignment->setAccess(AS_public);
8062  MoveAssignment->setDefaulted();
8063  MoveAssignment->setImplicit();
8064  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8065
8066  // Add the parameter to the operator.
8067  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8068                                               ClassLoc, ClassLoc, /*Id=*/0,
8069                                               ArgType, /*TInfo=*/0,
8070                                               SC_None,
8071                                               SC_None, 0);
8072  MoveAssignment->setParams(FromParam);
8073
8074  // Note that we have added this copy-assignment operator.
8075  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8076
8077  // C++0x [class.copy]p9:
8078  //   If the definition of a class X does not explicitly declare a move
8079  //   assignment operator, one will be implicitly declared as defaulted if and
8080  //   only if:
8081  //   [...]
8082  //   - the move assignment operator would not be implicitly defined as
8083  //     deleted.
8084  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8085    // Cache this result so that we don't try to generate this over and over
8086    // on every lookup, leaking memory and wasting time.
8087    ClassDecl->setFailedImplicitMoveAssignment();
8088    return 0;
8089  }
8090
8091  if (Scope *S = getScopeForContext(ClassDecl))
8092    PushOnScopeChains(MoveAssignment, S, false);
8093  ClassDecl->addDecl(MoveAssignment);
8094
8095  AddOverriddenMethods(ClassDecl, MoveAssignment);
8096  return MoveAssignment;
8097}
8098
8099void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8100                                        CXXMethodDecl *MoveAssignOperator) {
8101  assert((MoveAssignOperator->isDefaulted() &&
8102          MoveAssignOperator->isOverloadedOperator() &&
8103          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8104          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8105          !MoveAssignOperator->isDeleted()) &&
8106         "DefineImplicitMoveAssignment called for wrong function");
8107
8108  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8109
8110  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8111    MoveAssignOperator->setInvalidDecl();
8112    return;
8113  }
8114
8115  MoveAssignOperator->setUsed();
8116
8117  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8118  DiagnosticErrorTrap Trap(Diags);
8119
8120  // C++0x [class.copy]p28:
8121  //   The implicitly-defined or move assignment operator for a non-union class
8122  //   X performs memberwise move assignment of its subobjects. The direct base
8123  //   classes of X are assigned first, in the order of their declaration in the
8124  //   base-specifier-list, and then the immediate non-static data members of X
8125  //   are assigned, in the order in which they were declared in the class
8126  //   definition.
8127
8128  // The statements that form the synthesized function body.
8129  ASTOwningVector<Stmt*> Statements(*this);
8130
8131  // The parameter for the "other" object, which we are move from.
8132  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8133  QualType OtherRefType = Other->getType()->
8134      getAs<RValueReferenceType>()->getPointeeType();
8135  assert(OtherRefType.getQualifiers() == 0 &&
8136         "Bad argument type of defaulted move assignment");
8137
8138  // Our location for everything implicitly-generated.
8139  SourceLocation Loc = MoveAssignOperator->getLocation();
8140
8141  // Construct a reference to the "other" object. We'll be using this
8142  // throughout the generated ASTs.
8143  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8144  assert(OtherRef && "Reference to parameter cannot fail!");
8145  // Cast to rvalue.
8146  OtherRef = CastForMoving(*this, OtherRef);
8147
8148  // Construct the "this" pointer. We'll be using this throughout the generated
8149  // ASTs.
8150  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8151  assert(This && "Reference to this cannot fail!");
8152
8153  // Assign base classes.
8154  bool Invalid = false;
8155  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8156       E = ClassDecl->bases_end(); Base != E; ++Base) {
8157    // Form the assignment:
8158    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8159    QualType BaseType = Base->getType().getUnqualifiedType();
8160    if (!BaseType->isRecordType()) {
8161      Invalid = true;
8162      continue;
8163    }
8164
8165    CXXCastPath BasePath;
8166    BasePath.push_back(Base);
8167
8168    // Construct the "from" expression, which is an implicit cast to the
8169    // appropriately-qualified base type.
8170    Expr *From = OtherRef;
8171    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8172                             VK_XValue, &BasePath).take();
8173
8174    // Dereference "this".
8175    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8176
8177    // Implicitly cast "this" to the appropriately-qualified base type.
8178    To = ImpCastExprToType(To.take(),
8179                           Context.getCVRQualifiedType(BaseType,
8180                                     MoveAssignOperator->getTypeQualifiers()),
8181                           CK_UncheckedDerivedToBase,
8182                           VK_LValue, &BasePath);
8183
8184    // Build the move.
8185    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8186                                            To.get(), From,
8187                                            /*CopyingBaseSubobject=*/true,
8188                                            /*Copying=*/false);
8189    if (Move.isInvalid()) {
8190      Diag(CurrentLocation, diag::note_member_synthesized_at)
8191        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8192      MoveAssignOperator->setInvalidDecl();
8193      return;
8194    }
8195
8196    // Success! Record the move.
8197    Statements.push_back(Move.takeAs<Expr>());
8198  }
8199
8200  // \brief Reference to the __builtin_memcpy function.
8201  Expr *BuiltinMemCpyRef = 0;
8202  // \brief Reference to the __builtin_objc_memmove_collectable function.
8203  Expr *CollectableMemCpyRef = 0;
8204
8205  // Assign non-static members.
8206  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8207                                  FieldEnd = ClassDecl->field_end();
8208       Field != FieldEnd; ++Field) {
8209    if (Field->isUnnamedBitfield())
8210      continue;
8211
8212    // Check for members of reference type; we can't move those.
8213    if (Field->getType()->isReferenceType()) {
8214      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8215        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8216      Diag(Field->getLocation(), diag::note_declared_at);
8217      Diag(CurrentLocation, diag::note_member_synthesized_at)
8218        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8219      Invalid = true;
8220      continue;
8221    }
8222
8223    // Check for members of const-qualified, non-class type.
8224    QualType BaseType = Context.getBaseElementType(Field->getType());
8225    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8226      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8227        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8228      Diag(Field->getLocation(), diag::note_declared_at);
8229      Diag(CurrentLocation, diag::note_member_synthesized_at)
8230        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8231      Invalid = true;
8232      continue;
8233    }
8234
8235    // Suppress assigning zero-width bitfields.
8236    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8237      continue;
8238
8239    QualType FieldType = Field->getType().getNonReferenceType();
8240    if (FieldType->isIncompleteArrayType()) {
8241      assert(ClassDecl->hasFlexibleArrayMember() &&
8242             "Incomplete array type is not valid");
8243      continue;
8244    }
8245
8246    // Build references to the field in the object we're copying from and to.
8247    CXXScopeSpec SS; // Intentionally empty
8248    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8249                              LookupMemberName);
8250    MemberLookup.addDecl(*Field);
8251    MemberLookup.resolveKind();
8252    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8253                                               Loc, /*IsArrow=*/false,
8254                                               SS, SourceLocation(), 0,
8255                                               MemberLookup, 0);
8256    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8257                                             Loc, /*IsArrow=*/true,
8258                                             SS, SourceLocation(), 0,
8259                                             MemberLookup, 0);
8260    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8261    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8262
8263    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8264        "Member reference with rvalue base must be rvalue except for reference "
8265        "members, which aren't allowed for move assignment.");
8266
8267    // If the field should be copied with __builtin_memcpy rather than via
8268    // explicit assignments, do so. This optimization only applies for arrays
8269    // of scalars and arrays of class type with trivial move-assignment
8270    // operators.
8271    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8272        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8273      // Compute the size of the memory buffer to be copied.
8274      QualType SizeType = Context.getSizeType();
8275      llvm::APInt Size(Context.getTypeSize(SizeType),
8276                       Context.getTypeSizeInChars(BaseType).getQuantity());
8277      for (const ConstantArrayType *Array
8278              = Context.getAsConstantArrayType(FieldType);
8279           Array;
8280           Array = Context.getAsConstantArrayType(Array->getElementType())) {
8281        llvm::APInt ArraySize
8282          = Array->getSize().zextOrTrunc(Size.getBitWidth());
8283        Size *= ArraySize;
8284      }
8285
8286      // Take the address of the field references for "from" and "to". We
8287      // directly construct UnaryOperators here because semantic analysis
8288      // does not permit us to take the address of an xvalue.
8289      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8290                             Context.getPointerType(From.get()->getType()),
8291                             VK_RValue, OK_Ordinary, Loc);
8292      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8293                           Context.getPointerType(To.get()->getType()),
8294                           VK_RValue, OK_Ordinary, Loc);
8295
8296      bool NeedsCollectableMemCpy =
8297          (BaseType->isRecordType() &&
8298           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8299
8300      if (NeedsCollectableMemCpy) {
8301        if (!CollectableMemCpyRef) {
8302          // Create a reference to the __builtin_objc_memmove_collectable function.
8303          LookupResult R(*this,
8304                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
8305                         Loc, LookupOrdinaryName);
8306          LookupName(R, TUScope, true);
8307
8308          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8309          if (!CollectableMemCpy) {
8310            // Something went horribly wrong earlier, and we will have
8311            // complained about it.
8312            Invalid = true;
8313            continue;
8314          }
8315
8316          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8317                                                  CollectableMemCpy->getType(),
8318                                                  VK_LValue, Loc, 0).take();
8319          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8320        }
8321      }
8322      // Create a reference to the __builtin_memcpy builtin function.
8323      else if (!BuiltinMemCpyRef) {
8324        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8325                       LookupOrdinaryName);
8326        LookupName(R, TUScope, true);
8327
8328        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8329        if (!BuiltinMemCpy) {
8330          // Something went horribly wrong earlier, and we will have complained
8331          // about it.
8332          Invalid = true;
8333          continue;
8334        }
8335
8336        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8337                                            BuiltinMemCpy->getType(),
8338                                            VK_LValue, Loc, 0).take();
8339        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8340      }
8341
8342      ASTOwningVector<Expr*> CallArgs(*this);
8343      CallArgs.push_back(To.takeAs<Expr>());
8344      CallArgs.push_back(From.takeAs<Expr>());
8345      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8346      ExprResult Call = ExprError();
8347      if (NeedsCollectableMemCpy)
8348        Call = ActOnCallExpr(/*Scope=*/0,
8349                             CollectableMemCpyRef,
8350                             Loc, move_arg(CallArgs),
8351                             Loc);
8352      else
8353        Call = ActOnCallExpr(/*Scope=*/0,
8354                             BuiltinMemCpyRef,
8355                             Loc, move_arg(CallArgs),
8356                             Loc);
8357
8358      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8359      Statements.push_back(Call.takeAs<Expr>());
8360      continue;
8361    }
8362
8363    // Build the move of this field.
8364    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8365                                            To.get(), From.get(),
8366                                            /*CopyingBaseSubobject=*/false,
8367                                            /*Copying=*/false);
8368    if (Move.isInvalid()) {
8369      Diag(CurrentLocation, diag::note_member_synthesized_at)
8370        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8371      MoveAssignOperator->setInvalidDecl();
8372      return;
8373    }
8374
8375    // Success! Record the copy.
8376    Statements.push_back(Move.takeAs<Stmt>());
8377  }
8378
8379  if (!Invalid) {
8380    // Add a "return *this;"
8381    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8382
8383    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8384    if (Return.isInvalid())
8385      Invalid = true;
8386    else {
8387      Statements.push_back(Return.takeAs<Stmt>());
8388
8389      if (Trap.hasErrorOccurred()) {
8390        Diag(CurrentLocation, diag::note_member_synthesized_at)
8391          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8392        Invalid = true;
8393      }
8394    }
8395  }
8396
8397  if (Invalid) {
8398    MoveAssignOperator->setInvalidDecl();
8399    return;
8400  }
8401
8402  StmtResult Body;
8403  {
8404    CompoundScopeRAII CompoundScope(*this);
8405    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8406                             /*isStmtExpr=*/false);
8407    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8408  }
8409  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8410
8411  if (ASTMutationListener *L = getASTMutationListener()) {
8412    L->CompletedImplicitDefinition(MoveAssignOperator);
8413  }
8414}
8415
8416std::pair<Sema::ImplicitExceptionSpecification, bool>
8417Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
8418  if (ClassDecl->isInvalidDecl())
8419    return std::make_pair(ImplicitExceptionSpecification(Context), false);
8420
8421  // C++ [class.copy]p5:
8422  //   The implicitly-declared copy constructor for a class X will
8423  //   have the form
8424  //
8425  //       X::X(const X&)
8426  //
8427  //   if
8428  // FIXME: It ought to be possible to store this on the record.
8429  bool HasConstCopyConstructor = true;
8430
8431  //     -- each direct or virtual base class B of X has a copy
8432  //        constructor whose first parameter is of type const B& or
8433  //        const volatile B&, and
8434  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8435                                       BaseEnd = ClassDecl->bases_end();
8436       HasConstCopyConstructor && Base != BaseEnd;
8437       ++Base) {
8438    // Virtual bases are handled below.
8439    if (Base->isVirtual())
8440      continue;
8441
8442    CXXRecordDecl *BaseClassDecl
8443      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8444    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8445                             &HasConstCopyConstructor);
8446  }
8447
8448  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8449                                       BaseEnd = ClassDecl->vbases_end();
8450       HasConstCopyConstructor && Base != BaseEnd;
8451       ++Base) {
8452    CXXRecordDecl *BaseClassDecl
8453      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8454    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8455                             &HasConstCopyConstructor);
8456  }
8457
8458  //     -- for all the nonstatic data members of X that are of a
8459  //        class type M (or array thereof), each such class type
8460  //        has a copy constructor whose first parameter is of type
8461  //        const M& or const volatile M&.
8462  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8463                                  FieldEnd = ClassDecl->field_end();
8464       HasConstCopyConstructor && Field != FieldEnd;
8465       ++Field) {
8466    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8467    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8468      LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8469                               &HasConstCopyConstructor);
8470    }
8471  }
8472  //   Otherwise, the implicitly declared copy constructor will have
8473  //   the form
8474  //
8475  //       X::X(X&)
8476
8477  // C++ [except.spec]p14:
8478  //   An implicitly declared special member function (Clause 12) shall have an
8479  //   exception-specification. [...]
8480  ImplicitExceptionSpecification ExceptSpec(Context);
8481  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8482  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8483                                       BaseEnd = ClassDecl->bases_end();
8484       Base != BaseEnd;
8485       ++Base) {
8486    // Virtual bases are handled below.
8487    if (Base->isVirtual())
8488      continue;
8489
8490    CXXRecordDecl *BaseClassDecl
8491      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8492    if (CXXConstructorDecl *CopyConstructor =
8493          LookupCopyingConstructor(BaseClassDecl, Quals))
8494      ExceptSpec.CalledDecl(CopyConstructor);
8495  }
8496  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8497                                       BaseEnd = ClassDecl->vbases_end();
8498       Base != BaseEnd;
8499       ++Base) {
8500    CXXRecordDecl *BaseClassDecl
8501      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8502    if (CXXConstructorDecl *CopyConstructor =
8503          LookupCopyingConstructor(BaseClassDecl, Quals))
8504      ExceptSpec.CalledDecl(CopyConstructor);
8505  }
8506  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8507                                  FieldEnd = ClassDecl->field_end();
8508       Field != FieldEnd;
8509       ++Field) {
8510    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8511    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8512      if (CXXConstructorDecl *CopyConstructor =
8513        LookupCopyingConstructor(FieldClassDecl, Quals))
8514      ExceptSpec.CalledDecl(CopyConstructor);
8515    }
8516  }
8517
8518  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8519}
8520
8521CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8522                                                    CXXRecordDecl *ClassDecl) {
8523  // C++ [class.copy]p4:
8524  //   If the class definition does not explicitly declare a copy
8525  //   constructor, one is declared implicitly.
8526
8527  ImplicitExceptionSpecification Spec(Context);
8528  bool Const;
8529  llvm::tie(Spec, Const) =
8530    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8531
8532  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8533  QualType ArgType = ClassType;
8534  if (Const)
8535    ArgType = ArgType.withConst();
8536  ArgType = Context.getLValueReferenceType(ArgType);
8537
8538  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8539
8540  DeclarationName Name
8541    = Context.DeclarationNames.getCXXConstructorName(
8542                                           Context.getCanonicalType(ClassType));
8543  SourceLocation ClassLoc = ClassDecl->getLocation();
8544  DeclarationNameInfo NameInfo(Name, ClassLoc);
8545
8546  //   An implicitly-declared copy constructor is an inline public
8547  //   member of its class.
8548  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8549      Context, ClassDecl, ClassLoc, NameInfo,
8550      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8551      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8552      /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8553        getLangOpts().CPlusPlus0x);
8554  CopyConstructor->setAccess(AS_public);
8555  CopyConstructor->setDefaulted();
8556  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8557
8558  // Note that we have declared this constructor.
8559  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8560
8561  // Add the parameter to the constructor.
8562  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8563                                               ClassLoc, ClassLoc,
8564                                               /*IdentifierInfo=*/0,
8565                                               ArgType, /*TInfo=*/0,
8566                                               SC_None,
8567                                               SC_None, 0);
8568  CopyConstructor->setParams(FromParam);
8569
8570  if (Scope *S = getScopeForContext(ClassDecl))
8571    PushOnScopeChains(CopyConstructor, S, false);
8572  ClassDecl->addDecl(CopyConstructor);
8573
8574  // C++11 [class.copy]p8:
8575  //   ... If the class definition does not explicitly declare a copy
8576  //   constructor, there is no user-declared move constructor, and there is no
8577  //   user-declared move assignment operator, a copy constructor is implicitly
8578  //   declared as defaulted.
8579  if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8580      (ClassDecl->hasUserDeclaredMoveAssignment() &&
8581          !getLangOpts().MicrosoftMode) ||
8582      ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8583    CopyConstructor->setDeletedAsWritten();
8584
8585  return CopyConstructor;
8586}
8587
8588void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8589                                   CXXConstructorDecl *CopyConstructor) {
8590  assert((CopyConstructor->isDefaulted() &&
8591          CopyConstructor->isCopyConstructor() &&
8592          !CopyConstructor->doesThisDeclarationHaveABody() &&
8593          !CopyConstructor->isDeleted()) &&
8594         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8595
8596  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8597  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8598
8599  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8600  DiagnosticErrorTrap Trap(Diags);
8601
8602  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8603      Trap.hasErrorOccurred()) {
8604    Diag(CurrentLocation, diag::note_member_synthesized_at)
8605      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8606    CopyConstructor->setInvalidDecl();
8607  }  else {
8608    Sema::CompoundScopeRAII CompoundScope(*this);
8609    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8610                                               CopyConstructor->getLocation(),
8611                                               MultiStmtArg(*this, 0, 0),
8612                                               /*isStmtExpr=*/false)
8613                                                              .takeAs<Stmt>());
8614    CopyConstructor->setImplicitlyDefined(true);
8615  }
8616
8617  CopyConstructor->setUsed();
8618  if (ASTMutationListener *L = getASTMutationListener()) {
8619    L->CompletedImplicitDefinition(CopyConstructor);
8620  }
8621}
8622
8623Sema::ImplicitExceptionSpecification
8624Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8625  // C++ [except.spec]p14:
8626  //   An implicitly declared special member function (Clause 12) shall have an
8627  //   exception-specification. [...]
8628  ImplicitExceptionSpecification ExceptSpec(Context);
8629  if (ClassDecl->isInvalidDecl())
8630    return ExceptSpec;
8631
8632  // Direct base-class constructors.
8633  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8634                                       BEnd = ClassDecl->bases_end();
8635       B != BEnd; ++B) {
8636    if (B->isVirtual()) // Handled below.
8637      continue;
8638
8639    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8640      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8641      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8642      // If this is a deleted function, add it anyway. This might be conformant
8643      // with the standard. This might not. I'm not sure. It might not matter.
8644      if (Constructor)
8645        ExceptSpec.CalledDecl(Constructor);
8646    }
8647  }
8648
8649  // Virtual base-class constructors.
8650  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8651                                       BEnd = ClassDecl->vbases_end();
8652       B != BEnd; ++B) {
8653    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8654      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8655      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8656      // If this is a deleted function, add it anyway. This might be conformant
8657      // with the standard. This might not. I'm not sure. It might not matter.
8658      if (Constructor)
8659        ExceptSpec.CalledDecl(Constructor);
8660    }
8661  }
8662
8663  // Field constructors.
8664  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8665                               FEnd = ClassDecl->field_end();
8666       F != FEnd; ++F) {
8667    if (const RecordType *RecordTy
8668              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8669      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8670      CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8671      // If this is a deleted function, add it anyway. This might be conformant
8672      // with the standard. This might not. I'm not sure. It might not matter.
8673      // In particular, the problem is that this function never gets called. It
8674      // might just be ill-formed because this function attempts to refer to
8675      // a deleted function here.
8676      if (Constructor)
8677        ExceptSpec.CalledDecl(Constructor);
8678    }
8679  }
8680
8681  return ExceptSpec;
8682}
8683
8684CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8685                                                    CXXRecordDecl *ClassDecl) {
8686  ImplicitExceptionSpecification Spec(
8687      ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8688
8689  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8690  QualType ArgType = Context.getRValueReferenceType(ClassType);
8691
8692  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8693
8694  DeclarationName Name
8695    = Context.DeclarationNames.getCXXConstructorName(
8696                                           Context.getCanonicalType(ClassType));
8697  SourceLocation ClassLoc = ClassDecl->getLocation();
8698  DeclarationNameInfo NameInfo(Name, ClassLoc);
8699
8700  // C++0x [class.copy]p11:
8701  //   An implicitly-declared copy/move constructor is an inline public
8702  //   member of its class.
8703  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8704      Context, ClassDecl, ClassLoc, NameInfo,
8705      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8706      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8707      /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8708        getLangOpts().CPlusPlus0x);
8709  MoveConstructor->setAccess(AS_public);
8710  MoveConstructor->setDefaulted();
8711  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8712
8713  // Add the parameter to the constructor.
8714  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8715                                               ClassLoc, ClassLoc,
8716                                               /*IdentifierInfo=*/0,
8717                                               ArgType, /*TInfo=*/0,
8718                                               SC_None,
8719                                               SC_None, 0);
8720  MoveConstructor->setParams(FromParam);
8721
8722  // C++0x [class.copy]p9:
8723  //   If the definition of a class X does not explicitly declare a move
8724  //   constructor, one will be implicitly declared as defaulted if and only if:
8725  //   [...]
8726  //   - the move constructor would not be implicitly defined as deleted.
8727  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8728    // Cache this result so that we don't try to generate this over and over
8729    // on every lookup, leaking memory and wasting time.
8730    ClassDecl->setFailedImplicitMoveConstructor();
8731    return 0;
8732  }
8733
8734  // Note that we have declared this constructor.
8735  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8736
8737  if (Scope *S = getScopeForContext(ClassDecl))
8738    PushOnScopeChains(MoveConstructor, S, false);
8739  ClassDecl->addDecl(MoveConstructor);
8740
8741  return MoveConstructor;
8742}
8743
8744void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8745                                   CXXConstructorDecl *MoveConstructor) {
8746  assert((MoveConstructor->isDefaulted() &&
8747          MoveConstructor->isMoveConstructor() &&
8748          !MoveConstructor->doesThisDeclarationHaveABody() &&
8749          !MoveConstructor->isDeleted()) &&
8750         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8751
8752  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8753  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8754
8755  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8756  DiagnosticErrorTrap Trap(Diags);
8757
8758  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8759      Trap.hasErrorOccurred()) {
8760    Diag(CurrentLocation, diag::note_member_synthesized_at)
8761      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8762    MoveConstructor->setInvalidDecl();
8763  }  else {
8764    Sema::CompoundScopeRAII CompoundScope(*this);
8765    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8766                                               MoveConstructor->getLocation(),
8767                                               MultiStmtArg(*this, 0, 0),
8768                                               /*isStmtExpr=*/false)
8769                                                              .takeAs<Stmt>());
8770    MoveConstructor->setImplicitlyDefined(true);
8771  }
8772
8773  MoveConstructor->setUsed();
8774
8775  if (ASTMutationListener *L = getASTMutationListener()) {
8776    L->CompletedImplicitDefinition(MoveConstructor);
8777  }
8778}
8779
8780bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8781  return FD->isDeleted() &&
8782         (FD->isDefaulted() || FD->isImplicit()) &&
8783         isa<CXXMethodDecl>(FD);
8784}
8785
8786/// \brief Mark the call operator of the given lambda closure type as "used".
8787static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8788  CXXMethodDecl *CallOperator
8789    = cast<CXXMethodDecl>(
8790        *Lambda->lookup(
8791          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
8792  CallOperator->setReferenced();
8793  CallOperator->setUsed();
8794}
8795
8796void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8797       SourceLocation CurrentLocation,
8798       CXXConversionDecl *Conv)
8799{
8800  CXXRecordDecl *Lambda = Conv->getParent();
8801
8802  // Make sure that the lambda call operator is marked used.
8803  markLambdaCallOperatorUsed(*this, Lambda);
8804
8805  Conv->setUsed();
8806
8807  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8808  DiagnosticErrorTrap Trap(Diags);
8809
8810  // Return the address of the __invoke function.
8811  DeclarationName InvokeName = &Context.Idents.get("__invoke");
8812  CXXMethodDecl *Invoke
8813    = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8814  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8815                                       VK_LValue, Conv->getLocation()).take();
8816  assert(FunctionRef && "Can't refer to __invoke function?");
8817  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8818  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8819                                           Conv->getLocation(),
8820                                           Conv->getLocation()));
8821
8822  // Fill in the __invoke function with a dummy implementation. IR generation
8823  // will fill in the actual details.
8824  Invoke->setUsed();
8825  Invoke->setReferenced();
8826  Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8827                                             Conv->getLocation()));
8828
8829  if (ASTMutationListener *L = getASTMutationListener()) {
8830    L->CompletedImplicitDefinition(Conv);
8831    L->CompletedImplicitDefinition(Invoke);
8832  }
8833}
8834
8835void Sema::DefineImplicitLambdaToBlockPointerConversion(
8836       SourceLocation CurrentLocation,
8837       CXXConversionDecl *Conv)
8838{
8839  Conv->setUsed();
8840
8841  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8842  DiagnosticErrorTrap Trap(Diags);
8843
8844  // Copy-initialize the lambda object as needed to capture it.
8845  Expr *This = ActOnCXXThis(CurrentLocation).take();
8846  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
8847
8848  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8849                                                        Conv->getLocation(),
8850                                                        Conv, DerefThis);
8851
8852  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8853  // behavior.  Note that only the general conversion function does this
8854  // (since it's unusable otherwise); in the case where we inline the
8855  // block literal, it has block literal lifetime semantics.
8856  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
8857    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8858                                          CK_CopyAndAutoreleaseBlockObject,
8859                                          BuildBlock.get(), 0, VK_RValue);
8860
8861  if (BuildBlock.isInvalid()) {
8862    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8863    Conv->setInvalidDecl();
8864    return;
8865  }
8866
8867  // Create the return statement that returns the block from the conversion
8868  // function.
8869  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
8870  if (Return.isInvalid()) {
8871    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8872    Conv->setInvalidDecl();
8873    return;
8874  }
8875
8876  // Set the body of the conversion function.
8877  Stmt *ReturnS = Return.take();
8878  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8879                                           Conv->getLocation(),
8880                                           Conv->getLocation()));
8881
8882  // We're done; notify the mutation listener, if any.
8883  if (ASTMutationListener *L = getASTMutationListener()) {
8884    L->CompletedImplicitDefinition(Conv);
8885  }
8886}
8887
8888/// \brief Determine whether the given list arguments contains exactly one
8889/// "real" (non-default) argument.
8890static bool hasOneRealArgument(MultiExprArg Args) {
8891  switch (Args.size()) {
8892  case 0:
8893    return false;
8894
8895  default:
8896    if (!Args.get()[1]->isDefaultArgument())
8897      return false;
8898
8899    // fall through
8900  case 1:
8901    return !Args.get()[0]->isDefaultArgument();
8902  }
8903
8904  return false;
8905}
8906
8907ExprResult
8908Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8909                            CXXConstructorDecl *Constructor,
8910                            MultiExprArg ExprArgs,
8911                            bool HadMultipleCandidates,
8912                            bool RequiresZeroInit,
8913                            unsigned ConstructKind,
8914                            SourceRange ParenRange) {
8915  bool Elidable = false;
8916
8917  // C++0x [class.copy]p34:
8918  //   When certain criteria are met, an implementation is allowed to
8919  //   omit the copy/move construction of a class object, even if the
8920  //   copy/move constructor and/or destructor for the object have
8921  //   side effects. [...]
8922  //     - when a temporary class object that has not been bound to a
8923  //       reference (12.2) would be copied/moved to a class object
8924  //       with the same cv-unqualified type, the copy/move operation
8925  //       can be omitted by constructing the temporary object
8926  //       directly into the target of the omitted copy/move
8927  if (ConstructKind == CXXConstructExpr::CK_Complete &&
8928      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
8929    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
8930    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
8931  }
8932
8933  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
8934                               Elidable, move(ExprArgs), HadMultipleCandidates,
8935                               RequiresZeroInit, ConstructKind, ParenRange);
8936}
8937
8938/// BuildCXXConstructExpr - Creates a complete call to a constructor,
8939/// including handling of its default argument expressions.
8940ExprResult
8941Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8942                            CXXConstructorDecl *Constructor, bool Elidable,
8943                            MultiExprArg ExprArgs,
8944                            bool HadMultipleCandidates,
8945                            bool RequiresZeroInit,
8946                            unsigned ConstructKind,
8947                            SourceRange ParenRange) {
8948  unsigned NumExprs = ExprArgs.size();
8949  Expr **Exprs = (Expr **)ExprArgs.release();
8950
8951  for (specific_attr_iterator<NonNullAttr>
8952           i = Constructor->specific_attr_begin<NonNullAttr>(),
8953           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8954    const NonNullAttr *NonNull = *i;
8955    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8956  }
8957
8958  MarkFunctionReferenced(ConstructLoc, Constructor);
8959  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
8960                                        Constructor, Elidable, Exprs, NumExprs,
8961                                        HadMultipleCandidates, /*FIXME*/false,
8962                                        RequiresZeroInit,
8963              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8964                                        ParenRange));
8965}
8966
8967bool Sema::InitializeVarWithConstructor(VarDecl *VD,
8968                                        CXXConstructorDecl *Constructor,
8969                                        MultiExprArg Exprs,
8970                                        bool HadMultipleCandidates) {
8971  // FIXME: Provide the correct paren SourceRange when available.
8972  ExprResult TempResult =
8973    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
8974                          move(Exprs), HadMultipleCandidates, false,
8975                          CXXConstructExpr::CK_Complete, SourceRange());
8976  if (TempResult.isInvalid())
8977    return true;
8978
8979  Expr *Temp = TempResult.takeAs<Expr>();
8980  CheckImplicitConversions(Temp, VD->getLocation());
8981  MarkFunctionReferenced(VD->getLocation(), Constructor);
8982  Temp = MaybeCreateExprWithCleanups(Temp);
8983  VD->setInit(Temp);
8984
8985  return false;
8986}
8987
8988void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
8989  if (VD->isInvalidDecl()) return;
8990
8991  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
8992  if (ClassDecl->isInvalidDecl()) return;
8993  if (ClassDecl->hasIrrelevantDestructor()) return;
8994  if (ClassDecl->isDependentContext()) return;
8995
8996  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8997  MarkFunctionReferenced(VD->getLocation(), Destructor);
8998  CheckDestructorAccess(VD->getLocation(), Destructor,
8999                        PDiag(diag::err_access_dtor_var)
9000                        << VD->getDeclName()
9001                        << VD->getType());
9002  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9003
9004  if (!VD->hasGlobalStorage()) return;
9005
9006  // Emit warning for non-trivial dtor in global scope (a real global,
9007  // class-static, function-static).
9008  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9009
9010  // TODO: this should be re-enabled for static locals by !CXAAtExit
9011  if (!VD->isStaticLocal())
9012    Diag(VD->getLocation(), diag::warn_global_destructor);
9013}
9014
9015/// \brief Given a constructor and the set of arguments provided for the
9016/// constructor, convert the arguments and add any required default arguments
9017/// to form a proper call to this constructor.
9018///
9019/// \returns true if an error occurred, false otherwise.
9020bool
9021Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9022                              MultiExprArg ArgsPtr,
9023                              SourceLocation Loc,
9024                              ASTOwningVector<Expr*> &ConvertedArgs,
9025                              bool AllowExplicit) {
9026  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9027  unsigned NumArgs = ArgsPtr.size();
9028  Expr **Args = (Expr **)ArgsPtr.get();
9029
9030  const FunctionProtoType *Proto
9031    = Constructor->getType()->getAs<FunctionProtoType>();
9032  assert(Proto && "Constructor without a prototype?");
9033  unsigned NumArgsInProto = Proto->getNumArgs();
9034
9035  // If too few arguments are available, we'll fill in the rest with defaults.
9036  if (NumArgs < NumArgsInProto)
9037    ConvertedArgs.reserve(NumArgsInProto);
9038  else
9039    ConvertedArgs.reserve(NumArgs);
9040
9041  VariadicCallType CallType =
9042    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9043  SmallVector<Expr *, 8> AllArgs;
9044  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9045                                        Proto, 0, Args, NumArgs, AllArgs,
9046                                        CallType, AllowExplicit);
9047  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9048
9049  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9050
9051  // FIXME: Missing call to CheckFunctionCall or equivalent
9052
9053  return Invalid;
9054}
9055
9056static inline bool
9057CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9058                                       const FunctionDecl *FnDecl) {
9059  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9060  if (isa<NamespaceDecl>(DC)) {
9061    return SemaRef.Diag(FnDecl->getLocation(),
9062                        diag::err_operator_new_delete_declared_in_namespace)
9063      << FnDecl->getDeclName();
9064  }
9065
9066  if (isa<TranslationUnitDecl>(DC) &&
9067      FnDecl->getStorageClass() == SC_Static) {
9068    return SemaRef.Diag(FnDecl->getLocation(),
9069                        diag::err_operator_new_delete_declared_static)
9070      << FnDecl->getDeclName();
9071  }
9072
9073  return false;
9074}
9075
9076static inline bool
9077CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9078                            CanQualType ExpectedResultType,
9079                            CanQualType ExpectedFirstParamType,
9080                            unsigned DependentParamTypeDiag,
9081                            unsigned InvalidParamTypeDiag) {
9082  QualType ResultType =
9083    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9084
9085  // Check that the result type is not dependent.
9086  if (ResultType->isDependentType())
9087    return SemaRef.Diag(FnDecl->getLocation(),
9088                        diag::err_operator_new_delete_dependent_result_type)
9089    << FnDecl->getDeclName() << ExpectedResultType;
9090
9091  // Check that the result type is what we expect.
9092  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9093    return SemaRef.Diag(FnDecl->getLocation(),
9094                        diag::err_operator_new_delete_invalid_result_type)
9095    << FnDecl->getDeclName() << ExpectedResultType;
9096
9097  // A function template must have at least 2 parameters.
9098  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9099    return SemaRef.Diag(FnDecl->getLocation(),
9100                      diag::err_operator_new_delete_template_too_few_parameters)
9101        << FnDecl->getDeclName();
9102
9103  // The function decl must have at least 1 parameter.
9104  if (FnDecl->getNumParams() == 0)
9105    return SemaRef.Diag(FnDecl->getLocation(),
9106                        diag::err_operator_new_delete_too_few_parameters)
9107      << FnDecl->getDeclName();
9108
9109  // Check the the first parameter type is not dependent.
9110  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9111  if (FirstParamType->isDependentType())
9112    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9113      << FnDecl->getDeclName() << ExpectedFirstParamType;
9114
9115  // Check that the first parameter type is what we expect.
9116  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9117      ExpectedFirstParamType)
9118    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9119    << FnDecl->getDeclName() << ExpectedFirstParamType;
9120
9121  return false;
9122}
9123
9124static bool
9125CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9126  // C++ [basic.stc.dynamic.allocation]p1:
9127  //   A program is ill-formed if an allocation function is declared in a
9128  //   namespace scope other than global scope or declared static in global
9129  //   scope.
9130  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9131    return true;
9132
9133  CanQualType SizeTy =
9134    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9135
9136  // C++ [basic.stc.dynamic.allocation]p1:
9137  //  The return type shall be void*. The first parameter shall have type
9138  //  std::size_t.
9139  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9140                                  SizeTy,
9141                                  diag::err_operator_new_dependent_param_type,
9142                                  diag::err_operator_new_param_type))
9143    return true;
9144
9145  // C++ [basic.stc.dynamic.allocation]p1:
9146  //  The first parameter shall not have an associated default argument.
9147  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9148    return SemaRef.Diag(FnDecl->getLocation(),
9149                        diag::err_operator_new_default_arg)
9150      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9151
9152  return false;
9153}
9154
9155static bool
9156CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9157  // C++ [basic.stc.dynamic.deallocation]p1:
9158  //   A program is ill-formed if deallocation functions are declared in a
9159  //   namespace scope other than global scope or declared static in global
9160  //   scope.
9161  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9162    return true;
9163
9164  // C++ [basic.stc.dynamic.deallocation]p2:
9165  //   Each deallocation function shall return void and its first parameter
9166  //   shall be void*.
9167  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9168                                  SemaRef.Context.VoidPtrTy,
9169                                 diag::err_operator_delete_dependent_param_type,
9170                                 diag::err_operator_delete_param_type))
9171    return true;
9172
9173  return false;
9174}
9175
9176/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9177/// of this overloaded operator is well-formed. If so, returns false;
9178/// otherwise, emits appropriate diagnostics and returns true.
9179bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9180  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9181         "Expected an overloaded operator declaration");
9182
9183  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9184
9185  // C++ [over.oper]p5:
9186  //   The allocation and deallocation functions, operator new,
9187  //   operator new[], operator delete and operator delete[], are
9188  //   described completely in 3.7.3. The attributes and restrictions
9189  //   found in the rest of this subclause do not apply to them unless
9190  //   explicitly stated in 3.7.3.
9191  if (Op == OO_Delete || Op == OO_Array_Delete)
9192    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9193
9194  if (Op == OO_New || Op == OO_Array_New)
9195    return CheckOperatorNewDeclaration(*this, FnDecl);
9196
9197  // C++ [over.oper]p6:
9198  //   An operator function shall either be a non-static member
9199  //   function or be a non-member function and have at least one
9200  //   parameter whose type is a class, a reference to a class, an
9201  //   enumeration, or a reference to an enumeration.
9202  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9203    if (MethodDecl->isStatic())
9204      return Diag(FnDecl->getLocation(),
9205                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9206  } else {
9207    bool ClassOrEnumParam = false;
9208    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9209                                   ParamEnd = FnDecl->param_end();
9210         Param != ParamEnd; ++Param) {
9211      QualType ParamType = (*Param)->getType().getNonReferenceType();
9212      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9213          ParamType->isEnumeralType()) {
9214        ClassOrEnumParam = true;
9215        break;
9216      }
9217    }
9218
9219    if (!ClassOrEnumParam)
9220      return Diag(FnDecl->getLocation(),
9221                  diag::err_operator_overload_needs_class_or_enum)
9222        << FnDecl->getDeclName();
9223  }
9224
9225  // C++ [over.oper]p8:
9226  //   An operator function cannot have default arguments (8.3.6),
9227  //   except where explicitly stated below.
9228  //
9229  // Only the function-call operator allows default arguments
9230  // (C++ [over.call]p1).
9231  if (Op != OO_Call) {
9232    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9233         Param != FnDecl->param_end(); ++Param) {
9234      if ((*Param)->hasDefaultArg())
9235        return Diag((*Param)->getLocation(),
9236                    diag::err_operator_overload_default_arg)
9237          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9238    }
9239  }
9240
9241  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9242    { false, false, false }
9243#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9244    , { Unary, Binary, MemberOnly }
9245#include "clang/Basic/OperatorKinds.def"
9246  };
9247
9248  bool CanBeUnaryOperator = OperatorUses[Op][0];
9249  bool CanBeBinaryOperator = OperatorUses[Op][1];
9250  bool MustBeMemberOperator = OperatorUses[Op][2];
9251
9252  // C++ [over.oper]p8:
9253  //   [...] Operator functions cannot have more or fewer parameters
9254  //   than the number required for the corresponding operator, as
9255  //   described in the rest of this subclause.
9256  unsigned NumParams = FnDecl->getNumParams()
9257                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9258  if (Op != OO_Call &&
9259      ((NumParams == 1 && !CanBeUnaryOperator) ||
9260       (NumParams == 2 && !CanBeBinaryOperator) ||
9261       (NumParams < 1) || (NumParams > 2))) {
9262    // We have the wrong number of parameters.
9263    unsigned ErrorKind;
9264    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9265      ErrorKind = 2;  // 2 -> unary or binary.
9266    } else if (CanBeUnaryOperator) {
9267      ErrorKind = 0;  // 0 -> unary
9268    } else {
9269      assert(CanBeBinaryOperator &&
9270             "All non-call overloaded operators are unary or binary!");
9271      ErrorKind = 1;  // 1 -> binary
9272    }
9273
9274    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9275      << FnDecl->getDeclName() << NumParams << ErrorKind;
9276  }
9277
9278  // Overloaded operators other than operator() cannot be variadic.
9279  if (Op != OO_Call &&
9280      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9281    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9282      << FnDecl->getDeclName();
9283  }
9284
9285  // Some operators must be non-static member functions.
9286  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9287    return Diag(FnDecl->getLocation(),
9288                diag::err_operator_overload_must_be_member)
9289      << FnDecl->getDeclName();
9290  }
9291
9292  // C++ [over.inc]p1:
9293  //   The user-defined function called operator++ implements the
9294  //   prefix and postfix ++ operator. If this function is a member
9295  //   function with no parameters, or a non-member function with one
9296  //   parameter of class or enumeration type, it defines the prefix
9297  //   increment operator ++ for objects of that type. If the function
9298  //   is a member function with one parameter (which shall be of type
9299  //   int) or a non-member function with two parameters (the second
9300  //   of which shall be of type int), it defines the postfix
9301  //   increment operator ++ for objects of that type.
9302  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9303    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9304    bool ParamIsInt = false;
9305    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9306      ParamIsInt = BT->getKind() == BuiltinType::Int;
9307
9308    if (!ParamIsInt)
9309      return Diag(LastParam->getLocation(),
9310                  diag::err_operator_overload_post_incdec_must_be_int)
9311        << LastParam->getType() << (Op == OO_MinusMinus);
9312  }
9313
9314  return false;
9315}
9316
9317/// CheckLiteralOperatorDeclaration - Check whether the declaration
9318/// of this literal operator function is well-formed. If so, returns
9319/// false; otherwise, emits appropriate diagnostics and returns true.
9320bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9321  if (isa<CXXMethodDecl>(FnDecl)) {
9322    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9323      << FnDecl->getDeclName();
9324    return true;
9325  }
9326
9327  if (FnDecl->isExternC()) {
9328    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9329    return true;
9330  }
9331
9332  bool Valid = false;
9333
9334  // This might be the definition of a literal operator template.
9335  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9336  // This might be a specialization of a literal operator template.
9337  if (!TpDecl)
9338    TpDecl = FnDecl->getPrimaryTemplate();
9339
9340  // template <char...> type operator "" name() is the only valid template
9341  // signature, and the only valid signature with no parameters.
9342  if (TpDecl) {
9343    if (FnDecl->param_size() == 0) {
9344      // Must have only one template parameter
9345      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9346      if (Params->size() == 1) {
9347        NonTypeTemplateParmDecl *PmDecl =
9348          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9349
9350        // The template parameter must be a char parameter pack.
9351        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9352            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9353          Valid = true;
9354      }
9355    }
9356  } else if (FnDecl->param_size()) {
9357    // Check the first parameter
9358    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9359
9360    QualType T = (*Param)->getType().getUnqualifiedType();
9361
9362    // unsigned long long int, long double, and any character type are allowed
9363    // as the only parameters.
9364    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9365        Context.hasSameType(T, Context.LongDoubleTy) ||
9366        Context.hasSameType(T, Context.CharTy) ||
9367        Context.hasSameType(T, Context.WCharTy) ||
9368        Context.hasSameType(T, Context.Char16Ty) ||
9369        Context.hasSameType(T, Context.Char32Ty)) {
9370      if (++Param == FnDecl->param_end())
9371        Valid = true;
9372      goto FinishedParams;
9373    }
9374
9375    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9376    const PointerType *PT = T->getAs<PointerType>();
9377    if (!PT)
9378      goto FinishedParams;
9379    T = PT->getPointeeType();
9380    if (!T.isConstQualified() || T.isVolatileQualified())
9381      goto FinishedParams;
9382    T = T.getUnqualifiedType();
9383
9384    // Move on to the second parameter;
9385    ++Param;
9386
9387    // If there is no second parameter, the first must be a const char *
9388    if (Param == FnDecl->param_end()) {
9389      if (Context.hasSameType(T, Context.CharTy))
9390        Valid = true;
9391      goto FinishedParams;
9392    }
9393
9394    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9395    // are allowed as the first parameter to a two-parameter function
9396    if (!(Context.hasSameType(T, Context.CharTy) ||
9397          Context.hasSameType(T, Context.WCharTy) ||
9398          Context.hasSameType(T, Context.Char16Ty) ||
9399          Context.hasSameType(T, Context.Char32Ty)))
9400      goto FinishedParams;
9401
9402    // The second and final parameter must be an std::size_t
9403    T = (*Param)->getType().getUnqualifiedType();
9404    if (Context.hasSameType(T, Context.getSizeType()) &&
9405        ++Param == FnDecl->param_end())
9406      Valid = true;
9407  }
9408
9409  // FIXME: This diagnostic is absolutely terrible.
9410FinishedParams:
9411  if (!Valid) {
9412    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9413      << FnDecl->getDeclName();
9414    return true;
9415  }
9416
9417  // A parameter-declaration-clause containing a default argument is not
9418  // equivalent to any of the permitted forms.
9419  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9420                                    ParamEnd = FnDecl->param_end();
9421       Param != ParamEnd; ++Param) {
9422    if ((*Param)->hasDefaultArg()) {
9423      Diag((*Param)->getDefaultArgRange().getBegin(),
9424           diag::err_literal_operator_default_argument)
9425        << (*Param)->getDefaultArgRange();
9426      break;
9427    }
9428  }
9429
9430  StringRef LiteralName
9431    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9432  if (LiteralName[0] != '_') {
9433    // C++11 [usrlit.suffix]p1:
9434    //   Literal suffix identifiers that do not start with an underscore
9435    //   are reserved for future standardization.
9436    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9437  }
9438
9439  return false;
9440}
9441
9442/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9443/// linkage specification, including the language and (if present)
9444/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9445/// the location of the language string literal, which is provided
9446/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9447/// the '{' brace. Otherwise, this linkage specification does not
9448/// have any braces.
9449Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9450                                           SourceLocation LangLoc,
9451                                           StringRef Lang,
9452                                           SourceLocation LBraceLoc) {
9453  LinkageSpecDecl::LanguageIDs Language;
9454  if (Lang == "\"C\"")
9455    Language = LinkageSpecDecl::lang_c;
9456  else if (Lang == "\"C++\"")
9457    Language = LinkageSpecDecl::lang_cxx;
9458  else {
9459    Diag(LangLoc, diag::err_bad_language);
9460    return 0;
9461  }
9462
9463  // FIXME: Add all the various semantics of linkage specifications
9464
9465  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9466                                               ExternLoc, LangLoc, Language);
9467  CurContext->addDecl(D);
9468  PushDeclContext(S, D);
9469  return D;
9470}
9471
9472/// ActOnFinishLinkageSpecification - Complete the definition of
9473/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9474/// valid, it's the position of the closing '}' brace in a linkage
9475/// specification that uses braces.
9476Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9477                                            Decl *LinkageSpec,
9478                                            SourceLocation RBraceLoc) {
9479  if (LinkageSpec) {
9480    if (RBraceLoc.isValid()) {
9481      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9482      LSDecl->setRBraceLoc(RBraceLoc);
9483    }
9484    PopDeclContext();
9485  }
9486  return LinkageSpec;
9487}
9488
9489/// \brief Perform semantic analysis for the variable declaration that
9490/// occurs within a C++ catch clause, returning the newly-created
9491/// variable.
9492VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9493                                         TypeSourceInfo *TInfo,
9494                                         SourceLocation StartLoc,
9495                                         SourceLocation Loc,
9496                                         IdentifierInfo *Name) {
9497  bool Invalid = false;
9498  QualType ExDeclType = TInfo->getType();
9499
9500  // Arrays and functions decay.
9501  if (ExDeclType->isArrayType())
9502    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9503  else if (ExDeclType->isFunctionType())
9504    ExDeclType = Context.getPointerType(ExDeclType);
9505
9506  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9507  // The exception-declaration shall not denote a pointer or reference to an
9508  // incomplete type, other than [cv] void*.
9509  // N2844 forbids rvalue references.
9510  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9511    Diag(Loc, diag::err_catch_rvalue_ref);
9512    Invalid = true;
9513  }
9514
9515  QualType BaseType = ExDeclType;
9516  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9517  unsigned DK = diag::err_catch_incomplete;
9518  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9519    BaseType = Ptr->getPointeeType();
9520    Mode = 1;
9521    DK = diag::err_catch_incomplete_ptr;
9522  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9523    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9524    BaseType = Ref->getPointeeType();
9525    Mode = 2;
9526    DK = diag::err_catch_incomplete_ref;
9527  }
9528  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9529      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9530    Invalid = true;
9531
9532  if (!Invalid && !ExDeclType->isDependentType() &&
9533      RequireNonAbstractType(Loc, ExDeclType,
9534                             diag::err_abstract_type_in_decl,
9535                             AbstractVariableType))
9536    Invalid = true;
9537
9538  // Only the non-fragile NeXT runtime currently supports C++ catches
9539  // of ObjC types, and no runtime supports catching ObjC types by value.
9540  if (!Invalid && getLangOpts().ObjC1) {
9541    QualType T = ExDeclType;
9542    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9543      T = RT->getPointeeType();
9544
9545    if (T->isObjCObjectType()) {
9546      Diag(Loc, diag::err_objc_object_catch);
9547      Invalid = true;
9548    } else if (T->isObjCObjectPointerType()) {
9549      if (!getLangOpts().ObjCNonFragileABI)
9550        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9551    }
9552  }
9553
9554  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9555                                    ExDeclType, TInfo, SC_None, SC_None);
9556  ExDecl->setExceptionVariable(true);
9557
9558  // In ARC, infer 'retaining' for variables of retainable type.
9559  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9560    Invalid = true;
9561
9562  if (!Invalid && !ExDeclType->isDependentType()) {
9563    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9564      // C++ [except.handle]p16:
9565      //   The object declared in an exception-declaration or, if the
9566      //   exception-declaration does not specify a name, a temporary (12.2) is
9567      //   copy-initialized (8.5) from the exception object. [...]
9568      //   The object is destroyed when the handler exits, after the destruction
9569      //   of any automatic objects initialized within the handler.
9570      //
9571      // We just pretend to initialize the object with itself, then make sure
9572      // it can be destroyed later.
9573      QualType initType = ExDeclType;
9574
9575      InitializedEntity entity =
9576        InitializedEntity::InitializeVariable(ExDecl);
9577      InitializationKind initKind =
9578        InitializationKind::CreateCopy(Loc, SourceLocation());
9579
9580      Expr *opaqueValue =
9581        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9582      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9583      ExprResult result = sequence.Perform(*this, entity, initKind,
9584                                           MultiExprArg(&opaqueValue, 1));
9585      if (result.isInvalid())
9586        Invalid = true;
9587      else {
9588        // If the constructor used was non-trivial, set this as the
9589        // "initializer".
9590        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9591        if (!construct->getConstructor()->isTrivial()) {
9592          Expr *init = MaybeCreateExprWithCleanups(construct);
9593          ExDecl->setInit(init);
9594        }
9595
9596        // And make sure it's destructable.
9597        FinalizeVarWithDestructor(ExDecl, recordType);
9598      }
9599    }
9600  }
9601
9602  if (Invalid)
9603    ExDecl->setInvalidDecl();
9604
9605  return ExDecl;
9606}
9607
9608/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9609/// handler.
9610Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9611  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9612  bool Invalid = D.isInvalidType();
9613
9614  // Check for unexpanded parameter packs.
9615  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9616                                               UPPC_ExceptionType)) {
9617    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9618                                             D.getIdentifierLoc());
9619    Invalid = true;
9620  }
9621
9622  IdentifierInfo *II = D.getIdentifier();
9623  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9624                                             LookupOrdinaryName,
9625                                             ForRedeclaration)) {
9626    // The scope should be freshly made just for us. There is just no way
9627    // it contains any previous declaration.
9628    assert(!S->isDeclScope(PrevDecl));
9629    if (PrevDecl->isTemplateParameter()) {
9630      // Maybe we will complain about the shadowed template parameter.
9631      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9632      PrevDecl = 0;
9633    }
9634  }
9635
9636  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9637    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9638      << D.getCXXScopeSpec().getRange();
9639    Invalid = true;
9640  }
9641
9642  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9643                                              D.getLocStart(),
9644                                              D.getIdentifierLoc(),
9645                                              D.getIdentifier());
9646  if (Invalid)
9647    ExDecl->setInvalidDecl();
9648
9649  // Add the exception declaration into this scope.
9650  if (II)
9651    PushOnScopeChains(ExDecl, S);
9652  else
9653    CurContext->addDecl(ExDecl);
9654
9655  ProcessDeclAttributes(S, ExDecl, D);
9656  return ExDecl;
9657}
9658
9659Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9660                                         Expr *AssertExpr,
9661                                         Expr *AssertMessageExpr_,
9662                                         SourceLocation RParenLoc) {
9663  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
9664
9665  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9666    // In a static_assert-declaration, the constant-expression shall be a
9667    // constant expression that can be contextually converted to bool.
9668    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9669    if (Converted.isInvalid())
9670      return 0;
9671
9672    llvm::APSInt Cond;
9673    if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9674          PDiag(diag::err_static_assert_expression_is_not_constant),
9675          /*AllowFold=*/false).isInvalid())
9676      return 0;
9677
9678    if (!Cond) {
9679      llvm::SmallString<256> MsgBuffer;
9680      llvm::raw_svector_ostream Msg(MsgBuffer);
9681      AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
9682      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9683        << Msg.str() << AssertExpr->getSourceRange();
9684    }
9685  }
9686
9687  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9688    return 0;
9689
9690  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9691                                        AssertExpr, AssertMessage, RParenLoc);
9692
9693  CurContext->addDecl(Decl);
9694  return Decl;
9695}
9696
9697/// \brief Perform semantic analysis of the given friend type declaration.
9698///
9699/// \returns A friend declaration that.
9700FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9701                                      SourceLocation FriendLoc,
9702                                      TypeSourceInfo *TSInfo) {
9703  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9704
9705  QualType T = TSInfo->getType();
9706  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9707
9708  // C++03 [class.friend]p2:
9709  //   An elaborated-type-specifier shall be used in a friend declaration
9710  //   for a class.*
9711  //
9712  //   * The class-key of the elaborated-type-specifier is required.
9713  if (!ActiveTemplateInstantiations.empty()) {
9714    // Do not complain about the form of friend template types during
9715    // template instantiation; we will already have complained when the
9716    // template was declared.
9717  } else if (!T->isElaboratedTypeSpecifier()) {
9718    // If we evaluated the type to a record type, suggest putting
9719    // a tag in front.
9720    if (const RecordType *RT = T->getAs<RecordType>()) {
9721      RecordDecl *RD = RT->getDecl();
9722
9723      std::string InsertionText = std::string(" ") + RD->getKindName();
9724
9725      Diag(TypeRange.getBegin(),
9726           getLangOpts().CPlusPlus0x ?
9727             diag::warn_cxx98_compat_unelaborated_friend_type :
9728             diag::ext_unelaborated_friend_type)
9729        << (unsigned) RD->getTagKind()
9730        << T
9731        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9732                                      InsertionText);
9733    } else {
9734      Diag(FriendLoc,
9735           getLangOpts().CPlusPlus0x ?
9736             diag::warn_cxx98_compat_nonclass_type_friend :
9737             diag::ext_nonclass_type_friend)
9738        << T
9739        << SourceRange(FriendLoc, TypeRange.getEnd());
9740    }
9741  } else if (T->getAs<EnumType>()) {
9742    Diag(FriendLoc,
9743         getLangOpts().CPlusPlus0x ?
9744           diag::warn_cxx98_compat_enum_friend :
9745           diag::ext_enum_friend)
9746      << T
9747      << SourceRange(FriendLoc, TypeRange.getEnd());
9748  }
9749
9750  // C++0x [class.friend]p3:
9751  //   If the type specifier in a friend declaration designates a (possibly
9752  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9753  //   the friend declaration is ignored.
9754
9755  // FIXME: C++0x has some syntactic restrictions on friend type declarations
9756  // in [class.friend]p3 that we do not implement.
9757
9758  return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
9759}
9760
9761/// Handle a friend tag declaration where the scope specifier was
9762/// templated.
9763Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9764                                    unsigned TagSpec, SourceLocation TagLoc,
9765                                    CXXScopeSpec &SS,
9766                                    IdentifierInfo *Name, SourceLocation NameLoc,
9767                                    AttributeList *Attr,
9768                                    MultiTemplateParamsArg TempParamLists) {
9769  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9770
9771  bool isExplicitSpecialization = false;
9772  bool Invalid = false;
9773
9774  if (TemplateParameterList *TemplateParams
9775        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9776                                                  TempParamLists.get(),
9777                                                  TempParamLists.size(),
9778                                                  /*friend*/ true,
9779                                                  isExplicitSpecialization,
9780                                                  Invalid)) {
9781    if (TemplateParams->size() > 0) {
9782      // This is a declaration of a class template.
9783      if (Invalid)
9784        return 0;
9785
9786      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9787                                SS, Name, NameLoc, Attr,
9788                                TemplateParams, AS_public,
9789                                /*ModulePrivateLoc=*/SourceLocation(),
9790                                TempParamLists.size() - 1,
9791                   (TemplateParameterList**) TempParamLists.release()).take();
9792    } else {
9793      // The "template<>" header is extraneous.
9794      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9795        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9796      isExplicitSpecialization = true;
9797    }
9798  }
9799
9800  if (Invalid) return 0;
9801
9802  bool isAllExplicitSpecializations = true;
9803  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9804    if (TempParamLists.get()[I]->size()) {
9805      isAllExplicitSpecializations = false;
9806      break;
9807    }
9808  }
9809
9810  // FIXME: don't ignore attributes.
9811
9812  // If it's explicit specializations all the way down, just forget
9813  // about the template header and build an appropriate non-templated
9814  // friend.  TODO: for source fidelity, remember the headers.
9815  if (isAllExplicitSpecializations) {
9816    if (SS.isEmpty()) {
9817      bool Owned = false;
9818      bool IsDependent = false;
9819      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9820                      Attr, AS_public,
9821                      /*ModulePrivateLoc=*/SourceLocation(),
9822                      MultiTemplateParamsArg(), Owned, IsDependent,
9823                      /*ScopedEnumKWLoc=*/SourceLocation(),
9824                      /*ScopedEnumUsesClassTag=*/false,
9825                      /*UnderlyingType=*/TypeResult());
9826    }
9827
9828    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9829    ElaboratedTypeKeyword Keyword
9830      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9831    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9832                                   *Name, NameLoc);
9833    if (T.isNull())
9834      return 0;
9835
9836    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9837    if (isa<DependentNameType>(T)) {
9838      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9839      TL.setElaboratedKeywordLoc(TagLoc);
9840      TL.setQualifierLoc(QualifierLoc);
9841      TL.setNameLoc(NameLoc);
9842    } else {
9843      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9844      TL.setElaboratedKeywordLoc(TagLoc);
9845      TL.setQualifierLoc(QualifierLoc);
9846      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9847    }
9848
9849    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9850                                            TSI, FriendLoc);
9851    Friend->setAccess(AS_public);
9852    CurContext->addDecl(Friend);
9853    return Friend;
9854  }
9855
9856  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9857
9858
9859
9860  // Handle the case of a templated-scope friend class.  e.g.
9861  //   template <class T> class A<T>::B;
9862  // FIXME: we don't support these right now.
9863  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9864  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9865  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9866  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9867  TL.setElaboratedKeywordLoc(TagLoc);
9868  TL.setQualifierLoc(SS.getWithLocInContext(Context));
9869  TL.setNameLoc(NameLoc);
9870
9871  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9872                                          TSI, FriendLoc);
9873  Friend->setAccess(AS_public);
9874  Friend->setUnsupportedFriend(true);
9875  CurContext->addDecl(Friend);
9876  return Friend;
9877}
9878
9879
9880/// Handle a friend type declaration.  This works in tandem with
9881/// ActOnTag.
9882///
9883/// Notes on friend class templates:
9884///
9885/// We generally treat friend class declarations as if they were
9886/// declaring a class.  So, for example, the elaborated type specifier
9887/// in a friend declaration is required to obey the restrictions of a
9888/// class-head (i.e. no typedefs in the scope chain), template
9889/// parameters are required to match up with simple template-ids, &c.
9890/// However, unlike when declaring a template specialization, it's
9891/// okay to refer to a template specialization without an empty
9892/// template parameter declaration, e.g.
9893///   friend class A<T>::B<unsigned>;
9894/// We permit this as a special case; if there are any template
9895/// parameters present at all, require proper matching, i.e.
9896///   template <> template <class T> friend class A<int>::B;
9897Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
9898                                MultiTemplateParamsArg TempParams) {
9899  SourceLocation Loc = DS.getLocStart();
9900
9901  assert(DS.isFriendSpecified());
9902  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9903
9904  // Try to convert the decl specifier to a type.  This works for
9905  // friend templates because ActOnTag never produces a ClassTemplateDecl
9906  // for a TUK_Friend.
9907  Declarator TheDeclarator(DS, Declarator::MemberContext);
9908  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9909  QualType T = TSI->getType();
9910  if (TheDeclarator.isInvalidType())
9911    return 0;
9912
9913  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9914    return 0;
9915
9916  // This is definitely an error in C++98.  It's probably meant to
9917  // be forbidden in C++0x, too, but the specification is just
9918  // poorly written.
9919  //
9920  // The problem is with declarations like the following:
9921  //   template <T> friend A<T>::foo;
9922  // where deciding whether a class C is a friend or not now hinges
9923  // on whether there exists an instantiation of A that causes
9924  // 'foo' to equal C.  There are restrictions on class-heads
9925  // (which we declare (by fiat) elaborated friend declarations to
9926  // be) that makes this tractable.
9927  //
9928  // FIXME: handle "template <> friend class A<T>;", which
9929  // is possibly well-formed?  Who even knows?
9930  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
9931    Diag(Loc, diag::err_tagless_friend_type_template)
9932      << DS.getSourceRange();
9933    return 0;
9934  }
9935
9936  // C++98 [class.friend]p1: A friend of a class is a function
9937  //   or class that is not a member of the class . . .
9938  // This is fixed in DR77, which just barely didn't make the C++03
9939  // deadline.  It's also a very silly restriction that seriously
9940  // affects inner classes and which nobody else seems to implement;
9941  // thus we never diagnose it, not even in -pedantic.
9942  //
9943  // But note that we could warn about it: it's always useless to
9944  // friend one of your own members (it's not, however, worthless to
9945  // friend a member of an arbitrary specialization of your template).
9946
9947  Decl *D;
9948  if (unsigned NumTempParamLists = TempParams.size())
9949    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
9950                                   NumTempParamLists,
9951                                   TempParams.release(),
9952                                   TSI,
9953                                   DS.getFriendSpecLoc());
9954  else
9955    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
9956
9957  if (!D)
9958    return 0;
9959
9960  D->setAccess(AS_public);
9961  CurContext->addDecl(D);
9962
9963  return D;
9964}
9965
9966Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
9967                                    MultiTemplateParamsArg TemplateParams) {
9968  const DeclSpec &DS = D.getDeclSpec();
9969
9970  assert(DS.isFriendSpecified());
9971  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9972
9973  SourceLocation Loc = D.getIdentifierLoc();
9974  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9975
9976  // C++ [class.friend]p1
9977  //   A friend of a class is a function or class....
9978  // Note that this sees through typedefs, which is intended.
9979  // It *doesn't* see through dependent types, which is correct
9980  // according to [temp.arg.type]p3:
9981  //   If a declaration acquires a function type through a
9982  //   type dependent on a template-parameter and this causes
9983  //   a declaration that does not use the syntactic form of a
9984  //   function declarator to have a function type, the program
9985  //   is ill-formed.
9986  if (!TInfo->getType()->isFunctionType()) {
9987    Diag(Loc, diag::err_unexpected_friend);
9988
9989    // It might be worthwhile to try to recover by creating an
9990    // appropriate declaration.
9991    return 0;
9992  }
9993
9994  // C++ [namespace.memdef]p3
9995  //  - If a friend declaration in a non-local class first declares a
9996  //    class or function, the friend class or function is a member
9997  //    of the innermost enclosing namespace.
9998  //  - The name of the friend is not found by simple name lookup
9999  //    until a matching declaration is provided in that namespace
10000  //    scope (either before or after the class declaration granting
10001  //    friendship).
10002  //  - If a friend function is called, its name may be found by the
10003  //    name lookup that considers functions from namespaces and
10004  //    classes associated with the types of the function arguments.
10005  //  - When looking for a prior declaration of a class or a function
10006  //    declared as a friend, scopes outside the innermost enclosing
10007  //    namespace scope are not considered.
10008
10009  CXXScopeSpec &SS = D.getCXXScopeSpec();
10010  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10011  DeclarationName Name = NameInfo.getName();
10012  assert(Name);
10013
10014  // Check for unexpanded parameter packs.
10015  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10016      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10017      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10018    return 0;
10019
10020  // The context we found the declaration in, or in which we should
10021  // create the declaration.
10022  DeclContext *DC;
10023  Scope *DCScope = S;
10024  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10025                        ForRedeclaration);
10026
10027  // FIXME: there are different rules in local classes
10028
10029  // There are four cases here.
10030  //   - There's no scope specifier, in which case we just go to the
10031  //     appropriate scope and look for a function or function template
10032  //     there as appropriate.
10033  // Recover from invalid scope qualifiers as if they just weren't there.
10034  if (SS.isInvalid() || !SS.isSet()) {
10035    // C++0x [namespace.memdef]p3:
10036    //   If the name in a friend declaration is neither qualified nor
10037    //   a template-id and the declaration is a function or an
10038    //   elaborated-type-specifier, the lookup to determine whether
10039    //   the entity has been previously declared shall not consider
10040    //   any scopes outside the innermost enclosing namespace.
10041    // C++0x [class.friend]p11:
10042    //   If a friend declaration appears in a local class and the name
10043    //   specified is an unqualified name, a prior declaration is
10044    //   looked up without considering scopes that are outside the
10045    //   innermost enclosing non-class scope. For a friend function
10046    //   declaration, if there is no prior declaration, the program is
10047    //   ill-formed.
10048    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10049    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10050
10051    // Find the appropriate context according to the above.
10052    DC = CurContext;
10053    while (true) {
10054      // Skip class contexts.  If someone can cite chapter and verse
10055      // for this behavior, that would be nice --- it's what GCC and
10056      // EDG do, and it seems like a reasonable intent, but the spec
10057      // really only says that checks for unqualified existing
10058      // declarations should stop at the nearest enclosing namespace,
10059      // not that they should only consider the nearest enclosing
10060      // namespace.
10061      while (DC->isRecord() || DC->isTransparentContext())
10062        DC = DC->getParent();
10063
10064      LookupQualifiedName(Previous, DC);
10065
10066      // TODO: decide what we think about using declarations.
10067      if (isLocal || !Previous.empty())
10068        break;
10069
10070      if (isTemplateId) {
10071        if (isa<TranslationUnitDecl>(DC)) break;
10072      } else {
10073        if (DC->isFileContext()) break;
10074      }
10075      DC = DC->getParent();
10076    }
10077
10078    // C++ [class.friend]p1: A friend of a class is a function or
10079    //   class that is not a member of the class . . .
10080    // C++11 changes this for both friend types and functions.
10081    // Most C++ 98 compilers do seem to give an error here, so
10082    // we do, too.
10083    if (!Previous.empty() && DC->Equals(CurContext))
10084      Diag(DS.getFriendSpecLoc(),
10085           getLangOpts().CPlusPlus0x ?
10086             diag::warn_cxx98_compat_friend_is_member :
10087             diag::err_friend_is_member);
10088
10089    DCScope = getScopeForDeclContext(S, DC);
10090
10091    // C++ [class.friend]p6:
10092    //   A function can be defined in a friend declaration of a class if and
10093    //   only if the class is a non-local class (9.8), the function name is
10094    //   unqualified, and the function has namespace scope.
10095    if (isLocal && D.isFunctionDefinition()) {
10096      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10097    }
10098
10099  //   - There's a non-dependent scope specifier, in which case we
10100  //     compute it and do a previous lookup there for a function
10101  //     or function template.
10102  } else if (!SS.getScopeRep()->isDependent()) {
10103    DC = computeDeclContext(SS);
10104    if (!DC) return 0;
10105
10106    if (RequireCompleteDeclContext(SS, DC)) return 0;
10107
10108    LookupQualifiedName(Previous, DC);
10109
10110    // Ignore things found implicitly in the wrong scope.
10111    // TODO: better diagnostics for this case.  Suggesting the right
10112    // qualified scope would be nice...
10113    LookupResult::Filter F = Previous.makeFilter();
10114    while (F.hasNext()) {
10115      NamedDecl *D = F.next();
10116      if (!DC->InEnclosingNamespaceSetOf(
10117              D->getDeclContext()->getRedeclContext()))
10118        F.erase();
10119    }
10120    F.done();
10121
10122    if (Previous.empty()) {
10123      D.setInvalidType();
10124      Diag(Loc, diag::err_qualified_friend_not_found)
10125          << Name << TInfo->getType();
10126      return 0;
10127    }
10128
10129    // C++ [class.friend]p1: A friend of a class is a function or
10130    //   class that is not a member of the class . . .
10131    if (DC->Equals(CurContext))
10132      Diag(DS.getFriendSpecLoc(),
10133           getLangOpts().CPlusPlus0x ?
10134             diag::warn_cxx98_compat_friend_is_member :
10135             diag::err_friend_is_member);
10136
10137    if (D.isFunctionDefinition()) {
10138      // C++ [class.friend]p6:
10139      //   A function can be defined in a friend declaration of a class if and
10140      //   only if the class is a non-local class (9.8), the function name is
10141      //   unqualified, and the function has namespace scope.
10142      SemaDiagnosticBuilder DB
10143        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10144
10145      DB << SS.getScopeRep();
10146      if (DC->isFileContext())
10147        DB << FixItHint::CreateRemoval(SS.getRange());
10148      SS.clear();
10149    }
10150
10151  //   - There's a scope specifier that does not match any template
10152  //     parameter lists, in which case we use some arbitrary context,
10153  //     create a method or method template, and wait for instantiation.
10154  //   - There's a scope specifier that does match some template
10155  //     parameter lists, which we don't handle right now.
10156  } else {
10157    if (D.isFunctionDefinition()) {
10158      // C++ [class.friend]p6:
10159      //   A function can be defined in a friend declaration of a class if and
10160      //   only if the class is a non-local class (9.8), the function name is
10161      //   unqualified, and the function has namespace scope.
10162      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10163        << SS.getScopeRep();
10164    }
10165
10166    DC = CurContext;
10167    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10168  }
10169
10170  if (!DC->isRecord()) {
10171    // This implies that it has to be an operator or function.
10172    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10173        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10174        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10175      Diag(Loc, diag::err_introducing_special_friend) <<
10176        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10177         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10178      return 0;
10179    }
10180  }
10181
10182  // FIXME: This is an egregious hack to cope with cases where the scope stack
10183  // does not contain the declaration context, i.e., in an out-of-line
10184  // definition of a class.
10185  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10186  if (!DCScope) {
10187    FakeDCScope.setEntity(DC);
10188    DCScope = &FakeDCScope;
10189  }
10190
10191  bool AddToScope = true;
10192  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10193                                          move(TemplateParams), AddToScope);
10194  if (!ND) return 0;
10195
10196  assert(ND->getDeclContext() == DC);
10197  assert(ND->getLexicalDeclContext() == CurContext);
10198
10199  // Add the function declaration to the appropriate lookup tables,
10200  // adjusting the redeclarations list as necessary.  We don't
10201  // want to do this yet if the friending class is dependent.
10202  //
10203  // Also update the scope-based lookup if the target context's
10204  // lookup context is in lexical scope.
10205  if (!CurContext->isDependentContext()) {
10206    DC = DC->getRedeclContext();
10207    DC->makeDeclVisibleInContext(ND);
10208    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10209      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10210  }
10211
10212  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10213                                       D.getIdentifierLoc(), ND,
10214                                       DS.getFriendSpecLoc());
10215  FrD->setAccess(AS_public);
10216  CurContext->addDecl(FrD);
10217
10218  if (ND->isInvalidDecl())
10219    FrD->setInvalidDecl();
10220  else {
10221    FunctionDecl *FD;
10222    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10223      FD = FTD->getTemplatedDecl();
10224    else
10225      FD = cast<FunctionDecl>(ND);
10226
10227    // Mark templated-scope function declarations as unsupported.
10228    if (FD->getNumTemplateParameterLists())
10229      FrD->setUnsupportedFriend(true);
10230  }
10231
10232  return ND;
10233}
10234
10235void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10236  AdjustDeclIfTemplate(Dcl);
10237
10238  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10239  if (!Fn) {
10240    Diag(DelLoc, diag::err_deleted_non_function);
10241    return;
10242  }
10243  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10244    Diag(DelLoc, diag::err_deleted_decl_not_first);
10245    Diag(Prev->getLocation(), diag::note_previous_declaration);
10246    // If the declaration wasn't the first, we delete the function anyway for
10247    // recovery.
10248  }
10249  Fn->setDeletedAsWritten();
10250
10251  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10252  if (!MD)
10253    return;
10254
10255  // A deleted special member function is trivial if the corresponding
10256  // implicitly-declared function would have been.
10257  switch (getSpecialMember(MD)) {
10258  case CXXInvalid:
10259    break;
10260  case CXXDefaultConstructor:
10261    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10262    break;
10263  case CXXCopyConstructor:
10264    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10265    break;
10266  case CXXMoveConstructor:
10267    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10268    break;
10269  case CXXCopyAssignment:
10270    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10271    break;
10272  case CXXMoveAssignment:
10273    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10274    break;
10275  case CXXDestructor:
10276    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10277    break;
10278  }
10279}
10280
10281void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10282  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10283
10284  if (MD) {
10285    if (MD->getParent()->isDependentType()) {
10286      MD->setDefaulted();
10287      MD->setExplicitlyDefaulted();
10288      return;
10289    }
10290
10291    CXXSpecialMember Member = getSpecialMember(MD);
10292    if (Member == CXXInvalid) {
10293      Diag(DefaultLoc, diag::err_default_special_members);
10294      return;
10295    }
10296
10297    MD->setDefaulted();
10298    MD->setExplicitlyDefaulted();
10299
10300    // If this definition appears within the record, do the checking when
10301    // the record is complete.
10302    const FunctionDecl *Primary = MD;
10303    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10304      // Find the uninstantiated declaration that actually had the '= default'
10305      // on it.
10306      MD->getTemplateInstantiationPattern()->isDefined(Primary);
10307
10308    if (Primary == Primary->getCanonicalDecl())
10309      return;
10310
10311    switch (Member) {
10312    case CXXDefaultConstructor: {
10313      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10314      CheckExplicitlyDefaultedDefaultConstructor(CD);
10315      if (!CD->isInvalidDecl())
10316        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10317      break;
10318    }
10319
10320    case CXXCopyConstructor: {
10321      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10322      CheckExplicitlyDefaultedCopyConstructor(CD);
10323      if (!CD->isInvalidDecl())
10324        DefineImplicitCopyConstructor(DefaultLoc, CD);
10325      break;
10326    }
10327
10328    case CXXCopyAssignment: {
10329      CheckExplicitlyDefaultedCopyAssignment(MD);
10330      if (!MD->isInvalidDecl())
10331        DefineImplicitCopyAssignment(DefaultLoc, MD);
10332      break;
10333    }
10334
10335    case CXXDestructor: {
10336      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10337      CheckExplicitlyDefaultedDestructor(DD);
10338      if (!DD->isInvalidDecl())
10339        DefineImplicitDestructor(DefaultLoc, DD);
10340      break;
10341    }
10342
10343    case CXXMoveConstructor: {
10344      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10345      CheckExplicitlyDefaultedMoveConstructor(CD);
10346      if (!CD->isInvalidDecl())
10347        DefineImplicitMoveConstructor(DefaultLoc, CD);
10348      break;
10349    }
10350
10351    case CXXMoveAssignment: {
10352      CheckExplicitlyDefaultedMoveAssignment(MD);
10353      if (!MD->isInvalidDecl())
10354        DefineImplicitMoveAssignment(DefaultLoc, MD);
10355      break;
10356    }
10357
10358    case CXXInvalid:
10359      llvm_unreachable("Invalid special member.");
10360    }
10361  } else {
10362    Diag(DefaultLoc, diag::err_default_special_members);
10363  }
10364}
10365
10366static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10367  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10368    Stmt *SubStmt = *CI;
10369    if (!SubStmt)
10370      continue;
10371    if (isa<ReturnStmt>(SubStmt))
10372      Self.Diag(SubStmt->getLocStart(),
10373           diag::err_return_in_constructor_handler);
10374    if (!isa<Expr>(SubStmt))
10375      SearchForReturnInStmt(Self, SubStmt);
10376  }
10377}
10378
10379void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10380  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10381    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10382    SearchForReturnInStmt(*this, Handler);
10383  }
10384}
10385
10386bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10387                                             const CXXMethodDecl *Old) {
10388  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10389  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10390
10391  if (Context.hasSameType(NewTy, OldTy) ||
10392      NewTy->isDependentType() || OldTy->isDependentType())
10393    return false;
10394
10395  // Check if the return types are covariant
10396  QualType NewClassTy, OldClassTy;
10397
10398  /// Both types must be pointers or references to classes.
10399  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10400    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10401      NewClassTy = NewPT->getPointeeType();
10402      OldClassTy = OldPT->getPointeeType();
10403    }
10404  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10405    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10406      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10407        NewClassTy = NewRT->getPointeeType();
10408        OldClassTy = OldRT->getPointeeType();
10409      }
10410    }
10411  }
10412
10413  // The return types aren't either both pointers or references to a class type.
10414  if (NewClassTy.isNull()) {
10415    Diag(New->getLocation(),
10416         diag::err_different_return_type_for_overriding_virtual_function)
10417      << New->getDeclName() << NewTy << OldTy;
10418    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10419
10420    return true;
10421  }
10422
10423  // C++ [class.virtual]p6:
10424  //   If the return type of D::f differs from the return type of B::f, the
10425  //   class type in the return type of D::f shall be complete at the point of
10426  //   declaration of D::f or shall be the class type D.
10427  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10428    if (!RT->isBeingDefined() &&
10429        RequireCompleteType(New->getLocation(), NewClassTy,
10430                            PDiag(diag::err_covariant_return_incomplete)
10431                              << New->getDeclName()))
10432    return true;
10433  }
10434
10435  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10436    // Check if the new class derives from the old class.
10437    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10438      Diag(New->getLocation(),
10439           diag::err_covariant_return_not_derived)
10440      << New->getDeclName() << NewTy << OldTy;
10441      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10442      return true;
10443    }
10444
10445    // Check if we the conversion from derived to base is valid.
10446    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10447                    diag::err_covariant_return_inaccessible_base,
10448                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10449                    // FIXME: Should this point to the return type?
10450                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10451      // FIXME: this note won't trigger for delayed access control
10452      // diagnostics, and it's impossible to get an undelayed error
10453      // here from access control during the original parse because
10454      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10455      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10456      return true;
10457    }
10458  }
10459
10460  // The qualifiers of the return types must be the same.
10461  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10462    Diag(New->getLocation(),
10463         diag::err_covariant_return_type_different_qualifications)
10464    << New->getDeclName() << NewTy << OldTy;
10465    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10466    return true;
10467  };
10468
10469
10470  // The new class type must have the same or less qualifiers as the old type.
10471  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10472    Diag(New->getLocation(),
10473         diag::err_covariant_return_type_class_type_more_qualified)
10474    << New->getDeclName() << NewTy << OldTy;
10475    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10476    return true;
10477  };
10478
10479  return false;
10480}
10481
10482/// \brief Mark the given method pure.
10483///
10484/// \param Method the method to be marked pure.
10485///
10486/// \param InitRange the source range that covers the "0" initializer.
10487bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10488  SourceLocation EndLoc = InitRange.getEnd();
10489  if (EndLoc.isValid())
10490    Method->setRangeEnd(EndLoc);
10491
10492  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10493    Method->setPure();
10494    return false;
10495  }
10496
10497  if (!Method->isInvalidDecl())
10498    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10499      << Method->getDeclName() << InitRange;
10500  return true;
10501}
10502
10503/// \brief Determine whether the given declaration is a static data member.
10504static bool isStaticDataMember(Decl *D) {
10505  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10506  if (!Var)
10507    return false;
10508
10509  return Var->isStaticDataMember();
10510}
10511/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10512/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10513/// is a fresh scope pushed for just this purpose.
10514///
10515/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10516/// static data member of class X, names should be looked up in the scope of
10517/// class X.
10518void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10519  // If there is no declaration, there was an error parsing it.
10520  if (D == 0 || D->isInvalidDecl()) return;
10521
10522  // We should only get called for declarations with scope specifiers, like:
10523  //   int foo::bar;
10524  assert(D->isOutOfLine());
10525  EnterDeclaratorContext(S, D->getDeclContext());
10526
10527  // If we are parsing the initializer for a static data member, push a
10528  // new expression evaluation context that is associated with this static
10529  // data member.
10530  if (isStaticDataMember(D))
10531    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10532}
10533
10534/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10535/// initializer for the out-of-line declaration 'D'.
10536void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10537  // If there is no declaration, there was an error parsing it.
10538  if (D == 0 || D->isInvalidDecl()) return;
10539
10540  if (isStaticDataMember(D))
10541    PopExpressionEvaluationContext();
10542
10543  assert(D->isOutOfLine());
10544  ExitDeclaratorContext(S);
10545}
10546
10547/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10548/// C++ if/switch/while/for statement.
10549/// e.g: "if (int x = f()) {...}"
10550DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10551  // C++ 6.4p2:
10552  // The declarator shall not specify a function or an array.
10553  // The type-specifier-seq shall not contain typedef and shall not declare a
10554  // new class or enumeration.
10555  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10556         "Parser allowed 'typedef' as storage class of condition decl.");
10557
10558  Decl *Dcl = ActOnDeclarator(S, D);
10559  if (!Dcl)
10560    return true;
10561
10562  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10563    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10564      << D.getSourceRange();
10565    return true;
10566  }
10567
10568  return Dcl;
10569}
10570
10571void Sema::LoadExternalVTableUses() {
10572  if (!ExternalSource)
10573    return;
10574
10575  SmallVector<ExternalVTableUse, 4> VTables;
10576  ExternalSource->ReadUsedVTables(VTables);
10577  SmallVector<VTableUse, 4> NewUses;
10578  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10579    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10580      = VTablesUsed.find(VTables[I].Record);
10581    // Even if a definition wasn't required before, it may be required now.
10582    if (Pos != VTablesUsed.end()) {
10583      if (!Pos->second && VTables[I].DefinitionRequired)
10584        Pos->second = true;
10585      continue;
10586    }
10587
10588    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10589    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10590  }
10591
10592  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10593}
10594
10595void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10596                          bool DefinitionRequired) {
10597  // Ignore any vtable uses in unevaluated operands or for classes that do
10598  // not have a vtable.
10599  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10600      CurContext->isDependentContext() ||
10601      ExprEvalContexts.back().Context == Unevaluated)
10602    return;
10603
10604  // Try to insert this class into the map.
10605  LoadExternalVTableUses();
10606  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10607  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10608    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10609  if (!Pos.second) {
10610    // If we already had an entry, check to see if we are promoting this vtable
10611    // to required a definition. If so, we need to reappend to the VTableUses
10612    // list, since we may have already processed the first entry.
10613    if (DefinitionRequired && !Pos.first->second) {
10614      Pos.first->second = true;
10615    } else {
10616      // Otherwise, we can early exit.
10617      return;
10618    }
10619  }
10620
10621  // Local classes need to have their virtual members marked
10622  // immediately. For all other classes, we mark their virtual members
10623  // at the end of the translation unit.
10624  if (Class->isLocalClass())
10625    MarkVirtualMembersReferenced(Loc, Class);
10626  else
10627    VTableUses.push_back(std::make_pair(Class, Loc));
10628}
10629
10630bool Sema::DefineUsedVTables() {
10631  LoadExternalVTableUses();
10632  if (VTableUses.empty())
10633    return false;
10634
10635  // Note: The VTableUses vector could grow as a result of marking
10636  // the members of a class as "used", so we check the size each
10637  // time through the loop and prefer indices (with are stable) to
10638  // iterators (which are not).
10639  bool DefinedAnything = false;
10640  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10641    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10642    if (!Class)
10643      continue;
10644
10645    SourceLocation Loc = VTableUses[I].second;
10646
10647    // If this class has a key function, but that key function is
10648    // defined in another translation unit, we don't need to emit the
10649    // vtable even though we're using it.
10650    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10651    if (KeyFunction && !KeyFunction->hasBody()) {
10652      switch (KeyFunction->getTemplateSpecializationKind()) {
10653      case TSK_Undeclared:
10654      case TSK_ExplicitSpecialization:
10655      case TSK_ExplicitInstantiationDeclaration:
10656        // The key function is in another translation unit.
10657        continue;
10658
10659      case TSK_ExplicitInstantiationDefinition:
10660      case TSK_ImplicitInstantiation:
10661        // We will be instantiating the key function.
10662        break;
10663      }
10664    } else if (!KeyFunction) {
10665      // If we have a class with no key function that is the subject
10666      // of an explicit instantiation declaration, suppress the
10667      // vtable; it will live with the explicit instantiation
10668      // definition.
10669      bool IsExplicitInstantiationDeclaration
10670        = Class->getTemplateSpecializationKind()
10671                                      == TSK_ExplicitInstantiationDeclaration;
10672      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10673                                 REnd = Class->redecls_end();
10674           R != REnd; ++R) {
10675        TemplateSpecializationKind TSK
10676          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10677        if (TSK == TSK_ExplicitInstantiationDeclaration)
10678          IsExplicitInstantiationDeclaration = true;
10679        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10680          IsExplicitInstantiationDeclaration = false;
10681          break;
10682        }
10683      }
10684
10685      if (IsExplicitInstantiationDeclaration)
10686        continue;
10687    }
10688
10689    // Mark all of the virtual members of this class as referenced, so
10690    // that we can build a vtable. Then, tell the AST consumer that a
10691    // vtable for this class is required.
10692    DefinedAnything = true;
10693    MarkVirtualMembersReferenced(Loc, Class);
10694    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10695    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10696
10697    // Optionally warn if we're emitting a weak vtable.
10698    if (Class->getLinkage() == ExternalLinkage &&
10699        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10700      const FunctionDecl *KeyFunctionDef = 0;
10701      if (!KeyFunction ||
10702          (KeyFunction->hasBody(KeyFunctionDef) &&
10703           KeyFunctionDef->isInlined()))
10704        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10705             TSK_ExplicitInstantiationDefinition
10706             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10707          << Class;
10708    }
10709  }
10710  VTableUses.clear();
10711
10712  return DefinedAnything;
10713}
10714
10715void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10716                                        const CXXRecordDecl *RD) {
10717  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10718       e = RD->method_end(); i != e; ++i) {
10719    CXXMethodDecl *MD = *i;
10720
10721    // C++ [basic.def.odr]p2:
10722    //   [...] A virtual member function is used if it is not pure. [...]
10723    if (MD->isVirtual() && !MD->isPure())
10724      MarkFunctionReferenced(Loc, MD);
10725  }
10726
10727  // Only classes that have virtual bases need a VTT.
10728  if (RD->getNumVBases() == 0)
10729    return;
10730
10731  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10732           e = RD->bases_end(); i != e; ++i) {
10733    const CXXRecordDecl *Base =
10734        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10735    if (Base->getNumVBases() == 0)
10736      continue;
10737    MarkVirtualMembersReferenced(Loc, Base);
10738  }
10739}
10740
10741/// SetIvarInitializers - This routine builds initialization ASTs for the
10742/// Objective-C implementation whose ivars need be initialized.
10743void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10744  if (!getLangOpts().CPlusPlus)
10745    return;
10746  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10747    SmallVector<ObjCIvarDecl*, 8> ivars;
10748    CollectIvarsToConstructOrDestruct(OID, ivars);
10749    if (ivars.empty())
10750      return;
10751    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10752    for (unsigned i = 0; i < ivars.size(); i++) {
10753      FieldDecl *Field = ivars[i];
10754      if (Field->isInvalidDecl())
10755        continue;
10756
10757      CXXCtorInitializer *Member;
10758      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10759      InitializationKind InitKind =
10760        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10761
10762      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10763      ExprResult MemberInit =
10764        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10765      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10766      // Note, MemberInit could actually come back empty if no initialization
10767      // is required (e.g., because it would call a trivial default constructor)
10768      if (!MemberInit.get() || MemberInit.isInvalid())
10769        continue;
10770
10771      Member =
10772        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10773                                         SourceLocation(),
10774                                         MemberInit.takeAs<Expr>(),
10775                                         SourceLocation());
10776      AllToInit.push_back(Member);
10777
10778      // Be sure that the destructor is accessible and is marked as referenced.
10779      if (const RecordType *RecordTy
10780                  = Context.getBaseElementType(Field->getType())
10781                                                        ->getAs<RecordType>()) {
10782                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10783        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10784          MarkFunctionReferenced(Field->getLocation(), Destructor);
10785          CheckDestructorAccess(Field->getLocation(), Destructor,
10786                            PDiag(diag::err_access_dtor_ivar)
10787                              << Context.getBaseElementType(Field->getType()));
10788        }
10789      }
10790    }
10791    ObjCImplementation->setIvarInitializers(Context,
10792                                            AllToInit.data(), AllToInit.size());
10793  }
10794}
10795
10796static
10797void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10798                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10799                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10800                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10801                           Sema &S) {
10802  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10803                                                   CE = Current.end();
10804  if (Ctor->isInvalidDecl())
10805    return;
10806
10807  const FunctionDecl *FNTarget = 0;
10808  CXXConstructorDecl *Target;
10809
10810  // We ignore the result here since if we don't have a body, Target will be
10811  // null below.
10812  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10813  Target
10814= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10815
10816  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10817                     // Avoid dereferencing a null pointer here.
10818                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10819
10820  if (!Current.insert(Canonical))
10821    return;
10822
10823  // We know that beyond here, we aren't chaining into a cycle.
10824  if (!Target || !Target->isDelegatingConstructor() ||
10825      Target->isInvalidDecl() || Valid.count(TCanonical)) {
10826    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10827      Valid.insert(*CI);
10828    Current.clear();
10829  // We've hit a cycle.
10830  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10831             Current.count(TCanonical)) {
10832    // If we haven't diagnosed this cycle yet, do so now.
10833    if (!Invalid.count(TCanonical)) {
10834      S.Diag((*Ctor->init_begin())->getSourceLocation(),
10835             diag::warn_delegating_ctor_cycle)
10836        << Ctor;
10837
10838      // Don't add a note for a function delegating directo to itself.
10839      if (TCanonical != Canonical)
10840        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10841
10842      CXXConstructorDecl *C = Target;
10843      while (C->getCanonicalDecl() != Canonical) {
10844        (void)C->getTargetConstructor()->hasBody(FNTarget);
10845        assert(FNTarget && "Ctor cycle through bodiless function");
10846
10847        C
10848       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10849        S.Diag(C->getLocation(), diag::note_which_delegates_to);
10850      }
10851    }
10852
10853    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10854      Invalid.insert(*CI);
10855    Current.clear();
10856  } else {
10857    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10858  }
10859}
10860
10861
10862void Sema::CheckDelegatingCtorCycles() {
10863  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10864
10865  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10866                                                   CE = Current.end();
10867
10868  for (DelegatingCtorDeclsType::iterator
10869         I = DelegatingCtorDecls.begin(ExternalSource),
10870         E = DelegatingCtorDecls.end();
10871       I != E; ++I) {
10872   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
10873  }
10874
10875  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10876    (*CI)->setInvalidDecl();
10877}
10878
10879/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10880Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10881  // Implicitly declared functions (e.g. copy constructors) are
10882  // __host__ __device__
10883  if (D->isImplicit())
10884    return CFT_HostDevice;
10885
10886  if (D->hasAttr<CUDAGlobalAttr>())
10887    return CFT_Global;
10888
10889  if (D->hasAttr<CUDADeviceAttr>()) {
10890    if (D->hasAttr<CUDAHostAttr>())
10891      return CFT_HostDevice;
10892    else
10893      return CFT_Device;
10894  }
10895
10896  return CFT_Host;
10897}
10898
10899bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10900                           CUDAFunctionTarget CalleeTarget) {
10901  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10902  // Callable from the device only."
10903  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10904    return true;
10905
10906  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10907  // Callable from the host only."
10908  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10909  // Callable from the host only."
10910  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10911      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10912    return true;
10913
10914  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
10915    return true;
10916
10917  return false;
10918}
10919