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