SemaDeclCXX.cpp revision 831421f24057b93ea28bc92d8bd6290631a43caf
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/EvaluatedExprVisitor.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/RecordLayout.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/StmtVisitor.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/TypeOrdering.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Basic/PartialDiagnostic.h"
36#include "clang/Lex/Preprocessor.h"
37#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/STLExtras.h"
39#include <map>
40#include <set>
41
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// CheckDefaultArgumentVisitor
46//===----------------------------------------------------------------------===//
47
48namespace {
49  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
50  /// the default argument of a parameter to determine whether it
51  /// contains any ill-formed subexpressions. For example, this will
52  /// diagnose the use of local variables or parameters within the
53  /// default argument expression.
54  class CheckDefaultArgumentVisitor
55    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
56    Expr *DefaultArg;
57    Sema *S;
58
59  public:
60    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
61      : DefaultArg(defarg), S(s) {}
62
63    bool VisitExpr(Expr *Node);
64    bool VisitDeclRefExpr(DeclRefExpr *DRE);
65    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
66    bool VisitLambdaExpr(LambdaExpr *Lambda);
67  };
68
69  /// VisitExpr - Visit all of the children of this expression.
70  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
71    bool IsInvalid = false;
72    for (Stmt::child_range I = Node->children(); I; ++I)
73      IsInvalid |= Visit(*I);
74    return IsInvalid;
75  }
76
77  /// VisitDeclRefExpr - Visit a reference to a declaration, to
78  /// determine whether this declaration can be used in the default
79  /// argument expression.
80  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
81    NamedDecl *Decl = DRE->getDecl();
82    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
83      // C++ [dcl.fct.default]p9
84      //   Default arguments are evaluated each time the function is
85      //   called. The order of evaluation of function arguments is
86      //   unspecified. Consequently, parameters of a function shall not
87      //   be used in default argument expressions, even if they are not
88      //   evaluated. Parameters of a function declared before a default
89      //   argument expression are in scope and can hide namespace and
90      //   class member names.
91      return S->Diag(DRE->getLocStart(),
92                     diag::err_param_default_argument_references_param)
93         << Param->getDeclName() << DefaultArg->getSourceRange();
94    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
95      // C++ [dcl.fct.default]p7
96      //   Local variables shall not be used in default argument
97      //   expressions.
98      if (VDecl->isLocalVarDecl())
99        return S->Diag(DRE->getLocStart(),
100                       diag::err_param_default_argument_references_local)
101          << VDecl->getDeclName() << DefaultArg->getSourceRange();
102    }
103
104    return false;
105  }
106
107  /// VisitCXXThisExpr - Visit a C++ "this" expression.
108  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
109    // C++ [dcl.fct.default]p8:
110    //   The keyword this shall not be used in a default argument of a
111    //   member function.
112    return S->Diag(ThisE->getLocStart(),
113                   diag::err_param_default_argument_references_this)
114               << ThisE->getSourceRange();
115  }
116
117  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
118    // C++11 [expr.lambda.prim]p13:
119    //   A lambda-expression appearing in a default argument shall not
120    //   implicitly or explicitly capture any entity.
121    if (Lambda->capture_begin() == Lambda->capture_end())
122      return false;
123
124    return S->Diag(Lambda->getLocStart(),
125                   diag::err_lambda_capture_default_arg);
126  }
127}
128
129void Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
130                                                      CXXMethodDecl *Method) {
131  // If we have an MSAny or unknown spec already, don't bother.
132  if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
133    return;
134
135  const FunctionProtoType *Proto
136    = Method->getType()->getAs<FunctionProtoType>();
137  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
138  if (!Proto)
139    return;
140
141  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
142
143  // If this function can throw any exceptions, make a note of that.
144  if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
145    ClearExceptions();
146    ComputedEST = EST;
147    return;
148  }
149
150  // FIXME: If the call to this decl is using any of its default arguments, we
151  // need to search them for potentially-throwing calls.
152
153  // If this function has a basic noexcept, it doesn't affect the outcome.
154  if (EST == EST_BasicNoexcept)
155    return;
156
157  // If we have a throw-all spec at this point, ignore the function.
158  if (ComputedEST == EST_None)
159    return;
160
161  // If we're still at noexcept(true) and there's a nothrow() callee,
162  // change to that specification.
163  if (EST == EST_DynamicNone) {
164    if (ComputedEST == EST_BasicNoexcept)
165      ComputedEST = EST_DynamicNone;
166    return;
167  }
168
169  // Check out noexcept specs.
170  if (EST == EST_ComputedNoexcept) {
171    FunctionProtoType::NoexceptResult NR =
172        Proto->getNoexceptSpec(Self->Context);
173    assert(NR != FunctionProtoType::NR_NoNoexcept &&
174           "Must have noexcept result for EST_ComputedNoexcept.");
175    assert(NR != FunctionProtoType::NR_Dependent &&
176           "Should not generate implicit declarations for dependent cases, "
177           "and don't know how to handle them anyway.");
178
179    // noexcept(false) -> no spec on the new function
180    if (NR == FunctionProtoType::NR_Throw) {
181      ClearExceptions();
182      ComputedEST = EST_None;
183    }
184    // noexcept(true) won't change anything either.
185    return;
186  }
187
188  assert(EST == EST_Dynamic && "EST case not considered earlier.");
189  assert(ComputedEST != EST_None &&
190         "Shouldn't collect exceptions when throw-all is guaranteed.");
191  ComputedEST = EST_Dynamic;
192  // Record the exceptions in this function's exception specification.
193  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
194                                          EEnd = Proto->exception_end();
195       E != EEnd; ++E)
196    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
197      Exceptions.push_back(*E);
198}
199
200void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
201  if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
202    return;
203
204  // FIXME:
205  //
206  // C++0x [except.spec]p14:
207  //   [An] implicit exception-specification specifies the type-id T if and
208  // only if T is allowed by the exception-specification of a function directly
209  // invoked by f's implicit definition; f shall allow all exceptions if any
210  // function it directly invokes allows all exceptions, and f shall allow no
211  // exceptions if every function it directly invokes allows no exceptions.
212  //
213  // Note in particular that if an implicit exception-specification is generated
214  // for a function containing a throw-expression, that specification can still
215  // be noexcept(true).
216  //
217  // Note also that 'directly invoked' is not defined in the standard, and there
218  // is no indication that we should only consider potentially-evaluated calls.
219  //
220  // Ultimately we should implement the intent of the standard: the exception
221  // specification should be the set of exceptions which can be thrown by the
222  // implicit definition. For now, we assume that any non-nothrow expression can
223  // throw any exception.
224
225  if (Self->canThrow(E))
226    ComputedEST = EST_None;
227}
228
229bool
230Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
231                              SourceLocation EqualLoc) {
232  if (RequireCompleteType(Param->getLocation(), Param->getType(),
233                          diag::err_typecheck_decl_incomplete_type)) {
234    Param->setInvalidDecl();
235    return true;
236  }
237
238  // C++ [dcl.fct.default]p5
239  //   A default argument expression is implicitly converted (clause
240  //   4) to the parameter type. The default argument expression has
241  //   the same semantic constraints as the initializer expression in
242  //   a declaration of a variable of the parameter type, using the
243  //   copy-initialization semantics (8.5).
244  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245                                                                    Param);
246  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
247                                                           EqualLoc);
248  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
249  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
250                                      MultiExprArg(*this, &Arg, 1));
251  if (Result.isInvalid())
252    return true;
253  Arg = Result.takeAs<Expr>();
254
255  CheckImplicitConversions(Arg, EqualLoc);
256  Arg = MaybeCreateExprWithCleanups(Arg);
257
258  // Okay: add the default argument to the parameter
259  Param->setDefaultArg(Arg);
260
261  // We have already instantiated this parameter; provide each of the
262  // instantiations with the uninstantiated default argument.
263  UnparsedDefaultArgInstantiationsMap::iterator InstPos
264    = UnparsedDefaultArgInstantiations.find(Param);
265  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
266    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
267      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
268
269    // We're done tracking this parameter's instantiations.
270    UnparsedDefaultArgInstantiations.erase(InstPos);
271  }
272
273  return false;
274}
275
276/// ActOnParamDefaultArgument - Check whether the default argument
277/// provided for a function parameter is well-formed. If so, attach it
278/// to the parameter declaration.
279void
280Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
281                                Expr *DefaultArg) {
282  if (!param || !DefaultArg)
283    return;
284
285  ParmVarDecl *Param = cast<ParmVarDecl>(param);
286  UnparsedDefaultArgLocs.erase(Param);
287
288  // Default arguments are only permitted in C++
289  if (!getLangOpts().CPlusPlus) {
290    Diag(EqualLoc, diag::err_param_default_argument)
291      << DefaultArg->getSourceRange();
292    Param->setInvalidDecl();
293    return;
294  }
295
296  // Check for unexpanded parameter packs.
297  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
298    Param->setInvalidDecl();
299    return;
300  }
301
302  // Check that the default argument is well-formed
303  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
304  if (DefaultArgChecker.Visit(DefaultArg)) {
305    Param->setInvalidDecl();
306    return;
307  }
308
309  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
310}
311
312/// ActOnParamUnparsedDefaultArgument - We've seen a default
313/// argument for a function parameter, but we can't parse it yet
314/// because we're inside a class definition. Note that this default
315/// argument will be parsed later.
316void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
317                                             SourceLocation EqualLoc,
318                                             SourceLocation ArgLoc) {
319  if (!param)
320    return;
321
322  ParmVarDecl *Param = cast<ParmVarDecl>(param);
323  if (Param)
324    Param->setUnparsedDefaultArg();
325
326  UnparsedDefaultArgLocs[Param] = ArgLoc;
327}
328
329/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
330/// the default argument for the parameter param failed.
331void Sema::ActOnParamDefaultArgumentError(Decl *param) {
332  if (!param)
333    return;
334
335  ParmVarDecl *Param = cast<ParmVarDecl>(param);
336
337  Param->setInvalidDecl();
338
339  UnparsedDefaultArgLocs.erase(Param);
340}
341
342/// CheckExtraCXXDefaultArguments - Check for any extra default
343/// arguments in the declarator, which is not a function declaration
344/// or definition and therefore is not permitted to have default
345/// arguments. This routine should be invoked for every declarator
346/// that is not a function declaration or definition.
347void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
348  // C++ [dcl.fct.default]p3
349  //   A default argument expression shall be specified only in the
350  //   parameter-declaration-clause of a function declaration or in a
351  //   template-parameter (14.1). It shall not be specified for a
352  //   parameter pack. If it is specified in a
353  //   parameter-declaration-clause, it shall not occur within a
354  //   declarator or abstract-declarator of a parameter-declaration.
355  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
356    DeclaratorChunk &chunk = D.getTypeObject(i);
357    if (chunk.Kind == DeclaratorChunk::Function) {
358      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
359        ParmVarDecl *Param =
360          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
361        if (Param->hasUnparsedDefaultArg()) {
362          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
363          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
365          delete Toks;
366          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
367        } else if (Param->getDefaultArg()) {
368          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
369            << Param->getDefaultArg()->getSourceRange();
370          Param->setDefaultArg(0);
371        }
372      }
373    }
374  }
375}
376
377// MergeCXXFunctionDecl - Merge two declarations of the same C++
378// function, once we already know that they have the same
379// type. Subroutine of MergeFunctionDecl. Returns true if there was an
380// error, false otherwise.
381bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
382                                Scope *S) {
383  bool Invalid = false;
384
385  // C++ [dcl.fct.default]p4:
386  //   For non-template functions, default arguments can be added in
387  //   later declarations of a function in the same
388  //   scope. Declarations in different scopes have completely
389  //   distinct sets of default arguments. That is, declarations in
390  //   inner scopes do not acquire default arguments from
391  //   declarations in outer scopes, and vice versa. In a given
392  //   function declaration, all parameters subsequent to a
393  //   parameter with a default argument shall have default
394  //   arguments supplied in this or previous declarations. A
395  //   default argument shall not be redefined by a later
396  //   declaration (not even to the same value).
397  //
398  // C++ [dcl.fct.default]p6:
399  //   Except for member functions of class templates, the default arguments
400  //   in a member function definition that appears outside of the class
401  //   definition are added to the set of default arguments provided by the
402  //   member function declaration in the class definition.
403  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
404    ParmVarDecl *OldParam = Old->getParamDecl(p);
405    ParmVarDecl *NewParam = New->getParamDecl(p);
406
407    bool OldParamHasDfl = OldParam->hasDefaultArg();
408    bool NewParamHasDfl = NewParam->hasDefaultArg();
409
410    NamedDecl *ND = Old;
411    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
412      // Ignore default parameters of old decl if they are not in
413      // the same scope.
414      OldParamHasDfl = false;
415
416    if (OldParamHasDfl && NewParamHasDfl) {
417
418      unsigned DiagDefaultParamID =
419        diag::err_param_default_argument_redefinition;
420
421      // MSVC accepts that default parameters be redefined for member functions
422      // of template class. The new default parameter's value is ignored.
423      Invalid = true;
424      if (getLangOpts().MicrosoftExt) {
425        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
426        if (MD && MD->getParent()->getDescribedClassTemplate()) {
427          // Merge the old default argument into the new parameter.
428          NewParam->setHasInheritedDefaultArg();
429          if (OldParam->hasUninstantiatedDefaultArg())
430            NewParam->setUninstantiatedDefaultArg(
431                                      OldParam->getUninstantiatedDefaultArg());
432          else
433            NewParam->setDefaultArg(OldParam->getInit());
434          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
435          Invalid = false;
436        }
437      }
438
439      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
440      // hint here. Alternatively, we could walk the type-source information
441      // for NewParam to find the last source location in the type... but it
442      // isn't worth the effort right now. This is the kind of test case that
443      // is hard to get right:
444      //   int f(int);
445      //   void g(int (*fp)(int) = f);
446      //   void g(int (*fp)(int) = &f);
447      Diag(NewParam->getLocation(), DiagDefaultParamID)
448        << NewParam->getDefaultArgRange();
449
450      // Look for the function declaration where the default argument was
451      // actually written, which may be a declaration prior to Old.
452      for (FunctionDecl *Older = Old->getPreviousDecl();
453           Older; Older = Older->getPreviousDecl()) {
454        if (!Older->getParamDecl(p)->hasDefaultArg())
455          break;
456
457        OldParam = Older->getParamDecl(p);
458      }
459
460      Diag(OldParam->getLocation(), diag::note_previous_definition)
461        << OldParam->getDefaultArgRange();
462    } else if (OldParamHasDfl) {
463      // Merge the old default argument into the new parameter.
464      // It's important to use getInit() here;  getDefaultArg()
465      // strips off any top-level ExprWithCleanups.
466      NewParam->setHasInheritedDefaultArg();
467      if (OldParam->hasUninstantiatedDefaultArg())
468        NewParam->setUninstantiatedDefaultArg(
469                                      OldParam->getUninstantiatedDefaultArg());
470      else
471        NewParam->setDefaultArg(OldParam->getInit());
472    } else if (NewParamHasDfl) {
473      if (New->getDescribedFunctionTemplate()) {
474        // Paragraph 4, quoted above, only applies to non-template functions.
475        Diag(NewParam->getLocation(),
476             diag::err_param_default_argument_template_redecl)
477          << NewParam->getDefaultArgRange();
478        Diag(Old->getLocation(), diag::note_template_prev_declaration)
479          << false;
480      } else if (New->getTemplateSpecializationKind()
481                   != TSK_ImplicitInstantiation &&
482                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
483        // C++ [temp.expr.spec]p21:
484        //   Default function arguments shall not be specified in a declaration
485        //   or a definition for one of the following explicit specializations:
486        //     - the explicit specialization of a function template;
487        //     - the explicit specialization of a member function template;
488        //     - the explicit specialization of a member function of a class
489        //       template where the class template specialization to which the
490        //       member function specialization belongs is implicitly
491        //       instantiated.
492        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
493          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
494          << New->getDeclName()
495          << NewParam->getDefaultArgRange();
496      } else if (New->getDeclContext()->isDependentContext()) {
497        // C++ [dcl.fct.default]p6 (DR217):
498        //   Default arguments for a member function of a class template shall
499        //   be specified on the initial declaration of the member function
500        //   within the class template.
501        //
502        // Reading the tea leaves a bit in DR217 and its reference to DR205
503        // leads me to the conclusion that one cannot add default function
504        // arguments for an out-of-line definition of a member function of a
505        // dependent type.
506        int WhichKind = 2;
507        if (CXXRecordDecl *Record
508              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
509          if (Record->getDescribedClassTemplate())
510            WhichKind = 0;
511          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
512            WhichKind = 1;
513          else
514            WhichKind = 2;
515        }
516
517        Diag(NewParam->getLocation(),
518             diag::err_param_default_argument_member_template_redecl)
519          << WhichKind
520          << NewParam->getDefaultArgRange();
521      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
522        CXXSpecialMember NewSM = getSpecialMember(Ctor),
523                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
524        if (NewSM != OldSM) {
525          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
526            << NewParam->getDefaultArgRange() << NewSM;
527          Diag(Old->getLocation(), diag::note_previous_declaration_special)
528            << OldSM;
529        }
530      }
531    }
532  }
533
534  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
535  // template has a constexpr specifier then all its declarations shall
536  // contain the constexpr specifier.
537  if (New->isConstexpr() != Old->isConstexpr()) {
538    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
539      << New << New->isConstexpr();
540    Diag(Old->getLocation(), diag::note_previous_declaration);
541    Invalid = true;
542  }
543
544  if (CheckEquivalentExceptionSpec(Old, New))
545    Invalid = true;
546
547  return Invalid;
548}
549
550/// \brief Merge the exception specifications of two variable declarations.
551///
552/// This is called when there's a redeclaration of a VarDecl. The function
553/// checks if the redeclaration might have an exception specification and
554/// validates compatibility and merges the specs if necessary.
555void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
556  // Shortcut if exceptions are disabled.
557  if (!getLangOpts().CXXExceptions)
558    return;
559
560  assert(Context.hasSameType(New->getType(), Old->getType()) &&
561         "Should only be called if types are otherwise the same.");
562
563  QualType NewType = New->getType();
564  QualType OldType = Old->getType();
565
566  // We're only interested in pointers and references to functions, as well
567  // as pointers to member functions.
568  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
569    NewType = R->getPointeeType();
570    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
571  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
572    NewType = P->getPointeeType();
573    OldType = OldType->getAs<PointerType>()->getPointeeType();
574  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
575    NewType = M->getPointeeType();
576    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
577  }
578
579  if (!NewType->isFunctionProtoType())
580    return;
581
582  // There's lots of special cases for functions. For function pointers, system
583  // libraries are hopefully not as broken so that we don't need these
584  // workarounds.
585  if (CheckEquivalentExceptionSpec(
586        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
587        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
588    New->setInvalidDecl();
589  }
590}
591
592/// CheckCXXDefaultArguments - Verify that the default arguments for a
593/// function declaration are well-formed according to C++
594/// [dcl.fct.default].
595void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
596  unsigned NumParams = FD->getNumParams();
597  unsigned p;
598
599  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
600                  isa<CXXMethodDecl>(FD) &&
601                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
602
603  // Find first parameter with a default argument
604  for (p = 0; p < NumParams; ++p) {
605    ParmVarDecl *Param = FD->getParamDecl(p);
606    if (Param->hasDefaultArg()) {
607      // C++11 [expr.prim.lambda]p5:
608      //   [...] Default arguments (8.3.6) shall not be specified in the
609      //   parameter-declaration-clause of a lambda-declarator.
610      //
611      // FIXME: Core issue 974 strikes this sentence, we only provide an
612      // extension warning.
613      if (IsLambda)
614        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
615          << Param->getDefaultArgRange();
616      break;
617    }
618  }
619
620  // C++ [dcl.fct.default]p4:
621  //   In a given function declaration, all parameters
622  //   subsequent to a parameter with a default argument shall
623  //   have default arguments supplied in this or previous
624  //   declarations. A default argument shall not be redefined
625  //   by a later declaration (not even to the same value).
626  unsigned LastMissingDefaultArg = 0;
627  for (; p < NumParams; ++p) {
628    ParmVarDecl *Param = FD->getParamDecl(p);
629    if (!Param->hasDefaultArg()) {
630      if (Param->isInvalidDecl())
631        /* We already complained about this parameter. */;
632      else if (Param->getIdentifier())
633        Diag(Param->getLocation(),
634             diag::err_param_default_argument_missing_name)
635          << Param->getIdentifier();
636      else
637        Diag(Param->getLocation(),
638             diag::err_param_default_argument_missing);
639
640      LastMissingDefaultArg = p;
641    }
642  }
643
644  if (LastMissingDefaultArg > 0) {
645    // Some default arguments were missing. Clear out all of the
646    // default arguments up to (and including) the last missing
647    // default argument, so that we leave the function parameters
648    // in a semantically valid state.
649    for (p = 0; p <= LastMissingDefaultArg; ++p) {
650      ParmVarDecl *Param = FD->getParamDecl(p);
651      if (Param->hasDefaultArg()) {
652        Param->setDefaultArg(0);
653      }
654    }
655  }
656}
657
658// CheckConstexprParameterTypes - Check whether a function's parameter types
659// are all literal types. If so, return true. If not, produce a suitable
660// diagnostic and return false.
661static bool CheckConstexprParameterTypes(Sema &SemaRef,
662                                         const FunctionDecl *FD) {
663  unsigned ArgIndex = 0;
664  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
665  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
666       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
667    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
668    SourceLocation ParamLoc = PD->getLocation();
669    if (!(*i)->isDependentType() &&
670        SemaRef.RequireLiteralType(ParamLoc, *i,
671                                   diag::err_constexpr_non_literal_param,
672                                   ArgIndex+1, PD->getSourceRange(),
673                                   isa<CXXConstructorDecl>(FD)))
674      return false;
675  }
676  return true;
677}
678
679// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
680// the requirements of a constexpr function definition or a constexpr
681// constructor definition. If so, return true. If not, produce appropriate
682// diagnostics and return false.
683//
684// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
685bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
686  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
687  if (MD && MD->isInstance()) {
688    // C++11 [dcl.constexpr]p4:
689    //  The definition of a constexpr constructor shall satisfy the following
690    //  constraints:
691    //  - the class shall not have any virtual base classes;
692    const CXXRecordDecl *RD = MD->getParent();
693    if (RD->getNumVBases()) {
694      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
695        << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
696        << RD->getNumVBases();
697      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
698             E = RD->vbases_end(); I != E; ++I)
699        Diag(I->getLocStart(),
700             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
701      return false;
702    }
703  }
704
705  if (!isa<CXXConstructorDecl>(NewFD)) {
706    // C++11 [dcl.constexpr]p3:
707    //  The definition of a constexpr function shall satisfy the following
708    //  constraints:
709    // - it shall not be virtual;
710    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
711    if (Method && Method->isVirtual()) {
712      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
713
714      // If it's not obvious why this function is virtual, find an overridden
715      // function which uses the 'virtual' keyword.
716      const CXXMethodDecl *WrittenVirtual = Method;
717      while (!WrittenVirtual->isVirtualAsWritten())
718        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
719      if (WrittenVirtual != Method)
720        Diag(WrittenVirtual->getLocation(),
721             diag::note_overridden_virtual_function);
722      return false;
723    }
724
725    // - its return type shall be a literal type;
726    QualType RT = NewFD->getResultType();
727    if (!RT->isDependentType() &&
728        RequireLiteralType(NewFD->getLocation(), RT,
729                           diag::err_constexpr_non_literal_return))
730      return false;
731  }
732
733  // - each of its parameter types shall be a literal type;
734  if (!CheckConstexprParameterTypes(*this, NewFD))
735    return false;
736
737  return true;
738}
739
740/// Check the given declaration statement is legal within a constexpr function
741/// body. C++0x [dcl.constexpr]p3,p4.
742///
743/// \return true if the body is OK, false if we have diagnosed a problem.
744static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
745                                   DeclStmt *DS) {
746  // C++0x [dcl.constexpr]p3 and p4:
747  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
748  //  contain only
749  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
750         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
751    switch ((*DclIt)->getKind()) {
752    case Decl::StaticAssert:
753    case Decl::Using:
754    case Decl::UsingShadow:
755    case Decl::UsingDirective:
756    case Decl::UnresolvedUsingTypename:
757      //   - static_assert-declarations
758      //   - using-declarations,
759      //   - using-directives,
760      continue;
761
762    case Decl::Typedef:
763    case Decl::TypeAlias: {
764      //   - typedef declarations and alias-declarations that do not define
765      //     classes or enumerations,
766      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
767      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
768        // Don't allow variably-modified types in constexpr functions.
769        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
770        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
771          << TL.getSourceRange() << TL.getType()
772          << isa<CXXConstructorDecl>(Dcl);
773        return false;
774      }
775      continue;
776    }
777
778    case Decl::Enum:
779    case Decl::CXXRecord:
780      // As an extension, we allow the declaration (but not the definition) of
781      // classes and enumerations in all declarations, not just in typedef and
782      // alias declarations.
783      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
784        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
785          << isa<CXXConstructorDecl>(Dcl);
786        return false;
787      }
788      continue;
789
790    case Decl::Var:
791      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
792        << isa<CXXConstructorDecl>(Dcl);
793      return false;
794
795    default:
796      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
797        << isa<CXXConstructorDecl>(Dcl);
798      return false;
799    }
800  }
801
802  return true;
803}
804
805/// Check that the given field is initialized within a constexpr constructor.
806///
807/// \param Dcl The constexpr constructor being checked.
808/// \param Field The field being checked. This may be a member of an anonymous
809///        struct or union nested within the class being checked.
810/// \param Inits All declarations, including anonymous struct/union members and
811///        indirect members, for which any initialization was provided.
812/// \param Diagnosed Set to true if an error is produced.
813static void CheckConstexprCtorInitializer(Sema &SemaRef,
814                                          const FunctionDecl *Dcl,
815                                          FieldDecl *Field,
816                                          llvm::SmallSet<Decl*, 16> &Inits,
817                                          bool &Diagnosed) {
818  if (Field->isUnnamedBitfield())
819    return;
820
821  if (Field->isAnonymousStructOrUnion() &&
822      Field->getType()->getAsCXXRecordDecl()->isEmpty())
823    return;
824
825  if (!Inits.count(Field)) {
826    if (!Diagnosed) {
827      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
828      Diagnosed = true;
829    }
830    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
831  } else if (Field->isAnonymousStructOrUnion()) {
832    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
833    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
834         I != E; ++I)
835      // If an anonymous union contains an anonymous struct of which any member
836      // is initialized, all members must be initialized.
837      if (!RD->isUnion() || Inits.count(*I))
838        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
839  }
840}
841
842/// Check the body for the given constexpr function declaration only contains
843/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
844///
845/// \return true if the body is OK, false if we have diagnosed a problem.
846bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
847  if (isa<CXXTryStmt>(Body)) {
848    // C++11 [dcl.constexpr]p3:
849    //  The definition of a constexpr function shall satisfy the following
850    //  constraints: [...]
851    // - its function-body shall be = delete, = default, or a
852    //   compound-statement
853    //
854    // C++11 [dcl.constexpr]p4:
855    //  In the definition of a constexpr constructor, [...]
856    // - its function-body shall not be a function-try-block;
857    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
858      << isa<CXXConstructorDecl>(Dcl);
859    return false;
860  }
861
862  // - its function-body shall be [...] a compound-statement that contains only
863  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
864
865  llvm::SmallVector<SourceLocation, 4> ReturnStmts;
866  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
867         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
868    switch ((*BodyIt)->getStmtClass()) {
869    case Stmt::NullStmtClass:
870      //   - null statements,
871      continue;
872
873    case Stmt::DeclStmtClass:
874      //   - static_assert-declarations
875      //   - using-declarations,
876      //   - using-directives,
877      //   - typedef declarations and alias-declarations that do not define
878      //     classes or enumerations,
879      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
880        return false;
881      continue;
882
883    case Stmt::ReturnStmtClass:
884      //   - and exactly one return statement;
885      if (isa<CXXConstructorDecl>(Dcl))
886        break;
887
888      ReturnStmts.push_back((*BodyIt)->getLocStart());
889      continue;
890
891    default:
892      break;
893    }
894
895    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
896      << isa<CXXConstructorDecl>(Dcl);
897    return false;
898  }
899
900  if (const CXXConstructorDecl *Constructor
901        = dyn_cast<CXXConstructorDecl>(Dcl)) {
902    const CXXRecordDecl *RD = Constructor->getParent();
903    // DR1359:
904    // - every non-variant non-static data member and base class sub-object
905    //   shall be initialized;
906    // - if the class is a non-empty union, or for each non-empty anonymous
907    //   union member of a non-union class, exactly one non-static data member
908    //   shall be initialized;
909    if (RD->isUnion()) {
910      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
911        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
912        return false;
913      }
914    } else if (!Constructor->isDependentContext() &&
915               !Constructor->isDelegatingConstructor()) {
916      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
917
918      // Skip detailed checking if we have enough initializers, and we would
919      // allow at most one initializer per member.
920      bool AnyAnonStructUnionMembers = false;
921      unsigned Fields = 0;
922      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
923           E = RD->field_end(); I != E; ++I, ++Fields) {
924        if (I->isAnonymousStructOrUnion()) {
925          AnyAnonStructUnionMembers = true;
926          break;
927        }
928      }
929      if (AnyAnonStructUnionMembers ||
930          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
931        // Check initialization of non-static data members. Base classes are
932        // always initialized so do not need to be checked. Dependent bases
933        // might not have initializers in the member initializer list.
934        llvm::SmallSet<Decl*, 16> Inits;
935        for (CXXConstructorDecl::init_const_iterator
936               I = Constructor->init_begin(), E = Constructor->init_end();
937             I != E; ++I) {
938          if (FieldDecl *FD = (*I)->getMember())
939            Inits.insert(FD);
940          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
941            Inits.insert(ID->chain_begin(), ID->chain_end());
942        }
943
944        bool Diagnosed = false;
945        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
946             E = RD->field_end(); I != E; ++I)
947          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
948        if (Diagnosed)
949          return false;
950      }
951    }
952  } else {
953    if (ReturnStmts.empty()) {
954      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
955      return false;
956    }
957    if (ReturnStmts.size() > 1) {
958      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
959      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
960        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
961      return false;
962    }
963  }
964
965  // C++11 [dcl.constexpr]p5:
966  //   if no function argument values exist such that the function invocation
967  //   substitution would produce a constant expression, the program is
968  //   ill-formed; no diagnostic required.
969  // C++11 [dcl.constexpr]p3:
970  //   - every constructor call and implicit conversion used in initializing the
971  //     return value shall be one of those allowed in a constant expression.
972  // C++11 [dcl.constexpr]p4:
973  //   - every constructor involved in initializing non-static data members and
974  //     base class sub-objects shall be a constexpr constructor.
975  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
976  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
977    Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
978      << isa<CXXConstructorDecl>(Dcl);
979    for (size_t I = 0, N = Diags.size(); I != N; ++I)
980      Diag(Diags[I].first, Diags[I].second);
981    return false;
982  }
983
984  return true;
985}
986
987/// isCurrentClassName - Determine whether the identifier II is the
988/// name of the class type currently being defined. In the case of
989/// nested classes, this will only return true if II is the name of
990/// the innermost class.
991bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
992                              const CXXScopeSpec *SS) {
993  assert(getLangOpts().CPlusPlus && "No class names in C!");
994
995  CXXRecordDecl *CurDecl;
996  if (SS && SS->isSet() && !SS->isInvalid()) {
997    DeclContext *DC = computeDeclContext(*SS, true);
998    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
999  } else
1000    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1001
1002  if (CurDecl && CurDecl->getIdentifier())
1003    return &II == CurDecl->getIdentifier();
1004  else
1005    return false;
1006}
1007
1008/// \brief Check the validity of a C++ base class specifier.
1009///
1010/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1011/// and returns NULL otherwise.
1012CXXBaseSpecifier *
1013Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1014                         SourceRange SpecifierRange,
1015                         bool Virtual, AccessSpecifier Access,
1016                         TypeSourceInfo *TInfo,
1017                         SourceLocation EllipsisLoc) {
1018  QualType BaseType = TInfo->getType();
1019
1020  // C++ [class.union]p1:
1021  //   A union shall not have base classes.
1022  if (Class->isUnion()) {
1023    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1024      << SpecifierRange;
1025    return 0;
1026  }
1027
1028  if (EllipsisLoc.isValid() &&
1029      !TInfo->getType()->containsUnexpandedParameterPack()) {
1030    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1031      << TInfo->getTypeLoc().getSourceRange();
1032    EllipsisLoc = SourceLocation();
1033  }
1034
1035  if (BaseType->isDependentType())
1036    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1037                                          Class->getTagKind() == TTK_Class,
1038                                          Access, TInfo, EllipsisLoc);
1039
1040  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1041
1042  // Base specifiers must be record types.
1043  if (!BaseType->isRecordType()) {
1044    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1045    return 0;
1046  }
1047
1048  // C++ [class.union]p1:
1049  //   A union shall not be used as a base class.
1050  if (BaseType->isUnionType()) {
1051    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1052    return 0;
1053  }
1054
1055  // C++ [class.derived]p2:
1056  //   The class-name in a base-specifier shall not be an incompletely
1057  //   defined class.
1058  if (RequireCompleteType(BaseLoc, BaseType,
1059                          diag::err_incomplete_base_class, SpecifierRange)) {
1060    Class->setInvalidDecl();
1061    return 0;
1062  }
1063
1064  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1065  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1066  assert(BaseDecl && "Record type has no declaration");
1067  BaseDecl = BaseDecl->getDefinition();
1068  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1069  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1070  assert(CXXBaseDecl && "Base type is not a C++ type");
1071
1072  // C++ [class]p3:
1073  //   If a class is marked final and it appears as a base-type-specifier in
1074  //   base-clause, the program is ill-formed.
1075  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1076    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1077      << CXXBaseDecl->getDeclName();
1078    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1079      << CXXBaseDecl->getDeclName();
1080    return 0;
1081  }
1082
1083  if (BaseDecl->isInvalidDecl())
1084    Class->setInvalidDecl();
1085
1086  // Create the base specifier.
1087  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1088                                        Class->getTagKind() == TTK_Class,
1089                                        Access, TInfo, EllipsisLoc);
1090}
1091
1092/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1093/// one entry in the base class list of a class specifier, for
1094/// example:
1095///    class foo : public bar, virtual private baz {
1096/// 'public bar' and 'virtual private baz' are each base-specifiers.
1097BaseResult
1098Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1099                         bool Virtual, AccessSpecifier Access,
1100                         ParsedType basetype, SourceLocation BaseLoc,
1101                         SourceLocation EllipsisLoc) {
1102  if (!classdecl)
1103    return true;
1104
1105  AdjustDeclIfTemplate(classdecl);
1106  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1107  if (!Class)
1108    return true;
1109
1110  TypeSourceInfo *TInfo = 0;
1111  GetTypeFromParser(basetype, &TInfo);
1112
1113  if (EllipsisLoc.isInvalid() &&
1114      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1115                                      UPPC_BaseType))
1116    return true;
1117
1118  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1119                                                      Virtual, Access, TInfo,
1120                                                      EllipsisLoc))
1121    return BaseSpec;
1122
1123  return true;
1124}
1125
1126/// \brief Performs the actual work of attaching the given base class
1127/// specifiers to a C++ class.
1128bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1129                                unsigned NumBases) {
1130 if (NumBases == 0)
1131    return false;
1132
1133  // Used to keep track of which base types we have already seen, so
1134  // that we can properly diagnose redundant direct base types. Note
1135  // that the key is always the unqualified canonical type of the base
1136  // class.
1137  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1138
1139  // Copy non-redundant base specifiers into permanent storage.
1140  unsigned NumGoodBases = 0;
1141  bool Invalid = false;
1142  for (unsigned idx = 0; idx < NumBases; ++idx) {
1143    QualType NewBaseType
1144      = Context.getCanonicalType(Bases[idx]->getType());
1145    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1146
1147    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1148    if (KnownBase) {
1149      // C++ [class.mi]p3:
1150      //   A class shall not be specified as a direct base class of a
1151      //   derived class more than once.
1152      Diag(Bases[idx]->getLocStart(),
1153           diag::err_duplicate_base_class)
1154        << KnownBase->getType()
1155        << Bases[idx]->getSourceRange();
1156
1157      // Delete the duplicate base class specifier; we're going to
1158      // overwrite its pointer later.
1159      Context.Deallocate(Bases[idx]);
1160
1161      Invalid = true;
1162    } else {
1163      // Okay, add this new base class.
1164      KnownBase = Bases[idx];
1165      Bases[NumGoodBases++] = Bases[idx];
1166      if (const RecordType *Record = NewBaseType->getAs<RecordType>())
1167        if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1168          if (RD->hasAttr<WeakAttr>())
1169            Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1170    }
1171  }
1172
1173  // Attach the remaining base class specifiers to the derived class.
1174  Class->setBases(Bases, NumGoodBases);
1175
1176  // Delete the remaining (good) base class specifiers, since their
1177  // data has been copied into the CXXRecordDecl.
1178  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1179    Context.Deallocate(Bases[idx]);
1180
1181  return Invalid;
1182}
1183
1184/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1185/// class, after checking whether there are any duplicate base
1186/// classes.
1187void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1188                               unsigned NumBases) {
1189  if (!ClassDecl || !Bases || !NumBases)
1190    return;
1191
1192  AdjustDeclIfTemplate(ClassDecl);
1193  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1194                       (CXXBaseSpecifier**)(Bases), NumBases);
1195}
1196
1197static CXXRecordDecl *GetClassForType(QualType T) {
1198  if (const RecordType *RT = T->getAs<RecordType>())
1199    return cast<CXXRecordDecl>(RT->getDecl());
1200  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1201    return ICT->getDecl();
1202  else
1203    return 0;
1204}
1205
1206/// \brief Determine whether the type \p Derived is a C++ class that is
1207/// derived from the type \p Base.
1208bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1209  if (!getLangOpts().CPlusPlus)
1210    return false;
1211
1212  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1213  if (!DerivedRD)
1214    return false;
1215
1216  CXXRecordDecl *BaseRD = GetClassForType(Base);
1217  if (!BaseRD)
1218    return false;
1219
1220  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1221  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1222}
1223
1224/// \brief Determine whether the type \p Derived is a C++ class that is
1225/// derived from the type \p Base.
1226bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1227  if (!getLangOpts().CPlusPlus)
1228    return false;
1229
1230  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1231  if (!DerivedRD)
1232    return false;
1233
1234  CXXRecordDecl *BaseRD = GetClassForType(Base);
1235  if (!BaseRD)
1236    return false;
1237
1238  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1239}
1240
1241void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1242                              CXXCastPath &BasePathArray) {
1243  assert(BasePathArray.empty() && "Base path array must be empty!");
1244  assert(Paths.isRecordingPaths() && "Must record paths!");
1245
1246  const CXXBasePath &Path = Paths.front();
1247
1248  // We first go backward and check if we have a virtual base.
1249  // FIXME: It would be better if CXXBasePath had the base specifier for
1250  // the nearest virtual base.
1251  unsigned Start = 0;
1252  for (unsigned I = Path.size(); I != 0; --I) {
1253    if (Path[I - 1].Base->isVirtual()) {
1254      Start = I - 1;
1255      break;
1256    }
1257  }
1258
1259  // Now add all bases.
1260  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1261    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1262}
1263
1264/// \brief Determine whether the given base path includes a virtual
1265/// base class.
1266bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1267  for (CXXCastPath::const_iterator B = BasePath.begin(),
1268                                BEnd = BasePath.end();
1269       B != BEnd; ++B)
1270    if ((*B)->isVirtual())
1271      return true;
1272
1273  return false;
1274}
1275
1276/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1277/// conversion (where Derived and Base are class types) is
1278/// well-formed, meaning that the conversion is unambiguous (and
1279/// that all of the base classes are accessible). Returns true
1280/// and emits a diagnostic if the code is ill-formed, returns false
1281/// otherwise. Loc is the location where this routine should point to
1282/// if there is an error, and Range is the source range to highlight
1283/// if there is an error.
1284bool
1285Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1286                                   unsigned InaccessibleBaseID,
1287                                   unsigned AmbigiousBaseConvID,
1288                                   SourceLocation Loc, SourceRange Range,
1289                                   DeclarationName Name,
1290                                   CXXCastPath *BasePath) {
1291  // First, determine whether the path from Derived to Base is
1292  // ambiguous. This is slightly more expensive than checking whether
1293  // the Derived to Base conversion exists, because here we need to
1294  // explore multiple paths to determine if there is an ambiguity.
1295  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1296                     /*DetectVirtual=*/false);
1297  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1298  assert(DerivationOkay &&
1299         "Can only be used with a derived-to-base conversion");
1300  (void)DerivationOkay;
1301
1302  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1303    if (InaccessibleBaseID) {
1304      // Check that the base class can be accessed.
1305      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1306                                   InaccessibleBaseID)) {
1307        case AR_inaccessible:
1308          return true;
1309        case AR_accessible:
1310        case AR_dependent:
1311        case AR_delayed:
1312          break;
1313      }
1314    }
1315
1316    // Build a base path if necessary.
1317    if (BasePath)
1318      BuildBasePathArray(Paths, *BasePath);
1319    return false;
1320  }
1321
1322  // We know that the derived-to-base conversion is ambiguous, and
1323  // we're going to produce a diagnostic. Perform the derived-to-base
1324  // search just one more time to compute all of the possible paths so
1325  // that we can print them out. This is more expensive than any of
1326  // the previous derived-to-base checks we've done, but at this point
1327  // performance isn't as much of an issue.
1328  Paths.clear();
1329  Paths.setRecordingPaths(true);
1330  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1331  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1332  (void)StillOkay;
1333
1334  // Build up a textual representation of the ambiguous paths, e.g.,
1335  // D -> B -> A, that will be used to illustrate the ambiguous
1336  // conversions in the diagnostic. We only print one of the paths
1337  // to each base class subobject.
1338  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1339
1340  Diag(Loc, AmbigiousBaseConvID)
1341  << Derived << Base << PathDisplayStr << Range << Name;
1342  return true;
1343}
1344
1345bool
1346Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1347                                   SourceLocation Loc, SourceRange Range,
1348                                   CXXCastPath *BasePath,
1349                                   bool IgnoreAccess) {
1350  return CheckDerivedToBaseConversion(Derived, Base,
1351                                      IgnoreAccess ? 0
1352                                       : diag::err_upcast_to_inaccessible_base,
1353                                      diag::err_ambiguous_derived_to_base_conv,
1354                                      Loc, Range, DeclarationName(),
1355                                      BasePath);
1356}
1357
1358
1359/// @brief Builds a string representing ambiguous paths from a
1360/// specific derived class to different subobjects of the same base
1361/// class.
1362///
1363/// This function builds a string that can be used in error messages
1364/// to show the different paths that one can take through the
1365/// inheritance hierarchy to go from the derived class to different
1366/// subobjects of a base class. The result looks something like this:
1367/// @code
1368/// struct D -> struct B -> struct A
1369/// struct D -> struct C -> struct A
1370/// @endcode
1371std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1372  std::string PathDisplayStr;
1373  std::set<unsigned> DisplayedPaths;
1374  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1375       Path != Paths.end(); ++Path) {
1376    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1377      // We haven't displayed a path to this particular base
1378      // class subobject yet.
1379      PathDisplayStr += "\n    ";
1380      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1381      for (CXXBasePath::const_iterator Element = Path->begin();
1382           Element != Path->end(); ++Element)
1383        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1384    }
1385  }
1386
1387  return PathDisplayStr;
1388}
1389
1390//===----------------------------------------------------------------------===//
1391// C++ class member Handling
1392//===----------------------------------------------------------------------===//
1393
1394/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1395bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1396                                SourceLocation ASLoc,
1397                                SourceLocation ColonLoc,
1398                                AttributeList *Attrs) {
1399  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1400  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1401                                                  ASLoc, ColonLoc);
1402  CurContext->addHiddenDecl(ASDecl);
1403  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1404}
1405
1406/// CheckOverrideControl - Check C++0x override control semantics.
1407void Sema::CheckOverrideControl(const Decl *D) {
1408  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1409  if (!MD || !MD->isVirtual())
1410    return;
1411
1412  if (MD->isDependentContext())
1413    return;
1414
1415  // C++0x [class.virtual]p3:
1416  //   If a virtual function is marked with the virt-specifier override and does
1417  //   not override a member function of a base class,
1418  //   the program is ill-formed.
1419  bool HasOverriddenMethods =
1420    MD->begin_overridden_methods() != MD->end_overridden_methods();
1421  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1422    Diag(MD->getLocation(),
1423                 diag::err_function_marked_override_not_overriding)
1424      << MD->getDeclName();
1425    return;
1426  }
1427}
1428
1429/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1430/// function overrides a virtual member function marked 'final', according to
1431/// C++0x [class.virtual]p3.
1432bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1433                                                  const CXXMethodDecl *Old) {
1434  if (!Old->hasAttr<FinalAttr>())
1435    return false;
1436
1437  Diag(New->getLocation(), diag::err_final_function_overridden)
1438    << New->getDeclName();
1439  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1440  return true;
1441}
1442
1443static bool InitializationHasSideEffects(const FieldDecl &FD) {
1444  if (!FD.getType().isNull()) {
1445    if (const CXXRecordDecl *RD = FD.getType()->getAsCXXRecordDecl()) {
1446      return !RD->isCompleteDefinition() ||
1447             !RD->hasTrivialDefaultConstructor() ||
1448             !RD->hasTrivialDestructor();
1449    }
1450  }
1451  return false;
1452}
1453
1454/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1455/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1456/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1457/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1458/// present (but parsing it has been deferred).
1459Decl *
1460Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1461                               MultiTemplateParamsArg TemplateParameterLists,
1462                               Expr *BW, const VirtSpecifiers &VS,
1463                               InClassInitStyle InitStyle) {
1464  const DeclSpec &DS = D.getDeclSpec();
1465  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1466  DeclarationName Name = NameInfo.getName();
1467  SourceLocation Loc = NameInfo.getLoc();
1468
1469  // For anonymous bitfields, the location should point to the type.
1470  if (Loc.isInvalid())
1471    Loc = D.getLocStart();
1472
1473  Expr *BitWidth = static_cast<Expr*>(BW);
1474
1475  assert(isa<CXXRecordDecl>(CurContext));
1476  assert(!DS.isFriendSpecified());
1477
1478  bool isFunc = D.isDeclarationOfFunction();
1479
1480  // C++ 9.2p6: A member shall not be declared to have automatic storage
1481  // duration (auto, register) or with the extern storage-class-specifier.
1482  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1483  // data members and cannot be applied to names declared const or static,
1484  // and cannot be applied to reference members.
1485  switch (DS.getStorageClassSpec()) {
1486    case DeclSpec::SCS_unspecified:
1487    case DeclSpec::SCS_typedef:
1488    case DeclSpec::SCS_static:
1489      // FALL THROUGH.
1490      break;
1491    case DeclSpec::SCS_mutable:
1492      if (isFunc) {
1493        if (DS.getStorageClassSpecLoc().isValid())
1494          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1495        else
1496          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1497
1498        // FIXME: It would be nicer if the keyword was ignored only for this
1499        // declarator. Otherwise we could get follow-up errors.
1500        D.getMutableDeclSpec().ClearStorageClassSpecs();
1501      }
1502      break;
1503    default:
1504      if (DS.getStorageClassSpecLoc().isValid())
1505        Diag(DS.getStorageClassSpecLoc(),
1506             diag::err_storageclass_invalid_for_member);
1507      else
1508        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1509      D.getMutableDeclSpec().ClearStorageClassSpecs();
1510  }
1511
1512  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1513                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1514                      !isFunc);
1515
1516  Decl *Member;
1517  if (isInstField) {
1518    CXXScopeSpec &SS = D.getCXXScopeSpec();
1519
1520    // Data members must have identifiers for names.
1521    if (!Name.isIdentifier()) {
1522      Diag(Loc, diag::err_bad_variable_name)
1523        << Name;
1524      return 0;
1525    }
1526
1527    IdentifierInfo *II = Name.getAsIdentifierInfo();
1528
1529    // Member field could not be with "template" keyword.
1530    // So TemplateParameterLists should be empty in this case.
1531    if (TemplateParameterLists.size()) {
1532      TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1533      if (TemplateParams->size()) {
1534        // There is no such thing as a member field template.
1535        Diag(D.getIdentifierLoc(), diag::err_template_member)
1536            << II
1537            << SourceRange(TemplateParams->getTemplateLoc(),
1538                TemplateParams->getRAngleLoc());
1539      } else {
1540        // There is an extraneous 'template<>' for this member.
1541        Diag(TemplateParams->getTemplateLoc(),
1542            diag::err_template_member_noparams)
1543            << II
1544            << SourceRange(TemplateParams->getTemplateLoc(),
1545                TemplateParams->getRAngleLoc());
1546      }
1547      return 0;
1548    }
1549
1550    if (SS.isSet() && !SS.isInvalid()) {
1551      // The user provided a superfluous scope specifier inside a class
1552      // definition:
1553      //
1554      // class X {
1555      //   int X::member;
1556      // };
1557      if (DeclContext *DC = computeDeclContext(SS, false))
1558        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1559      else
1560        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1561          << Name << SS.getRange();
1562
1563      SS.clear();
1564    }
1565
1566    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1567                         InitStyle, AS);
1568    assert(Member && "HandleField never returns null");
1569  } else {
1570    assert(InitStyle == ICIS_NoInit);
1571
1572    Member = HandleDeclarator(S, D, move(TemplateParameterLists));
1573    if (!Member) {
1574      return 0;
1575    }
1576
1577    // Non-instance-fields can't have a bitfield.
1578    if (BitWidth) {
1579      if (Member->isInvalidDecl()) {
1580        // don't emit another diagnostic.
1581      } else if (isa<VarDecl>(Member)) {
1582        // C++ 9.6p3: A bit-field shall not be a static member.
1583        // "static member 'A' cannot be a bit-field"
1584        Diag(Loc, diag::err_static_not_bitfield)
1585          << Name << BitWidth->getSourceRange();
1586      } else if (isa<TypedefDecl>(Member)) {
1587        // "typedef member 'x' cannot be a bit-field"
1588        Diag(Loc, diag::err_typedef_not_bitfield)
1589          << Name << BitWidth->getSourceRange();
1590      } else {
1591        // A function typedef ("typedef int f(); f a;").
1592        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1593        Diag(Loc, diag::err_not_integral_type_bitfield)
1594          << Name << cast<ValueDecl>(Member)->getType()
1595          << BitWidth->getSourceRange();
1596      }
1597
1598      BitWidth = 0;
1599      Member->setInvalidDecl();
1600    }
1601
1602    Member->setAccess(AS);
1603
1604    // If we have declared a member function template, set the access of the
1605    // templated declaration as well.
1606    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1607      FunTmpl->getTemplatedDecl()->setAccess(AS);
1608  }
1609
1610  if (VS.isOverrideSpecified()) {
1611    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1612    if (!MD || !MD->isVirtual()) {
1613      Diag(Member->getLocStart(),
1614           diag::override_keyword_only_allowed_on_virtual_member_functions)
1615        << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1616    } else
1617      MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1618  }
1619  if (VS.isFinalSpecified()) {
1620    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1621    if (!MD || !MD->isVirtual()) {
1622      Diag(Member->getLocStart(),
1623           diag::override_keyword_only_allowed_on_virtual_member_functions)
1624      << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1625    } else
1626      MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1627  }
1628
1629  if (VS.getLastLocation().isValid()) {
1630    // Update the end location of a method that has a virt-specifiers.
1631    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1632      MD->setRangeEnd(VS.getLastLocation());
1633  }
1634
1635  CheckOverrideControl(Member);
1636
1637  assert((Name || isInstField) && "No identifier for non-field ?");
1638
1639  if (isInstField) {
1640    FieldDecl *FD = cast<FieldDecl>(Member);
1641    FieldCollector->Add(FD);
1642
1643    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
1644                                 FD->getLocation())
1645          != DiagnosticsEngine::Ignored) {
1646      // Remember all explicit private FieldDecls that have a name, no side
1647      // effects and are not part of a dependent type declaration.
1648      if (!FD->isImplicit() && FD->getDeclName() &&
1649          FD->getAccess() == AS_private &&
1650          !FD->hasAttr<UnusedAttr>() &&
1651          !FD->getParent()->getTypeForDecl()->isDependentType() &&
1652          !InitializationHasSideEffects(*FD))
1653        UnusedPrivateFields.insert(FD);
1654    }
1655  }
1656
1657  return Member;
1658}
1659
1660/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1661/// in-class initializer for a non-static C++ class member, and after
1662/// instantiating an in-class initializer in a class template. Such actions
1663/// are deferred until the class is complete.
1664void
1665Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
1666                                       Expr *InitExpr) {
1667  FieldDecl *FD = cast<FieldDecl>(D);
1668  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
1669         "must set init style when field is created");
1670
1671  if (!InitExpr) {
1672    FD->setInvalidDecl();
1673    FD->removeInClassInitializer();
1674    return;
1675  }
1676
1677  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1678    FD->setInvalidDecl();
1679    FD->removeInClassInitializer();
1680    return;
1681  }
1682
1683  ExprResult Init = InitExpr;
1684  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1685    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1686      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1687        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1688    }
1689    Expr **Inits = &InitExpr;
1690    unsigned NumInits = 1;
1691    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1692    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
1693        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1694        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
1695    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1696    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1697    if (Init.isInvalid()) {
1698      FD->setInvalidDecl();
1699      return;
1700    }
1701
1702    CheckImplicitConversions(Init.get(), InitLoc);
1703  }
1704
1705  // C++0x [class.base.init]p7:
1706  //   The initialization of each base and member constitutes a
1707  //   full-expression.
1708  Init = MaybeCreateExprWithCleanups(Init);
1709  if (Init.isInvalid()) {
1710    FD->setInvalidDecl();
1711    return;
1712  }
1713
1714  InitExpr = Init.release();
1715
1716  FD->setInClassInitializer(InitExpr);
1717}
1718
1719/// \brief Find the direct and/or virtual base specifiers that
1720/// correspond to the given base type, for use in base initialization
1721/// within a constructor.
1722static bool FindBaseInitializer(Sema &SemaRef,
1723                                CXXRecordDecl *ClassDecl,
1724                                QualType BaseType,
1725                                const CXXBaseSpecifier *&DirectBaseSpec,
1726                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1727  // First, check for a direct base class.
1728  DirectBaseSpec = 0;
1729  for (CXXRecordDecl::base_class_const_iterator Base
1730         = ClassDecl->bases_begin();
1731       Base != ClassDecl->bases_end(); ++Base) {
1732    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1733      // We found a direct base of this type. That's what we're
1734      // initializing.
1735      DirectBaseSpec = &*Base;
1736      break;
1737    }
1738  }
1739
1740  // Check for a virtual base class.
1741  // FIXME: We might be able to short-circuit this if we know in advance that
1742  // there are no virtual bases.
1743  VirtualBaseSpec = 0;
1744  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1745    // We haven't found a base yet; search the class hierarchy for a
1746    // virtual base class.
1747    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1748                       /*DetectVirtual=*/false);
1749    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1750                              BaseType, Paths)) {
1751      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1752           Path != Paths.end(); ++Path) {
1753        if (Path->back().Base->isVirtual()) {
1754          VirtualBaseSpec = Path->back().Base;
1755          break;
1756        }
1757      }
1758    }
1759  }
1760
1761  return DirectBaseSpec || VirtualBaseSpec;
1762}
1763
1764/// \brief Handle a C++ member initializer using braced-init-list syntax.
1765MemInitResult
1766Sema::ActOnMemInitializer(Decl *ConstructorD,
1767                          Scope *S,
1768                          CXXScopeSpec &SS,
1769                          IdentifierInfo *MemberOrBase,
1770                          ParsedType TemplateTypeTy,
1771                          const DeclSpec &DS,
1772                          SourceLocation IdLoc,
1773                          Expr *InitList,
1774                          SourceLocation EllipsisLoc) {
1775  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1776                             DS, IdLoc, InitList,
1777                             EllipsisLoc);
1778}
1779
1780/// \brief Handle a C++ member initializer using parentheses syntax.
1781MemInitResult
1782Sema::ActOnMemInitializer(Decl *ConstructorD,
1783                          Scope *S,
1784                          CXXScopeSpec &SS,
1785                          IdentifierInfo *MemberOrBase,
1786                          ParsedType TemplateTypeTy,
1787                          const DeclSpec &DS,
1788                          SourceLocation IdLoc,
1789                          SourceLocation LParenLoc,
1790                          Expr **Args, unsigned NumArgs,
1791                          SourceLocation RParenLoc,
1792                          SourceLocation EllipsisLoc) {
1793  Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1794                                           RParenLoc);
1795  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1796                             DS, IdLoc, List, EllipsisLoc);
1797}
1798
1799namespace {
1800
1801// Callback to only accept typo corrections that can be a valid C++ member
1802// intializer: either a non-static field member or a base class.
1803class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1804 public:
1805  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1806      : ClassDecl(ClassDecl) {}
1807
1808  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1809    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1810      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1811        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1812      else
1813        return isa<TypeDecl>(ND);
1814    }
1815    return false;
1816  }
1817
1818 private:
1819  CXXRecordDecl *ClassDecl;
1820};
1821
1822}
1823
1824/// \brief Handle a C++ member initializer.
1825MemInitResult
1826Sema::BuildMemInitializer(Decl *ConstructorD,
1827                          Scope *S,
1828                          CXXScopeSpec &SS,
1829                          IdentifierInfo *MemberOrBase,
1830                          ParsedType TemplateTypeTy,
1831                          const DeclSpec &DS,
1832                          SourceLocation IdLoc,
1833                          Expr *Init,
1834                          SourceLocation EllipsisLoc) {
1835  if (!ConstructorD)
1836    return true;
1837
1838  AdjustDeclIfTemplate(ConstructorD);
1839
1840  CXXConstructorDecl *Constructor
1841    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1842  if (!Constructor) {
1843    // The user wrote a constructor initializer on a function that is
1844    // not a C++ constructor. Ignore the error for now, because we may
1845    // have more member initializers coming; we'll diagnose it just
1846    // once in ActOnMemInitializers.
1847    return true;
1848  }
1849
1850  CXXRecordDecl *ClassDecl = Constructor->getParent();
1851
1852  // C++ [class.base.init]p2:
1853  //   Names in a mem-initializer-id are looked up in the scope of the
1854  //   constructor's class and, if not found in that scope, are looked
1855  //   up in the scope containing the constructor's definition.
1856  //   [Note: if the constructor's class contains a member with the
1857  //   same name as a direct or virtual base class of the class, a
1858  //   mem-initializer-id naming the member or base class and composed
1859  //   of a single identifier refers to the class member. A
1860  //   mem-initializer-id for the hidden base class may be specified
1861  //   using a qualified name. ]
1862  if (!SS.getScopeRep() && !TemplateTypeTy) {
1863    // Look for a member, first.
1864    DeclContext::lookup_result Result
1865      = ClassDecl->lookup(MemberOrBase);
1866    if (Result.first != Result.second) {
1867      ValueDecl *Member;
1868      if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1869          (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
1870        if (EllipsisLoc.isValid())
1871          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1872            << MemberOrBase
1873            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
1874
1875        return BuildMemberInitializer(Member, Init, IdLoc);
1876      }
1877    }
1878  }
1879  // It didn't name a member, so see if it names a class.
1880  QualType BaseType;
1881  TypeSourceInfo *TInfo = 0;
1882
1883  if (TemplateTypeTy) {
1884    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1885  } else if (DS.getTypeSpecType() == TST_decltype) {
1886    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
1887  } else {
1888    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1889    LookupParsedName(R, S, &SS);
1890
1891    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1892    if (!TyD) {
1893      if (R.isAmbiguous()) return true;
1894
1895      // We don't want access-control diagnostics here.
1896      R.suppressDiagnostics();
1897
1898      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1899        bool NotUnknownSpecialization = false;
1900        DeclContext *DC = computeDeclContext(SS, false);
1901        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1902          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1903
1904        if (!NotUnknownSpecialization) {
1905          // When the scope specifier can refer to a member of an unknown
1906          // specialization, we take it as a type name.
1907          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1908                                       SS.getWithLocInContext(Context),
1909                                       *MemberOrBase, IdLoc);
1910          if (BaseType.isNull())
1911            return true;
1912
1913          R.clear();
1914          R.setLookupName(MemberOrBase);
1915        }
1916      }
1917
1918      // If no results were found, try to correct typos.
1919      TypoCorrection Corr;
1920      MemInitializerValidatorCCC Validator(ClassDecl);
1921      if (R.empty() && BaseType.isNull() &&
1922          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1923                              Validator, ClassDecl))) {
1924        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1925        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
1926        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1927          // We have found a non-static data member with a similar
1928          // name to what was typed; complain and initialize that
1929          // member.
1930          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1931            << MemberOrBase << true << CorrectedQuotedStr
1932            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1933          Diag(Member->getLocation(), diag::note_previous_decl)
1934            << CorrectedQuotedStr;
1935
1936          return BuildMemberInitializer(Member, Init, IdLoc);
1937        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1938          const CXXBaseSpecifier *DirectBaseSpec;
1939          const CXXBaseSpecifier *VirtualBaseSpec;
1940          if (FindBaseInitializer(*this, ClassDecl,
1941                                  Context.getTypeDeclType(Type),
1942                                  DirectBaseSpec, VirtualBaseSpec)) {
1943            // We have found a direct or virtual base class with a
1944            // similar name to what was typed; complain and initialize
1945            // that base class.
1946            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1947              << MemberOrBase << false << CorrectedQuotedStr
1948              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1949
1950            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1951                                                             : VirtualBaseSpec;
1952            Diag(BaseSpec->getLocStart(),
1953                 diag::note_base_class_specified_here)
1954              << BaseSpec->getType()
1955              << BaseSpec->getSourceRange();
1956
1957            TyD = Type;
1958          }
1959        }
1960      }
1961
1962      if (!TyD && BaseType.isNull()) {
1963        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1964          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
1965        return true;
1966      }
1967    }
1968
1969    if (BaseType.isNull()) {
1970      BaseType = Context.getTypeDeclType(TyD);
1971      if (SS.isSet()) {
1972        NestedNameSpecifier *Qualifier =
1973          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1974
1975        // FIXME: preserve source range information
1976        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1977      }
1978    }
1979  }
1980
1981  if (!TInfo)
1982    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1983
1984  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
1985}
1986
1987/// Checks a member initializer expression for cases where reference (or
1988/// pointer) members are bound to by-value parameters (or their addresses).
1989static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1990                                               Expr *Init,
1991                                               SourceLocation IdLoc) {
1992  QualType MemberTy = Member->getType();
1993
1994  // We only handle pointers and references currently.
1995  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1996  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1997    return;
1998
1999  const bool IsPointer = MemberTy->isPointerType();
2000  if (IsPointer) {
2001    if (const UnaryOperator *Op
2002          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2003      // The only case we're worried about with pointers requires taking the
2004      // address.
2005      if (Op->getOpcode() != UO_AddrOf)
2006        return;
2007
2008      Init = Op->getSubExpr();
2009    } else {
2010      // We only handle address-of expression initializers for pointers.
2011      return;
2012    }
2013  }
2014
2015  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
2016    // Taking the address of a temporary will be diagnosed as a hard error.
2017    if (IsPointer)
2018      return;
2019
2020    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
2021      << Member << Init->getSourceRange();
2022  } else if (const DeclRefExpr *DRE
2023               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2024    // We only warn when referring to a non-reference parameter declaration.
2025    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2026    if (!Parameter || Parameter->getType()->isReferenceType())
2027      return;
2028
2029    S.Diag(Init->getExprLoc(),
2030           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2031                     : diag::warn_bind_ref_member_to_parameter)
2032      << Member << Parameter << Init->getSourceRange();
2033  } else {
2034    // Other initializers are fine.
2035    return;
2036  }
2037
2038  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2039    << (unsigned)IsPointer;
2040}
2041
2042namespace {
2043  class UninitializedFieldVisitor
2044      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2045    Sema &S;
2046    ValueDecl *VD;
2047  public:
2048    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2049    UninitializedFieldVisitor(Sema &S, ValueDecl *VD) : Inherited(S.Context),
2050                                                        S(S), VD(VD) {
2051    }
2052
2053    void HandleExpr(Expr *E) {
2054      if (!E) return;
2055
2056      // Expressions like x(x) sometimes lack the surrounding expressions
2057      // but need to be checked anyways.
2058      HandleValue(E);
2059      Visit(E);
2060    }
2061
2062    void HandleValue(Expr *E) {
2063      E = E->IgnoreParens();
2064
2065      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2066        if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2067            return;
2068        Expr *Base = E;
2069        while (isa<MemberExpr>(Base)) {
2070          ME = dyn_cast<MemberExpr>(Base);
2071          if (VarDecl *VarD = dyn_cast<VarDecl>(ME->getMemberDecl()))
2072            if (VarD->hasGlobalStorage())
2073              return;
2074          Base = ME->getBase();
2075        }
2076
2077        if (VD == ME->getMemberDecl() && isa<CXXThisExpr>(Base)) {
2078          S.Diag(ME->getExprLoc(), diag::warn_field_is_uninit);
2079          return;
2080        }
2081      }
2082
2083      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2084        HandleValue(CO->getTrueExpr());
2085        HandleValue(CO->getFalseExpr());
2086        return;
2087      }
2088
2089      if (BinaryConditionalOperator *BCO =
2090              dyn_cast<BinaryConditionalOperator>(E)) {
2091        HandleValue(BCO->getCommon());
2092        HandleValue(BCO->getFalseExpr());
2093        return;
2094      }
2095
2096      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2097        switch (BO->getOpcode()) {
2098        default:
2099          return;
2100        case(BO_PtrMemD):
2101        case(BO_PtrMemI):
2102          HandleValue(BO->getLHS());
2103          return;
2104        case(BO_Comma):
2105          HandleValue(BO->getRHS());
2106          return;
2107        }
2108      }
2109    }
2110
2111    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2112      if (E->getCastKind() == CK_LValueToRValue)
2113        HandleValue(E->getSubExpr());
2114
2115      Inherited::VisitImplicitCastExpr(E);
2116    }
2117
2118    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2119      Expr *Callee = E->getCallee();
2120      if (isa<MemberExpr>(Callee))
2121        HandleValue(Callee);
2122
2123      Inherited::VisitCXXMemberCallExpr(E);
2124    }
2125  };
2126  static void CheckInitExprContainsUninitializedFields(Sema &S, Expr *E,
2127                                                       ValueDecl *VD) {
2128    UninitializedFieldVisitor(S, VD).HandleExpr(E);
2129  }
2130} // namespace
2131
2132MemInitResult
2133Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2134                             SourceLocation IdLoc) {
2135  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2136  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2137  assert((DirectMember || IndirectMember) &&
2138         "Member must be a FieldDecl or IndirectFieldDecl");
2139
2140  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2141    return true;
2142
2143  if (Member->isInvalidDecl())
2144    return true;
2145
2146  // Diagnose value-uses of fields to initialize themselves, e.g.
2147  //   foo(foo)
2148  // where foo is not also a parameter to the constructor.
2149  // TODO: implement -Wuninitialized and fold this into that framework.
2150  Expr **Args;
2151  unsigned NumArgs;
2152  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2153    Args = ParenList->getExprs();
2154    NumArgs = ParenList->getNumExprs();
2155  } else {
2156    InitListExpr *InitList = cast<InitListExpr>(Init);
2157    Args = InitList->getInits();
2158    NumArgs = InitList->getNumInits();
2159  }
2160
2161  // Mark FieldDecl as being used if it is a non-primitive type and the
2162  // initializer does not call the default constructor (which is trivial
2163  // for all entries in UnusedPrivateFields).
2164  // FIXME: Make this smarter once more side effect-free types can be
2165  // determined.
2166  if (NumArgs > 0) {
2167    if (Member->getType()->isRecordType()) {
2168      UnusedPrivateFields.remove(Member);
2169    } else {
2170      for (unsigned i = 0; i < NumArgs; ++i) {
2171        if (Args[i]->HasSideEffects(Context)) {
2172          UnusedPrivateFields.remove(Member);
2173          break;
2174        }
2175      }
2176    }
2177  }
2178
2179  if (getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit, IdLoc)
2180        != DiagnosticsEngine::Ignored)
2181    for (unsigned i = 0; i < NumArgs; ++i)
2182      // FIXME: Warn about the case when other fields are used before being
2183      // uninitialized. For example, let this field be the i'th field. When
2184      // initializing the i'th field, throw a warning if any of the >= i'th
2185      // fields are used, as they are not yet initialized.
2186      // Right now we are only handling the case where the i'th field uses
2187      // itself in its initializer.
2188      CheckInitExprContainsUninitializedFields(*this, Args[i], Member);
2189
2190  SourceRange InitRange = Init->getSourceRange();
2191
2192  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2193    // Can't check initialization for a member of dependent type or when
2194    // any of the arguments are type-dependent expressions.
2195    DiscardCleanupsInEvaluationContext();
2196  } else {
2197    bool InitList = false;
2198    if (isa<InitListExpr>(Init)) {
2199      InitList = true;
2200      Args = &Init;
2201      NumArgs = 1;
2202
2203      if (isStdInitializerList(Member->getType(), 0)) {
2204        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2205            << /*at end of ctor*/1 << InitRange;
2206      }
2207    }
2208
2209    // Initialize the member.
2210    InitializedEntity MemberEntity =
2211      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2212                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2213    InitializationKind Kind =
2214      InitList ? InitializationKind::CreateDirectList(IdLoc)
2215               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2216                                                  InitRange.getEnd());
2217
2218    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2219    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2220                                            MultiExprArg(*this, Args, NumArgs),
2221                                            0);
2222    if (MemberInit.isInvalid())
2223      return true;
2224
2225    CheckImplicitConversions(MemberInit.get(),
2226                             InitRange.getBegin());
2227
2228    // C++0x [class.base.init]p7:
2229    //   The initialization of each base and member constitutes a
2230    //   full-expression.
2231    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2232    if (MemberInit.isInvalid())
2233      return true;
2234
2235    // If we are in a dependent context, template instantiation will
2236    // perform this type-checking again. Just save the arguments that we
2237    // received.
2238    // FIXME: This isn't quite ideal, since our ASTs don't capture all
2239    // of the information that we have about the member
2240    // initializer. However, deconstructing the ASTs is a dicey process,
2241    // and this approach is far more likely to get the corner cases right.
2242    if (CurContext->isDependentContext()) {
2243      // The existing Init will do fine.
2244    } else {
2245      Init = MemberInit.get();
2246      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2247    }
2248  }
2249
2250  if (DirectMember) {
2251    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2252                                            InitRange.getBegin(), Init,
2253                                            InitRange.getEnd());
2254  } else {
2255    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2256                                            InitRange.getBegin(), Init,
2257                                            InitRange.getEnd());
2258  }
2259}
2260
2261MemInitResult
2262Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2263                                 CXXRecordDecl *ClassDecl) {
2264  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2265  if (!LangOpts.CPlusPlus0x)
2266    return Diag(NameLoc, diag::err_delegating_ctor)
2267      << TInfo->getTypeLoc().getLocalSourceRange();
2268  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2269
2270  bool InitList = true;
2271  Expr **Args = &Init;
2272  unsigned NumArgs = 1;
2273  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2274    InitList = false;
2275    Args = ParenList->getExprs();
2276    NumArgs = ParenList->getNumExprs();
2277  }
2278
2279  SourceRange InitRange = Init->getSourceRange();
2280  // Initialize the object.
2281  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2282                                     QualType(ClassDecl->getTypeForDecl(), 0));
2283  InitializationKind Kind =
2284    InitList ? InitializationKind::CreateDirectList(NameLoc)
2285             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2286                                                InitRange.getEnd());
2287  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2288  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2289                                              MultiExprArg(*this, Args,NumArgs),
2290                                              0);
2291  if (DelegationInit.isInvalid())
2292    return true;
2293
2294  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2295         "Delegating constructor with no target?");
2296
2297  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2298
2299  // C++0x [class.base.init]p7:
2300  //   The initialization of each base and member constitutes a
2301  //   full-expression.
2302  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2303  if (DelegationInit.isInvalid())
2304    return true;
2305
2306  // If we are in a dependent context, template instantiation will
2307  // perform this type-checking again. Just save the arguments that we
2308  // received in a ParenListExpr.
2309  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2310  // of the information that we have about the base
2311  // initializer. However, deconstructing the ASTs is a dicey process,
2312  // and this approach is far more likely to get the corner cases right.
2313  if (CurContext->isDependentContext())
2314    DelegationInit = Owned(Init);
2315
2316  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2317                                          DelegationInit.takeAs<Expr>(),
2318                                          InitRange.getEnd());
2319}
2320
2321MemInitResult
2322Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2323                           Expr *Init, CXXRecordDecl *ClassDecl,
2324                           SourceLocation EllipsisLoc) {
2325  SourceLocation BaseLoc
2326    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2327
2328  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2329    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2330             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2331
2332  // C++ [class.base.init]p2:
2333  //   [...] Unless the mem-initializer-id names a nonstatic data
2334  //   member of the constructor's class or a direct or virtual base
2335  //   of that class, the mem-initializer is ill-formed. A
2336  //   mem-initializer-list can initialize a base class using any
2337  //   name that denotes that base class type.
2338  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2339
2340  SourceRange InitRange = Init->getSourceRange();
2341  if (EllipsisLoc.isValid()) {
2342    // This is a pack expansion.
2343    if (!BaseType->containsUnexpandedParameterPack())  {
2344      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2345        << SourceRange(BaseLoc, InitRange.getEnd());
2346
2347      EllipsisLoc = SourceLocation();
2348    }
2349  } else {
2350    // Check for any unexpanded parameter packs.
2351    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2352      return true;
2353
2354    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2355      return true;
2356  }
2357
2358  // Check for direct and virtual base classes.
2359  const CXXBaseSpecifier *DirectBaseSpec = 0;
2360  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2361  if (!Dependent) {
2362    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2363                                       BaseType))
2364      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2365
2366    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2367                        VirtualBaseSpec);
2368
2369    // C++ [base.class.init]p2:
2370    // Unless the mem-initializer-id names a nonstatic data member of the
2371    // constructor's class or a direct or virtual base of that class, the
2372    // mem-initializer is ill-formed.
2373    if (!DirectBaseSpec && !VirtualBaseSpec) {
2374      // If the class has any dependent bases, then it's possible that
2375      // one of those types will resolve to the same type as
2376      // BaseType. Therefore, just treat this as a dependent base
2377      // class initialization.  FIXME: Should we try to check the
2378      // initialization anyway? It seems odd.
2379      if (ClassDecl->hasAnyDependentBases())
2380        Dependent = true;
2381      else
2382        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2383          << BaseType << Context.getTypeDeclType(ClassDecl)
2384          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2385    }
2386  }
2387
2388  if (Dependent) {
2389    DiscardCleanupsInEvaluationContext();
2390
2391    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2392                                            /*IsVirtual=*/false,
2393                                            InitRange.getBegin(), Init,
2394                                            InitRange.getEnd(), EllipsisLoc);
2395  }
2396
2397  // C++ [base.class.init]p2:
2398  //   If a mem-initializer-id is ambiguous because it designates both
2399  //   a direct non-virtual base class and an inherited virtual base
2400  //   class, the mem-initializer is ill-formed.
2401  if (DirectBaseSpec && VirtualBaseSpec)
2402    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2403      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2404
2405  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2406  if (!BaseSpec)
2407    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2408
2409  // Initialize the base.
2410  bool InitList = true;
2411  Expr **Args = &Init;
2412  unsigned NumArgs = 1;
2413  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2414    InitList = false;
2415    Args = ParenList->getExprs();
2416    NumArgs = ParenList->getNumExprs();
2417  }
2418
2419  InitializedEntity BaseEntity =
2420    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2421  InitializationKind Kind =
2422    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2423             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2424                                                InitRange.getEnd());
2425  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2426  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2427                                          MultiExprArg(*this, Args, NumArgs),
2428                                          0);
2429  if (BaseInit.isInvalid())
2430    return true;
2431
2432  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2433
2434  // C++0x [class.base.init]p7:
2435  //   The initialization of each base and member constitutes a
2436  //   full-expression.
2437  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2438  if (BaseInit.isInvalid())
2439    return true;
2440
2441  // If we are in a dependent context, template instantiation will
2442  // perform this type-checking again. Just save the arguments that we
2443  // received in a ParenListExpr.
2444  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2445  // of the information that we have about the base
2446  // initializer. However, deconstructing the ASTs is a dicey process,
2447  // and this approach is far more likely to get the corner cases right.
2448  if (CurContext->isDependentContext())
2449    BaseInit = Owned(Init);
2450
2451  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2452                                          BaseSpec->isVirtual(),
2453                                          InitRange.getBegin(),
2454                                          BaseInit.takeAs<Expr>(),
2455                                          InitRange.getEnd(), EllipsisLoc);
2456}
2457
2458// Create a static_cast\<T&&>(expr).
2459static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2460  QualType ExprType = E->getType();
2461  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2462  SourceLocation ExprLoc = E->getLocStart();
2463  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2464      TargetType, ExprLoc);
2465
2466  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2467                                   SourceRange(ExprLoc, ExprLoc),
2468                                   E->getSourceRange()).take();
2469}
2470
2471/// ImplicitInitializerKind - How an implicit base or member initializer should
2472/// initialize its base or member.
2473enum ImplicitInitializerKind {
2474  IIK_Default,
2475  IIK_Copy,
2476  IIK_Move
2477};
2478
2479static bool
2480BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2481                             ImplicitInitializerKind ImplicitInitKind,
2482                             CXXBaseSpecifier *BaseSpec,
2483                             bool IsInheritedVirtualBase,
2484                             CXXCtorInitializer *&CXXBaseInit) {
2485  InitializedEntity InitEntity
2486    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2487                                        IsInheritedVirtualBase);
2488
2489  ExprResult BaseInit;
2490
2491  switch (ImplicitInitKind) {
2492  case IIK_Default: {
2493    InitializationKind InitKind
2494      = InitializationKind::CreateDefault(Constructor->getLocation());
2495    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2496    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2497                               MultiExprArg(SemaRef, 0, 0));
2498    break;
2499  }
2500
2501  case IIK_Move:
2502  case IIK_Copy: {
2503    bool Moving = ImplicitInitKind == IIK_Move;
2504    ParmVarDecl *Param = Constructor->getParamDecl(0);
2505    QualType ParamType = Param->getType().getNonReferenceType();
2506
2507    Expr *CopyCtorArg =
2508      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2509                          SourceLocation(), Param, false,
2510                          Constructor->getLocation(), ParamType,
2511                          VK_LValue, 0);
2512
2513    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2514
2515    // Cast to the base class to avoid ambiguities.
2516    QualType ArgTy =
2517      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2518                                       ParamType.getQualifiers());
2519
2520    if (Moving) {
2521      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2522    }
2523
2524    CXXCastPath BasePath;
2525    BasePath.push_back(BaseSpec);
2526    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2527                                            CK_UncheckedDerivedToBase,
2528                                            Moving ? VK_XValue : VK_LValue,
2529                                            &BasePath).take();
2530
2531    InitializationKind InitKind
2532      = InitializationKind::CreateDirect(Constructor->getLocation(),
2533                                         SourceLocation(), SourceLocation());
2534    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2535                                   &CopyCtorArg, 1);
2536    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2537                               MultiExprArg(&CopyCtorArg, 1));
2538    break;
2539  }
2540  }
2541
2542  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2543  if (BaseInit.isInvalid())
2544    return true;
2545
2546  CXXBaseInit =
2547    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2548               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2549                                                        SourceLocation()),
2550                                             BaseSpec->isVirtual(),
2551                                             SourceLocation(),
2552                                             BaseInit.takeAs<Expr>(),
2553                                             SourceLocation(),
2554                                             SourceLocation());
2555
2556  return false;
2557}
2558
2559static bool RefersToRValueRef(Expr *MemRef) {
2560  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2561  return Referenced->getType()->isRValueReferenceType();
2562}
2563
2564static bool
2565BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2566                               ImplicitInitializerKind ImplicitInitKind,
2567                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2568                               CXXCtorInitializer *&CXXMemberInit) {
2569  if (Field->isInvalidDecl())
2570    return true;
2571
2572  SourceLocation Loc = Constructor->getLocation();
2573
2574  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2575    bool Moving = ImplicitInitKind == IIK_Move;
2576    ParmVarDecl *Param = Constructor->getParamDecl(0);
2577    QualType ParamType = Param->getType().getNonReferenceType();
2578
2579    // Suppress copying zero-width bitfields.
2580    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2581      return false;
2582
2583    Expr *MemberExprBase =
2584      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2585                          SourceLocation(), Param, false,
2586                          Loc, ParamType, VK_LValue, 0);
2587
2588    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2589
2590    if (Moving) {
2591      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2592    }
2593
2594    // Build a reference to this field within the parameter.
2595    CXXScopeSpec SS;
2596    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2597                              Sema::LookupMemberName);
2598    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2599                                  : cast<ValueDecl>(Field), AS_public);
2600    MemberLookup.resolveKind();
2601    ExprResult CtorArg
2602      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2603                                         ParamType, Loc,
2604                                         /*IsArrow=*/false,
2605                                         SS,
2606                                         /*TemplateKWLoc=*/SourceLocation(),
2607                                         /*FirstQualifierInScope=*/0,
2608                                         MemberLookup,
2609                                         /*TemplateArgs=*/0);
2610    if (CtorArg.isInvalid())
2611      return true;
2612
2613    // C++11 [class.copy]p15:
2614    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2615    //     with static_cast<T&&>(x.m);
2616    if (RefersToRValueRef(CtorArg.get())) {
2617      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2618    }
2619
2620    // When the field we are copying is an array, create index variables for
2621    // each dimension of the array. We use these index variables to subscript
2622    // the source array, and other clients (e.g., CodeGen) will perform the
2623    // necessary iteration with these index variables.
2624    SmallVector<VarDecl *, 4> IndexVariables;
2625    QualType BaseType = Field->getType();
2626    QualType SizeType = SemaRef.Context.getSizeType();
2627    bool InitializingArray = false;
2628    while (const ConstantArrayType *Array
2629                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2630      InitializingArray = true;
2631      // Create the iteration variable for this array index.
2632      IdentifierInfo *IterationVarName = 0;
2633      {
2634        SmallString<8> Str;
2635        llvm::raw_svector_ostream OS(Str);
2636        OS << "__i" << IndexVariables.size();
2637        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2638      }
2639      VarDecl *IterationVar
2640        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2641                          IterationVarName, SizeType,
2642                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2643                          SC_None, SC_None);
2644      IndexVariables.push_back(IterationVar);
2645
2646      // Create a reference to the iteration variable.
2647      ExprResult IterationVarRef
2648        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2649      assert(!IterationVarRef.isInvalid() &&
2650             "Reference to invented variable cannot fail!");
2651      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2652      assert(!IterationVarRef.isInvalid() &&
2653             "Conversion of invented variable cannot fail!");
2654
2655      // Subscript the array with this iteration variable.
2656      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2657                                                        IterationVarRef.take(),
2658                                                        Loc);
2659      if (CtorArg.isInvalid())
2660        return true;
2661
2662      BaseType = Array->getElementType();
2663    }
2664
2665    // The array subscript expression is an lvalue, which is wrong for moving.
2666    if (Moving && InitializingArray)
2667      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2668
2669    // Construct the entity that we will be initializing. For an array, this
2670    // will be first element in the array, which may require several levels
2671    // of array-subscript entities.
2672    SmallVector<InitializedEntity, 4> Entities;
2673    Entities.reserve(1 + IndexVariables.size());
2674    if (Indirect)
2675      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2676    else
2677      Entities.push_back(InitializedEntity::InitializeMember(Field));
2678    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2679      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2680                                                              0,
2681                                                              Entities.back()));
2682
2683    // Direct-initialize to use the copy constructor.
2684    InitializationKind InitKind =
2685      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2686
2687    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2688    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2689                                   &CtorArgE, 1);
2690
2691    ExprResult MemberInit
2692      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2693                        MultiExprArg(&CtorArgE, 1));
2694    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2695    if (MemberInit.isInvalid())
2696      return true;
2697
2698    if (Indirect) {
2699      assert(IndexVariables.size() == 0 &&
2700             "Indirect field improperly initialized");
2701      CXXMemberInit
2702        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2703                                                   Loc, Loc,
2704                                                   MemberInit.takeAs<Expr>(),
2705                                                   Loc);
2706    } else
2707      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2708                                                 Loc, MemberInit.takeAs<Expr>(),
2709                                                 Loc,
2710                                                 IndexVariables.data(),
2711                                                 IndexVariables.size());
2712    return false;
2713  }
2714
2715  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2716
2717  QualType FieldBaseElementType =
2718    SemaRef.Context.getBaseElementType(Field->getType());
2719
2720  if (FieldBaseElementType->isRecordType()) {
2721    InitializedEntity InitEntity
2722      = Indirect? InitializedEntity::InitializeMember(Indirect)
2723                : InitializedEntity::InitializeMember(Field);
2724    InitializationKind InitKind =
2725      InitializationKind::CreateDefault(Loc);
2726
2727    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2728    ExprResult MemberInit =
2729      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2730
2731    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2732    if (MemberInit.isInvalid())
2733      return true;
2734
2735    if (Indirect)
2736      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2737                                                               Indirect, Loc,
2738                                                               Loc,
2739                                                               MemberInit.get(),
2740                                                               Loc);
2741    else
2742      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2743                                                               Field, Loc, Loc,
2744                                                               MemberInit.get(),
2745                                                               Loc);
2746    return false;
2747  }
2748
2749  if (!Field->getParent()->isUnion()) {
2750    if (FieldBaseElementType->isReferenceType()) {
2751      SemaRef.Diag(Constructor->getLocation(),
2752                   diag::err_uninitialized_member_in_ctor)
2753      << (int)Constructor->isImplicit()
2754      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2755      << 0 << Field->getDeclName();
2756      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2757      return true;
2758    }
2759
2760    if (FieldBaseElementType.isConstQualified()) {
2761      SemaRef.Diag(Constructor->getLocation(),
2762                   diag::err_uninitialized_member_in_ctor)
2763      << (int)Constructor->isImplicit()
2764      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2765      << 1 << Field->getDeclName();
2766      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2767      return true;
2768    }
2769  }
2770
2771  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2772      FieldBaseElementType->isObjCRetainableType() &&
2773      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2774      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2775    // Instant objects:
2776    //   Default-initialize Objective-C pointers to NULL.
2777    CXXMemberInit
2778      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2779                                                 Loc, Loc,
2780                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2781                                                 Loc);
2782    return false;
2783  }
2784
2785  // Nothing to initialize.
2786  CXXMemberInit = 0;
2787  return false;
2788}
2789
2790namespace {
2791struct BaseAndFieldInfo {
2792  Sema &S;
2793  CXXConstructorDecl *Ctor;
2794  bool AnyErrorsInInits;
2795  ImplicitInitializerKind IIK;
2796  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2797  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2798
2799  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2800    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2801    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2802    if (Generated && Ctor->isCopyConstructor())
2803      IIK = IIK_Copy;
2804    else if (Generated && Ctor->isMoveConstructor())
2805      IIK = IIK_Move;
2806    else
2807      IIK = IIK_Default;
2808  }
2809
2810  bool isImplicitCopyOrMove() const {
2811    switch (IIK) {
2812    case IIK_Copy:
2813    case IIK_Move:
2814      return true;
2815
2816    case IIK_Default:
2817      return false;
2818    }
2819
2820    llvm_unreachable("Invalid ImplicitInitializerKind!");
2821  }
2822};
2823}
2824
2825/// \brief Determine whether the given indirect field declaration is somewhere
2826/// within an anonymous union.
2827static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2828  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2829                                      CEnd = F->chain_end();
2830       C != CEnd; ++C)
2831    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2832      if (Record->isUnion())
2833        return true;
2834
2835  return false;
2836}
2837
2838/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2839/// array type.
2840static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2841  if (T->isIncompleteArrayType())
2842    return true;
2843
2844  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2845    if (!ArrayT->getSize())
2846      return true;
2847
2848    T = ArrayT->getElementType();
2849  }
2850
2851  return false;
2852}
2853
2854static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2855                                    FieldDecl *Field,
2856                                    IndirectFieldDecl *Indirect = 0) {
2857
2858  // Overwhelmingly common case: we have a direct initializer for this field.
2859  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2860    Info.AllToInit.push_back(Init);
2861    return false;
2862  }
2863
2864  // C++0x [class.base.init]p8: if the entity is a non-static data member that
2865  // has a brace-or-equal-initializer, the entity is initialized as specified
2866  // in [dcl.init].
2867  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
2868    CXXCtorInitializer *Init;
2869    if (Indirect)
2870      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2871                                                      SourceLocation(),
2872                                                      SourceLocation(), 0,
2873                                                      SourceLocation());
2874    else
2875      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2876                                                      SourceLocation(),
2877                                                      SourceLocation(), 0,
2878                                                      SourceLocation());
2879    Info.AllToInit.push_back(Init);
2880
2881    // Check whether this initializer makes the field "used".
2882    Expr *InitExpr = Field->getInClassInitializer();
2883    if (Field->getType()->isRecordType() ||
2884        (InitExpr && InitExpr->HasSideEffects(SemaRef.Context)))
2885      SemaRef.UnusedPrivateFields.remove(Field);
2886
2887    return false;
2888  }
2889
2890  // Don't build an implicit initializer for union members if none was
2891  // explicitly specified.
2892  if (Field->getParent()->isUnion() ||
2893      (Indirect && isWithinAnonymousUnion(Indirect)))
2894    return false;
2895
2896  // Don't initialize incomplete or zero-length arrays.
2897  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2898    return false;
2899
2900  // Don't try to build an implicit initializer if there were semantic
2901  // errors in any of the initializers (and therefore we might be
2902  // missing some that the user actually wrote).
2903  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2904    return false;
2905
2906  CXXCtorInitializer *Init = 0;
2907  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2908                                     Indirect, Init))
2909    return true;
2910
2911  if (Init)
2912    Info.AllToInit.push_back(Init);
2913
2914  return false;
2915}
2916
2917bool
2918Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2919                               CXXCtorInitializer *Initializer) {
2920  assert(Initializer->isDelegatingInitializer());
2921  Constructor->setNumCtorInitializers(1);
2922  CXXCtorInitializer **initializer =
2923    new (Context) CXXCtorInitializer*[1];
2924  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2925  Constructor->setCtorInitializers(initializer);
2926
2927  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2928    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
2929    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2930  }
2931
2932  DelegatingCtorDecls.push_back(Constructor);
2933
2934  return false;
2935}
2936
2937bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2938                               CXXCtorInitializer **Initializers,
2939                               unsigned NumInitializers,
2940                               bool AnyErrors) {
2941  if (Constructor->isDependentContext()) {
2942    // Just store the initializers as written, they will be checked during
2943    // instantiation.
2944    if (NumInitializers > 0) {
2945      Constructor->setNumCtorInitializers(NumInitializers);
2946      CXXCtorInitializer **baseOrMemberInitializers =
2947        new (Context) CXXCtorInitializer*[NumInitializers];
2948      memcpy(baseOrMemberInitializers, Initializers,
2949             NumInitializers * sizeof(CXXCtorInitializer*));
2950      Constructor->setCtorInitializers(baseOrMemberInitializers);
2951    }
2952
2953    return false;
2954  }
2955
2956  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2957
2958  // We need to build the initializer AST according to order of construction
2959  // and not what user specified in the Initializers list.
2960  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2961  if (!ClassDecl)
2962    return true;
2963
2964  bool HadError = false;
2965
2966  for (unsigned i = 0; i < NumInitializers; i++) {
2967    CXXCtorInitializer *Member = Initializers[i];
2968
2969    if (Member->isBaseInitializer())
2970      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2971    else
2972      Info.AllBaseFields[Member->getAnyMember()] = Member;
2973  }
2974
2975  // Keep track of the direct virtual bases.
2976  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2977  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2978       E = ClassDecl->bases_end(); I != E; ++I) {
2979    if (I->isVirtual())
2980      DirectVBases.insert(I);
2981  }
2982
2983  // Push virtual bases before others.
2984  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2985       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2986
2987    if (CXXCtorInitializer *Value
2988        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2989      Info.AllToInit.push_back(Value);
2990    } else if (!AnyErrors) {
2991      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2992      CXXCtorInitializer *CXXBaseInit;
2993      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2994                                       VBase, IsInheritedVirtualBase,
2995                                       CXXBaseInit)) {
2996        HadError = true;
2997        continue;
2998      }
2999
3000      Info.AllToInit.push_back(CXXBaseInit);
3001    }
3002  }
3003
3004  // Non-virtual bases.
3005  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3006       E = ClassDecl->bases_end(); Base != E; ++Base) {
3007    // Virtuals are in the virtual base list and already constructed.
3008    if (Base->isVirtual())
3009      continue;
3010
3011    if (CXXCtorInitializer *Value
3012          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3013      Info.AllToInit.push_back(Value);
3014    } else if (!AnyErrors) {
3015      CXXCtorInitializer *CXXBaseInit;
3016      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3017                                       Base, /*IsInheritedVirtualBase=*/false,
3018                                       CXXBaseInit)) {
3019        HadError = true;
3020        continue;
3021      }
3022
3023      Info.AllToInit.push_back(CXXBaseInit);
3024    }
3025  }
3026
3027  // Fields.
3028  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3029                               MemEnd = ClassDecl->decls_end();
3030       Mem != MemEnd; ++Mem) {
3031    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3032      // C++ [class.bit]p2:
3033      //   A declaration for a bit-field that omits the identifier declares an
3034      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3035      //   initialized.
3036      if (F->isUnnamedBitfield())
3037        continue;
3038
3039      // If we're not generating the implicit copy/move constructor, then we'll
3040      // handle anonymous struct/union fields based on their individual
3041      // indirect fields.
3042      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
3043        continue;
3044
3045      if (CollectFieldInitializer(*this, Info, F))
3046        HadError = true;
3047      continue;
3048    }
3049
3050    // Beyond this point, we only consider default initialization.
3051    if (Info.IIK != IIK_Default)
3052      continue;
3053
3054    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3055      if (F->getType()->isIncompleteArrayType()) {
3056        assert(ClassDecl->hasFlexibleArrayMember() &&
3057               "Incomplete array type is not valid");
3058        continue;
3059      }
3060
3061      // Initialize each field of an anonymous struct individually.
3062      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3063        HadError = true;
3064
3065      continue;
3066    }
3067  }
3068
3069  NumInitializers = Info.AllToInit.size();
3070  if (NumInitializers > 0) {
3071    Constructor->setNumCtorInitializers(NumInitializers);
3072    CXXCtorInitializer **baseOrMemberInitializers =
3073      new (Context) CXXCtorInitializer*[NumInitializers];
3074    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3075           NumInitializers * sizeof(CXXCtorInitializer*));
3076    Constructor->setCtorInitializers(baseOrMemberInitializers);
3077
3078    // Constructors implicitly reference the base and member
3079    // destructors.
3080    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3081                                           Constructor->getParent());
3082  }
3083
3084  return HadError;
3085}
3086
3087static void *GetKeyForTopLevelField(FieldDecl *Field) {
3088  // For anonymous unions, use the class declaration as the key.
3089  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3090    if (RT->getDecl()->isAnonymousStructOrUnion())
3091      return static_cast<void *>(RT->getDecl());
3092  }
3093  return static_cast<void *>(Field);
3094}
3095
3096static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3097  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3098}
3099
3100static void *GetKeyForMember(ASTContext &Context,
3101                             CXXCtorInitializer *Member) {
3102  if (!Member->isAnyMemberInitializer())
3103    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3104
3105  // For fields injected into the class via declaration of an anonymous union,
3106  // use its anonymous union class declaration as the unique key.
3107  FieldDecl *Field = Member->getAnyMember();
3108
3109  // If the field is a member of an anonymous struct or union, our key
3110  // is the anonymous record decl that's a direct child of the class.
3111  RecordDecl *RD = Field->getParent();
3112  if (RD->isAnonymousStructOrUnion()) {
3113    while (true) {
3114      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3115      if (Parent->isAnonymousStructOrUnion())
3116        RD = Parent;
3117      else
3118        break;
3119    }
3120
3121    return static_cast<void *>(RD);
3122  }
3123
3124  return static_cast<void *>(Field);
3125}
3126
3127static void
3128DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3129                                  const CXXConstructorDecl *Constructor,
3130                                  CXXCtorInitializer **Inits,
3131                                  unsigned NumInits) {
3132  if (Constructor->getDeclContext()->isDependentContext())
3133    return;
3134
3135  // Don't check initializers order unless the warning is enabled at the
3136  // location of at least one initializer.
3137  bool ShouldCheckOrder = false;
3138  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3139    CXXCtorInitializer *Init = Inits[InitIndex];
3140    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3141                                         Init->getSourceLocation())
3142          != DiagnosticsEngine::Ignored) {
3143      ShouldCheckOrder = true;
3144      break;
3145    }
3146  }
3147  if (!ShouldCheckOrder)
3148    return;
3149
3150  // Build the list of bases and members in the order that they'll
3151  // actually be initialized.  The explicit initializers should be in
3152  // this same order but may be missing things.
3153  SmallVector<const void*, 32> IdealInitKeys;
3154
3155  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3156
3157  // 1. Virtual bases.
3158  for (CXXRecordDecl::base_class_const_iterator VBase =
3159       ClassDecl->vbases_begin(),
3160       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3161    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3162
3163  // 2. Non-virtual bases.
3164  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3165       E = ClassDecl->bases_end(); Base != E; ++Base) {
3166    if (Base->isVirtual())
3167      continue;
3168    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3169  }
3170
3171  // 3. Direct fields.
3172  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3173       E = ClassDecl->field_end(); Field != E; ++Field) {
3174    if (Field->isUnnamedBitfield())
3175      continue;
3176
3177    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3178  }
3179
3180  unsigned NumIdealInits = IdealInitKeys.size();
3181  unsigned IdealIndex = 0;
3182
3183  CXXCtorInitializer *PrevInit = 0;
3184  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3185    CXXCtorInitializer *Init = Inits[InitIndex];
3186    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3187
3188    // Scan forward to try to find this initializer in the idealized
3189    // initializers list.
3190    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3191      if (InitKey == IdealInitKeys[IdealIndex])
3192        break;
3193
3194    // If we didn't find this initializer, it must be because we
3195    // scanned past it on a previous iteration.  That can only
3196    // happen if we're out of order;  emit a warning.
3197    if (IdealIndex == NumIdealInits && PrevInit) {
3198      Sema::SemaDiagnosticBuilder D =
3199        SemaRef.Diag(PrevInit->getSourceLocation(),
3200                     diag::warn_initializer_out_of_order);
3201
3202      if (PrevInit->isAnyMemberInitializer())
3203        D << 0 << PrevInit->getAnyMember()->getDeclName();
3204      else
3205        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3206
3207      if (Init->isAnyMemberInitializer())
3208        D << 0 << Init->getAnyMember()->getDeclName();
3209      else
3210        D << 1 << Init->getTypeSourceInfo()->getType();
3211
3212      // Move back to the initializer's location in the ideal list.
3213      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3214        if (InitKey == IdealInitKeys[IdealIndex])
3215          break;
3216
3217      assert(IdealIndex != NumIdealInits &&
3218             "initializer not found in initializer list");
3219    }
3220
3221    PrevInit = Init;
3222  }
3223}
3224
3225namespace {
3226bool CheckRedundantInit(Sema &S,
3227                        CXXCtorInitializer *Init,
3228                        CXXCtorInitializer *&PrevInit) {
3229  if (!PrevInit) {
3230    PrevInit = Init;
3231    return false;
3232  }
3233
3234  if (FieldDecl *Field = Init->getMember())
3235    S.Diag(Init->getSourceLocation(),
3236           diag::err_multiple_mem_initialization)
3237      << Field->getDeclName()
3238      << Init->getSourceRange();
3239  else {
3240    const Type *BaseClass = Init->getBaseClass();
3241    assert(BaseClass && "neither field nor base");
3242    S.Diag(Init->getSourceLocation(),
3243           diag::err_multiple_base_initialization)
3244      << QualType(BaseClass, 0)
3245      << Init->getSourceRange();
3246  }
3247  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3248    << 0 << PrevInit->getSourceRange();
3249
3250  return true;
3251}
3252
3253typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3254typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3255
3256bool CheckRedundantUnionInit(Sema &S,
3257                             CXXCtorInitializer *Init,
3258                             RedundantUnionMap &Unions) {
3259  FieldDecl *Field = Init->getAnyMember();
3260  RecordDecl *Parent = Field->getParent();
3261  NamedDecl *Child = Field;
3262
3263  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3264    if (Parent->isUnion()) {
3265      UnionEntry &En = Unions[Parent];
3266      if (En.first && En.first != Child) {
3267        S.Diag(Init->getSourceLocation(),
3268               diag::err_multiple_mem_union_initialization)
3269          << Field->getDeclName()
3270          << Init->getSourceRange();
3271        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3272          << 0 << En.second->getSourceRange();
3273        return true;
3274      }
3275      if (!En.first) {
3276        En.first = Child;
3277        En.second = Init;
3278      }
3279      if (!Parent->isAnonymousStructOrUnion())
3280        return false;
3281    }
3282
3283    Child = Parent;
3284    Parent = cast<RecordDecl>(Parent->getDeclContext());
3285  }
3286
3287  return false;
3288}
3289}
3290
3291/// ActOnMemInitializers - Handle the member initializers for a constructor.
3292void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3293                                SourceLocation ColonLoc,
3294                                CXXCtorInitializer **meminits,
3295                                unsigned NumMemInits,
3296                                bool AnyErrors) {
3297  if (!ConstructorDecl)
3298    return;
3299
3300  AdjustDeclIfTemplate(ConstructorDecl);
3301
3302  CXXConstructorDecl *Constructor
3303    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3304
3305  if (!Constructor) {
3306    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3307    return;
3308  }
3309
3310  CXXCtorInitializer **MemInits =
3311    reinterpret_cast<CXXCtorInitializer **>(meminits);
3312
3313  // Mapping for the duplicate initializers check.
3314  // For member initializers, this is keyed with a FieldDecl*.
3315  // For base initializers, this is keyed with a Type*.
3316  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3317
3318  // Mapping for the inconsistent anonymous-union initializers check.
3319  RedundantUnionMap MemberUnions;
3320
3321  bool HadError = false;
3322  for (unsigned i = 0; i < NumMemInits; i++) {
3323    CXXCtorInitializer *Init = MemInits[i];
3324
3325    // Set the source order index.
3326    Init->setSourceOrder(i);
3327
3328    if (Init->isAnyMemberInitializer()) {
3329      FieldDecl *Field = Init->getAnyMember();
3330      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3331          CheckRedundantUnionInit(*this, Init, MemberUnions))
3332        HadError = true;
3333    } else if (Init->isBaseInitializer()) {
3334      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3335      if (CheckRedundantInit(*this, Init, Members[Key]))
3336        HadError = true;
3337    } else {
3338      assert(Init->isDelegatingInitializer());
3339      // This must be the only initializer
3340      if (i != 0 || NumMemInits > 1) {
3341        Diag(MemInits[0]->getSourceLocation(),
3342             diag::err_delegating_initializer_alone)
3343          << MemInits[0]->getSourceRange();
3344        HadError = true;
3345        // We will treat this as being the only initializer.
3346      }
3347      SetDelegatingInitializer(Constructor, MemInits[i]);
3348      // Return immediately as the initializer is set.
3349      return;
3350    }
3351  }
3352
3353  if (HadError)
3354    return;
3355
3356  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3357
3358  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3359}
3360
3361void
3362Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3363                                             CXXRecordDecl *ClassDecl) {
3364  // Ignore dependent contexts. Also ignore unions, since their members never
3365  // have destructors implicitly called.
3366  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3367    return;
3368
3369  // FIXME: all the access-control diagnostics are positioned on the
3370  // field/base declaration.  That's probably good; that said, the
3371  // user might reasonably want to know why the destructor is being
3372  // emitted, and we currently don't say.
3373
3374  // Non-static data members.
3375  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3376       E = ClassDecl->field_end(); I != E; ++I) {
3377    FieldDecl *Field = *I;
3378    if (Field->isInvalidDecl())
3379      continue;
3380
3381    // Don't destroy incomplete or zero-length arrays.
3382    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3383      continue;
3384
3385    QualType FieldType = Context.getBaseElementType(Field->getType());
3386
3387    const RecordType* RT = FieldType->getAs<RecordType>();
3388    if (!RT)
3389      continue;
3390
3391    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3392    if (FieldClassDecl->isInvalidDecl())
3393      continue;
3394    if (FieldClassDecl->hasIrrelevantDestructor())
3395      continue;
3396    // The destructor for an implicit anonymous union member is never invoked.
3397    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3398      continue;
3399
3400    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3401    assert(Dtor && "No dtor found for FieldClassDecl!");
3402    CheckDestructorAccess(Field->getLocation(), Dtor,
3403                          PDiag(diag::err_access_dtor_field)
3404                            << Field->getDeclName()
3405                            << FieldType);
3406
3407    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3408    DiagnoseUseOfDecl(Dtor, Location);
3409  }
3410
3411  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3412
3413  // Bases.
3414  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3415       E = ClassDecl->bases_end(); Base != E; ++Base) {
3416    // Bases are always records in a well-formed non-dependent class.
3417    const RecordType *RT = Base->getType()->getAs<RecordType>();
3418
3419    // Remember direct virtual bases.
3420    if (Base->isVirtual())
3421      DirectVirtualBases.insert(RT);
3422
3423    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3424    // If our base class is invalid, we probably can't get its dtor anyway.
3425    if (BaseClassDecl->isInvalidDecl())
3426      continue;
3427    if (BaseClassDecl->hasIrrelevantDestructor())
3428      continue;
3429
3430    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3431    assert(Dtor && "No dtor found for BaseClassDecl!");
3432
3433    // FIXME: caret should be on the start of the class name
3434    CheckDestructorAccess(Base->getLocStart(), Dtor,
3435                          PDiag(diag::err_access_dtor_base)
3436                            << Base->getType()
3437                            << Base->getSourceRange(),
3438                          Context.getTypeDeclType(ClassDecl));
3439
3440    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3441    DiagnoseUseOfDecl(Dtor, Location);
3442  }
3443
3444  // Virtual bases.
3445  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3446       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3447
3448    // Bases are always records in a well-formed non-dependent class.
3449    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3450
3451    // Ignore direct virtual bases.
3452    if (DirectVirtualBases.count(RT))
3453      continue;
3454
3455    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3456    // If our base class is invalid, we probably can't get its dtor anyway.
3457    if (BaseClassDecl->isInvalidDecl())
3458      continue;
3459    if (BaseClassDecl->hasIrrelevantDestructor())
3460      continue;
3461
3462    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3463    assert(Dtor && "No dtor found for BaseClassDecl!");
3464    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3465                          PDiag(diag::err_access_dtor_vbase)
3466                            << VBase->getType(),
3467                          Context.getTypeDeclType(ClassDecl));
3468
3469    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3470    DiagnoseUseOfDecl(Dtor, Location);
3471  }
3472}
3473
3474void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3475  if (!CDtorDecl)
3476    return;
3477
3478  if (CXXConstructorDecl *Constructor
3479      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3480    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3481}
3482
3483bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3484                                  unsigned DiagID, AbstractDiagSelID SelID) {
3485  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
3486    unsigned DiagID;
3487    AbstractDiagSelID SelID;
3488
3489  public:
3490    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
3491      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
3492
3493    virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
3494      if (SelID == -1)
3495        S.Diag(Loc, DiagID) << T;
3496      else
3497        S.Diag(Loc, DiagID) << SelID << T;
3498    }
3499  } Diagnoser(DiagID, SelID);
3500
3501  return RequireNonAbstractType(Loc, T, Diagnoser);
3502}
3503
3504bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3505                                  TypeDiagnoser &Diagnoser) {
3506  if (!getLangOpts().CPlusPlus)
3507    return false;
3508
3509  if (const ArrayType *AT = Context.getAsArrayType(T))
3510    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3511
3512  if (const PointerType *PT = T->getAs<PointerType>()) {
3513    // Find the innermost pointer type.
3514    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3515      PT = T;
3516
3517    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3518      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
3519  }
3520
3521  const RecordType *RT = T->getAs<RecordType>();
3522  if (!RT)
3523    return false;
3524
3525  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3526
3527  // We can't answer whether something is abstract until it has a
3528  // definition.  If it's currently being defined, we'll walk back
3529  // over all the declarations when we have a full definition.
3530  const CXXRecordDecl *Def = RD->getDefinition();
3531  if (!Def || Def->isBeingDefined())
3532    return false;
3533
3534  if (!RD->isAbstract())
3535    return false;
3536
3537  Diagnoser.diagnose(*this, Loc, T);
3538  DiagnoseAbstractType(RD);
3539
3540  return true;
3541}
3542
3543void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3544  // Check if we've already emitted the list of pure virtual functions
3545  // for this class.
3546  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3547    return;
3548
3549  CXXFinalOverriderMap FinalOverriders;
3550  RD->getFinalOverriders(FinalOverriders);
3551
3552  // Keep a set of seen pure methods so we won't diagnose the same method
3553  // more than once.
3554  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3555
3556  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3557                                   MEnd = FinalOverriders.end();
3558       M != MEnd;
3559       ++M) {
3560    for (OverridingMethods::iterator SO = M->second.begin(),
3561                                  SOEnd = M->second.end();
3562         SO != SOEnd; ++SO) {
3563      // C++ [class.abstract]p4:
3564      //   A class is abstract if it contains or inherits at least one
3565      //   pure virtual function for which the final overrider is pure
3566      //   virtual.
3567
3568      //
3569      if (SO->second.size() != 1)
3570        continue;
3571
3572      if (!SO->second.front().Method->isPure())
3573        continue;
3574
3575      if (!SeenPureMethods.insert(SO->second.front().Method))
3576        continue;
3577
3578      Diag(SO->second.front().Method->getLocation(),
3579           diag::note_pure_virtual_function)
3580        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3581    }
3582  }
3583
3584  if (!PureVirtualClassDiagSet)
3585    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3586  PureVirtualClassDiagSet->insert(RD);
3587}
3588
3589namespace {
3590struct AbstractUsageInfo {
3591  Sema &S;
3592  CXXRecordDecl *Record;
3593  CanQualType AbstractType;
3594  bool Invalid;
3595
3596  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3597    : S(S), Record(Record),
3598      AbstractType(S.Context.getCanonicalType(
3599                   S.Context.getTypeDeclType(Record))),
3600      Invalid(false) {}
3601
3602  void DiagnoseAbstractType() {
3603    if (Invalid) return;
3604    S.DiagnoseAbstractType(Record);
3605    Invalid = true;
3606  }
3607
3608  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3609};
3610
3611struct CheckAbstractUsage {
3612  AbstractUsageInfo &Info;
3613  const NamedDecl *Ctx;
3614
3615  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3616    : Info(Info), Ctx(Ctx) {}
3617
3618  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3619    switch (TL.getTypeLocClass()) {
3620#define ABSTRACT_TYPELOC(CLASS, PARENT)
3621#define TYPELOC(CLASS, PARENT) \
3622    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3623#include "clang/AST/TypeLocNodes.def"
3624    }
3625  }
3626
3627  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3628    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3629    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3630      if (!TL.getArg(I))
3631        continue;
3632
3633      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3634      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3635    }
3636  }
3637
3638  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3639    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3640  }
3641
3642  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3643    // Visit the type parameters from a permissive context.
3644    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3645      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3646      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3647        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3648          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3649      // TODO: other template argument types?
3650    }
3651  }
3652
3653  // Visit pointee types from a permissive context.
3654#define CheckPolymorphic(Type) \
3655  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3656    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3657  }
3658  CheckPolymorphic(PointerTypeLoc)
3659  CheckPolymorphic(ReferenceTypeLoc)
3660  CheckPolymorphic(MemberPointerTypeLoc)
3661  CheckPolymorphic(BlockPointerTypeLoc)
3662  CheckPolymorphic(AtomicTypeLoc)
3663
3664  /// Handle all the types we haven't given a more specific
3665  /// implementation for above.
3666  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3667    // Every other kind of type that we haven't called out already
3668    // that has an inner type is either (1) sugar or (2) contains that
3669    // inner type in some way as a subobject.
3670    if (TypeLoc Next = TL.getNextTypeLoc())
3671      return Visit(Next, Sel);
3672
3673    // If there's no inner type and we're in a permissive context,
3674    // don't diagnose.
3675    if (Sel == Sema::AbstractNone) return;
3676
3677    // Check whether the type matches the abstract type.
3678    QualType T = TL.getType();
3679    if (T->isArrayType()) {
3680      Sel = Sema::AbstractArrayType;
3681      T = Info.S.Context.getBaseElementType(T);
3682    }
3683    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3684    if (CT != Info.AbstractType) return;
3685
3686    // It matched; do some magic.
3687    if (Sel == Sema::AbstractArrayType) {
3688      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3689        << T << TL.getSourceRange();
3690    } else {
3691      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3692        << Sel << T << TL.getSourceRange();
3693    }
3694    Info.DiagnoseAbstractType();
3695  }
3696};
3697
3698void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3699                                  Sema::AbstractDiagSelID Sel) {
3700  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3701}
3702
3703}
3704
3705/// Check for invalid uses of an abstract type in a method declaration.
3706static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3707                                    CXXMethodDecl *MD) {
3708  // No need to do the check on definitions, which require that
3709  // the return/param types be complete.
3710  if (MD->doesThisDeclarationHaveABody())
3711    return;
3712
3713  // For safety's sake, just ignore it if we don't have type source
3714  // information.  This should never happen for non-implicit methods,
3715  // but...
3716  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3717    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3718}
3719
3720/// Check for invalid uses of an abstract type within a class definition.
3721static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3722                                    CXXRecordDecl *RD) {
3723  for (CXXRecordDecl::decl_iterator
3724         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3725    Decl *D = *I;
3726    if (D->isImplicit()) continue;
3727
3728    // Methods and method templates.
3729    if (isa<CXXMethodDecl>(D)) {
3730      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3731    } else if (isa<FunctionTemplateDecl>(D)) {
3732      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3733      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3734
3735    // Fields and static variables.
3736    } else if (isa<FieldDecl>(D)) {
3737      FieldDecl *FD = cast<FieldDecl>(D);
3738      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3739        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3740    } else if (isa<VarDecl>(D)) {
3741      VarDecl *VD = cast<VarDecl>(D);
3742      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3743        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3744
3745    // Nested classes and class templates.
3746    } else if (isa<CXXRecordDecl>(D)) {
3747      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3748    } else if (isa<ClassTemplateDecl>(D)) {
3749      CheckAbstractClassUsage(Info,
3750                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3751    }
3752  }
3753}
3754
3755/// \brief Perform semantic checks on a class definition that has been
3756/// completing, introducing implicitly-declared members, checking for
3757/// abstract types, etc.
3758void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3759  if (!Record)
3760    return;
3761
3762  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3763    AbstractUsageInfo Info(*this, Record);
3764    CheckAbstractClassUsage(Info, Record);
3765  }
3766
3767  // If this is not an aggregate type and has no user-declared constructor,
3768  // complain about any non-static data members of reference or const scalar
3769  // type, since they will never get initializers.
3770  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3771      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3772      !Record->isLambda()) {
3773    bool Complained = false;
3774    for (RecordDecl::field_iterator F = Record->field_begin(),
3775                                 FEnd = Record->field_end();
3776         F != FEnd; ++F) {
3777      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3778        continue;
3779
3780      if (F->getType()->isReferenceType() ||
3781          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3782        if (!Complained) {
3783          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3784            << Record->getTagKind() << Record;
3785          Complained = true;
3786        }
3787
3788        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3789          << F->getType()->isReferenceType()
3790          << F->getDeclName();
3791      }
3792    }
3793  }
3794
3795  if (Record->isDynamicClass() && !Record->isDependentType())
3796    DynamicClasses.push_back(Record);
3797
3798  if (Record->getIdentifier()) {
3799    // C++ [class.mem]p13:
3800    //   If T is the name of a class, then each of the following shall have a
3801    //   name different from T:
3802    //     - every member of every anonymous union that is a member of class T.
3803    //
3804    // C++ [class.mem]p14:
3805    //   In addition, if class T has a user-declared constructor (12.1), every
3806    //   non-static data member of class T shall have a name different from T.
3807    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3808         R.first != R.second; ++R.first) {
3809      NamedDecl *D = *R.first;
3810      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3811          isa<IndirectFieldDecl>(D)) {
3812        Diag(D->getLocation(), diag::err_member_name_of_class)
3813          << D->getDeclName();
3814        break;
3815      }
3816    }
3817  }
3818
3819  // Warn if the class has virtual methods but non-virtual public destructor.
3820  if (Record->isPolymorphic() && !Record->isDependentType()) {
3821    CXXDestructorDecl *dtor = Record->getDestructor();
3822    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3823      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3824           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3825  }
3826
3827  // See if a method overloads virtual methods in a base
3828  /// class without overriding any.
3829  if (!Record->isDependentType()) {
3830    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3831                                     MEnd = Record->method_end();
3832         M != MEnd; ++M) {
3833      if (!M->isStatic())
3834        DiagnoseHiddenVirtualMethods(Record, *M);
3835    }
3836  }
3837
3838  // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3839  // function that is not a constructor declares that member function to be
3840  // const. [...] The class of which that function is a member shall be
3841  // a literal type.
3842  //
3843  // If the class has virtual bases, any constexpr members will already have
3844  // been diagnosed by the checks performed on the member declaration, so
3845  // suppress this (less useful) diagnostic.
3846  if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3847      !Record->isLiteral() && !Record->getNumVBases()) {
3848    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3849                                     MEnd = Record->method_end();
3850         M != MEnd; ++M) {
3851      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3852        switch (Record->getTemplateSpecializationKind()) {
3853        case TSK_ImplicitInstantiation:
3854        case TSK_ExplicitInstantiationDeclaration:
3855        case TSK_ExplicitInstantiationDefinition:
3856          // If a template instantiates to a non-literal type, but its members
3857          // instantiate to constexpr functions, the template is technically
3858          // ill-formed, but we allow it for sanity.
3859          continue;
3860
3861        case TSK_Undeclared:
3862        case TSK_ExplicitSpecialization:
3863          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
3864                             diag::err_constexpr_method_non_literal);
3865          break;
3866        }
3867
3868        // Only produce one error per class.
3869        break;
3870      }
3871    }
3872  }
3873
3874  // Declare inherited constructors. We do this eagerly here because:
3875  // - The standard requires an eager diagnostic for conflicting inherited
3876  //   constructors from different classes.
3877  // - The lazy declaration of the other implicit constructors is so as to not
3878  //   waste space and performance on classes that are not meant to be
3879  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3880  //   have inherited constructors.
3881  DeclareInheritedConstructors(Record);
3882
3883  if (!Record->isDependentType())
3884    CheckExplicitlyDefaultedMethods(Record);
3885}
3886
3887void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3888  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3889                                      ME = Record->method_end();
3890       MI != ME; ++MI)
3891    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted())
3892      CheckExplicitlyDefaultedSpecialMember(*MI);
3893}
3894
3895/// Is the special member function which would be selected to perform the
3896/// specified operation on the specified class type a constexpr constructor?
3897static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3898                                     Sema::CXXSpecialMember CSM,
3899                                     bool ConstArg) {
3900  Sema::SpecialMemberOverloadResult *SMOR =
3901      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
3902                            false, false, false, false);
3903  if (!SMOR || !SMOR->getMethod())
3904    // A constructor we wouldn't select can't be "involved in initializing"
3905    // anything.
3906    return true;
3907  return SMOR->getMethod()->isConstexpr();
3908}
3909
3910/// Determine whether the specified special member function would be constexpr
3911/// if it were implicitly defined.
3912static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
3913                                              Sema::CXXSpecialMember CSM,
3914                                              bool ConstArg) {
3915  if (!S.getLangOpts().CPlusPlus0x)
3916    return false;
3917
3918  // C++11 [dcl.constexpr]p4:
3919  // In the definition of a constexpr constructor [...]
3920  switch (CSM) {
3921  case Sema::CXXDefaultConstructor:
3922    // Since default constructor lookup is essentially trivial (and cannot
3923    // involve, for instance, template instantiation), we compute whether a
3924    // defaulted default constructor is constexpr directly within CXXRecordDecl.
3925    //
3926    // This is important for performance; we need to know whether the default
3927    // constructor is constexpr to determine whether the type is a literal type.
3928    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
3929
3930  case Sema::CXXCopyConstructor:
3931  case Sema::CXXMoveConstructor:
3932    // For copy or move constructors, we need to perform overload resolution.
3933    break;
3934
3935  case Sema::CXXCopyAssignment:
3936  case Sema::CXXMoveAssignment:
3937  case Sema::CXXDestructor:
3938  case Sema::CXXInvalid:
3939    return false;
3940  }
3941
3942  //   -- if the class is a non-empty union, or for each non-empty anonymous
3943  //      union member of a non-union class, exactly one non-static data member
3944  //      shall be initialized; [DR1359]
3945  //
3946  // If we squint, this is guaranteed, since exactly one non-static data member
3947  // will be initialized (if the constructor isn't deleted), we just don't know
3948  // which one.
3949  if (ClassDecl->isUnion())
3950    return true;
3951
3952  //   -- the class shall not have any virtual base classes;
3953  if (ClassDecl->getNumVBases())
3954    return false;
3955
3956  //   -- every constructor involved in initializing [...] base class
3957  //      sub-objects shall be a constexpr constructor;
3958  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
3959                                       BEnd = ClassDecl->bases_end();
3960       B != BEnd; ++B) {
3961    const RecordType *BaseType = B->getType()->getAs<RecordType>();
3962    if (!BaseType) continue;
3963
3964    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3965    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
3966      return false;
3967  }
3968
3969  //   -- every constructor involved in initializing non-static data members
3970  //      [...] shall be a constexpr constructor;
3971  //   -- every non-static data member and base class sub-object shall be
3972  //      initialized
3973  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
3974                               FEnd = ClassDecl->field_end();
3975       F != FEnd; ++F) {
3976    if (F->isInvalidDecl())
3977      continue;
3978    if (const RecordType *RecordTy =
3979            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
3980      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
3981      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
3982        return false;
3983    }
3984  }
3985
3986  // All OK, it's constexpr!
3987  return true;
3988}
3989
3990void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
3991  CXXRecordDecl *RD = MD->getParent();
3992  CXXSpecialMember CSM = getSpecialMember(MD);
3993
3994  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
3995         "not an explicitly-defaulted special member");
3996
3997  // Whether this was the first-declared instance of the constructor.
3998  // This affects whether we implicitly add an exception spec and constexpr.
3999  bool First = MD == MD->getCanonicalDecl();
4000
4001  bool HadError = false;
4002
4003  // C++11 [dcl.fct.def.default]p1:
4004  //   A function that is explicitly defaulted shall
4005  //     -- be a special member function (checked elsewhere),
4006  //     -- have the same type (except for ref-qualifiers, and except that a
4007  //        copy operation can take a non-const reference) as an implicit
4008  //        declaration, and
4009  //     -- not have default arguments.
4010  unsigned ExpectedParams = 1;
4011  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4012    ExpectedParams = 0;
4013  if (MD->getNumParams() != ExpectedParams) {
4014    // This also checks for default arguments: a copy or move constructor with a
4015    // default argument is classified as a default constructor, and assignment
4016    // operations and destructors can't have default arguments.
4017    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4018      << CSM << MD->getSourceRange();
4019    HadError = true;
4020  }
4021
4022  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4023
4024  // Compute implicit exception specification, argument constness, constexpr
4025  // and triviality.
4026  ImplicitExceptionSpecification Spec(*this);
4027  bool CanHaveConstParam = false;
4028  bool Trivial;
4029  switch (CSM) {
4030  case CXXDefaultConstructor:
4031    Spec = ComputeDefaultedDefaultCtorExceptionSpec(RD);
4032    if (Spec.isDelayed())
4033      // Exception specification depends on some deferred part of the class.
4034      // We'll try again when the class's definition has been fully processed.
4035      return;
4036    Trivial = RD->hasTrivialDefaultConstructor();
4037    break;
4038  case CXXCopyConstructor:
4039    llvm::tie(Spec, CanHaveConstParam) =
4040      ComputeDefaultedCopyCtorExceptionSpecAndConst(RD);
4041    Trivial = RD->hasTrivialCopyConstructor();
4042    break;
4043  case CXXCopyAssignment:
4044    llvm::tie(Spec, CanHaveConstParam) =
4045      ComputeDefaultedCopyAssignmentExceptionSpecAndConst(RD);
4046    Trivial = RD->hasTrivialCopyAssignment();
4047    break;
4048  case CXXMoveConstructor:
4049    Spec = ComputeDefaultedMoveCtorExceptionSpec(RD);
4050    Trivial = RD->hasTrivialMoveConstructor();
4051    break;
4052  case CXXMoveAssignment:
4053    Spec = ComputeDefaultedMoveAssignmentExceptionSpec(RD);
4054    Trivial = RD->hasTrivialMoveAssignment();
4055    break;
4056  case CXXDestructor:
4057    Spec = ComputeDefaultedDtorExceptionSpec(RD);
4058    Trivial = RD->hasTrivialDestructor();
4059    break;
4060  case CXXInvalid:
4061    llvm_unreachable("non-special member explicitly defaulted!");
4062  }
4063
4064  QualType ReturnType = Context.VoidTy;
4065  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4066    // Check for return type matching.
4067    ReturnType = Type->getResultType();
4068    QualType ExpectedReturnType =
4069        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4070    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4071      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4072        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4073      HadError = true;
4074    }
4075
4076    // A defaulted special member cannot have cv-qualifiers.
4077    if (Type->getTypeQuals()) {
4078      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4079        << (CSM == CXXMoveAssignment);
4080      HadError = true;
4081    }
4082  }
4083
4084  // Check for parameter type matching.
4085  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4086  bool HasConstParam = false;
4087  if (ExpectedParams && ArgType->isReferenceType()) {
4088    // Argument must be reference to possibly-const T.
4089    QualType ReferentType = ArgType->getPointeeType();
4090    HasConstParam = ReferentType.isConstQualified();
4091
4092    if (ReferentType.isVolatileQualified()) {
4093      Diag(MD->getLocation(),
4094           diag::err_defaulted_special_member_volatile_param) << CSM;
4095      HadError = true;
4096    }
4097
4098    if (HasConstParam && !CanHaveConstParam) {
4099      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4100        Diag(MD->getLocation(),
4101             diag::err_defaulted_special_member_copy_const_param)
4102          << (CSM == CXXCopyAssignment);
4103        // FIXME: Explain why this special member can't be const.
4104      } else {
4105        Diag(MD->getLocation(),
4106             diag::err_defaulted_special_member_move_const_param)
4107          << (CSM == CXXMoveAssignment);
4108      }
4109      HadError = true;
4110    }
4111
4112    // If a function is explicitly defaulted on its first declaration, it shall
4113    // have the same parameter type as if it had been implicitly declared.
4114    // (Presumably this is to prevent it from being trivial?)
4115    if (!HasConstParam && CanHaveConstParam && First)
4116      Diag(MD->getLocation(),
4117           diag::err_defaulted_special_member_copy_non_const_param)
4118        << (CSM == CXXCopyAssignment);
4119  } else if (ExpectedParams) {
4120    // A copy assignment operator can take its argument by value, but a
4121    // defaulted one cannot.
4122    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4123    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4124    HadError = true;
4125  }
4126
4127  // Rebuild the type with the implicit exception specification added.
4128  FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4129  Spec.getEPI(EPI);
4130  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4131    Context.getFunctionType(ReturnType, &ArgType, ExpectedParams, EPI));
4132
4133  // C++11 [dcl.fct.def.default]p2:
4134  //   An explicitly-defaulted function may be declared constexpr only if it
4135  //   would have been implicitly declared as constexpr,
4136  // Do not apply this rule to members of class templates, since core issue 1358
4137  // makes such functions always instantiate to constexpr functions. For
4138  // non-constructors, this is checked elsewhere.
4139  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4140                                                     HasConstParam);
4141  if (isa<CXXConstructorDecl>(MD) && MD->isConstexpr() && !Constexpr &&
4142      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4143    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4144    // FIXME: Explain why the constructor can't be constexpr.
4145    HadError = true;
4146  }
4147  //   and may have an explicit exception-specification only if it is compatible
4148  //   with the exception-specification on the implicit declaration.
4149  if (Type->hasExceptionSpec() &&
4150      CheckEquivalentExceptionSpec(
4151        PDiag(diag::err_incorrect_defaulted_exception_spec) << CSM,
4152        PDiag(), ImplicitType, SourceLocation(), Type, MD->getLocation()))
4153    HadError = true;
4154
4155  //   If a function is explicitly defaulted on its first declaration,
4156  if (First) {
4157    //  -- it is implicitly considered to be constexpr if the implicit
4158    //     definition would be,
4159    MD->setConstexpr(Constexpr);
4160
4161    //  -- it is implicitly considered to have the same exception-specification
4162    //     as if it had been implicitly declared,
4163    MD->setType(QualType(ImplicitType, 0));
4164
4165    // Such a function is also trivial if the implicitly-declared function
4166    // would have been.
4167    MD->setTrivial(Trivial);
4168  }
4169
4170  if (ShouldDeleteSpecialMember(MD, CSM)) {
4171    if (First) {
4172      MD->setDeletedAsWritten();
4173    } else {
4174      // C++11 [dcl.fct.def.default]p4:
4175      //   [For a] user-provided explicitly-defaulted function [...] if such a
4176      //   function is implicitly defined as deleted, the program is ill-formed.
4177      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4178      HadError = true;
4179    }
4180  }
4181
4182  if (HadError)
4183    MD->setInvalidDecl();
4184}
4185
4186namespace {
4187struct SpecialMemberDeletionInfo {
4188  Sema &S;
4189  CXXMethodDecl *MD;
4190  Sema::CXXSpecialMember CSM;
4191  bool Diagnose;
4192
4193  // Properties of the special member, computed for convenience.
4194  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4195  SourceLocation Loc;
4196
4197  bool AllFieldsAreConst;
4198
4199  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4200                            Sema::CXXSpecialMember CSM, bool Diagnose)
4201    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4202      IsConstructor(false), IsAssignment(false), IsMove(false),
4203      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4204      AllFieldsAreConst(true) {
4205    switch (CSM) {
4206      case Sema::CXXDefaultConstructor:
4207      case Sema::CXXCopyConstructor:
4208        IsConstructor = true;
4209        break;
4210      case Sema::CXXMoveConstructor:
4211        IsConstructor = true;
4212        IsMove = true;
4213        break;
4214      case Sema::CXXCopyAssignment:
4215        IsAssignment = true;
4216        break;
4217      case Sema::CXXMoveAssignment:
4218        IsAssignment = true;
4219        IsMove = true;
4220        break;
4221      case Sema::CXXDestructor:
4222        break;
4223      case Sema::CXXInvalid:
4224        llvm_unreachable("invalid special member kind");
4225    }
4226
4227    if (MD->getNumParams()) {
4228      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4229      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4230    }
4231  }
4232
4233  bool inUnion() const { return MD->getParent()->isUnion(); }
4234
4235  /// Look up the corresponding special member in the given class.
4236  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4237    unsigned TQ = MD->getTypeQualifiers();
4238    return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4239                                 MD->getRefQualifier() == RQ_RValue,
4240                                 TQ & Qualifiers::Const,
4241                                 TQ & Qualifiers::Volatile);
4242  }
4243
4244  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4245
4246  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4247  bool shouldDeleteForField(FieldDecl *FD);
4248  bool shouldDeleteForAllConstMembers();
4249
4250  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
4251  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4252                                    Sema::SpecialMemberOverloadResult *SMOR,
4253                                    bool IsDtorCallInCtor);
4254
4255  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4256};
4257}
4258
4259/// Is the given special member inaccessible when used on the given
4260/// sub-object.
4261bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4262                                             CXXMethodDecl *target) {
4263  /// If we're operating on a base class, the object type is the
4264  /// type of this special member.
4265  QualType objectTy;
4266  AccessSpecifier access = target->getAccess();;
4267  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4268    objectTy = S.Context.getTypeDeclType(MD->getParent());
4269    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4270
4271  // If we're operating on a field, the object type is the type of the field.
4272  } else {
4273    objectTy = S.Context.getTypeDeclType(target->getParent());
4274  }
4275
4276  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4277}
4278
4279/// Check whether we should delete a special member due to the implicit
4280/// definition containing a call to a special member of a subobject.
4281bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4282    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4283    bool IsDtorCallInCtor) {
4284  CXXMethodDecl *Decl = SMOR->getMethod();
4285  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4286
4287  int DiagKind = -1;
4288
4289  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4290    DiagKind = !Decl ? 0 : 1;
4291  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4292    DiagKind = 2;
4293  else if (!isAccessible(Subobj, Decl))
4294    DiagKind = 3;
4295  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4296           !Decl->isTrivial()) {
4297    // A member of a union must have a trivial corresponding special member.
4298    // As a weird special case, a destructor call from a union's constructor
4299    // must be accessible and non-deleted, but need not be trivial. Such a
4300    // destructor is never actually called, but is semantically checked as
4301    // if it were.
4302    DiagKind = 4;
4303  }
4304
4305  if (DiagKind == -1)
4306    return false;
4307
4308  if (Diagnose) {
4309    if (Field) {
4310      S.Diag(Field->getLocation(),
4311             diag::note_deleted_special_member_class_subobject)
4312        << CSM << MD->getParent() << /*IsField*/true
4313        << Field << DiagKind << IsDtorCallInCtor;
4314    } else {
4315      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4316      S.Diag(Base->getLocStart(),
4317             diag::note_deleted_special_member_class_subobject)
4318        << CSM << MD->getParent() << /*IsField*/false
4319        << Base->getType() << DiagKind << IsDtorCallInCtor;
4320    }
4321
4322    if (DiagKind == 1)
4323      S.NoteDeletedFunction(Decl);
4324    // FIXME: Explain inaccessibility if DiagKind == 3.
4325  }
4326
4327  return true;
4328}
4329
4330/// Check whether we should delete a special member function due to having a
4331/// direct or virtual base class or static data member of class type M.
4332bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4333    CXXRecordDecl *Class, Subobject Subobj) {
4334  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4335
4336  // C++11 [class.ctor]p5:
4337  // -- any direct or virtual base class, or non-static data member with no
4338  //    brace-or-equal-initializer, has class type M (or array thereof) and
4339  //    either M has no default constructor or overload resolution as applied
4340  //    to M's default constructor results in an ambiguity or in a function
4341  //    that is deleted or inaccessible
4342  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4343  // -- a direct or virtual base class B that cannot be copied/moved because
4344  //    overload resolution, as applied to B's corresponding special member,
4345  //    results in an ambiguity or a function that is deleted or inaccessible
4346  //    from the defaulted special member
4347  // C++11 [class.dtor]p5:
4348  // -- any direct or virtual base class [...] has a type with a destructor
4349  //    that is deleted or inaccessible
4350  if (!(CSM == Sema::CXXDefaultConstructor &&
4351        Field && Field->hasInClassInitializer()) &&
4352      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
4353    return true;
4354
4355  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4356  // -- any direct or virtual base class or non-static data member has a
4357  //    type with a destructor that is deleted or inaccessible
4358  if (IsConstructor) {
4359    Sema::SpecialMemberOverloadResult *SMOR =
4360        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4361                              false, false, false, false, false);
4362    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4363      return true;
4364  }
4365
4366  return false;
4367}
4368
4369/// Check whether we should delete a special member function due to the class
4370/// having a particular direct or virtual base class.
4371bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4372  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4373  return shouldDeleteForClassSubobject(BaseClass, Base);
4374}
4375
4376/// Check whether we should delete a special member function due to the class
4377/// having a particular non-static data member.
4378bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4379  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4380  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4381
4382  if (CSM == Sema::CXXDefaultConstructor) {
4383    // For a default constructor, all references must be initialized in-class
4384    // and, if a union, it must have a non-const member.
4385    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4386      if (Diagnose)
4387        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4388          << MD->getParent() << FD << FieldType << /*Reference*/0;
4389      return true;
4390    }
4391    // C++11 [class.ctor]p5: any non-variant non-static data member of
4392    // const-qualified type (or array thereof) with no
4393    // brace-or-equal-initializer does not have a user-provided default
4394    // constructor.
4395    if (!inUnion() && FieldType.isConstQualified() &&
4396        !FD->hasInClassInitializer() &&
4397        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4398      if (Diagnose)
4399        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4400          << MD->getParent() << FD << FD->getType() << /*Const*/1;
4401      return true;
4402    }
4403
4404    if (inUnion() && !FieldType.isConstQualified())
4405      AllFieldsAreConst = false;
4406  } else if (CSM == Sema::CXXCopyConstructor) {
4407    // For a copy constructor, data members must not be of rvalue reference
4408    // type.
4409    if (FieldType->isRValueReferenceType()) {
4410      if (Diagnose)
4411        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4412          << MD->getParent() << FD << FieldType;
4413      return true;
4414    }
4415  } else if (IsAssignment) {
4416    // For an assignment operator, data members must not be of reference type.
4417    if (FieldType->isReferenceType()) {
4418      if (Diagnose)
4419        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4420          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4421      return true;
4422    }
4423    if (!FieldRecord && FieldType.isConstQualified()) {
4424      // C++11 [class.copy]p23:
4425      // -- a non-static data member of const non-class type (or array thereof)
4426      if (Diagnose)
4427        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4428          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
4429      return true;
4430    }
4431  }
4432
4433  if (FieldRecord) {
4434    // Some additional restrictions exist on the variant members.
4435    if (!inUnion() && FieldRecord->isUnion() &&
4436        FieldRecord->isAnonymousStructOrUnion()) {
4437      bool AllVariantFieldsAreConst = true;
4438
4439      // FIXME: Handle anonymous unions declared within anonymous unions.
4440      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4441                                         UE = FieldRecord->field_end();
4442           UI != UE; ++UI) {
4443        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4444
4445        if (!UnionFieldType.isConstQualified())
4446          AllVariantFieldsAreConst = false;
4447
4448        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4449        if (UnionFieldRecord &&
4450            shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4451          return true;
4452      }
4453
4454      // At least one member in each anonymous union must be non-const
4455      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4456          FieldRecord->field_begin() != FieldRecord->field_end()) {
4457        if (Diagnose)
4458          S.Diag(FieldRecord->getLocation(),
4459                 diag::note_deleted_default_ctor_all_const)
4460            << MD->getParent() << /*anonymous union*/1;
4461        return true;
4462      }
4463
4464      // Don't check the implicit member of the anonymous union type.
4465      // This is technically non-conformant, but sanity demands it.
4466      return false;
4467    }
4468
4469    if (shouldDeleteForClassSubobject(FieldRecord, FD))
4470      return true;
4471  }
4472
4473  return false;
4474}
4475
4476/// C++11 [class.ctor] p5:
4477///   A defaulted default constructor for a class X is defined as deleted if
4478/// X is a union and all of its variant members are of const-qualified type.
4479bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4480  // This is a silly definition, because it gives an empty union a deleted
4481  // default constructor. Don't do that.
4482  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4483      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4484    if (Diagnose)
4485      S.Diag(MD->getParent()->getLocation(),
4486             diag::note_deleted_default_ctor_all_const)
4487        << MD->getParent() << /*not anonymous union*/0;
4488    return true;
4489  }
4490  return false;
4491}
4492
4493/// Determine whether a defaulted special member function should be defined as
4494/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4495/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4496bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4497                                     bool Diagnose) {
4498  assert(!MD->isInvalidDecl());
4499  CXXRecordDecl *RD = MD->getParent();
4500  assert(!RD->isDependentType() && "do deletion after instantiation");
4501  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4502    return false;
4503
4504  // C++11 [expr.lambda.prim]p19:
4505  //   The closure type associated with a lambda-expression has a
4506  //   deleted (8.4.3) default constructor and a deleted copy
4507  //   assignment operator.
4508  if (RD->isLambda() &&
4509      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4510    if (Diagnose)
4511      Diag(RD->getLocation(), diag::note_lambda_decl);
4512    return true;
4513  }
4514
4515  // For an anonymous struct or union, the copy and assignment special members
4516  // will never be used, so skip the check. For an anonymous union declared at
4517  // namespace scope, the constructor and destructor are used.
4518  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4519      RD->isAnonymousStructOrUnion())
4520    return false;
4521
4522  // C++11 [class.copy]p7, p18:
4523  //   If the class definition declares a move constructor or move assignment
4524  //   operator, an implicitly declared copy constructor or copy assignment
4525  //   operator is defined as deleted.
4526  if (MD->isImplicit() &&
4527      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4528    CXXMethodDecl *UserDeclaredMove = 0;
4529
4530    // In Microsoft mode, a user-declared move only causes the deletion of the
4531    // corresponding copy operation, not both copy operations.
4532    if (RD->hasUserDeclaredMoveConstructor() &&
4533        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4534      if (!Diagnose) return true;
4535      UserDeclaredMove = RD->getMoveConstructor();
4536      assert(UserDeclaredMove);
4537    } else if (RD->hasUserDeclaredMoveAssignment() &&
4538               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4539      if (!Diagnose) return true;
4540      UserDeclaredMove = RD->getMoveAssignmentOperator();
4541      assert(UserDeclaredMove);
4542    }
4543
4544    if (UserDeclaredMove) {
4545      Diag(UserDeclaredMove->getLocation(),
4546           diag::note_deleted_copy_user_declared_move)
4547        << (CSM == CXXCopyAssignment) << RD
4548        << UserDeclaredMove->isMoveAssignmentOperator();
4549      return true;
4550    }
4551  }
4552
4553  // Do access control from the special member function
4554  ContextRAII MethodContext(*this, MD);
4555
4556  // C++11 [class.dtor]p5:
4557  // -- for a virtual destructor, lookup of the non-array deallocation function
4558  //    results in an ambiguity or in a function that is deleted or inaccessible
4559  if (CSM == CXXDestructor && MD->isVirtual()) {
4560    FunctionDecl *OperatorDelete = 0;
4561    DeclarationName Name =
4562      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4563    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4564                                 OperatorDelete, false)) {
4565      if (Diagnose)
4566        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4567      return true;
4568    }
4569  }
4570
4571  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4572
4573  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4574                                          BE = RD->bases_end(); BI != BE; ++BI)
4575    if (!BI->isVirtual() &&
4576        SMI.shouldDeleteForBase(BI))
4577      return true;
4578
4579  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4580                                          BE = RD->vbases_end(); BI != BE; ++BI)
4581    if (SMI.shouldDeleteForBase(BI))
4582      return true;
4583
4584  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4585                                     FE = RD->field_end(); FI != FE; ++FI)
4586    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4587        SMI.shouldDeleteForField(*FI))
4588      return true;
4589
4590  if (SMI.shouldDeleteForAllConstMembers())
4591    return true;
4592
4593  return false;
4594}
4595
4596/// \brief Data used with FindHiddenVirtualMethod
4597namespace {
4598  struct FindHiddenVirtualMethodData {
4599    Sema *S;
4600    CXXMethodDecl *Method;
4601    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4602    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4603  };
4604}
4605
4606/// \brief Member lookup function that determines whether a given C++
4607/// method overloads virtual methods in a base class without overriding any,
4608/// to be used with CXXRecordDecl::lookupInBases().
4609static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4610                                    CXXBasePath &Path,
4611                                    void *UserData) {
4612  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4613
4614  FindHiddenVirtualMethodData &Data
4615    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4616
4617  DeclarationName Name = Data.Method->getDeclName();
4618  assert(Name.getNameKind() == DeclarationName::Identifier);
4619
4620  bool foundSameNameMethod = false;
4621  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4622  for (Path.Decls = BaseRecord->lookup(Name);
4623       Path.Decls.first != Path.Decls.second;
4624       ++Path.Decls.first) {
4625    NamedDecl *D = *Path.Decls.first;
4626    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4627      MD = MD->getCanonicalDecl();
4628      foundSameNameMethod = true;
4629      // Interested only in hidden virtual methods.
4630      if (!MD->isVirtual())
4631        continue;
4632      // If the method we are checking overrides a method from its base
4633      // don't warn about the other overloaded methods.
4634      if (!Data.S->IsOverload(Data.Method, MD, false))
4635        return true;
4636      // Collect the overload only if its hidden.
4637      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4638        overloadedMethods.push_back(MD);
4639    }
4640  }
4641
4642  if (foundSameNameMethod)
4643    Data.OverloadedMethods.append(overloadedMethods.begin(),
4644                                   overloadedMethods.end());
4645  return foundSameNameMethod;
4646}
4647
4648/// \brief See if a method overloads virtual methods in a base class without
4649/// overriding any.
4650void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4651  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4652                               MD->getLocation()) == DiagnosticsEngine::Ignored)
4653    return;
4654  if (!MD->getDeclName().isIdentifier())
4655    return;
4656
4657  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4658                     /*bool RecordPaths=*/false,
4659                     /*bool DetectVirtual=*/false);
4660  FindHiddenVirtualMethodData Data;
4661  Data.Method = MD;
4662  Data.S = this;
4663
4664  // Keep the base methods that were overriden or introduced in the subclass
4665  // by 'using' in a set. A base method not in this set is hidden.
4666  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4667       res.first != res.second; ++res.first) {
4668    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4669      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4670                                          E = MD->end_overridden_methods();
4671           I != E; ++I)
4672        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4673    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4674      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4675        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4676  }
4677
4678  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4679      !Data.OverloadedMethods.empty()) {
4680    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4681      << MD << (Data.OverloadedMethods.size() > 1);
4682
4683    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4684      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4685      Diag(overloadedMD->getLocation(),
4686           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4687    }
4688  }
4689}
4690
4691void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4692                                             Decl *TagDecl,
4693                                             SourceLocation LBrac,
4694                                             SourceLocation RBrac,
4695                                             AttributeList *AttrList) {
4696  if (!TagDecl)
4697    return;
4698
4699  AdjustDeclIfTemplate(TagDecl);
4700
4701  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4702              // strict aliasing violation!
4703              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4704              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4705
4706  CheckCompletedCXXClass(
4707                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4708}
4709
4710/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4711/// special functions, such as the default constructor, copy
4712/// constructor, or destructor, to the given C++ class (C++
4713/// [special]p1).  This routine can only be executed just before the
4714/// definition of the class is complete.
4715void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4716  if (!ClassDecl->hasUserDeclaredConstructor())
4717    ++ASTContext::NumImplicitDefaultConstructors;
4718
4719  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4720    ++ASTContext::NumImplicitCopyConstructors;
4721
4722  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4723    ++ASTContext::NumImplicitMoveConstructors;
4724
4725  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4726    ++ASTContext::NumImplicitCopyAssignmentOperators;
4727
4728    // If we have a dynamic class, then the copy assignment operator may be
4729    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4730    // it shows up in the right place in the vtable and that we diagnose
4731    // problems with the implicit exception specification.
4732    if (ClassDecl->isDynamicClass())
4733      DeclareImplicitCopyAssignment(ClassDecl);
4734  }
4735
4736  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
4737    ++ASTContext::NumImplicitMoveAssignmentOperators;
4738
4739    // Likewise for the move assignment operator.
4740    if (ClassDecl->isDynamicClass())
4741      DeclareImplicitMoveAssignment(ClassDecl);
4742  }
4743
4744  if (!ClassDecl->hasUserDeclaredDestructor()) {
4745    ++ASTContext::NumImplicitDestructors;
4746
4747    // If we have a dynamic class, then the destructor may be virtual, so we
4748    // have to declare the destructor immediately. This ensures that, e.g., it
4749    // shows up in the right place in the vtable and that we diagnose problems
4750    // with the implicit exception specification.
4751    if (ClassDecl->isDynamicClass())
4752      DeclareImplicitDestructor(ClassDecl);
4753  }
4754}
4755
4756void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4757  if (!D)
4758    return;
4759
4760  int NumParamList = D->getNumTemplateParameterLists();
4761  for (int i = 0; i < NumParamList; i++) {
4762    TemplateParameterList* Params = D->getTemplateParameterList(i);
4763    for (TemplateParameterList::iterator Param = Params->begin(),
4764                                      ParamEnd = Params->end();
4765          Param != ParamEnd; ++Param) {
4766      NamedDecl *Named = cast<NamedDecl>(*Param);
4767      if (Named->getDeclName()) {
4768        S->AddDecl(Named);
4769        IdResolver.AddDecl(Named);
4770      }
4771    }
4772  }
4773}
4774
4775void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4776  if (!D)
4777    return;
4778
4779  TemplateParameterList *Params = 0;
4780  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4781    Params = Template->getTemplateParameters();
4782  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4783           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4784    Params = PartialSpec->getTemplateParameters();
4785  else
4786    return;
4787
4788  for (TemplateParameterList::iterator Param = Params->begin(),
4789                                    ParamEnd = Params->end();
4790       Param != ParamEnd; ++Param) {
4791    NamedDecl *Named = cast<NamedDecl>(*Param);
4792    if (Named->getDeclName()) {
4793      S->AddDecl(Named);
4794      IdResolver.AddDecl(Named);
4795    }
4796  }
4797}
4798
4799void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4800  if (!RecordD) return;
4801  AdjustDeclIfTemplate(RecordD);
4802  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4803  PushDeclContext(S, Record);
4804}
4805
4806void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4807  if (!RecordD) return;
4808  PopDeclContext();
4809}
4810
4811/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4812/// parsing a top-level (non-nested) C++ class, and we are now
4813/// parsing those parts of the given Method declaration that could
4814/// not be parsed earlier (C++ [class.mem]p2), such as default
4815/// arguments. This action should enter the scope of the given
4816/// Method declaration as if we had just parsed the qualified method
4817/// name. However, it should not bring the parameters into scope;
4818/// that will be performed by ActOnDelayedCXXMethodParameter.
4819void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4820}
4821
4822/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4823/// C++ method declaration. We're (re-)introducing the given
4824/// function parameter into scope for use in parsing later parts of
4825/// the method declaration. For example, we could see an
4826/// ActOnParamDefaultArgument event for this parameter.
4827void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4828  if (!ParamD)
4829    return;
4830
4831  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4832
4833  // If this parameter has an unparsed default argument, clear it out
4834  // to make way for the parsed default argument.
4835  if (Param->hasUnparsedDefaultArg())
4836    Param->setDefaultArg(0);
4837
4838  S->AddDecl(Param);
4839  if (Param->getDeclName())
4840    IdResolver.AddDecl(Param);
4841}
4842
4843/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4844/// processing the delayed method declaration for Method. The method
4845/// declaration is now considered finished. There may be a separate
4846/// ActOnStartOfFunctionDef action later (not necessarily
4847/// immediately!) for this method, if it was also defined inside the
4848/// class body.
4849void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4850  if (!MethodD)
4851    return;
4852
4853  AdjustDeclIfTemplate(MethodD);
4854
4855  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4856
4857  // Now that we have our default arguments, check the constructor
4858  // again. It could produce additional diagnostics or affect whether
4859  // the class has implicitly-declared destructors, among other
4860  // things.
4861  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4862    CheckConstructor(Constructor);
4863
4864  // Check the default arguments, which we may have added.
4865  if (!Method->isInvalidDecl())
4866    CheckCXXDefaultArguments(Method);
4867}
4868
4869/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4870/// the well-formedness of the constructor declarator @p D with type @p
4871/// R. If there are any errors in the declarator, this routine will
4872/// emit diagnostics and set the invalid bit to true.  In any case, the type
4873/// will be updated to reflect a well-formed type for the constructor and
4874/// returned.
4875QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4876                                          StorageClass &SC) {
4877  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4878
4879  // C++ [class.ctor]p3:
4880  //   A constructor shall not be virtual (10.3) or static (9.4). A
4881  //   constructor can be invoked for a const, volatile or const
4882  //   volatile object. A constructor shall not be declared const,
4883  //   volatile, or const volatile (9.3.2).
4884  if (isVirtual) {
4885    if (!D.isInvalidType())
4886      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4887        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4888        << SourceRange(D.getIdentifierLoc());
4889    D.setInvalidType();
4890  }
4891  if (SC == SC_Static) {
4892    if (!D.isInvalidType())
4893      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4894        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4895        << SourceRange(D.getIdentifierLoc());
4896    D.setInvalidType();
4897    SC = SC_None;
4898  }
4899
4900  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4901  if (FTI.TypeQuals != 0) {
4902    if (FTI.TypeQuals & Qualifiers::Const)
4903      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4904        << "const" << SourceRange(D.getIdentifierLoc());
4905    if (FTI.TypeQuals & Qualifiers::Volatile)
4906      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4907        << "volatile" << SourceRange(D.getIdentifierLoc());
4908    if (FTI.TypeQuals & Qualifiers::Restrict)
4909      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4910        << "restrict" << SourceRange(D.getIdentifierLoc());
4911    D.setInvalidType();
4912  }
4913
4914  // C++0x [class.ctor]p4:
4915  //   A constructor shall not be declared with a ref-qualifier.
4916  if (FTI.hasRefQualifier()) {
4917    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4918      << FTI.RefQualifierIsLValueRef
4919      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4920    D.setInvalidType();
4921  }
4922
4923  // Rebuild the function type "R" without any type qualifiers (in
4924  // case any of the errors above fired) and with "void" as the
4925  // return type, since constructors don't have return types.
4926  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4927  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4928    return R;
4929
4930  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4931  EPI.TypeQuals = 0;
4932  EPI.RefQualifier = RQ_None;
4933
4934  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4935                                 Proto->getNumArgs(), EPI);
4936}
4937
4938/// CheckConstructor - Checks a fully-formed constructor for
4939/// well-formedness, issuing any diagnostics required. Returns true if
4940/// the constructor declarator is invalid.
4941void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4942  CXXRecordDecl *ClassDecl
4943    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4944  if (!ClassDecl)
4945    return Constructor->setInvalidDecl();
4946
4947  // C++ [class.copy]p3:
4948  //   A declaration of a constructor for a class X is ill-formed if
4949  //   its first parameter is of type (optionally cv-qualified) X and
4950  //   either there are no other parameters or else all other
4951  //   parameters have default arguments.
4952  if (!Constructor->isInvalidDecl() &&
4953      ((Constructor->getNumParams() == 1) ||
4954       (Constructor->getNumParams() > 1 &&
4955        Constructor->getParamDecl(1)->hasDefaultArg())) &&
4956      Constructor->getTemplateSpecializationKind()
4957                                              != TSK_ImplicitInstantiation) {
4958    QualType ParamType = Constructor->getParamDecl(0)->getType();
4959    QualType ClassTy = Context.getTagDeclType(ClassDecl);
4960    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4961      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4962      const char *ConstRef
4963        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4964                                                        : " const &";
4965      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4966        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4967
4968      // FIXME: Rather that making the constructor invalid, we should endeavor
4969      // to fix the type.
4970      Constructor->setInvalidDecl();
4971    }
4972  }
4973}
4974
4975/// CheckDestructor - Checks a fully-formed destructor definition for
4976/// well-formedness, issuing any diagnostics required.  Returns true
4977/// on error.
4978bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4979  CXXRecordDecl *RD = Destructor->getParent();
4980
4981  if (Destructor->isVirtual()) {
4982    SourceLocation Loc;
4983
4984    if (!Destructor->isImplicit())
4985      Loc = Destructor->getLocation();
4986    else
4987      Loc = RD->getLocation();
4988
4989    // If we have a virtual destructor, look up the deallocation function
4990    FunctionDecl *OperatorDelete = 0;
4991    DeclarationName Name =
4992    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4993    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4994      return true;
4995
4996    MarkFunctionReferenced(Loc, OperatorDelete);
4997
4998    Destructor->setOperatorDelete(OperatorDelete);
4999  }
5000
5001  return false;
5002}
5003
5004static inline bool
5005FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5006  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5007          FTI.ArgInfo[0].Param &&
5008          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5009}
5010
5011/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5012/// the well-formednes of the destructor declarator @p D with type @p
5013/// R. If there are any errors in the declarator, this routine will
5014/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5015/// will be updated to reflect a well-formed type for the destructor and
5016/// returned.
5017QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5018                                         StorageClass& SC) {
5019  // C++ [class.dtor]p1:
5020  //   [...] A typedef-name that names a class is a class-name
5021  //   (7.1.3); however, a typedef-name that names a class shall not
5022  //   be used as the identifier in the declarator for a destructor
5023  //   declaration.
5024  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5025  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5026    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5027      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5028  else if (const TemplateSpecializationType *TST =
5029             DeclaratorType->getAs<TemplateSpecializationType>())
5030    if (TST->isTypeAlias())
5031      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5032        << DeclaratorType << 1;
5033
5034  // C++ [class.dtor]p2:
5035  //   A destructor is used to destroy objects of its class type. A
5036  //   destructor takes no parameters, and no return type can be
5037  //   specified for it (not even void). The address of a destructor
5038  //   shall not be taken. A destructor shall not be static. A
5039  //   destructor can be invoked for a const, volatile or const
5040  //   volatile object. A destructor shall not be declared const,
5041  //   volatile or const volatile (9.3.2).
5042  if (SC == SC_Static) {
5043    if (!D.isInvalidType())
5044      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5045        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5046        << SourceRange(D.getIdentifierLoc())
5047        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5048
5049    SC = SC_None;
5050  }
5051  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5052    // Destructors don't have return types, but the parser will
5053    // happily parse something like:
5054    //
5055    //   class X {
5056    //     float ~X();
5057    //   };
5058    //
5059    // The return type will be eliminated later.
5060    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5061      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5062      << SourceRange(D.getIdentifierLoc());
5063  }
5064
5065  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5066  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5067    if (FTI.TypeQuals & Qualifiers::Const)
5068      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5069        << "const" << SourceRange(D.getIdentifierLoc());
5070    if (FTI.TypeQuals & Qualifiers::Volatile)
5071      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5072        << "volatile" << SourceRange(D.getIdentifierLoc());
5073    if (FTI.TypeQuals & Qualifiers::Restrict)
5074      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5075        << "restrict" << SourceRange(D.getIdentifierLoc());
5076    D.setInvalidType();
5077  }
5078
5079  // C++0x [class.dtor]p2:
5080  //   A destructor shall not be declared with a ref-qualifier.
5081  if (FTI.hasRefQualifier()) {
5082    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5083      << FTI.RefQualifierIsLValueRef
5084      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5085    D.setInvalidType();
5086  }
5087
5088  // Make sure we don't have any parameters.
5089  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5090    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5091
5092    // Delete the parameters.
5093    FTI.freeArgs();
5094    D.setInvalidType();
5095  }
5096
5097  // Make sure the destructor isn't variadic.
5098  if (FTI.isVariadic) {
5099    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5100    D.setInvalidType();
5101  }
5102
5103  // Rebuild the function type "R" without any type qualifiers or
5104  // parameters (in case any of the errors above fired) and with
5105  // "void" as the return type, since destructors don't have return
5106  // types.
5107  if (!D.isInvalidType())
5108    return R;
5109
5110  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5111  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5112  EPI.Variadic = false;
5113  EPI.TypeQuals = 0;
5114  EPI.RefQualifier = RQ_None;
5115  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5116}
5117
5118/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5119/// well-formednes of the conversion function declarator @p D with
5120/// type @p R. If there are any errors in the declarator, this routine
5121/// will emit diagnostics and return true. Otherwise, it will return
5122/// false. Either way, the type @p R will be updated to reflect a
5123/// well-formed type for the conversion operator.
5124void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5125                                     StorageClass& SC) {
5126  // C++ [class.conv.fct]p1:
5127  //   Neither parameter types nor return type can be specified. The
5128  //   type of a conversion function (8.3.5) is "function taking no
5129  //   parameter returning conversion-type-id."
5130  if (SC == SC_Static) {
5131    if (!D.isInvalidType())
5132      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5133        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5134        << SourceRange(D.getIdentifierLoc());
5135    D.setInvalidType();
5136    SC = SC_None;
5137  }
5138
5139  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5140
5141  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5142    // Conversion functions don't have return types, but the parser will
5143    // happily parse something like:
5144    //
5145    //   class X {
5146    //     float operator bool();
5147    //   };
5148    //
5149    // The return type will be changed later anyway.
5150    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5151      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5152      << SourceRange(D.getIdentifierLoc());
5153    D.setInvalidType();
5154  }
5155
5156  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5157
5158  // Make sure we don't have any parameters.
5159  if (Proto->getNumArgs() > 0) {
5160    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5161
5162    // Delete the parameters.
5163    D.getFunctionTypeInfo().freeArgs();
5164    D.setInvalidType();
5165  } else if (Proto->isVariadic()) {
5166    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5167    D.setInvalidType();
5168  }
5169
5170  // Diagnose "&operator bool()" and other such nonsense.  This
5171  // is actually a gcc extension which we don't support.
5172  if (Proto->getResultType() != ConvType) {
5173    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5174      << Proto->getResultType();
5175    D.setInvalidType();
5176    ConvType = Proto->getResultType();
5177  }
5178
5179  // C++ [class.conv.fct]p4:
5180  //   The conversion-type-id shall not represent a function type nor
5181  //   an array type.
5182  if (ConvType->isArrayType()) {
5183    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5184    ConvType = Context.getPointerType(ConvType);
5185    D.setInvalidType();
5186  } else if (ConvType->isFunctionType()) {
5187    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5188    ConvType = Context.getPointerType(ConvType);
5189    D.setInvalidType();
5190  }
5191
5192  // Rebuild the function type "R" without any parameters (in case any
5193  // of the errors above fired) and with the conversion type as the
5194  // return type.
5195  if (D.isInvalidType())
5196    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5197
5198  // C++0x explicit conversion operators.
5199  if (D.getDeclSpec().isExplicitSpecified())
5200    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5201         getLangOpts().CPlusPlus0x ?
5202           diag::warn_cxx98_compat_explicit_conversion_functions :
5203           diag::ext_explicit_conversion_functions)
5204      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5205}
5206
5207/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5208/// the declaration of the given C++ conversion function. This routine
5209/// is responsible for recording the conversion function in the C++
5210/// class, if possible.
5211Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5212  assert(Conversion && "Expected to receive a conversion function declaration");
5213
5214  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5215
5216  // Make sure we aren't redeclaring the conversion function.
5217  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5218
5219  // C++ [class.conv.fct]p1:
5220  //   [...] A conversion function is never used to convert a
5221  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5222  //   same object type (or a reference to it), to a (possibly
5223  //   cv-qualified) base class of that type (or a reference to it),
5224  //   or to (possibly cv-qualified) void.
5225  // FIXME: Suppress this warning if the conversion function ends up being a
5226  // virtual function that overrides a virtual function in a base class.
5227  QualType ClassType
5228    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5229  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5230    ConvType = ConvTypeRef->getPointeeType();
5231  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5232      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5233    /* Suppress diagnostics for instantiations. */;
5234  else if (ConvType->isRecordType()) {
5235    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5236    if (ConvType == ClassType)
5237      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5238        << ClassType;
5239    else if (IsDerivedFrom(ClassType, ConvType))
5240      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5241        <<  ClassType << ConvType;
5242  } else if (ConvType->isVoidType()) {
5243    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5244      << ClassType << ConvType;
5245  }
5246
5247  if (FunctionTemplateDecl *ConversionTemplate
5248                                = Conversion->getDescribedFunctionTemplate())
5249    return ConversionTemplate;
5250
5251  return Conversion;
5252}
5253
5254//===----------------------------------------------------------------------===//
5255// Namespace Handling
5256//===----------------------------------------------------------------------===//
5257
5258
5259
5260/// ActOnStartNamespaceDef - This is called at the start of a namespace
5261/// definition.
5262Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5263                                   SourceLocation InlineLoc,
5264                                   SourceLocation NamespaceLoc,
5265                                   SourceLocation IdentLoc,
5266                                   IdentifierInfo *II,
5267                                   SourceLocation LBrace,
5268                                   AttributeList *AttrList) {
5269  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5270  // For anonymous namespace, take the location of the left brace.
5271  SourceLocation Loc = II ? IdentLoc : LBrace;
5272  bool IsInline = InlineLoc.isValid();
5273  bool IsInvalid = false;
5274  bool IsStd = false;
5275  bool AddToKnown = false;
5276  Scope *DeclRegionScope = NamespcScope->getParent();
5277
5278  NamespaceDecl *PrevNS = 0;
5279  if (II) {
5280    // C++ [namespace.def]p2:
5281    //   The identifier in an original-namespace-definition shall not
5282    //   have been previously defined in the declarative region in
5283    //   which the original-namespace-definition appears. The
5284    //   identifier in an original-namespace-definition is the name of
5285    //   the namespace. Subsequently in that declarative region, it is
5286    //   treated as an original-namespace-name.
5287    //
5288    // Since namespace names are unique in their scope, and we don't
5289    // look through using directives, just look for any ordinary names.
5290
5291    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5292    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5293    Decl::IDNS_Namespace;
5294    NamedDecl *PrevDecl = 0;
5295    for (DeclContext::lookup_result R
5296         = CurContext->getRedeclContext()->lookup(II);
5297         R.first != R.second; ++R.first) {
5298      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5299        PrevDecl = *R.first;
5300        break;
5301      }
5302    }
5303
5304    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5305
5306    if (PrevNS) {
5307      // This is an extended namespace definition.
5308      if (IsInline != PrevNS->isInline()) {
5309        // inline-ness must match
5310        if (PrevNS->isInline()) {
5311          // The user probably just forgot the 'inline', so suggest that it
5312          // be added back.
5313          Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5314            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5315        } else {
5316          Diag(Loc, diag::err_inline_namespace_mismatch)
5317            << IsInline;
5318        }
5319        Diag(PrevNS->getLocation(), diag::note_previous_definition);
5320
5321        IsInline = PrevNS->isInline();
5322      }
5323    } else if (PrevDecl) {
5324      // This is an invalid name redefinition.
5325      Diag(Loc, diag::err_redefinition_different_kind)
5326        << II;
5327      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5328      IsInvalid = true;
5329      // Continue on to push Namespc as current DeclContext and return it.
5330    } else if (II->isStr("std") &&
5331               CurContext->getRedeclContext()->isTranslationUnit()) {
5332      // This is the first "real" definition of the namespace "std", so update
5333      // our cache of the "std" namespace to point at this definition.
5334      PrevNS = getStdNamespace();
5335      IsStd = true;
5336      AddToKnown = !IsInline;
5337    } else {
5338      // We've seen this namespace for the first time.
5339      AddToKnown = !IsInline;
5340    }
5341  } else {
5342    // Anonymous namespaces.
5343
5344    // Determine whether the parent already has an anonymous namespace.
5345    DeclContext *Parent = CurContext->getRedeclContext();
5346    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5347      PrevNS = TU->getAnonymousNamespace();
5348    } else {
5349      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5350      PrevNS = ND->getAnonymousNamespace();
5351    }
5352
5353    if (PrevNS && IsInline != PrevNS->isInline()) {
5354      // inline-ness must match
5355      Diag(Loc, diag::err_inline_namespace_mismatch)
5356        << IsInline;
5357      Diag(PrevNS->getLocation(), diag::note_previous_definition);
5358
5359      // Recover by ignoring the new namespace's inline status.
5360      IsInline = PrevNS->isInline();
5361    }
5362  }
5363
5364  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5365                                                 StartLoc, Loc, II, PrevNS);
5366  if (IsInvalid)
5367    Namespc->setInvalidDecl();
5368
5369  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5370
5371  // FIXME: Should we be merging attributes?
5372  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5373    PushNamespaceVisibilityAttr(Attr, Loc);
5374
5375  if (IsStd)
5376    StdNamespace = Namespc;
5377  if (AddToKnown)
5378    KnownNamespaces[Namespc] = false;
5379
5380  if (II) {
5381    PushOnScopeChains(Namespc, DeclRegionScope);
5382  } else {
5383    // Link the anonymous namespace into its parent.
5384    DeclContext *Parent = CurContext->getRedeclContext();
5385    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5386      TU->setAnonymousNamespace(Namespc);
5387    } else {
5388      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5389    }
5390
5391    CurContext->addDecl(Namespc);
5392
5393    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5394    //   behaves as if it were replaced by
5395    //     namespace unique { /* empty body */ }
5396    //     using namespace unique;
5397    //     namespace unique { namespace-body }
5398    //   where all occurrences of 'unique' in a translation unit are
5399    //   replaced by the same identifier and this identifier differs
5400    //   from all other identifiers in the entire program.
5401
5402    // We just create the namespace with an empty name and then add an
5403    // implicit using declaration, just like the standard suggests.
5404    //
5405    // CodeGen enforces the "universally unique" aspect by giving all
5406    // declarations semantically contained within an anonymous
5407    // namespace internal linkage.
5408
5409    if (!PrevNS) {
5410      UsingDirectiveDecl* UD
5411        = UsingDirectiveDecl::Create(Context, CurContext,
5412                                     /* 'using' */ LBrace,
5413                                     /* 'namespace' */ SourceLocation(),
5414                                     /* qualifier */ NestedNameSpecifierLoc(),
5415                                     /* identifier */ SourceLocation(),
5416                                     Namespc,
5417                                     /* Ancestor */ CurContext);
5418      UD->setImplicit();
5419      CurContext->addDecl(UD);
5420    }
5421  }
5422
5423  // Although we could have an invalid decl (i.e. the namespace name is a
5424  // redefinition), push it as current DeclContext and try to continue parsing.
5425  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5426  // for the namespace has the declarations that showed up in that particular
5427  // namespace definition.
5428  PushDeclContext(NamespcScope, Namespc);
5429  return Namespc;
5430}
5431
5432/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5433/// is a namespace alias, returns the namespace it points to.
5434static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5435  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5436    return AD->getNamespace();
5437  return dyn_cast_or_null<NamespaceDecl>(D);
5438}
5439
5440/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5441/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5442void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5443  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5444  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5445  Namespc->setRBraceLoc(RBrace);
5446  PopDeclContext();
5447  if (Namespc->hasAttr<VisibilityAttr>())
5448    PopPragmaVisibility(true, RBrace);
5449}
5450
5451CXXRecordDecl *Sema::getStdBadAlloc() const {
5452  return cast_or_null<CXXRecordDecl>(
5453                                  StdBadAlloc.get(Context.getExternalSource()));
5454}
5455
5456NamespaceDecl *Sema::getStdNamespace() const {
5457  return cast_or_null<NamespaceDecl>(
5458                                 StdNamespace.get(Context.getExternalSource()));
5459}
5460
5461/// \brief Retrieve the special "std" namespace, which may require us to
5462/// implicitly define the namespace.
5463NamespaceDecl *Sema::getOrCreateStdNamespace() {
5464  if (!StdNamespace) {
5465    // The "std" namespace has not yet been defined, so build one implicitly.
5466    StdNamespace = NamespaceDecl::Create(Context,
5467                                         Context.getTranslationUnitDecl(),
5468                                         /*Inline=*/false,
5469                                         SourceLocation(), SourceLocation(),
5470                                         &PP.getIdentifierTable().get("std"),
5471                                         /*PrevDecl=*/0);
5472    getStdNamespace()->setImplicit(true);
5473  }
5474
5475  return getStdNamespace();
5476}
5477
5478bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5479  assert(getLangOpts().CPlusPlus &&
5480         "Looking for std::initializer_list outside of C++.");
5481
5482  // We're looking for implicit instantiations of
5483  // template <typename E> class std::initializer_list.
5484
5485  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5486    return false;
5487
5488  ClassTemplateDecl *Template = 0;
5489  const TemplateArgument *Arguments = 0;
5490
5491  if (const RecordType *RT = Ty->getAs<RecordType>()) {
5492
5493    ClassTemplateSpecializationDecl *Specialization =
5494        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5495    if (!Specialization)
5496      return false;
5497
5498    Template = Specialization->getSpecializedTemplate();
5499    Arguments = Specialization->getTemplateArgs().data();
5500  } else if (const TemplateSpecializationType *TST =
5501                 Ty->getAs<TemplateSpecializationType>()) {
5502    Template = dyn_cast_or_null<ClassTemplateDecl>(
5503        TST->getTemplateName().getAsTemplateDecl());
5504    Arguments = TST->getArgs();
5505  }
5506  if (!Template)
5507    return false;
5508
5509  if (!StdInitializerList) {
5510    // Haven't recognized std::initializer_list yet, maybe this is it.
5511    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5512    if (TemplateClass->getIdentifier() !=
5513            &PP.getIdentifierTable().get("initializer_list") ||
5514        !getStdNamespace()->InEnclosingNamespaceSetOf(
5515            TemplateClass->getDeclContext()))
5516      return false;
5517    // This is a template called std::initializer_list, but is it the right
5518    // template?
5519    TemplateParameterList *Params = Template->getTemplateParameters();
5520    if (Params->getMinRequiredArguments() != 1)
5521      return false;
5522    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5523      return false;
5524
5525    // It's the right template.
5526    StdInitializerList = Template;
5527  }
5528
5529  if (Template != StdInitializerList)
5530    return false;
5531
5532  // This is an instance of std::initializer_list. Find the argument type.
5533  if (Element)
5534    *Element = Arguments[0].getAsType();
5535  return true;
5536}
5537
5538static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5539  NamespaceDecl *Std = S.getStdNamespace();
5540  if (!Std) {
5541    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5542    return 0;
5543  }
5544
5545  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5546                      Loc, Sema::LookupOrdinaryName);
5547  if (!S.LookupQualifiedName(Result, Std)) {
5548    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5549    return 0;
5550  }
5551  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5552  if (!Template) {
5553    Result.suppressDiagnostics();
5554    // We found something weird. Complain about the first thing we found.
5555    NamedDecl *Found = *Result.begin();
5556    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5557    return 0;
5558  }
5559
5560  // We found some template called std::initializer_list. Now verify that it's
5561  // correct.
5562  TemplateParameterList *Params = Template->getTemplateParameters();
5563  if (Params->getMinRequiredArguments() != 1 ||
5564      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5565    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5566    return 0;
5567  }
5568
5569  return Template;
5570}
5571
5572QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5573  if (!StdInitializerList) {
5574    StdInitializerList = LookupStdInitializerList(*this, Loc);
5575    if (!StdInitializerList)
5576      return QualType();
5577  }
5578
5579  TemplateArgumentListInfo Args(Loc, Loc);
5580  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5581                                       Context.getTrivialTypeSourceInfo(Element,
5582                                                                        Loc)));
5583  return Context.getCanonicalType(
5584      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5585}
5586
5587bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5588  // C++ [dcl.init.list]p2:
5589  //   A constructor is an initializer-list constructor if its first parameter
5590  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5591  //   std::initializer_list<E> for some type E, and either there are no other
5592  //   parameters or else all other parameters have default arguments.
5593  if (Ctor->getNumParams() < 1 ||
5594      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5595    return false;
5596
5597  QualType ArgType = Ctor->getParamDecl(0)->getType();
5598  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5599    ArgType = RT->getPointeeType().getUnqualifiedType();
5600
5601  return isStdInitializerList(ArgType, 0);
5602}
5603
5604/// \brief Determine whether a using statement is in a context where it will be
5605/// apply in all contexts.
5606static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5607  switch (CurContext->getDeclKind()) {
5608    case Decl::TranslationUnit:
5609      return true;
5610    case Decl::LinkageSpec:
5611      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5612    default:
5613      return false;
5614  }
5615}
5616
5617namespace {
5618
5619// Callback to only accept typo corrections that are namespaces.
5620class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5621 public:
5622  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5623    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5624      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5625    }
5626    return false;
5627  }
5628};
5629
5630}
5631
5632static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5633                                       CXXScopeSpec &SS,
5634                                       SourceLocation IdentLoc,
5635                                       IdentifierInfo *Ident) {
5636  NamespaceValidatorCCC Validator;
5637  R.clear();
5638  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5639                                               R.getLookupKind(), Sc, &SS,
5640                                               Validator)) {
5641    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5642    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5643    if (DeclContext *DC = S.computeDeclContext(SS, false))
5644      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5645        << Ident << DC << CorrectedQuotedStr << SS.getRange()
5646        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5647    else
5648      S.Diag(IdentLoc, diag::err_using_directive_suggest)
5649        << Ident << CorrectedQuotedStr
5650        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5651
5652    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5653         diag::note_namespace_defined_here) << CorrectedQuotedStr;
5654
5655    R.addDecl(Corrected.getCorrectionDecl());
5656    return true;
5657  }
5658  return false;
5659}
5660
5661Decl *Sema::ActOnUsingDirective(Scope *S,
5662                                          SourceLocation UsingLoc,
5663                                          SourceLocation NamespcLoc,
5664                                          CXXScopeSpec &SS,
5665                                          SourceLocation IdentLoc,
5666                                          IdentifierInfo *NamespcName,
5667                                          AttributeList *AttrList) {
5668  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5669  assert(NamespcName && "Invalid NamespcName.");
5670  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5671
5672  // This can only happen along a recovery path.
5673  while (S->getFlags() & Scope::TemplateParamScope)
5674    S = S->getParent();
5675  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5676
5677  UsingDirectiveDecl *UDir = 0;
5678  NestedNameSpecifier *Qualifier = 0;
5679  if (SS.isSet())
5680    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5681
5682  // Lookup namespace name.
5683  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5684  LookupParsedName(R, S, &SS);
5685  if (R.isAmbiguous())
5686    return 0;
5687
5688  if (R.empty()) {
5689    R.clear();
5690    // Allow "using namespace std;" or "using namespace ::std;" even if
5691    // "std" hasn't been defined yet, for GCC compatibility.
5692    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5693        NamespcName->isStr("std")) {
5694      Diag(IdentLoc, diag::ext_using_undefined_std);
5695      R.addDecl(getOrCreateStdNamespace());
5696      R.resolveKind();
5697    }
5698    // Otherwise, attempt typo correction.
5699    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5700  }
5701
5702  if (!R.empty()) {
5703    NamedDecl *Named = R.getFoundDecl();
5704    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5705        && "expected namespace decl");
5706    // C++ [namespace.udir]p1:
5707    //   A using-directive specifies that the names in the nominated
5708    //   namespace can be used in the scope in which the
5709    //   using-directive appears after the using-directive. During
5710    //   unqualified name lookup (3.4.1), the names appear as if they
5711    //   were declared in the nearest enclosing namespace which
5712    //   contains both the using-directive and the nominated
5713    //   namespace. [Note: in this context, "contains" means "contains
5714    //   directly or indirectly". ]
5715
5716    // Find enclosing context containing both using-directive and
5717    // nominated namespace.
5718    NamespaceDecl *NS = getNamespaceDecl(Named);
5719    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5720    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5721      CommonAncestor = CommonAncestor->getParent();
5722
5723    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5724                                      SS.getWithLocInContext(Context),
5725                                      IdentLoc, Named, CommonAncestor);
5726
5727    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5728        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5729      Diag(IdentLoc, diag::warn_using_directive_in_header);
5730    }
5731
5732    PushUsingDirective(S, UDir);
5733  } else {
5734    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5735  }
5736
5737  // FIXME: We ignore attributes for now.
5738  return UDir;
5739}
5740
5741void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5742  // If the scope has an associated entity and the using directive is at
5743  // namespace or translation unit scope, add the UsingDirectiveDecl into
5744  // its lookup structure so qualified name lookup can find it.
5745  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5746  if (Ctx && !Ctx->isFunctionOrMethod())
5747    Ctx->addDecl(UDir);
5748  else
5749    // Otherwise, it is at block sope. The using-directives will affect lookup
5750    // only to the end of the scope.
5751    S->PushUsingDirective(UDir);
5752}
5753
5754
5755Decl *Sema::ActOnUsingDeclaration(Scope *S,
5756                                  AccessSpecifier AS,
5757                                  bool HasUsingKeyword,
5758                                  SourceLocation UsingLoc,
5759                                  CXXScopeSpec &SS,
5760                                  UnqualifiedId &Name,
5761                                  AttributeList *AttrList,
5762                                  bool IsTypeName,
5763                                  SourceLocation TypenameLoc) {
5764  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5765
5766  switch (Name.getKind()) {
5767  case UnqualifiedId::IK_ImplicitSelfParam:
5768  case UnqualifiedId::IK_Identifier:
5769  case UnqualifiedId::IK_OperatorFunctionId:
5770  case UnqualifiedId::IK_LiteralOperatorId:
5771  case UnqualifiedId::IK_ConversionFunctionId:
5772    break;
5773
5774  case UnqualifiedId::IK_ConstructorName:
5775  case UnqualifiedId::IK_ConstructorTemplateId:
5776    // C++11 inheriting constructors.
5777    Diag(Name.getLocStart(),
5778         getLangOpts().CPlusPlus0x ?
5779           // FIXME: Produce warn_cxx98_compat_using_decl_constructor
5780           //        instead once inheriting constructors work.
5781           diag::err_using_decl_constructor_unsupported :
5782           diag::err_using_decl_constructor)
5783      << SS.getRange();
5784
5785    if (getLangOpts().CPlusPlus0x) break;
5786
5787    return 0;
5788
5789  case UnqualifiedId::IK_DestructorName:
5790    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5791      << SS.getRange();
5792    return 0;
5793
5794  case UnqualifiedId::IK_TemplateId:
5795    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5796      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5797    return 0;
5798  }
5799
5800  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5801  DeclarationName TargetName = TargetNameInfo.getName();
5802  if (!TargetName)
5803    return 0;
5804
5805  // Warn about using declarations.
5806  // TODO: store that the declaration was written without 'using' and
5807  // talk about access decls instead of using decls in the
5808  // diagnostics.
5809  if (!HasUsingKeyword) {
5810    UsingLoc = Name.getLocStart();
5811
5812    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5813      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5814  }
5815
5816  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5817      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5818    return 0;
5819
5820  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5821                                        TargetNameInfo, AttrList,
5822                                        /* IsInstantiation */ false,
5823                                        IsTypeName, TypenameLoc);
5824  if (UD)
5825    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5826
5827  return UD;
5828}
5829
5830/// \brief Determine whether a using declaration considers the given
5831/// declarations as "equivalent", e.g., if they are redeclarations of
5832/// the same entity or are both typedefs of the same type.
5833static bool
5834IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5835                         bool &SuppressRedeclaration) {
5836  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5837    SuppressRedeclaration = false;
5838    return true;
5839  }
5840
5841  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5842    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5843      SuppressRedeclaration = true;
5844      return Context.hasSameType(TD1->getUnderlyingType(),
5845                                 TD2->getUnderlyingType());
5846    }
5847
5848  return false;
5849}
5850
5851
5852/// Determines whether to create a using shadow decl for a particular
5853/// decl, given the set of decls existing prior to this using lookup.
5854bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5855                                const LookupResult &Previous) {
5856  // Diagnose finding a decl which is not from a base class of the
5857  // current class.  We do this now because there are cases where this
5858  // function will silently decide not to build a shadow decl, which
5859  // will pre-empt further diagnostics.
5860  //
5861  // We don't need to do this in C++0x because we do the check once on
5862  // the qualifier.
5863  //
5864  // FIXME: diagnose the following if we care enough:
5865  //   struct A { int foo; };
5866  //   struct B : A { using A::foo; };
5867  //   template <class T> struct C : A {};
5868  //   template <class T> struct D : C<T> { using B::foo; } // <---
5869  // This is invalid (during instantiation) in C++03 because B::foo
5870  // resolves to the using decl in B, which is not a base class of D<T>.
5871  // We can't diagnose it immediately because C<T> is an unknown
5872  // specialization.  The UsingShadowDecl in D<T> then points directly
5873  // to A::foo, which will look well-formed when we instantiate.
5874  // The right solution is to not collapse the shadow-decl chain.
5875  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
5876    DeclContext *OrigDC = Orig->getDeclContext();
5877
5878    // Handle enums and anonymous structs.
5879    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5880    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5881    while (OrigRec->isAnonymousStructOrUnion())
5882      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5883
5884    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5885      if (OrigDC == CurContext) {
5886        Diag(Using->getLocation(),
5887             diag::err_using_decl_nested_name_specifier_is_current_class)
5888          << Using->getQualifierLoc().getSourceRange();
5889        Diag(Orig->getLocation(), diag::note_using_decl_target);
5890        return true;
5891      }
5892
5893      Diag(Using->getQualifierLoc().getBeginLoc(),
5894           diag::err_using_decl_nested_name_specifier_is_not_base_class)
5895        << Using->getQualifier()
5896        << cast<CXXRecordDecl>(CurContext)
5897        << Using->getQualifierLoc().getSourceRange();
5898      Diag(Orig->getLocation(), diag::note_using_decl_target);
5899      return true;
5900    }
5901  }
5902
5903  if (Previous.empty()) return false;
5904
5905  NamedDecl *Target = Orig;
5906  if (isa<UsingShadowDecl>(Target))
5907    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5908
5909  // If the target happens to be one of the previous declarations, we
5910  // don't have a conflict.
5911  //
5912  // FIXME: but we might be increasing its access, in which case we
5913  // should redeclare it.
5914  NamedDecl *NonTag = 0, *Tag = 0;
5915  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5916         I != E; ++I) {
5917    NamedDecl *D = (*I)->getUnderlyingDecl();
5918    bool Result;
5919    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5920      return Result;
5921
5922    (isa<TagDecl>(D) ? Tag : NonTag) = D;
5923  }
5924
5925  if (Target->isFunctionOrFunctionTemplate()) {
5926    FunctionDecl *FD;
5927    if (isa<FunctionTemplateDecl>(Target))
5928      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5929    else
5930      FD = cast<FunctionDecl>(Target);
5931
5932    NamedDecl *OldDecl = 0;
5933    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5934    case Ovl_Overload:
5935      return false;
5936
5937    case Ovl_NonFunction:
5938      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5939      break;
5940
5941    // We found a decl with the exact signature.
5942    case Ovl_Match:
5943      // If we're in a record, we want to hide the target, so we
5944      // return true (without a diagnostic) to tell the caller not to
5945      // build a shadow decl.
5946      if (CurContext->isRecord())
5947        return true;
5948
5949      // If we're not in a record, this is an error.
5950      Diag(Using->getLocation(), diag::err_using_decl_conflict);
5951      break;
5952    }
5953
5954    Diag(Target->getLocation(), diag::note_using_decl_target);
5955    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5956    return true;
5957  }
5958
5959  // Target is not a function.
5960
5961  if (isa<TagDecl>(Target)) {
5962    // No conflict between a tag and a non-tag.
5963    if (!Tag) return false;
5964
5965    Diag(Using->getLocation(), diag::err_using_decl_conflict);
5966    Diag(Target->getLocation(), diag::note_using_decl_target);
5967    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5968    return true;
5969  }
5970
5971  // No conflict between a tag and a non-tag.
5972  if (!NonTag) return false;
5973
5974  Diag(Using->getLocation(), diag::err_using_decl_conflict);
5975  Diag(Target->getLocation(), diag::note_using_decl_target);
5976  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5977  return true;
5978}
5979
5980/// Builds a shadow declaration corresponding to a 'using' declaration.
5981UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5982                                            UsingDecl *UD,
5983                                            NamedDecl *Orig) {
5984
5985  // If we resolved to another shadow declaration, just coalesce them.
5986  NamedDecl *Target = Orig;
5987  if (isa<UsingShadowDecl>(Target)) {
5988    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5989    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5990  }
5991
5992  UsingShadowDecl *Shadow
5993    = UsingShadowDecl::Create(Context, CurContext,
5994                              UD->getLocation(), UD, Target);
5995  UD->addShadowDecl(Shadow);
5996
5997  Shadow->setAccess(UD->getAccess());
5998  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5999    Shadow->setInvalidDecl();
6000
6001  if (S)
6002    PushOnScopeChains(Shadow, S);
6003  else
6004    CurContext->addDecl(Shadow);
6005
6006
6007  return Shadow;
6008}
6009
6010/// Hides a using shadow declaration.  This is required by the current
6011/// using-decl implementation when a resolvable using declaration in a
6012/// class is followed by a declaration which would hide or override
6013/// one or more of the using decl's targets; for example:
6014///
6015///   struct Base { void foo(int); };
6016///   struct Derived : Base {
6017///     using Base::foo;
6018///     void foo(int);
6019///   };
6020///
6021/// The governing language is C++03 [namespace.udecl]p12:
6022///
6023///   When a using-declaration brings names from a base class into a
6024///   derived class scope, member functions in the derived class
6025///   override and/or hide member functions with the same name and
6026///   parameter types in a base class (rather than conflicting).
6027///
6028/// There are two ways to implement this:
6029///   (1) optimistically create shadow decls when they're not hidden
6030///       by existing declarations, or
6031///   (2) don't create any shadow decls (or at least don't make them
6032///       visible) until we've fully parsed/instantiated the class.
6033/// The problem with (1) is that we might have to retroactively remove
6034/// a shadow decl, which requires several O(n) operations because the
6035/// decl structures are (very reasonably) not designed for removal.
6036/// (2) avoids this but is very fiddly and phase-dependent.
6037void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6038  if (Shadow->getDeclName().getNameKind() ==
6039        DeclarationName::CXXConversionFunctionName)
6040    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6041
6042  // Remove it from the DeclContext...
6043  Shadow->getDeclContext()->removeDecl(Shadow);
6044
6045  // ...and the scope, if applicable...
6046  if (S) {
6047    S->RemoveDecl(Shadow);
6048    IdResolver.RemoveDecl(Shadow);
6049  }
6050
6051  // ...and the using decl.
6052  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6053
6054  // TODO: complain somehow if Shadow was used.  It shouldn't
6055  // be possible for this to happen, because...?
6056}
6057
6058/// Builds a using declaration.
6059///
6060/// \param IsInstantiation - Whether this call arises from an
6061///   instantiation of an unresolved using declaration.  We treat
6062///   the lookup differently for these declarations.
6063NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6064                                       SourceLocation UsingLoc,
6065                                       CXXScopeSpec &SS,
6066                                       const DeclarationNameInfo &NameInfo,
6067                                       AttributeList *AttrList,
6068                                       bool IsInstantiation,
6069                                       bool IsTypeName,
6070                                       SourceLocation TypenameLoc) {
6071  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6072  SourceLocation IdentLoc = NameInfo.getLoc();
6073  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6074
6075  // FIXME: We ignore attributes for now.
6076
6077  if (SS.isEmpty()) {
6078    Diag(IdentLoc, diag::err_using_requires_qualname);
6079    return 0;
6080  }
6081
6082  // Do the redeclaration lookup in the current scope.
6083  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6084                        ForRedeclaration);
6085  Previous.setHideTags(false);
6086  if (S) {
6087    LookupName(Previous, S);
6088
6089    // It is really dumb that we have to do this.
6090    LookupResult::Filter F = Previous.makeFilter();
6091    while (F.hasNext()) {
6092      NamedDecl *D = F.next();
6093      if (!isDeclInScope(D, CurContext, S))
6094        F.erase();
6095    }
6096    F.done();
6097  } else {
6098    assert(IsInstantiation && "no scope in non-instantiation");
6099    assert(CurContext->isRecord() && "scope not record in instantiation");
6100    LookupQualifiedName(Previous, CurContext);
6101  }
6102
6103  // Check for invalid redeclarations.
6104  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6105    return 0;
6106
6107  // Check for bad qualifiers.
6108  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6109    return 0;
6110
6111  DeclContext *LookupContext = computeDeclContext(SS);
6112  NamedDecl *D;
6113  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6114  if (!LookupContext) {
6115    if (IsTypeName) {
6116      // FIXME: not all declaration name kinds are legal here
6117      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6118                                              UsingLoc, TypenameLoc,
6119                                              QualifierLoc,
6120                                              IdentLoc, NameInfo.getName());
6121    } else {
6122      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6123                                           QualifierLoc, NameInfo);
6124    }
6125  } else {
6126    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6127                          NameInfo, IsTypeName);
6128  }
6129  D->setAccess(AS);
6130  CurContext->addDecl(D);
6131
6132  if (!LookupContext) return D;
6133  UsingDecl *UD = cast<UsingDecl>(D);
6134
6135  if (RequireCompleteDeclContext(SS, LookupContext)) {
6136    UD->setInvalidDecl();
6137    return UD;
6138  }
6139
6140  // The normal rules do not apply to inheriting constructor declarations.
6141  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6142    if (CheckInheritingConstructorUsingDecl(UD))
6143      UD->setInvalidDecl();
6144    return UD;
6145  }
6146
6147  // Otherwise, look up the target name.
6148
6149  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6150
6151  // Unlike most lookups, we don't always want to hide tag
6152  // declarations: tag names are visible through the using declaration
6153  // even if hidden by ordinary names, *except* in a dependent context
6154  // where it's important for the sanity of two-phase lookup.
6155  if (!IsInstantiation)
6156    R.setHideTags(false);
6157
6158  // For the purposes of this lookup, we have a base object type
6159  // equal to that of the current context.
6160  if (CurContext->isRecord()) {
6161    R.setBaseObjectType(
6162                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6163  }
6164
6165  LookupQualifiedName(R, LookupContext);
6166
6167  if (R.empty()) {
6168    Diag(IdentLoc, diag::err_no_member)
6169      << NameInfo.getName() << LookupContext << SS.getRange();
6170    UD->setInvalidDecl();
6171    return UD;
6172  }
6173
6174  if (R.isAmbiguous()) {
6175    UD->setInvalidDecl();
6176    return UD;
6177  }
6178
6179  if (IsTypeName) {
6180    // If we asked for a typename and got a non-type decl, error out.
6181    if (!R.getAsSingle<TypeDecl>()) {
6182      Diag(IdentLoc, diag::err_using_typename_non_type);
6183      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6184        Diag((*I)->getUnderlyingDecl()->getLocation(),
6185             diag::note_using_decl_target);
6186      UD->setInvalidDecl();
6187      return UD;
6188    }
6189  } else {
6190    // If we asked for a non-typename and we got a type, error out,
6191    // but only if this is an instantiation of an unresolved using
6192    // decl.  Otherwise just silently find the type name.
6193    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6194      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6195      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6196      UD->setInvalidDecl();
6197      return UD;
6198    }
6199  }
6200
6201  // C++0x N2914 [namespace.udecl]p6:
6202  // A using-declaration shall not name a namespace.
6203  if (R.getAsSingle<NamespaceDecl>()) {
6204    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6205      << SS.getRange();
6206    UD->setInvalidDecl();
6207    return UD;
6208  }
6209
6210  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6211    if (!CheckUsingShadowDecl(UD, *I, Previous))
6212      BuildUsingShadowDecl(S, UD, *I);
6213  }
6214
6215  return UD;
6216}
6217
6218/// Additional checks for a using declaration referring to a constructor name.
6219bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6220  assert(!UD->isTypeName() && "expecting a constructor name");
6221
6222  const Type *SourceType = UD->getQualifier()->getAsType();
6223  assert(SourceType &&
6224         "Using decl naming constructor doesn't have type in scope spec.");
6225  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6226
6227  // Check whether the named type is a direct base class.
6228  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6229  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6230  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6231       BaseIt != BaseE; ++BaseIt) {
6232    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6233    if (CanonicalSourceType == BaseType)
6234      break;
6235    if (BaseIt->getType()->isDependentType())
6236      break;
6237  }
6238
6239  if (BaseIt == BaseE) {
6240    // Did not find SourceType in the bases.
6241    Diag(UD->getUsingLocation(),
6242         diag::err_using_decl_constructor_not_in_direct_base)
6243      << UD->getNameInfo().getSourceRange()
6244      << QualType(SourceType, 0) << TargetClass;
6245    return true;
6246  }
6247
6248  if (!CurContext->isDependentContext())
6249    BaseIt->setInheritConstructors();
6250
6251  return false;
6252}
6253
6254/// Checks that the given using declaration is not an invalid
6255/// redeclaration.  Note that this is checking only for the using decl
6256/// itself, not for any ill-formedness among the UsingShadowDecls.
6257bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6258                                       bool isTypeName,
6259                                       const CXXScopeSpec &SS,
6260                                       SourceLocation NameLoc,
6261                                       const LookupResult &Prev) {
6262  // C++03 [namespace.udecl]p8:
6263  // C++0x [namespace.udecl]p10:
6264  //   A using-declaration is a declaration and can therefore be used
6265  //   repeatedly where (and only where) multiple declarations are
6266  //   allowed.
6267  //
6268  // That's in non-member contexts.
6269  if (!CurContext->getRedeclContext()->isRecord())
6270    return false;
6271
6272  NestedNameSpecifier *Qual
6273    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6274
6275  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6276    NamedDecl *D = *I;
6277
6278    bool DTypename;
6279    NestedNameSpecifier *DQual;
6280    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6281      DTypename = UD->isTypeName();
6282      DQual = UD->getQualifier();
6283    } else if (UnresolvedUsingValueDecl *UD
6284                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6285      DTypename = false;
6286      DQual = UD->getQualifier();
6287    } else if (UnresolvedUsingTypenameDecl *UD
6288                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6289      DTypename = true;
6290      DQual = UD->getQualifier();
6291    } else continue;
6292
6293    // using decls differ if one says 'typename' and the other doesn't.
6294    // FIXME: non-dependent using decls?
6295    if (isTypeName != DTypename) continue;
6296
6297    // using decls differ if they name different scopes (but note that
6298    // template instantiation can cause this check to trigger when it
6299    // didn't before instantiation).
6300    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6301        Context.getCanonicalNestedNameSpecifier(DQual))
6302      continue;
6303
6304    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6305    Diag(D->getLocation(), diag::note_using_decl) << 1;
6306    return true;
6307  }
6308
6309  return false;
6310}
6311
6312
6313/// Checks that the given nested-name qualifier used in a using decl
6314/// in the current context is appropriately related to the current
6315/// scope.  If an error is found, diagnoses it and returns true.
6316bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6317                                   const CXXScopeSpec &SS,
6318                                   SourceLocation NameLoc) {
6319  DeclContext *NamedContext = computeDeclContext(SS);
6320
6321  if (!CurContext->isRecord()) {
6322    // C++03 [namespace.udecl]p3:
6323    // C++0x [namespace.udecl]p8:
6324    //   A using-declaration for a class member shall be a member-declaration.
6325
6326    // If we weren't able to compute a valid scope, it must be a
6327    // dependent class scope.
6328    if (!NamedContext || NamedContext->isRecord()) {
6329      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6330        << SS.getRange();
6331      return true;
6332    }
6333
6334    // Otherwise, everything is known to be fine.
6335    return false;
6336  }
6337
6338  // The current scope is a record.
6339
6340  // If the named context is dependent, we can't decide much.
6341  if (!NamedContext) {
6342    // FIXME: in C++0x, we can diagnose if we can prove that the
6343    // nested-name-specifier does not refer to a base class, which is
6344    // still possible in some cases.
6345
6346    // Otherwise we have to conservatively report that things might be
6347    // okay.
6348    return false;
6349  }
6350
6351  if (!NamedContext->isRecord()) {
6352    // Ideally this would point at the last name in the specifier,
6353    // but we don't have that level of source info.
6354    Diag(SS.getRange().getBegin(),
6355         diag::err_using_decl_nested_name_specifier_is_not_class)
6356      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6357    return true;
6358  }
6359
6360  if (!NamedContext->isDependentContext() &&
6361      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6362    return true;
6363
6364  if (getLangOpts().CPlusPlus0x) {
6365    // C++0x [namespace.udecl]p3:
6366    //   In a using-declaration used as a member-declaration, the
6367    //   nested-name-specifier shall name a base class of the class
6368    //   being defined.
6369
6370    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6371                                 cast<CXXRecordDecl>(NamedContext))) {
6372      if (CurContext == NamedContext) {
6373        Diag(NameLoc,
6374             diag::err_using_decl_nested_name_specifier_is_current_class)
6375          << SS.getRange();
6376        return true;
6377      }
6378
6379      Diag(SS.getRange().getBegin(),
6380           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6381        << (NestedNameSpecifier*) SS.getScopeRep()
6382        << cast<CXXRecordDecl>(CurContext)
6383        << SS.getRange();
6384      return true;
6385    }
6386
6387    return false;
6388  }
6389
6390  // C++03 [namespace.udecl]p4:
6391  //   A using-declaration used as a member-declaration shall refer
6392  //   to a member of a base class of the class being defined [etc.].
6393
6394  // Salient point: SS doesn't have to name a base class as long as
6395  // lookup only finds members from base classes.  Therefore we can
6396  // diagnose here only if we can prove that that can't happen,
6397  // i.e. if the class hierarchies provably don't intersect.
6398
6399  // TODO: it would be nice if "definitely valid" results were cached
6400  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6401  // need to be repeated.
6402
6403  struct UserData {
6404    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6405
6406    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6407      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6408      Data->Bases.insert(Base);
6409      return true;
6410    }
6411
6412    bool hasDependentBases(const CXXRecordDecl *Class) {
6413      return !Class->forallBases(collect, this);
6414    }
6415
6416    /// Returns true if the base is dependent or is one of the
6417    /// accumulated base classes.
6418    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6419      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6420      return !Data->Bases.count(Base);
6421    }
6422
6423    bool mightShareBases(const CXXRecordDecl *Class) {
6424      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6425    }
6426  };
6427
6428  UserData Data;
6429
6430  // Returns false if we find a dependent base.
6431  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6432    return false;
6433
6434  // Returns false if the class has a dependent base or if it or one
6435  // of its bases is present in the base set of the current context.
6436  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6437    return false;
6438
6439  Diag(SS.getRange().getBegin(),
6440       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6441    << (NestedNameSpecifier*) SS.getScopeRep()
6442    << cast<CXXRecordDecl>(CurContext)
6443    << SS.getRange();
6444
6445  return true;
6446}
6447
6448Decl *Sema::ActOnAliasDeclaration(Scope *S,
6449                                  AccessSpecifier AS,
6450                                  MultiTemplateParamsArg TemplateParamLists,
6451                                  SourceLocation UsingLoc,
6452                                  UnqualifiedId &Name,
6453                                  TypeResult Type) {
6454  // Skip up to the relevant declaration scope.
6455  while (S->getFlags() & Scope::TemplateParamScope)
6456    S = S->getParent();
6457  assert((S->getFlags() & Scope::DeclScope) &&
6458         "got alias-declaration outside of declaration scope");
6459
6460  if (Type.isInvalid())
6461    return 0;
6462
6463  bool Invalid = false;
6464  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6465  TypeSourceInfo *TInfo = 0;
6466  GetTypeFromParser(Type.get(), &TInfo);
6467
6468  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6469    return 0;
6470
6471  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6472                                      UPPC_DeclarationType)) {
6473    Invalid = true;
6474    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6475                                             TInfo->getTypeLoc().getBeginLoc());
6476  }
6477
6478  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6479  LookupName(Previous, S);
6480
6481  // Warn about shadowing the name of a template parameter.
6482  if (Previous.isSingleResult() &&
6483      Previous.getFoundDecl()->isTemplateParameter()) {
6484    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6485    Previous.clear();
6486  }
6487
6488  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6489         "name in alias declaration must be an identifier");
6490  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6491                                               Name.StartLocation,
6492                                               Name.Identifier, TInfo);
6493
6494  NewTD->setAccess(AS);
6495
6496  if (Invalid)
6497    NewTD->setInvalidDecl();
6498
6499  CheckTypedefForVariablyModifiedType(S, NewTD);
6500  Invalid |= NewTD->isInvalidDecl();
6501
6502  bool Redeclaration = false;
6503
6504  NamedDecl *NewND;
6505  if (TemplateParamLists.size()) {
6506    TypeAliasTemplateDecl *OldDecl = 0;
6507    TemplateParameterList *OldTemplateParams = 0;
6508
6509    if (TemplateParamLists.size() != 1) {
6510      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6511        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6512         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6513    }
6514    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6515
6516    // Only consider previous declarations in the same scope.
6517    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6518                         /*ExplicitInstantiationOrSpecialization*/false);
6519    if (!Previous.empty()) {
6520      Redeclaration = true;
6521
6522      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6523      if (!OldDecl && !Invalid) {
6524        Diag(UsingLoc, diag::err_redefinition_different_kind)
6525          << Name.Identifier;
6526
6527        NamedDecl *OldD = Previous.getRepresentativeDecl();
6528        if (OldD->getLocation().isValid())
6529          Diag(OldD->getLocation(), diag::note_previous_definition);
6530
6531        Invalid = true;
6532      }
6533
6534      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6535        if (TemplateParameterListsAreEqual(TemplateParams,
6536                                           OldDecl->getTemplateParameters(),
6537                                           /*Complain=*/true,
6538                                           TPL_TemplateMatch))
6539          OldTemplateParams = OldDecl->getTemplateParameters();
6540        else
6541          Invalid = true;
6542
6543        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6544        if (!Invalid &&
6545            !Context.hasSameType(OldTD->getUnderlyingType(),
6546                                 NewTD->getUnderlyingType())) {
6547          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6548          // but we can't reasonably accept it.
6549          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6550            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6551          if (OldTD->getLocation().isValid())
6552            Diag(OldTD->getLocation(), diag::note_previous_definition);
6553          Invalid = true;
6554        }
6555      }
6556    }
6557
6558    // Merge any previous default template arguments into our parameters,
6559    // and check the parameter list.
6560    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6561                                   TPC_TypeAliasTemplate))
6562      return 0;
6563
6564    TypeAliasTemplateDecl *NewDecl =
6565      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6566                                    Name.Identifier, TemplateParams,
6567                                    NewTD);
6568
6569    NewDecl->setAccess(AS);
6570
6571    if (Invalid)
6572      NewDecl->setInvalidDecl();
6573    else if (OldDecl)
6574      NewDecl->setPreviousDeclaration(OldDecl);
6575
6576    NewND = NewDecl;
6577  } else {
6578    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6579    NewND = NewTD;
6580  }
6581
6582  if (!Redeclaration)
6583    PushOnScopeChains(NewND, S);
6584
6585  return NewND;
6586}
6587
6588Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6589                                             SourceLocation NamespaceLoc,
6590                                             SourceLocation AliasLoc,
6591                                             IdentifierInfo *Alias,
6592                                             CXXScopeSpec &SS,
6593                                             SourceLocation IdentLoc,
6594                                             IdentifierInfo *Ident) {
6595
6596  // Lookup the namespace name.
6597  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6598  LookupParsedName(R, S, &SS);
6599
6600  // Check if we have a previous declaration with the same name.
6601  NamedDecl *PrevDecl
6602    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6603                       ForRedeclaration);
6604  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6605    PrevDecl = 0;
6606
6607  if (PrevDecl) {
6608    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6609      // We already have an alias with the same name that points to the same
6610      // namespace, so don't create a new one.
6611      // FIXME: At some point, we'll want to create the (redundant)
6612      // declaration to maintain better source information.
6613      if (!R.isAmbiguous() && !R.empty() &&
6614          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6615        return 0;
6616    }
6617
6618    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6619      diag::err_redefinition_different_kind;
6620    Diag(AliasLoc, DiagID) << Alias;
6621    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6622    return 0;
6623  }
6624
6625  if (R.isAmbiguous())
6626    return 0;
6627
6628  if (R.empty()) {
6629    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6630      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6631      return 0;
6632    }
6633  }
6634
6635  NamespaceAliasDecl *AliasDecl =
6636    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6637                               Alias, SS.getWithLocInContext(Context),
6638                               IdentLoc, R.getFoundDecl());
6639
6640  PushOnScopeChains(AliasDecl, S);
6641  return AliasDecl;
6642}
6643
6644namespace {
6645  /// \brief Scoped object used to handle the state changes required in Sema
6646  /// to implicitly define the body of a C++ member function;
6647  class ImplicitlyDefinedFunctionScope {
6648    Sema &S;
6649    Sema::ContextRAII SavedContext;
6650
6651  public:
6652    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6653      : S(S), SavedContext(S, Method)
6654    {
6655      S.PushFunctionScope();
6656      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6657    }
6658
6659    ~ImplicitlyDefinedFunctionScope() {
6660      S.PopExpressionEvaluationContext();
6661      S.PopFunctionScopeInfo();
6662    }
6663  };
6664}
6665
6666Sema::ImplicitExceptionSpecification
6667Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6668  // C++ [except.spec]p14:
6669  //   An implicitly declared special member function (Clause 12) shall have an
6670  //   exception-specification. [...]
6671  ImplicitExceptionSpecification ExceptSpec(*this);
6672  if (ClassDecl->isInvalidDecl())
6673    return ExceptSpec;
6674
6675  // Direct base-class constructors.
6676  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6677                                       BEnd = ClassDecl->bases_end();
6678       B != BEnd; ++B) {
6679    if (B->isVirtual()) // Handled below.
6680      continue;
6681
6682    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6683      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6684      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6685      // If this is a deleted function, add it anyway. This might be conformant
6686      // with the standard. This might not. I'm not sure. It might not matter.
6687      if (Constructor)
6688        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6689    }
6690  }
6691
6692  // Virtual base-class constructors.
6693  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6694                                       BEnd = ClassDecl->vbases_end();
6695       B != BEnd; ++B) {
6696    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6697      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6698      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6699      // If this is a deleted function, add it anyway. This might be conformant
6700      // with the standard. This might not. I'm not sure. It might not matter.
6701      if (Constructor)
6702        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
6703    }
6704  }
6705
6706  // Field constructors.
6707  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6708                               FEnd = ClassDecl->field_end();
6709       F != FEnd; ++F) {
6710    if (F->hasInClassInitializer()) {
6711      if (Expr *E = F->getInClassInitializer())
6712        ExceptSpec.CalledExpr(E);
6713      else if (!F->isInvalidDecl())
6714        ExceptSpec.SetDelayed();
6715    } else if (const RecordType *RecordTy
6716              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6717      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6718      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6719      // If this is a deleted function, add it anyway. This might be conformant
6720      // with the standard. This might not. I'm not sure. It might not matter.
6721      // In particular, the problem is that this function never gets called. It
6722      // might just be ill-formed because this function attempts to refer to
6723      // a deleted function here.
6724      if (Constructor)
6725        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
6726    }
6727  }
6728
6729  return ExceptSpec;
6730}
6731
6732CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6733                                                     CXXRecordDecl *ClassDecl) {
6734  // C++ [class.ctor]p5:
6735  //   A default constructor for a class X is a constructor of class X
6736  //   that can be called without an argument. If there is no
6737  //   user-declared constructor for class X, a default constructor is
6738  //   implicitly declared. An implicitly-declared default constructor
6739  //   is an inline public member of its class.
6740  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6741         "Should not build implicit default constructor!");
6742
6743  ImplicitExceptionSpecification Spec =
6744    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6745  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6746
6747  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
6748                                                     CXXDefaultConstructor,
6749                                                     false);
6750
6751  // Create the actual constructor declaration.
6752  CanQualType ClassType
6753    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6754  SourceLocation ClassLoc = ClassDecl->getLocation();
6755  DeclarationName Name
6756    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6757  DeclarationNameInfo NameInfo(Name, ClassLoc);
6758  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6759      Context, ClassDecl, ClassLoc, NameInfo,
6760      Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6761      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6762      Constexpr);
6763  DefaultCon->setAccess(AS_public);
6764  DefaultCon->setDefaulted();
6765  DefaultCon->setImplicit();
6766  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6767
6768  // Note that we have declared this constructor.
6769  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6770
6771  if (Scope *S = getScopeForContext(ClassDecl))
6772    PushOnScopeChains(DefaultCon, S, false);
6773  ClassDecl->addDecl(DefaultCon);
6774
6775  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6776    DefaultCon->setDeletedAsWritten();
6777
6778  return DefaultCon;
6779}
6780
6781void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6782                                            CXXConstructorDecl *Constructor) {
6783  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6784          !Constructor->doesThisDeclarationHaveABody() &&
6785          !Constructor->isDeleted()) &&
6786    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6787
6788  CXXRecordDecl *ClassDecl = Constructor->getParent();
6789  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6790
6791  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6792  DiagnosticErrorTrap Trap(Diags);
6793  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6794      Trap.hasErrorOccurred()) {
6795    Diag(CurrentLocation, diag::note_member_synthesized_at)
6796      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6797    Constructor->setInvalidDecl();
6798    return;
6799  }
6800
6801  SourceLocation Loc = Constructor->getLocation();
6802  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6803
6804  Constructor->setUsed();
6805  MarkVTableUsed(CurrentLocation, ClassDecl);
6806
6807  if (ASTMutationListener *L = getASTMutationListener()) {
6808    L->CompletedImplicitDefinition(Constructor);
6809  }
6810}
6811
6812/// Get any existing defaulted default constructor for the given class. Do not
6813/// implicitly define one if it does not exist.
6814static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6815                                                             CXXRecordDecl *D) {
6816  ASTContext &Context = Self.Context;
6817  QualType ClassType = Context.getTypeDeclType(D);
6818  DeclarationName ConstructorName
6819    = Context.DeclarationNames.getCXXConstructorName(
6820                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6821
6822  DeclContext::lookup_const_iterator Con, ConEnd;
6823  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6824       Con != ConEnd; ++Con) {
6825    // A function template cannot be defaulted.
6826    if (isa<FunctionTemplateDecl>(*Con))
6827      continue;
6828
6829    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6830    if (Constructor->isDefaultConstructor())
6831      return Constructor->isDefaulted() ? Constructor : 0;
6832  }
6833  return 0;
6834}
6835
6836void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6837  if (!D) return;
6838  AdjustDeclIfTemplate(D);
6839
6840  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6841  CXXConstructorDecl *CtorDecl
6842    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6843
6844  if (!CtorDecl) return;
6845
6846  // Compute the exception specification for the default constructor.
6847  const FunctionProtoType *CtorTy =
6848    CtorDecl->getType()->castAs<FunctionProtoType>();
6849  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6850    // FIXME: Don't do this unless the exception spec is needed.
6851    ImplicitExceptionSpecification Spec =
6852      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6853    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6854    assert(EPI.ExceptionSpecType != EST_Delayed);
6855
6856    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6857  }
6858
6859  // If the default constructor is explicitly defaulted, checking the exception
6860  // specification is deferred until now.
6861  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6862      !ClassDecl->isDependentType())
6863    CheckExplicitlyDefaultedSpecialMember(CtorDecl);
6864}
6865
6866void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6867  // We start with an initial pass over the base classes to collect those that
6868  // inherit constructors from. If there are none, we can forgo all further
6869  // processing.
6870  typedef SmallVector<const RecordType *, 4> BasesVector;
6871  BasesVector BasesToInheritFrom;
6872  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6873                                          BaseE = ClassDecl->bases_end();
6874         BaseIt != BaseE; ++BaseIt) {
6875    if (BaseIt->getInheritConstructors()) {
6876      QualType Base = BaseIt->getType();
6877      if (Base->isDependentType()) {
6878        // If we inherit constructors from anything that is dependent, just
6879        // abort processing altogether. We'll get another chance for the
6880        // instantiations.
6881        return;
6882      }
6883      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6884    }
6885  }
6886  if (BasesToInheritFrom.empty())
6887    return;
6888
6889  // Now collect the constructors that we already have in the current class.
6890  // Those take precedence over inherited constructors.
6891  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6892  //   unless there is a user-declared constructor with the same signature in
6893  //   the class where the using-declaration appears.
6894  llvm::SmallSet<const Type *, 8> ExistingConstructors;
6895  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6896                                    CtorE = ClassDecl->ctor_end();
6897       CtorIt != CtorE; ++CtorIt) {
6898    ExistingConstructors.insert(
6899        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6900  }
6901
6902  DeclarationName CreatedCtorName =
6903      Context.DeclarationNames.getCXXConstructorName(
6904          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6905
6906  // Now comes the true work.
6907  // First, we keep a map from constructor types to the base that introduced
6908  // them. Needed for finding conflicting constructors. We also keep the
6909  // actually inserted declarations in there, for pretty diagnostics.
6910  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6911  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6912  ConstructorToSourceMap InheritedConstructors;
6913  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6914                             BaseE = BasesToInheritFrom.end();
6915       BaseIt != BaseE; ++BaseIt) {
6916    const RecordType *Base = *BaseIt;
6917    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6918    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6919    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6920                                      CtorE = BaseDecl->ctor_end();
6921         CtorIt != CtorE; ++CtorIt) {
6922      // Find the using declaration for inheriting this base's constructors.
6923      // FIXME: Don't perform name lookup just to obtain a source location!
6924      DeclarationName Name =
6925          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6926      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
6927      LookupQualifiedName(Result, CurContext);
6928      UsingDecl *UD = Result.getAsSingle<UsingDecl>();
6929      SourceLocation UsingLoc = UD ? UD->getLocation() :
6930                                     ClassDecl->getLocation();
6931
6932      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6933      //   from the class X named in the using-declaration consists of actual
6934      //   constructors and notional constructors that result from the
6935      //   transformation of defaulted parameters as follows:
6936      //   - all non-template default constructors of X, and
6937      //   - for each non-template constructor of X that has at least one
6938      //     parameter with a default argument, the set of constructors that
6939      //     results from omitting any ellipsis parameter specification and
6940      //     successively omitting parameters with a default argument from the
6941      //     end of the parameter-type-list.
6942      CXXConstructorDecl *BaseCtor = *CtorIt;
6943      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6944      const FunctionProtoType *BaseCtorType =
6945          BaseCtor->getType()->getAs<FunctionProtoType>();
6946
6947      for (unsigned params = BaseCtor->getMinRequiredArguments(),
6948                    maxParams = BaseCtor->getNumParams();
6949           params <= maxParams; ++params) {
6950        // Skip default constructors. They're never inherited.
6951        if (params == 0)
6952          continue;
6953        // Skip copy and move constructors for the same reason.
6954        if (CanBeCopyOrMove && params == 1)
6955          continue;
6956
6957        // Build up a function type for this particular constructor.
6958        // FIXME: The working paper does not consider that the exception spec
6959        // for the inheriting constructor might be larger than that of the
6960        // source. This code doesn't yet, either. When it does, this code will
6961        // need to be delayed until after exception specifications and in-class
6962        // member initializers are attached.
6963        const Type *NewCtorType;
6964        if (params == maxParams)
6965          NewCtorType = BaseCtorType;
6966        else {
6967          SmallVector<QualType, 16> Args;
6968          for (unsigned i = 0; i < params; ++i) {
6969            Args.push_back(BaseCtorType->getArgType(i));
6970          }
6971          FunctionProtoType::ExtProtoInfo ExtInfo =
6972              BaseCtorType->getExtProtoInfo();
6973          ExtInfo.Variadic = false;
6974          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6975                                                Args.data(), params, ExtInfo)
6976                       .getTypePtr();
6977        }
6978        const Type *CanonicalNewCtorType =
6979            Context.getCanonicalType(NewCtorType);
6980
6981        // Now that we have the type, first check if the class already has a
6982        // constructor with this signature.
6983        if (ExistingConstructors.count(CanonicalNewCtorType))
6984          continue;
6985
6986        // Then we check if we have already declared an inherited constructor
6987        // with this signature.
6988        std::pair<ConstructorToSourceMap::iterator, bool> result =
6989            InheritedConstructors.insert(std::make_pair(
6990                CanonicalNewCtorType,
6991                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6992        if (!result.second) {
6993          // Already in the map. If it came from a different class, that's an
6994          // error. Not if it's from the same.
6995          CanQualType PreviousBase = result.first->second.first;
6996          if (CanonicalBase != PreviousBase) {
6997            const CXXConstructorDecl *PrevCtor = result.first->second.second;
6998            const CXXConstructorDecl *PrevBaseCtor =
6999                PrevCtor->getInheritedConstructor();
7000            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7001
7002            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7003            Diag(BaseCtor->getLocation(),
7004                 diag::note_using_decl_constructor_conflict_current_ctor);
7005            Diag(PrevBaseCtor->getLocation(),
7006                 diag::note_using_decl_constructor_conflict_previous_ctor);
7007            Diag(PrevCtor->getLocation(),
7008                 diag::note_using_decl_constructor_conflict_previous_using);
7009          }
7010          continue;
7011        }
7012
7013        // OK, we're there, now add the constructor.
7014        // C++0x [class.inhctor]p8: [...] that would be performed by a
7015        //   user-written inline constructor [...]
7016        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7017        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7018            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7019            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7020            /*ImplicitlyDeclared=*/true,
7021            // FIXME: Due to a defect in the standard, we treat inherited
7022            // constructors as constexpr even if that makes them ill-formed.
7023            /*Constexpr=*/BaseCtor->isConstexpr());
7024        NewCtor->setAccess(BaseCtor->getAccess());
7025
7026        // Build up the parameter decls and add them.
7027        SmallVector<ParmVarDecl *, 16> ParamDecls;
7028        for (unsigned i = 0; i < params; ++i) {
7029          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7030                                                   UsingLoc, UsingLoc,
7031                                                   /*IdentifierInfo=*/0,
7032                                                   BaseCtorType->getArgType(i),
7033                                                   /*TInfo=*/0, SC_None,
7034                                                   SC_None, /*DefaultArg=*/0));
7035        }
7036        NewCtor->setParams(ParamDecls);
7037        NewCtor->setInheritedConstructor(BaseCtor);
7038
7039        ClassDecl->addDecl(NewCtor);
7040        result.first->second.second = NewCtor;
7041      }
7042    }
7043  }
7044}
7045
7046Sema::ImplicitExceptionSpecification
7047Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
7048  // C++ [except.spec]p14:
7049  //   An implicitly declared special member function (Clause 12) shall have
7050  //   an exception-specification.
7051  ImplicitExceptionSpecification ExceptSpec(*this);
7052  if (ClassDecl->isInvalidDecl())
7053    return ExceptSpec;
7054
7055  // Direct base-class destructors.
7056  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7057                                       BEnd = ClassDecl->bases_end();
7058       B != BEnd; ++B) {
7059    if (B->isVirtual()) // Handled below.
7060      continue;
7061
7062    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7063      ExceptSpec.CalledDecl(B->getLocStart(),
7064                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7065  }
7066
7067  // Virtual base-class destructors.
7068  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7069                                       BEnd = ClassDecl->vbases_end();
7070       B != BEnd; ++B) {
7071    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7072      ExceptSpec.CalledDecl(B->getLocStart(),
7073                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7074  }
7075
7076  // Field destructors.
7077  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7078                               FEnd = ClassDecl->field_end();
7079       F != FEnd; ++F) {
7080    if (const RecordType *RecordTy
7081        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7082      ExceptSpec.CalledDecl(F->getLocation(),
7083                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7084  }
7085
7086  return ExceptSpec;
7087}
7088
7089CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7090  // C++ [class.dtor]p2:
7091  //   If a class has no user-declared destructor, a destructor is
7092  //   declared implicitly. An implicitly-declared destructor is an
7093  //   inline public member of its class.
7094
7095  ImplicitExceptionSpecification Spec =
7096      ComputeDefaultedDtorExceptionSpec(ClassDecl);
7097  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7098
7099  // Create the actual destructor declaration.
7100  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
7101
7102  CanQualType ClassType
7103    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7104  SourceLocation ClassLoc = ClassDecl->getLocation();
7105  DeclarationName Name
7106    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7107  DeclarationNameInfo NameInfo(Name, ClassLoc);
7108  CXXDestructorDecl *Destructor
7109      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7110                                  /*isInline=*/true,
7111                                  /*isImplicitlyDeclared=*/true);
7112  Destructor->setAccess(AS_public);
7113  Destructor->setDefaulted();
7114  Destructor->setImplicit();
7115  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7116
7117  // Note that we have declared this destructor.
7118  ++ASTContext::NumImplicitDestructorsDeclared;
7119
7120  // Introduce this destructor into its scope.
7121  if (Scope *S = getScopeForContext(ClassDecl))
7122    PushOnScopeChains(Destructor, S, false);
7123  ClassDecl->addDecl(Destructor);
7124
7125  // This could be uniqued if it ever proves significant.
7126  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
7127
7128  AddOverriddenMethods(ClassDecl, Destructor);
7129
7130  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7131    Destructor->setDeletedAsWritten();
7132
7133  return Destructor;
7134}
7135
7136void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7137                                    CXXDestructorDecl *Destructor) {
7138  assert((Destructor->isDefaulted() &&
7139          !Destructor->doesThisDeclarationHaveABody() &&
7140          !Destructor->isDeleted()) &&
7141         "DefineImplicitDestructor - call it for implicit default dtor");
7142  CXXRecordDecl *ClassDecl = Destructor->getParent();
7143  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7144
7145  if (Destructor->isInvalidDecl())
7146    return;
7147
7148  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7149
7150  DiagnosticErrorTrap Trap(Diags);
7151  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7152                                         Destructor->getParent());
7153
7154  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7155    Diag(CurrentLocation, diag::note_member_synthesized_at)
7156      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7157
7158    Destructor->setInvalidDecl();
7159    return;
7160  }
7161
7162  SourceLocation Loc = Destructor->getLocation();
7163  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7164  Destructor->setImplicitlyDefined(true);
7165  Destructor->setUsed();
7166  MarkVTableUsed(CurrentLocation, ClassDecl);
7167
7168  if (ASTMutationListener *L = getASTMutationListener()) {
7169    L->CompletedImplicitDefinition(Destructor);
7170  }
7171}
7172
7173/// \brief Perform any semantic analysis which needs to be delayed until all
7174/// pending class member declarations have been parsed.
7175void Sema::ActOnFinishCXXMemberDecls() {
7176  // Now we have parsed all exception specifications, determine the implicit
7177  // exception specifications for destructors.
7178  for (unsigned i = 0, e = DelayedDestructorExceptionSpecs.size();
7179       i != e; ++i) {
7180    CXXDestructorDecl *Dtor = DelayedDestructorExceptionSpecs[i];
7181    AdjustDestructorExceptionSpec(Dtor->getParent(), Dtor, true);
7182  }
7183  DelayedDestructorExceptionSpecs.clear();
7184
7185  // Perform any deferred checking of exception specifications for virtual
7186  // destructors.
7187  for (unsigned i = 0, e = DelayedDestructorExceptionSpecChecks.size();
7188       i != e; ++i) {
7189    const CXXDestructorDecl *Dtor =
7190        DelayedDestructorExceptionSpecChecks[i].first;
7191    assert(!Dtor->getParent()->isDependentType() &&
7192           "Should not ever add destructors of templates into the list.");
7193    CheckOverridingFunctionExceptionSpec(Dtor,
7194        DelayedDestructorExceptionSpecChecks[i].second);
7195  }
7196  DelayedDestructorExceptionSpecChecks.clear();
7197}
7198
7199void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7200                                         CXXDestructorDecl *destructor,
7201                                         bool WasDelayed) {
7202  // C++11 [class.dtor]p3:
7203  //   A declaration of a destructor that does not have an exception-
7204  //   specification is implicitly considered to have the same exception-
7205  //   specification as an implicit declaration.
7206  const FunctionProtoType *dtorType = destructor->getType()->
7207                                        getAs<FunctionProtoType>();
7208  if (!WasDelayed && dtorType->hasExceptionSpec())
7209    return;
7210
7211  ImplicitExceptionSpecification exceptSpec =
7212      ComputeDefaultedDtorExceptionSpec(classDecl);
7213
7214  // Replace the destructor's type, building off the existing one. Fortunately,
7215  // the only thing of interest in the destructor type is its extended info.
7216  // The return and arguments are fixed.
7217  FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
7218  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7219  epi.NumExceptions = exceptSpec.size();
7220  epi.Exceptions = exceptSpec.data();
7221  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7222
7223  destructor->setType(ty);
7224
7225  // If we can't compute the exception specification for this destructor yet
7226  // (because it depends on an exception specification which we have not parsed
7227  // yet), make a note that we need to try again when the class is complete.
7228  if (epi.ExceptionSpecType == EST_Delayed) {
7229    assert(!WasDelayed && "couldn't compute destructor exception spec");
7230    DelayedDestructorExceptionSpecs.push_back(destructor);
7231  }
7232
7233  // FIXME: If the destructor has a body that could throw, and the newly created
7234  // spec doesn't allow exceptions, we should emit a warning, because this
7235  // change in behavior can break conforming C++03 programs at runtime.
7236  // However, we don't have a body yet, so it needs to be done somewhere else.
7237}
7238
7239/// \brief Builds a statement that copies/moves the given entity from \p From to
7240/// \c To.
7241///
7242/// This routine is used to copy/move the members of a class with an
7243/// implicitly-declared copy/move assignment operator. When the entities being
7244/// copied are arrays, this routine builds for loops to copy them.
7245///
7246/// \param S The Sema object used for type-checking.
7247///
7248/// \param Loc The location where the implicit copy/move is being generated.
7249///
7250/// \param T The type of the expressions being copied/moved. Both expressions
7251/// must have this type.
7252///
7253/// \param To The expression we are copying/moving to.
7254///
7255/// \param From The expression we are copying/moving from.
7256///
7257/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7258/// Otherwise, it's a non-static member subobject.
7259///
7260/// \param Copying Whether we're copying or moving.
7261///
7262/// \param Depth Internal parameter recording the depth of the recursion.
7263///
7264/// \returns A statement or a loop that copies the expressions.
7265static StmtResult
7266BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7267                      Expr *To, Expr *From,
7268                      bool CopyingBaseSubobject, bool Copying,
7269                      unsigned Depth = 0) {
7270  // C++0x [class.copy]p28:
7271  //   Each subobject is assigned in the manner appropriate to its type:
7272  //
7273  //     - if the subobject is of class type, as if by a call to operator= with
7274  //       the subobject as the object expression and the corresponding
7275  //       subobject of x as a single function argument (as if by explicit
7276  //       qualification; that is, ignoring any possible virtual overriding
7277  //       functions in more derived classes);
7278  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7279    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7280
7281    // Look for operator=.
7282    DeclarationName Name
7283      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7284    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7285    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7286
7287    // Filter out any result that isn't a copy/move-assignment operator.
7288    LookupResult::Filter F = OpLookup.makeFilter();
7289    while (F.hasNext()) {
7290      NamedDecl *D = F.next();
7291      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7292        if (Method->isCopyAssignmentOperator() ||
7293            (!Copying && Method->isMoveAssignmentOperator()))
7294          continue;
7295
7296      F.erase();
7297    }
7298    F.done();
7299
7300    // Suppress the protected check (C++ [class.protected]) for each of the
7301    // assignment operators we found. This strange dance is required when
7302    // we're assigning via a base classes's copy-assignment operator. To
7303    // ensure that we're getting the right base class subobject (without
7304    // ambiguities), we need to cast "this" to that subobject type; to
7305    // ensure that we don't go through the virtual call mechanism, we need
7306    // to qualify the operator= name with the base class (see below). However,
7307    // this means that if the base class has a protected copy assignment
7308    // operator, the protected member access check will fail. So, we
7309    // rewrite "protected" access to "public" access in this case, since we
7310    // know by construction that we're calling from a derived class.
7311    if (CopyingBaseSubobject) {
7312      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7313           L != LEnd; ++L) {
7314        if (L.getAccess() == AS_protected)
7315          L.setAccess(AS_public);
7316      }
7317    }
7318
7319    // Create the nested-name-specifier that will be used to qualify the
7320    // reference to operator=; this is required to suppress the virtual
7321    // call mechanism.
7322    CXXScopeSpec SS;
7323    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7324    SS.MakeTrivial(S.Context,
7325                   NestedNameSpecifier::Create(S.Context, 0, false,
7326                                               CanonicalT),
7327                   Loc);
7328
7329    // Create the reference to operator=.
7330    ExprResult OpEqualRef
7331      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7332                                   /*TemplateKWLoc=*/SourceLocation(),
7333                                   /*FirstQualifierInScope=*/0,
7334                                   OpLookup,
7335                                   /*TemplateArgs=*/0,
7336                                   /*SuppressQualifierCheck=*/true);
7337    if (OpEqualRef.isInvalid())
7338      return StmtError();
7339
7340    // Build the call to the assignment operator.
7341
7342    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7343                                                  OpEqualRef.takeAs<Expr>(),
7344                                                  Loc, &From, 1, Loc);
7345    if (Call.isInvalid())
7346      return StmtError();
7347
7348    return S.Owned(Call.takeAs<Stmt>());
7349  }
7350
7351  //     - if the subobject is of scalar type, the built-in assignment
7352  //       operator is used.
7353  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7354  if (!ArrayTy) {
7355    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7356    if (Assignment.isInvalid())
7357      return StmtError();
7358
7359    return S.Owned(Assignment.takeAs<Stmt>());
7360  }
7361
7362  //     - if the subobject is an array, each element is assigned, in the
7363  //       manner appropriate to the element type;
7364
7365  // Construct a loop over the array bounds, e.g.,
7366  //
7367  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7368  //
7369  // that will copy each of the array elements.
7370  QualType SizeType = S.Context.getSizeType();
7371
7372  // Create the iteration variable.
7373  IdentifierInfo *IterationVarName = 0;
7374  {
7375    SmallString<8> Str;
7376    llvm::raw_svector_ostream OS(Str);
7377    OS << "__i" << Depth;
7378    IterationVarName = &S.Context.Idents.get(OS.str());
7379  }
7380  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7381                                          IterationVarName, SizeType,
7382                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7383                                          SC_None, SC_None);
7384
7385  // Initialize the iteration variable to zero.
7386  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7387  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7388
7389  // Create a reference to the iteration variable; we'll use this several
7390  // times throughout.
7391  Expr *IterationVarRef
7392    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7393  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7394  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7395  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7396
7397  // Create the DeclStmt that holds the iteration variable.
7398  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7399
7400  // Create the comparison against the array bound.
7401  llvm::APInt Upper
7402    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7403  Expr *Comparison
7404    = new (S.Context) BinaryOperator(IterationVarRefRVal,
7405                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7406                                     BO_NE, S.Context.BoolTy,
7407                                     VK_RValue, OK_Ordinary, Loc);
7408
7409  // Create the pre-increment of the iteration variable.
7410  Expr *Increment
7411    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7412                                    VK_LValue, OK_Ordinary, Loc);
7413
7414  // Subscript the "from" and "to" expressions with the iteration variable.
7415  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7416                                                         IterationVarRefRVal,
7417                                                         Loc));
7418  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7419                                                       IterationVarRefRVal,
7420                                                       Loc));
7421  if (!Copying) // Cast to rvalue
7422    From = CastForMoving(S, From);
7423
7424  // Build the copy/move for an individual element of the array.
7425  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7426                                          To, From, CopyingBaseSubobject,
7427                                          Copying, Depth + 1);
7428  if (Copy.isInvalid())
7429    return StmtError();
7430
7431  // Construct the loop that copies all elements of this array.
7432  return S.ActOnForStmt(Loc, Loc, InitStmt,
7433                        S.MakeFullExpr(Comparison),
7434                        0, S.MakeFullExpr(Increment),
7435                        Loc, Copy.take());
7436}
7437
7438std::pair<Sema::ImplicitExceptionSpecification, bool>
7439Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7440                                                   CXXRecordDecl *ClassDecl) {
7441  if (ClassDecl->isInvalidDecl())
7442    return std::make_pair(ImplicitExceptionSpecification(*this), true);
7443
7444  // C++ [class.copy]p10:
7445  //   If the class definition does not explicitly declare a copy
7446  //   assignment operator, one is declared implicitly.
7447  //   The implicitly-defined copy assignment operator for a class X
7448  //   will have the form
7449  //
7450  //       X& X::operator=(const X&)
7451  //
7452  //   if
7453  bool HasConstCopyAssignment = true;
7454
7455  //       -- each direct base class B of X has a copy assignment operator
7456  //          whose parameter is of type const B&, const volatile B& or B,
7457  //          and
7458  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7459                                       BaseEnd = ClassDecl->bases_end();
7460       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7461    // We'll handle this below
7462    if (LangOpts.CPlusPlus0x && Base->isVirtual())
7463      continue;
7464
7465    assert(!Base->getType()->isDependentType() &&
7466           "Cannot generate implicit members for class with dependent bases.");
7467    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7468    HasConstCopyAssignment &=
7469      (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7470                                    false, 0);
7471  }
7472
7473  // In C++11, the above citation has "or virtual" added
7474  if (LangOpts.CPlusPlus0x) {
7475    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7476                                         BaseEnd = ClassDecl->vbases_end();
7477         HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7478      assert(!Base->getType()->isDependentType() &&
7479             "Cannot generate implicit members for class with dependent bases.");
7480      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7481      HasConstCopyAssignment &=
7482        (bool)LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const,
7483                                      false, 0);
7484    }
7485  }
7486
7487  //       -- for all the nonstatic data members of X that are of a class
7488  //          type M (or array thereof), each such class type has a copy
7489  //          assignment operator whose parameter is of type const M&,
7490  //          const volatile M& or M.
7491  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7492                                  FieldEnd = ClassDecl->field_end();
7493       HasConstCopyAssignment && Field != FieldEnd;
7494       ++Field) {
7495    QualType FieldType = Context.getBaseElementType(Field->getType());
7496    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7497      HasConstCopyAssignment &=
7498        (bool)LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const,
7499                                      false, 0);
7500    }
7501  }
7502
7503  //   Otherwise, the implicitly declared copy assignment operator will
7504  //   have the form
7505  //
7506  //       X& X::operator=(X&)
7507
7508  // C++ [except.spec]p14:
7509  //   An implicitly declared special member function (Clause 12) shall have an
7510  //   exception-specification. [...]
7511
7512  // It is unspecified whether or not an implicit copy assignment operator
7513  // attempts to deduplicate calls to assignment operators of virtual bases are
7514  // made. As such, this exception specification is effectively unspecified.
7515  // Based on a similar decision made for constness in C++0x, we're erring on
7516  // the side of assuming such calls to be made regardless of whether they
7517  // actually happen.
7518  ImplicitExceptionSpecification ExceptSpec(*this);
7519  unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
7520  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7521                                       BaseEnd = ClassDecl->bases_end();
7522       Base != BaseEnd; ++Base) {
7523    if (Base->isVirtual())
7524      continue;
7525
7526    CXXRecordDecl *BaseClassDecl
7527      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7528    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7529                                                            ArgQuals, false, 0))
7530      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7531  }
7532
7533  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7534                                       BaseEnd = ClassDecl->vbases_end();
7535       Base != BaseEnd; ++Base) {
7536    CXXRecordDecl *BaseClassDecl
7537      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7538    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7539                                                            ArgQuals, false, 0))
7540      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
7541  }
7542
7543  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7544                                  FieldEnd = ClassDecl->field_end();
7545       Field != FieldEnd;
7546       ++Field) {
7547    QualType FieldType = Context.getBaseElementType(Field->getType());
7548    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7549      if (CXXMethodDecl *CopyAssign =
7550          LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7551        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
7552    }
7553  }
7554
7555  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7556}
7557
7558CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7559  // Note: The following rules are largely analoguous to the copy
7560  // constructor rules. Note that virtual bases are not taken into account
7561  // for determining the argument type of the operator. Note also that
7562  // operators taking an object instead of a reference are allowed.
7563
7564  ImplicitExceptionSpecification Spec(*this);
7565  bool Const;
7566  llvm::tie(Spec, Const) =
7567    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7568
7569  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7570  QualType RetType = Context.getLValueReferenceType(ArgType);
7571  if (Const)
7572    ArgType = ArgType.withConst();
7573  ArgType = Context.getLValueReferenceType(ArgType);
7574
7575  //   An implicitly-declared copy assignment operator is an inline public
7576  //   member of its class.
7577  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7578  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7579  SourceLocation ClassLoc = ClassDecl->getLocation();
7580  DeclarationNameInfo NameInfo(Name, ClassLoc);
7581  CXXMethodDecl *CopyAssignment
7582    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7583                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7584                            /*TInfo=*/0, /*isStatic=*/false,
7585                            /*StorageClassAsWritten=*/SC_None,
7586                            /*isInline=*/true, /*isConstexpr=*/false,
7587                            SourceLocation());
7588  CopyAssignment->setAccess(AS_public);
7589  CopyAssignment->setDefaulted();
7590  CopyAssignment->setImplicit();
7591  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7592
7593  // Add the parameter to the operator.
7594  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7595                                               ClassLoc, ClassLoc, /*Id=*/0,
7596                                               ArgType, /*TInfo=*/0,
7597                                               SC_None,
7598                                               SC_None, 0);
7599  CopyAssignment->setParams(FromParam);
7600
7601  // Note that we have added this copy-assignment operator.
7602  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7603
7604  if (Scope *S = getScopeForContext(ClassDecl))
7605    PushOnScopeChains(CopyAssignment, S, false);
7606  ClassDecl->addDecl(CopyAssignment);
7607
7608  // C++0x [class.copy]p19:
7609  //   ....  If the class definition does not explicitly declare a copy
7610  //   assignment operator, there is no user-declared move constructor, and
7611  //   there is no user-declared move assignment operator, a copy assignment
7612  //   operator is implicitly declared as defaulted.
7613  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7614    CopyAssignment->setDeletedAsWritten();
7615
7616  AddOverriddenMethods(ClassDecl, CopyAssignment);
7617  return CopyAssignment;
7618}
7619
7620void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7621                                        CXXMethodDecl *CopyAssignOperator) {
7622  assert((CopyAssignOperator->isDefaulted() &&
7623          CopyAssignOperator->isOverloadedOperator() &&
7624          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7625          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7626          !CopyAssignOperator->isDeleted()) &&
7627         "DefineImplicitCopyAssignment called for wrong function");
7628
7629  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7630
7631  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7632    CopyAssignOperator->setInvalidDecl();
7633    return;
7634  }
7635
7636  CopyAssignOperator->setUsed();
7637
7638  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7639  DiagnosticErrorTrap Trap(Diags);
7640
7641  // C++0x [class.copy]p30:
7642  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7643  //   for a non-union class X performs memberwise copy assignment of its
7644  //   subobjects. The direct base classes of X are assigned first, in the
7645  //   order of their declaration in the base-specifier-list, and then the
7646  //   immediate non-static data members of X are assigned, in the order in
7647  //   which they were declared in the class definition.
7648
7649  // The statements that form the synthesized function body.
7650  ASTOwningVector<Stmt*> Statements(*this);
7651
7652  // The parameter for the "other" object, which we are copying from.
7653  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7654  Qualifiers OtherQuals = Other->getType().getQualifiers();
7655  QualType OtherRefType = Other->getType();
7656  if (const LValueReferenceType *OtherRef
7657                                = OtherRefType->getAs<LValueReferenceType>()) {
7658    OtherRefType = OtherRef->getPointeeType();
7659    OtherQuals = OtherRefType.getQualifiers();
7660  }
7661
7662  // Our location for everything implicitly-generated.
7663  SourceLocation Loc = CopyAssignOperator->getLocation();
7664
7665  // Construct a reference to the "other" object. We'll be using this
7666  // throughout the generated ASTs.
7667  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7668  assert(OtherRef && "Reference to parameter cannot fail!");
7669
7670  // Construct the "this" pointer. We'll be using this throughout the generated
7671  // ASTs.
7672  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7673  assert(This && "Reference to this cannot fail!");
7674
7675  // Assign base classes.
7676  bool Invalid = false;
7677  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7678       E = ClassDecl->bases_end(); Base != E; ++Base) {
7679    // Form the assignment:
7680    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7681    QualType BaseType = Base->getType().getUnqualifiedType();
7682    if (!BaseType->isRecordType()) {
7683      Invalid = true;
7684      continue;
7685    }
7686
7687    CXXCastPath BasePath;
7688    BasePath.push_back(Base);
7689
7690    // Construct the "from" expression, which is an implicit cast to the
7691    // appropriately-qualified base type.
7692    Expr *From = OtherRef;
7693    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7694                             CK_UncheckedDerivedToBase,
7695                             VK_LValue, &BasePath).take();
7696
7697    // Dereference "this".
7698    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7699
7700    // Implicitly cast "this" to the appropriately-qualified base type.
7701    To = ImpCastExprToType(To.take(),
7702                           Context.getCVRQualifiedType(BaseType,
7703                                     CopyAssignOperator->getTypeQualifiers()),
7704                           CK_UncheckedDerivedToBase,
7705                           VK_LValue, &BasePath);
7706
7707    // Build the copy.
7708    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7709                                            To.get(), From,
7710                                            /*CopyingBaseSubobject=*/true,
7711                                            /*Copying=*/true);
7712    if (Copy.isInvalid()) {
7713      Diag(CurrentLocation, diag::note_member_synthesized_at)
7714        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7715      CopyAssignOperator->setInvalidDecl();
7716      return;
7717    }
7718
7719    // Success! Record the copy.
7720    Statements.push_back(Copy.takeAs<Expr>());
7721  }
7722
7723  // \brief Reference to the __builtin_memcpy function.
7724  Expr *BuiltinMemCpyRef = 0;
7725  // \brief Reference to the __builtin_objc_memmove_collectable function.
7726  Expr *CollectableMemCpyRef = 0;
7727
7728  // Assign non-static members.
7729  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7730                                  FieldEnd = ClassDecl->field_end();
7731       Field != FieldEnd; ++Field) {
7732    if (Field->isUnnamedBitfield())
7733      continue;
7734
7735    // Check for members of reference type; we can't copy those.
7736    if (Field->getType()->isReferenceType()) {
7737      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7738        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7739      Diag(Field->getLocation(), diag::note_declared_at);
7740      Diag(CurrentLocation, diag::note_member_synthesized_at)
7741        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7742      Invalid = true;
7743      continue;
7744    }
7745
7746    // Check for members of const-qualified, non-class type.
7747    QualType BaseType = Context.getBaseElementType(Field->getType());
7748    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7749      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7750        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7751      Diag(Field->getLocation(), diag::note_declared_at);
7752      Diag(CurrentLocation, diag::note_member_synthesized_at)
7753        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7754      Invalid = true;
7755      continue;
7756    }
7757
7758    // Suppress assigning zero-width bitfields.
7759    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7760      continue;
7761
7762    QualType FieldType = Field->getType().getNonReferenceType();
7763    if (FieldType->isIncompleteArrayType()) {
7764      assert(ClassDecl->hasFlexibleArrayMember() &&
7765             "Incomplete array type is not valid");
7766      continue;
7767    }
7768
7769    // Build references to the field in the object we're copying from and to.
7770    CXXScopeSpec SS; // Intentionally empty
7771    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7772                              LookupMemberName);
7773    MemberLookup.addDecl(*Field);
7774    MemberLookup.resolveKind();
7775    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7776                                               Loc, /*IsArrow=*/false,
7777                                               SS, SourceLocation(), 0,
7778                                               MemberLookup, 0);
7779    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7780                                             Loc, /*IsArrow=*/true,
7781                                             SS, SourceLocation(), 0,
7782                                             MemberLookup, 0);
7783    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7784    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7785
7786    // If the field should be copied with __builtin_memcpy rather than via
7787    // explicit assignments, do so. This optimization only applies for arrays
7788    // of scalars and arrays of class type with trivial copy-assignment
7789    // operators.
7790    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7791        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7792      // Compute the size of the memory buffer to be copied.
7793      QualType SizeType = Context.getSizeType();
7794      llvm::APInt Size(Context.getTypeSize(SizeType),
7795                       Context.getTypeSizeInChars(BaseType).getQuantity());
7796      for (const ConstantArrayType *Array
7797              = Context.getAsConstantArrayType(FieldType);
7798           Array;
7799           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7800        llvm::APInt ArraySize
7801          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7802        Size *= ArraySize;
7803      }
7804
7805      // Take the address of the field references for "from" and "to".
7806      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7807      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7808
7809      bool NeedsCollectableMemCpy =
7810          (BaseType->isRecordType() &&
7811           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7812
7813      if (NeedsCollectableMemCpy) {
7814        if (!CollectableMemCpyRef) {
7815          // Create a reference to the __builtin_objc_memmove_collectable function.
7816          LookupResult R(*this,
7817                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7818                         Loc, LookupOrdinaryName);
7819          LookupName(R, TUScope, true);
7820
7821          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7822          if (!CollectableMemCpy) {
7823            // Something went horribly wrong earlier, and we will have
7824            // complained about it.
7825            Invalid = true;
7826            continue;
7827          }
7828
7829          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7830                                                  CollectableMemCpy->getType(),
7831                                                  VK_LValue, Loc, 0).take();
7832          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7833        }
7834      }
7835      // Create a reference to the __builtin_memcpy builtin function.
7836      else if (!BuiltinMemCpyRef) {
7837        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7838                       LookupOrdinaryName);
7839        LookupName(R, TUScope, true);
7840
7841        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7842        if (!BuiltinMemCpy) {
7843          // Something went horribly wrong earlier, and we will have complained
7844          // about it.
7845          Invalid = true;
7846          continue;
7847        }
7848
7849        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7850                                            BuiltinMemCpy->getType(),
7851                                            VK_LValue, Loc, 0).take();
7852        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7853      }
7854
7855      ASTOwningVector<Expr*> CallArgs(*this);
7856      CallArgs.push_back(To.takeAs<Expr>());
7857      CallArgs.push_back(From.takeAs<Expr>());
7858      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7859      ExprResult Call = ExprError();
7860      if (NeedsCollectableMemCpy)
7861        Call = ActOnCallExpr(/*Scope=*/0,
7862                             CollectableMemCpyRef,
7863                             Loc, move_arg(CallArgs),
7864                             Loc);
7865      else
7866        Call = ActOnCallExpr(/*Scope=*/0,
7867                             BuiltinMemCpyRef,
7868                             Loc, move_arg(CallArgs),
7869                             Loc);
7870
7871      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7872      Statements.push_back(Call.takeAs<Expr>());
7873      continue;
7874    }
7875
7876    // Build the copy of this field.
7877    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7878                                            To.get(), From.get(),
7879                                            /*CopyingBaseSubobject=*/false,
7880                                            /*Copying=*/true);
7881    if (Copy.isInvalid()) {
7882      Diag(CurrentLocation, diag::note_member_synthesized_at)
7883        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7884      CopyAssignOperator->setInvalidDecl();
7885      return;
7886    }
7887
7888    // Success! Record the copy.
7889    Statements.push_back(Copy.takeAs<Stmt>());
7890  }
7891
7892  if (!Invalid) {
7893    // Add a "return *this;"
7894    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7895
7896    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7897    if (Return.isInvalid())
7898      Invalid = true;
7899    else {
7900      Statements.push_back(Return.takeAs<Stmt>());
7901
7902      if (Trap.hasErrorOccurred()) {
7903        Diag(CurrentLocation, diag::note_member_synthesized_at)
7904          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7905        Invalid = true;
7906      }
7907    }
7908  }
7909
7910  if (Invalid) {
7911    CopyAssignOperator->setInvalidDecl();
7912    return;
7913  }
7914
7915  StmtResult Body;
7916  {
7917    CompoundScopeRAII CompoundScope(*this);
7918    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7919                             /*isStmtExpr=*/false);
7920    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7921  }
7922  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7923
7924  if (ASTMutationListener *L = getASTMutationListener()) {
7925    L->CompletedImplicitDefinition(CopyAssignOperator);
7926  }
7927}
7928
7929Sema::ImplicitExceptionSpecification
7930Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7931  ImplicitExceptionSpecification ExceptSpec(*this);
7932
7933  if (ClassDecl->isInvalidDecl())
7934    return ExceptSpec;
7935
7936  // C++0x [except.spec]p14:
7937  //   An implicitly declared special member function (Clause 12) shall have an
7938  //   exception-specification. [...]
7939
7940  // It is unspecified whether or not an implicit move assignment operator
7941  // attempts to deduplicate calls to assignment operators of virtual bases are
7942  // made. As such, this exception specification is effectively unspecified.
7943  // Based on a similar decision made for constness in C++0x, we're erring on
7944  // the side of assuming such calls to be made regardless of whether they
7945  // actually happen.
7946  // Note that a move constructor is not implicitly declared when there are
7947  // virtual bases, but it can still be user-declared and explicitly defaulted.
7948  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7949                                       BaseEnd = ClassDecl->bases_end();
7950       Base != BaseEnd; ++Base) {
7951    if (Base->isVirtual())
7952      continue;
7953
7954    CXXRecordDecl *BaseClassDecl
7955      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7956    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7957                                                           false, 0))
7958      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
7959  }
7960
7961  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7962                                       BaseEnd = ClassDecl->vbases_end();
7963       Base != BaseEnd; ++Base) {
7964    CXXRecordDecl *BaseClassDecl
7965      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7966    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7967                                                           false, 0))
7968      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
7969  }
7970
7971  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7972                                  FieldEnd = ClassDecl->field_end();
7973       Field != FieldEnd;
7974       ++Field) {
7975    QualType FieldType = Context.getBaseElementType(Field->getType());
7976    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7977      if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7978                                                             false, 0))
7979        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
7980    }
7981  }
7982
7983  return ExceptSpec;
7984}
7985
7986/// Determine whether the class type has any direct or indirect virtual base
7987/// classes which have a non-trivial move assignment operator.
7988static bool
7989hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
7990  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7991                                          BaseEnd = ClassDecl->vbases_end();
7992       Base != BaseEnd; ++Base) {
7993    CXXRecordDecl *BaseClass =
7994        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7995
7996    // Try to declare the move assignment. If it would be deleted, then the
7997    // class does not have a non-trivial move assignment.
7998    if (BaseClass->needsImplicitMoveAssignment())
7999      S.DeclareImplicitMoveAssignment(BaseClass);
8000
8001    // If the class has both a trivial move assignment and a non-trivial move
8002    // assignment, hasTrivialMoveAssignment() is false.
8003    if (BaseClass->hasDeclaredMoveAssignment() &&
8004        !BaseClass->hasTrivialMoveAssignment())
8005      return true;
8006  }
8007
8008  return false;
8009}
8010
8011/// Determine whether the given type either has a move constructor or is
8012/// trivially copyable.
8013static bool
8014hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8015  Type = S.Context.getBaseElementType(Type);
8016
8017  // FIXME: Technically, non-trivially-copyable non-class types, such as
8018  // reference types, are supposed to return false here, but that appears
8019  // to be a standard defect.
8020  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8021  if (!ClassDecl || !ClassDecl->getDefinition())
8022    return true;
8023
8024  if (Type.isTriviallyCopyableType(S.Context))
8025    return true;
8026
8027  if (IsConstructor) {
8028    if (ClassDecl->needsImplicitMoveConstructor())
8029      S.DeclareImplicitMoveConstructor(ClassDecl);
8030    return ClassDecl->hasDeclaredMoveConstructor();
8031  }
8032
8033  if (ClassDecl->needsImplicitMoveAssignment())
8034    S.DeclareImplicitMoveAssignment(ClassDecl);
8035  return ClassDecl->hasDeclaredMoveAssignment();
8036}
8037
8038/// Determine whether all non-static data members and direct or virtual bases
8039/// of class \p ClassDecl have either a move operation, or are trivially
8040/// copyable.
8041static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8042                                            bool IsConstructor) {
8043  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8044                                          BaseEnd = ClassDecl->bases_end();
8045       Base != BaseEnd; ++Base) {
8046    if (Base->isVirtual())
8047      continue;
8048
8049    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8050      return false;
8051  }
8052
8053  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8054                                          BaseEnd = ClassDecl->vbases_end();
8055       Base != BaseEnd; ++Base) {
8056    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8057      return false;
8058  }
8059
8060  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8061                                     FieldEnd = ClassDecl->field_end();
8062       Field != FieldEnd; ++Field) {
8063    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
8064      return false;
8065  }
8066
8067  return true;
8068}
8069
8070CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8071  // C++11 [class.copy]p20:
8072  //   If the definition of a class X does not explicitly declare a move
8073  //   assignment operator, one will be implicitly declared as defaulted
8074  //   if and only if:
8075  //
8076  //   - [first 4 bullets]
8077  assert(ClassDecl->needsImplicitMoveAssignment());
8078
8079  // [Checked after we build the declaration]
8080  //   - the move assignment operator would not be implicitly defined as
8081  //     deleted,
8082
8083  // [DR1402]:
8084  //   - X has no direct or indirect virtual base class with a non-trivial
8085  //     move assignment operator, and
8086  //   - each of X's non-static data members and direct or virtual base classes
8087  //     has a type that either has a move assignment operator or is trivially
8088  //     copyable.
8089  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8090      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8091    ClassDecl->setFailedImplicitMoveAssignment();
8092    return 0;
8093  }
8094
8095  // Note: The following rules are largely analoguous to the move
8096  // constructor rules.
8097
8098  ImplicitExceptionSpecification Spec(
8099      ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8100
8101  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8102  QualType RetType = Context.getLValueReferenceType(ArgType);
8103  ArgType = Context.getRValueReferenceType(ArgType);
8104
8105  //   An implicitly-declared move assignment operator is an inline public
8106  //   member of its class.
8107  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8108  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8109  SourceLocation ClassLoc = ClassDecl->getLocation();
8110  DeclarationNameInfo NameInfo(Name, ClassLoc);
8111  CXXMethodDecl *MoveAssignment
8112    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8113                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
8114                            /*TInfo=*/0, /*isStatic=*/false,
8115                            /*StorageClassAsWritten=*/SC_None,
8116                            /*isInline=*/true,
8117                            /*isConstexpr=*/false,
8118                            SourceLocation());
8119  MoveAssignment->setAccess(AS_public);
8120  MoveAssignment->setDefaulted();
8121  MoveAssignment->setImplicit();
8122  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8123
8124  // Add the parameter to the operator.
8125  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8126                                               ClassLoc, ClassLoc, /*Id=*/0,
8127                                               ArgType, /*TInfo=*/0,
8128                                               SC_None,
8129                                               SC_None, 0);
8130  MoveAssignment->setParams(FromParam);
8131
8132  // Note that we have added this copy-assignment operator.
8133  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8134
8135  // C++0x [class.copy]p9:
8136  //   If the definition of a class X does not explicitly declare a move
8137  //   assignment operator, one will be implicitly declared as defaulted if and
8138  //   only if:
8139  //   [...]
8140  //   - the move assignment operator would not be implicitly defined as
8141  //     deleted.
8142  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8143    // Cache this result so that we don't try to generate this over and over
8144    // on every lookup, leaking memory and wasting time.
8145    ClassDecl->setFailedImplicitMoveAssignment();
8146    return 0;
8147  }
8148
8149  if (Scope *S = getScopeForContext(ClassDecl))
8150    PushOnScopeChains(MoveAssignment, S, false);
8151  ClassDecl->addDecl(MoveAssignment);
8152
8153  AddOverriddenMethods(ClassDecl, MoveAssignment);
8154  return MoveAssignment;
8155}
8156
8157void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8158                                        CXXMethodDecl *MoveAssignOperator) {
8159  assert((MoveAssignOperator->isDefaulted() &&
8160          MoveAssignOperator->isOverloadedOperator() &&
8161          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8162          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8163          !MoveAssignOperator->isDeleted()) &&
8164         "DefineImplicitMoveAssignment called for wrong function");
8165
8166  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8167
8168  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8169    MoveAssignOperator->setInvalidDecl();
8170    return;
8171  }
8172
8173  MoveAssignOperator->setUsed();
8174
8175  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8176  DiagnosticErrorTrap Trap(Diags);
8177
8178  // C++0x [class.copy]p28:
8179  //   The implicitly-defined or move assignment operator for a non-union class
8180  //   X performs memberwise move assignment of its subobjects. The direct base
8181  //   classes of X are assigned first, in the order of their declaration in the
8182  //   base-specifier-list, and then the immediate non-static data members of X
8183  //   are assigned, in the order in which they were declared in the class
8184  //   definition.
8185
8186  // The statements that form the synthesized function body.
8187  ASTOwningVector<Stmt*> Statements(*this);
8188
8189  // The parameter for the "other" object, which we are move from.
8190  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8191  QualType OtherRefType = Other->getType()->
8192      getAs<RValueReferenceType>()->getPointeeType();
8193  assert(OtherRefType.getQualifiers() == 0 &&
8194         "Bad argument type of defaulted move assignment");
8195
8196  // Our location for everything implicitly-generated.
8197  SourceLocation Loc = MoveAssignOperator->getLocation();
8198
8199  // Construct a reference to the "other" object. We'll be using this
8200  // throughout the generated ASTs.
8201  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8202  assert(OtherRef && "Reference to parameter cannot fail!");
8203  // Cast to rvalue.
8204  OtherRef = CastForMoving(*this, OtherRef);
8205
8206  // Construct the "this" pointer. We'll be using this throughout the generated
8207  // ASTs.
8208  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8209  assert(This && "Reference to this cannot fail!");
8210
8211  // Assign base classes.
8212  bool Invalid = false;
8213  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8214       E = ClassDecl->bases_end(); Base != E; ++Base) {
8215    // Form the assignment:
8216    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8217    QualType BaseType = Base->getType().getUnqualifiedType();
8218    if (!BaseType->isRecordType()) {
8219      Invalid = true;
8220      continue;
8221    }
8222
8223    CXXCastPath BasePath;
8224    BasePath.push_back(Base);
8225
8226    // Construct the "from" expression, which is an implicit cast to the
8227    // appropriately-qualified base type.
8228    Expr *From = OtherRef;
8229    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8230                             VK_XValue, &BasePath).take();
8231
8232    // Dereference "this".
8233    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8234
8235    // Implicitly cast "this" to the appropriately-qualified base type.
8236    To = ImpCastExprToType(To.take(),
8237                           Context.getCVRQualifiedType(BaseType,
8238                                     MoveAssignOperator->getTypeQualifiers()),
8239                           CK_UncheckedDerivedToBase,
8240                           VK_LValue, &BasePath);
8241
8242    // Build the move.
8243    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8244                                            To.get(), From,
8245                                            /*CopyingBaseSubobject=*/true,
8246                                            /*Copying=*/false);
8247    if (Move.isInvalid()) {
8248      Diag(CurrentLocation, diag::note_member_synthesized_at)
8249        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8250      MoveAssignOperator->setInvalidDecl();
8251      return;
8252    }
8253
8254    // Success! Record the move.
8255    Statements.push_back(Move.takeAs<Expr>());
8256  }
8257
8258  // \brief Reference to the __builtin_memcpy function.
8259  Expr *BuiltinMemCpyRef = 0;
8260  // \brief Reference to the __builtin_objc_memmove_collectable function.
8261  Expr *CollectableMemCpyRef = 0;
8262
8263  // Assign non-static members.
8264  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8265                                  FieldEnd = ClassDecl->field_end();
8266       Field != FieldEnd; ++Field) {
8267    if (Field->isUnnamedBitfield())
8268      continue;
8269
8270    // Check for members of reference type; we can't move those.
8271    if (Field->getType()->isReferenceType()) {
8272      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8273        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8274      Diag(Field->getLocation(), diag::note_declared_at);
8275      Diag(CurrentLocation, diag::note_member_synthesized_at)
8276        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8277      Invalid = true;
8278      continue;
8279    }
8280
8281    // Check for members of const-qualified, non-class type.
8282    QualType BaseType = Context.getBaseElementType(Field->getType());
8283    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8284      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8285        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8286      Diag(Field->getLocation(), diag::note_declared_at);
8287      Diag(CurrentLocation, diag::note_member_synthesized_at)
8288        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8289      Invalid = true;
8290      continue;
8291    }
8292
8293    // Suppress assigning zero-width bitfields.
8294    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8295      continue;
8296
8297    QualType FieldType = Field->getType().getNonReferenceType();
8298    if (FieldType->isIncompleteArrayType()) {
8299      assert(ClassDecl->hasFlexibleArrayMember() &&
8300             "Incomplete array type is not valid");
8301      continue;
8302    }
8303
8304    // Build references to the field in the object we're copying from and to.
8305    CXXScopeSpec SS; // Intentionally empty
8306    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8307                              LookupMemberName);
8308    MemberLookup.addDecl(*Field);
8309    MemberLookup.resolveKind();
8310    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8311                                               Loc, /*IsArrow=*/false,
8312                                               SS, SourceLocation(), 0,
8313                                               MemberLookup, 0);
8314    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8315                                             Loc, /*IsArrow=*/true,
8316                                             SS, SourceLocation(), 0,
8317                                             MemberLookup, 0);
8318    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8319    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8320
8321    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8322        "Member reference with rvalue base must be rvalue except for reference "
8323        "members, which aren't allowed for move assignment.");
8324
8325    // If the field should be copied with __builtin_memcpy rather than via
8326    // explicit assignments, do so. This optimization only applies for arrays
8327    // of scalars and arrays of class type with trivial move-assignment
8328    // operators.
8329    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8330        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8331      // Compute the size of the memory buffer to be copied.
8332      QualType SizeType = Context.getSizeType();
8333      llvm::APInt Size(Context.getTypeSize(SizeType),
8334                       Context.getTypeSizeInChars(BaseType).getQuantity());
8335      for (const ConstantArrayType *Array
8336              = Context.getAsConstantArrayType(FieldType);
8337           Array;
8338           Array = Context.getAsConstantArrayType(Array->getElementType())) {
8339        llvm::APInt ArraySize
8340          = Array->getSize().zextOrTrunc(Size.getBitWidth());
8341        Size *= ArraySize;
8342      }
8343
8344      // Take the address of the field references for "from" and "to". We
8345      // directly construct UnaryOperators here because semantic analysis
8346      // does not permit us to take the address of an xvalue.
8347      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8348                             Context.getPointerType(From.get()->getType()),
8349                             VK_RValue, OK_Ordinary, Loc);
8350      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8351                           Context.getPointerType(To.get()->getType()),
8352                           VK_RValue, OK_Ordinary, Loc);
8353
8354      bool NeedsCollectableMemCpy =
8355          (BaseType->isRecordType() &&
8356           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8357
8358      if (NeedsCollectableMemCpy) {
8359        if (!CollectableMemCpyRef) {
8360          // Create a reference to the __builtin_objc_memmove_collectable function.
8361          LookupResult R(*this,
8362                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
8363                         Loc, LookupOrdinaryName);
8364          LookupName(R, TUScope, true);
8365
8366          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8367          if (!CollectableMemCpy) {
8368            // Something went horribly wrong earlier, and we will have
8369            // complained about it.
8370            Invalid = true;
8371            continue;
8372          }
8373
8374          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8375                                                  CollectableMemCpy->getType(),
8376                                                  VK_LValue, Loc, 0).take();
8377          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8378        }
8379      }
8380      // Create a reference to the __builtin_memcpy builtin function.
8381      else if (!BuiltinMemCpyRef) {
8382        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8383                       LookupOrdinaryName);
8384        LookupName(R, TUScope, true);
8385
8386        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8387        if (!BuiltinMemCpy) {
8388          // Something went horribly wrong earlier, and we will have complained
8389          // about it.
8390          Invalid = true;
8391          continue;
8392        }
8393
8394        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8395                                            BuiltinMemCpy->getType(),
8396                                            VK_LValue, Loc, 0).take();
8397        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8398      }
8399
8400      ASTOwningVector<Expr*> CallArgs(*this);
8401      CallArgs.push_back(To.takeAs<Expr>());
8402      CallArgs.push_back(From.takeAs<Expr>());
8403      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8404      ExprResult Call = ExprError();
8405      if (NeedsCollectableMemCpy)
8406        Call = ActOnCallExpr(/*Scope=*/0,
8407                             CollectableMemCpyRef,
8408                             Loc, move_arg(CallArgs),
8409                             Loc);
8410      else
8411        Call = ActOnCallExpr(/*Scope=*/0,
8412                             BuiltinMemCpyRef,
8413                             Loc, move_arg(CallArgs),
8414                             Loc);
8415
8416      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8417      Statements.push_back(Call.takeAs<Expr>());
8418      continue;
8419    }
8420
8421    // Build the move of this field.
8422    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8423                                            To.get(), From.get(),
8424                                            /*CopyingBaseSubobject=*/false,
8425                                            /*Copying=*/false);
8426    if (Move.isInvalid()) {
8427      Diag(CurrentLocation, diag::note_member_synthesized_at)
8428        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8429      MoveAssignOperator->setInvalidDecl();
8430      return;
8431    }
8432
8433    // Success! Record the copy.
8434    Statements.push_back(Move.takeAs<Stmt>());
8435  }
8436
8437  if (!Invalid) {
8438    // Add a "return *this;"
8439    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8440
8441    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8442    if (Return.isInvalid())
8443      Invalid = true;
8444    else {
8445      Statements.push_back(Return.takeAs<Stmt>());
8446
8447      if (Trap.hasErrorOccurred()) {
8448        Diag(CurrentLocation, diag::note_member_synthesized_at)
8449          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8450        Invalid = true;
8451      }
8452    }
8453  }
8454
8455  if (Invalid) {
8456    MoveAssignOperator->setInvalidDecl();
8457    return;
8458  }
8459
8460  StmtResult Body;
8461  {
8462    CompoundScopeRAII CompoundScope(*this);
8463    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8464                             /*isStmtExpr=*/false);
8465    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8466  }
8467  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8468
8469  if (ASTMutationListener *L = getASTMutationListener()) {
8470    L->CompletedImplicitDefinition(MoveAssignOperator);
8471  }
8472}
8473
8474std::pair<Sema::ImplicitExceptionSpecification, bool>
8475Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
8476  if (ClassDecl->isInvalidDecl())
8477    return std::make_pair(ImplicitExceptionSpecification(*this), true);
8478
8479  // C++ [class.copy]p5:
8480  //   The implicitly-declared copy constructor for a class X will
8481  //   have the form
8482  //
8483  //       X::X(const X&)
8484  //
8485  //   if
8486  // FIXME: It ought to be possible to store this on the record.
8487  bool HasConstCopyConstructor = true;
8488
8489  //     -- each direct or virtual base class B of X has a copy
8490  //        constructor whose first parameter is of type const B& or
8491  //        const volatile B&, and
8492  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8493                                       BaseEnd = ClassDecl->bases_end();
8494       HasConstCopyConstructor && Base != BaseEnd;
8495       ++Base) {
8496    // Virtual bases are handled below.
8497    if (Base->isVirtual())
8498      continue;
8499
8500    CXXRecordDecl *BaseClassDecl
8501      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8502    HasConstCopyConstructor &=
8503      (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
8504  }
8505
8506  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8507                                       BaseEnd = ClassDecl->vbases_end();
8508       HasConstCopyConstructor && Base != BaseEnd;
8509       ++Base) {
8510    CXXRecordDecl *BaseClassDecl
8511      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8512    HasConstCopyConstructor &=
8513      (bool)LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const);
8514  }
8515
8516  //     -- for all the nonstatic data members of X that are of a
8517  //        class type M (or array thereof), each such class type
8518  //        has a copy constructor whose first parameter is of type
8519  //        const M& or const volatile M&.
8520  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8521                                  FieldEnd = ClassDecl->field_end();
8522       HasConstCopyConstructor && Field != FieldEnd;
8523       ++Field) {
8524    QualType FieldType = Context.getBaseElementType(Field->getType());
8525    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8526      HasConstCopyConstructor &=
8527        (bool)LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const);
8528    }
8529  }
8530  //   Otherwise, the implicitly declared copy constructor will have
8531  //   the form
8532  //
8533  //       X::X(X&)
8534
8535  // C++ [except.spec]p14:
8536  //   An implicitly declared special member function (Clause 12) shall have an
8537  //   exception-specification. [...]
8538  ImplicitExceptionSpecification ExceptSpec(*this);
8539  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8540  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8541                                       BaseEnd = ClassDecl->bases_end();
8542       Base != BaseEnd;
8543       ++Base) {
8544    // Virtual bases are handled below.
8545    if (Base->isVirtual())
8546      continue;
8547
8548    CXXRecordDecl *BaseClassDecl
8549      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8550    if (CXXConstructorDecl *CopyConstructor =
8551          LookupCopyingConstructor(BaseClassDecl, Quals))
8552      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8553  }
8554  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8555                                       BaseEnd = ClassDecl->vbases_end();
8556       Base != BaseEnd;
8557       ++Base) {
8558    CXXRecordDecl *BaseClassDecl
8559      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8560    if (CXXConstructorDecl *CopyConstructor =
8561          LookupCopyingConstructor(BaseClassDecl, Quals))
8562      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
8563  }
8564  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8565                                  FieldEnd = ClassDecl->field_end();
8566       Field != FieldEnd;
8567       ++Field) {
8568    QualType FieldType = Context.getBaseElementType(Field->getType());
8569    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8570      if (CXXConstructorDecl *CopyConstructor =
8571        LookupCopyingConstructor(FieldClassDecl, Quals))
8572      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
8573    }
8574  }
8575
8576  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8577}
8578
8579CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8580                                                    CXXRecordDecl *ClassDecl) {
8581  // C++ [class.copy]p4:
8582  //   If the class definition does not explicitly declare a copy
8583  //   constructor, one is declared implicitly.
8584
8585  ImplicitExceptionSpecification Spec(*this);
8586  bool Const;
8587  llvm::tie(Spec, Const) =
8588    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8589
8590  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8591  QualType ArgType = ClassType;
8592  if (Const)
8593    ArgType = ArgType.withConst();
8594  ArgType = Context.getLValueReferenceType(ArgType);
8595
8596  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8597
8598  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8599                                                     CXXCopyConstructor,
8600                                                     Const);
8601
8602  DeclarationName Name
8603    = Context.DeclarationNames.getCXXConstructorName(
8604                                           Context.getCanonicalType(ClassType));
8605  SourceLocation ClassLoc = ClassDecl->getLocation();
8606  DeclarationNameInfo NameInfo(Name, ClassLoc);
8607
8608  //   An implicitly-declared copy constructor is an inline public
8609  //   member of its class.
8610  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8611      Context, ClassDecl, ClassLoc, NameInfo,
8612      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8613      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8614      Constexpr);
8615  CopyConstructor->setAccess(AS_public);
8616  CopyConstructor->setDefaulted();
8617  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8618
8619  // Note that we have declared this constructor.
8620  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8621
8622  // Add the parameter to the constructor.
8623  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8624                                               ClassLoc, ClassLoc,
8625                                               /*IdentifierInfo=*/0,
8626                                               ArgType, /*TInfo=*/0,
8627                                               SC_None,
8628                                               SC_None, 0);
8629  CopyConstructor->setParams(FromParam);
8630
8631  if (Scope *S = getScopeForContext(ClassDecl))
8632    PushOnScopeChains(CopyConstructor, S, false);
8633  ClassDecl->addDecl(CopyConstructor);
8634
8635  // C++11 [class.copy]p8:
8636  //   ... If the class definition does not explicitly declare a copy
8637  //   constructor, there is no user-declared move constructor, and there is no
8638  //   user-declared move assignment operator, a copy constructor is implicitly
8639  //   declared as defaulted.
8640  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8641    CopyConstructor->setDeletedAsWritten();
8642
8643  return CopyConstructor;
8644}
8645
8646void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8647                                   CXXConstructorDecl *CopyConstructor) {
8648  assert((CopyConstructor->isDefaulted() &&
8649          CopyConstructor->isCopyConstructor() &&
8650          !CopyConstructor->doesThisDeclarationHaveABody() &&
8651          !CopyConstructor->isDeleted()) &&
8652         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8653
8654  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8655  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8656
8657  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8658  DiagnosticErrorTrap Trap(Diags);
8659
8660  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8661      Trap.hasErrorOccurred()) {
8662    Diag(CurrentLocation, diag::note_member_synthesized_at)
8663      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8664    CopyConstructor->setInvalidDecl();
8665  }  else {
8666    Sema::CompoundScopeRAII CompoundScope(*this);
8667    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8668                                               CopyConstructor->getLocation(),
8669                                               MultiStmtArg(*this, 0, 0),
8670                                               /*isStmtExpr=*/false)
8671                                                              .takeAs<Stmt>());
8672    CopyConstructor->setImplicitlyDefined(true);
8673  }
8674
8675  CopyConstructor->setUsed();
8676  if (ASTMutationListener *L = getASTMutationListener()) {
8677    L->CompletedImplicitDefinition(CopyConstructor);
8678  }
8679}
8680
8681Sema::ImplicitExceptionSpecification
8682Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8683  // C++ [except.spec]p14:
8684  //   An implicitly declared special member function (Clause 12) shall have an
8685  //   exception-specification. [...]
8686  ImplicitExceptionSpecification ExceptSpec(*this);
8687  if (ClassDecl->isInvalidDecl())
8688    return ExceptSpec;
8689
8690  // Direct base-class constructors.
8691  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8692                                       BEnd = ClassDecl->bases_end();
8693       B != BEnd; ++B) {
8694    if (B->isVirtual()) // Handled below.
8695      continue;
8696
8697    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8698      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8699      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8700      // If this is a deleted function, add it anyway. This might be conformant
8701      // with the standard. This might not. I'm not sure. It might not matter.
8702      if (Constructor)
8703        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8704    }
8705  }
8706
8707  // Virtual base-class constructors.
8708  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8709                                       BEnd = ClassDecl->vbases_end();
8710       B != BEnd; ++B) {
8711    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8712      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8713      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8714      // If this is a deleted function, add it anyway. This might be conformant
8715      // with the standard. This might not. I'm not sure. It might not matter.
8716      if (Constructor)
8717        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8718    }
8719  }
8720
8721  // Field constructors.
8722  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8723                               FEnd = ClassDecl->field_end();
8724       F != FEnd; ++F) {
8725    if (const RecordType *RecordTy
8726              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8727      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8728      CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8729      // If this is a deleted function, add it anyway. This might be conformant
8730      // with the standard. This might not. I'm not sure. It might not matter.
8731      // In particular, the problem is that this function never gets called. It
8732      // might just be ill-formed because this function attempts to refer to
8733      // a deleted function here.
8734      if (Constructor)
8735        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8736    }
8737  }
8738
8739  return ExceptSpec;
8740}
8741
8742CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8743                                                    CXXRecordDecl *ClassDecl) {
8744  // C++11 [class.copy]p9:
8745  //   If the definition of a class X does not explicitly declare a move
8746  //   constructor, one will be implicitly declared as defaulted if and only if:
8747  //
8748  //   - [first 4 bullets]
8749  assert(ClassDecl->needsImplicitMoveConstructor());
8750
8751  // [Checked after we build the declaration]
8752  //   - the move assignment operator would not be implicitly defined as
8753  //     deleted,
8754
8755  // [DR1402]:
8756  //   - each of X's non-static data members and direct or virtual base classes
8757  //     has a type that either has a move constructor or is trivially copyable.
8758  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8759    ClassDecl->setFailedImplicitMoveConstructor();
8760    return 0;
8761  }
8762
8763  ImplicitExceptionSpecification Spec(
8764      ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8765
8766  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8767  QualType ArgType = Context.getRValueReferenceType(ClassType);
8768
8769  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8770
8771  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8772                                                     CXXMoveConstructor,
8773                                                     false);
8774
8775  DeclarationName Name
8776    = Context.DeclarationNames.getCXXConstructorName(
8777                                           Context.getCanonicalType(ClassType));
8778  SourceLocation ClassLoc = ClassDecl->getLocation();
8779  DeclarationNameInfo NameInfo(Name, ClassLoc);
8780
8781  // C++0x [class.copy]p11:
8782  //   An implicitly-declared copy/move constructor is an inline public
8783  //   member of its class.
8784  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8785      Context, ClassDecl, ClassLoc, NameInfo,
8786      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8787      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8788      Constexpr);
8789  MoveConstructor->setAccess(AS_public);
8790  MoveConstructor->setDefaulted();
8791  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8792
8793  // Add the parameter to the constructor.
8794  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8795                                               ClassLoc, ClassLoc,
8796                                               /*IdentifierInfo=*/0,
8797                                               ArgType, /*TInfo=*/0,
8798                                               SC_None,
8799                                               SC_None, 0);
8800  MoveConstructor->setParams(FromParam);
8801
8802  // C++0x [class.copy]p9:
8803  //   If the definition of a class X does not explicitly declare a move
8804  //   constructor, one will be implicitly declared as defaulted if and only if:
8805  //   [...]
8806  //   - the move constructor would not be implicitly defined as deleted.
8807  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8808    // Cache this result so that we don't try to generate this over and over
8809    // on every lookup, leaking memory and wasting time.
8810    ClassDecl->setFailedImplicitMoveConstructor();
8811    return 0;
8812  }
8813
8814  // Note that we have declared this constructor.
8815  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8816
8817  if (Scope *S = getScopeForContext(ClassDecl))
8818    PushOnScopeChains(MoveConstructor, S, false);
8819  ClassDecl->addDecl(MoveConstructor);
8820
8821  return MoveConstructor;
8822}
8823
8824void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8825                                   CXXConstructorDecl *MoveConstructor) {
8826  assert((MoveConstructor->isDefaulted() &&
8827          MoveConstructor->isMoveConstructor() &&
8828          !MoveConstructor->doesThisDeclarationHaveABody() &&
8829          !MoveConstructor->isDeleted()) &&
8830         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8831
8832  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8833  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8834
8835  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8836  DiagnosticErrorTrap Trap(Diags);
8837
8838  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8839      Trap.hasErrorOccurred()) {
8840    Diag(CurrentLocation, diag::note_member_synthesized_at)
8841      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8842    MoveConstructor->setInvalidDecl();
8843  }  else {
8844    Sema::CompoundScopeRAII CompoundScope(*this);
8845    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8846                                               MoveConstructor->getLocation(),
8847                                               MultiStmtArg(*this, 0, 0),
8848                                               /*isStmtExpr=*/false)
8849                                                              .takeAs<Stmt>());
8850    MoveConstructor->setImplicitlyDefined(true);
8851  }
8852
8853  MoveConstructor->setUsed();
8854
8855  if (ASTMutationListener *L = getASTMutationListener()) {
8856    L->CompletedImplicitDefinition(MoveConstructor);
8857  }
8858}
8859
8860bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8861  return FD->isDeleted() &&
8862         (FD->isDefaulted() || FD->isImplicit()) &&
8863         isa<CXXMethodDecl>(FD);
8864}
8865
8866/// \brief Mark the call operator of the given lambda closure type as "used".
8867static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8868  CXXMethodDecl *CallOperator
8869    = cast<CXXMethodDecl>(
8870        *Lambda->lookup(
8871          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
8872  CallOperator->setReferenced();
8873  CallOperator->setUsed();
8874}
8875
8876void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8877       SourceLocation CurrentLocation,
8878       CXXConversionDecl *Conv)
8879{
8880  CXXRecordDecl *Lambda = Conv->getParent();
8881
8882  // Make sure that the lambda call operator is marked used.
8883  markLambdaCallOperatorUsed(*this, Lambda);
8884
8885  Conv->setUsed();
8886
8887  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8888  DiagnosticErrorTrap Trap(Diags);
8889
8890  // Return the address of the __invoke function.
8891  DeclarationName InvokeName = &Context.Idents.get("__invoke");
8892  CXXMethodDecl *Invoke
8893    = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8894  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8895                                       VK_LValue, Conv->getLocation()).take();
8896  assert(FunctionRef && "Can't refer to __invoke function?");
8897  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8898  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8899                                           Conv->getLocation(),
8900                                           Conv->getLocation()));
8901
8902  // Fill in the __invoke function with a dummy implementation. IR generation
8903  // will fill in the actual details.
8904  Invoke->setUsed();
8905  Invoke->setReferenced();
8906  Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
8907                                             Conv->getLocation()));
8908
8909  if (ASTMutationListener *L = getASTMutationListener()) {
8910    L->CompletedImplicitDefinition(Conv);
8911    L->CompletedImplicitDefinition(Invoke);
8912  }
8913}
8914
8915void Sema::DefineImplicitLambdaToBlockPointerConversion(
8916       SourceLocation CurrentLocation,
8917       CXXConversionDecl *Conv)
8918{
8919  Conv->setUsed();
8920
8921  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8922  DiagnosticErrorTrap Trap(Diags);
8923
8924  // Copy-initialize the lambda object as needed to capture it.
8925  Expr *This = ActOnCXXThis(CurrentLocation).take();
8926  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
8927
8928  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
8929                                                        Conv->getLocation(),
8930                                                        Conv, DerefThis);
8931
8932  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
8933  // behavior.  Note that only the general conversion function does this
8934  // (since it's unusable otherwise); in the case where we inline the
8935  // block literal, it has block literal lifetime semantics.
8936  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
8937    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
8938                                          CK_CopyAndAutoreleaseBlockObject,
8939                                          BuildBlock.get(), 0, VK_RValue);
8940
8941  if (BuildBlock.isInvalid()) {
8942    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8943    Conv->setInvalidDecl();
8944    return;
8945  }
8946
8947  // Create the return statement that returns the block from the conversion
8948  // function.
8949  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
8950  if (Return.isInvalid()) {
8951    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
8952    Conv->setInvalidDecl();
8953    return;
8954  }
8955
8956  // Set the body of the conversion function.
8957  Stmt *ReturnS = Return.take();
8958  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
8959                                           Conv->getLocation(),
8960                                           Conv->getLocation()));
8961
8962  // We're done; notify the mutation listener, if any.
8963  if (ASTMutationListener *L = getASTMutationListener()) {
8964    L->CompletedImplicitDefinition(Conv);
8965  }
8966}
8967
8968/// \brief Determine whether the given list arguments contains exactly one
8969/// "real" (non-default) argument.
8970static bool hasOneRealArgument(MultiExprArg Args) {
8971  switch (Args.size()) {
8972  case 0:
8973    return false;
8974
8975  default:
8976    if (!Args.get()[1]->isDefaultArgument())
8977      return false;
8978
8979    // fall through
8980  case 1:
8981    return !Args.get()[0]->isDefaultArgument();
8982  }
8983
8984  return false;
8985}
8986
8987ExprResult
8988Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8989                            CXXConstructorDecl *Constructor,
8990                            MultiExprArg ExprArgs,
8991                            bool HadMultipleCandidates,
8992                            bool RequiresZeroInit,
8993                            unsigned ConstructKind,
8994                            SourceRange ParenRange) {
8995  bool Elidable = false;
8996
8997  // C++0x [class.copy]p34:
8998  //   When certain criteria are met, an implementation is allowed to
8999  //   omit the copy/move construction of a class object, even if the
9000  //   copy/move constructor and/or destructor for the object have
9001  //   side effects. [...]
9002  //     - when a temporary class object that has not been bound to a
9003  //       reference (12.2) would be copied/moved to a class object
9004  //       with the same cv-unqualified type, the copy/move operation
9005  //       can be omitted by constructing the temporary object
9006  //       directly into the target of the omitted copy/move
9007  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9008      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9009    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
9010    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9011  }
9012
9013  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9014                               Elidable, move(ExprArgs), HadMultipleCandidates,
9015                               RequiresZeroInit, ConstructKind, ParenRange);
9016}
9017
9018/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9019/// including handling of its default argument expressions.
9020ExprResult
9021Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9022                            CXXConstructorDecl *Constructor, bool Elidable,
9023                            MultiExprArg ExprArgs,
9024                            bool HadMultipleCandidates,
9025                            bool RequiresZeroInit,
9026                            unsigned ConstructKind,
9027                            SourceRange ParenRange) {
9028  unsigned NumExprs = ExprArgs.size();
9029  Expr **Exprs = (Expr **)ExprArgs.release();
9030
9031  MarkFunctionReferenced(ConstructLoc, Constructor);
9032  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9033                                        Constructor, Elidable, Exprs, NumExprs,
9034                                        HadMultipleCandidates, /*FIXME*/false,
9035                                        RequiresZeroInit,
9036              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9037                                        ParenRange));
9038}
9039
9040bool Sema::InitializeVarWithConstructor(VarDecl *VD,
9041                                        CXXConstructorDecl *Constructor,
9042                                        MultiExprArg Exprs,
9043                                        bool HadMultipleCandidates) {
9044  // FIXME: Provide the correct paren SourceRange when available.
9045  ExprResult TempResult =
9046    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
9047                          move(Exprs), HadMultipleCandidates, false,
9048                          CXXConstructExpr::CK_Complete, SourceRange());
9049  if (TempResult.isInvalid())
9050    return true;
9051
9052  Expr *Temp = TempResult.takeAs<Expr>();
9053  CheckImplicitConversions(Temp, VD->getLocation());
9054  MarkFunctionReferenced(VD->getLocation(), Constructor);
9055  Temp = MaybeCreateExprWithCleanups(Temp);
9056  VD->setInit(Temp);
9057
9058  return false;
9059}
9060
9061void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9062  if (VD->isInvalidDecl()) return;
9063
9064  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9065  if (ClassDecl->isInvalidDecl()) return;
9066  if (ClassDecl->hasIrrelevantDestructor()) return;
9067  if (ClassDecl->isDependentContext()) return;
9068
9069  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9070  MarkFunctionReferenced(VD->getLocation(), Destructor);
9071  CheckDestructorAccess(VD->getLocation(), Destructor,
9072                        PDiag(diag::err_access_dtor_var)
9073                        << VD->getDeclName()
9074                        << VD->getType());
9075  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9076
9077  if (!VD->hasGlobalStorage()) return;
9078
9079  // Emit warning for non-trivial dtor in global scope (a real global,
9080  // class-static, function-static).
9081  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9082
9083  // TODO: this should be re-enabled for static locals by !CXAAtExit
9084  if (!VD->isStaticLocal())
9085    Diag(VD->getLocation(), diag::warn_global_destructor);
9086}
9087
9088/// \brief Given a constructor and the set of arguments provided for the
9089/// constructor, convert the arguments and add any required default arguments
9090/// to form a proper call to this constructor.
9091///
9092/// \returns true if an error occurred, false otherwise.
9093bool
9094Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9095                              MultiExprArg ArgsPtr,
9096                              SourceLocation Loc,
9097                              ASTOwningVector<Expr*> &ConvertedArgs,
9098                              bool AllowExplicit) {
9099  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9100  unsigned NumArgs = ArgsPtr.size();
9101  Expr **Args = (Expr **)ArgsPtr.get();
9102
9103  const FunctionProtoType *Proto
9104    = Constructor->getType()->getAs<FunctionProtoType>();
9105  assert(Proto && "Constructor without a prototype?");
9106  unsigned NumArgsInProto = Proto->getNumArgs();
9107
9108  // If too few arguments are available, we'll fill in the rest with defaults.
9109  if (NumArgs < NumArgsInProto)
9110    ConvertedArgs.reserve(NumArgsInProto);
9111  else
9112    ConvertedArgs.reserve(NumArgs);
9113
9114  VariadicCallType CallType =
9115    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9116  SmallVector<Expr *, 8> AllArgs;
9117  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9118                                        Proto, 0, Args, NumArgs, AllArgs,
9119                                        CallType, AllowExplicit);
9120  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9121
9122  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9123
9124  CheckConstructorCall(Constructor, AllArgs.data(), AllArgs.size(),
9125                       Proto, Loc);
9126
9127  return Invalid;
9128}
9129
9130static inline bool
9131CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9132                                       const FunctionDecl *FnDecl) {
9133  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9134  if (isa<NamespaceDecl>(DC)) {
9135    return SemaRef.Diag(FnDecl->getLocation(),
9136                        diag::err_operator_new_delete_declared_in_namespace)
9137      << FnDecl->getDeclName();
9138  }
9139
9140  if (isa<TranslationUnitDecl>(DC) &&
9141      FnDecl->getStorageClass() == SC_Static) {
9142    return SemaRef.Diag(FnDecl->getLocation(),
9143                        diag::err_operator_new_delete_declared_static)
9144      << FnDecl->getDeclName();
9145  }
9146
9147  return false;
9148}
9149
9150static inline bool
9151CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9152                            CanQualType ExpectedResultType,
9153                            CanQualType ExpectedFirstParamType,
9154                            unsigned DependentParamTypeDiag,
9155                            unsigned InvalidParamTypeDiag) {
9156  QualType ResultType =
9157    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9158
9159  // Check that the result type is not dependent.
9160  if (ResultType->isDependentType())
9161    return SemaRef.Diag(FnDecl->getLocation(),
9162                        diag::err_operator_new_delete_dependent_result_type)
9163    << FnDecl->getDeclName() << ExpectedResultType;
9164
9165  // Check that the result type is what we expect.
9166  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9167    return SemaRef.Diag(FnDecl->getLocation(),
9168                        diag::err_operator_new_delete_invalid_result_type)
9169    << FnDecl->getDeclName() << ExpectedResultType;
9170
9171  // A function template must have at least 2 parameters.
9172  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9173    return SemaRef.Diag(FnDecl->getLocation(),
9174                      diag::err_operator_new_delete_template_too_few_parameters)
9175        << FnDecl->getDeclName();
9176
9177  // The function decl must have at least 1 parameter.
9178  if (FnDecl->getNumParams() == 0)
9179    return SemaRef.Diag(FnDecl->getLocation(),
9180                        diag::err_operator_new_delete_too_few_parameters)
9181      << FnDecl->getDeclName();
9182
9183  // Check the the first parameter type is not dependent.
9184  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9185  if (FirstParamType->isDependentType())
9186    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9187      << FnDecl->getDeclName() << ExpectedFirstParamType;
9188
9189  // Check that the first parameter type is what we expect.
9190  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9191      ExpectedFirstParamType)
9192    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9193    << FnDecl->getDeclName() << ExpectedFirstParamType;
9194
9195  return false;
9196}
9197
9198static bool
9199CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9200  // C++ [basic.stc.dynamic.allocation]p1:
9201  //   A program is ill-formed if an allocation function is declared in a
9202  //   namespace scope other than global scope or declared static in global
9203  //   scope.
9204  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9205    return true;
9206
9207  CanQualType SizeTy =
9208    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9209
9210  // C++ [basic.stc.dynamic.allocation]p1:
9211  //  The return type shall be void*. The first parameter shall have type
9212  //  std::size_t.
9213  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9214                                  SizeTy,
9215                                  diag::err_operator_new_dependent_param_type,
9216                                  diag::err_operator_new_param_type))
9217    return true;
9218
9219  // C++ [basic.stc.dynamic.allocation]p1:
9220  //  The first parameter shall not have an associated default argument.
9221  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9222    return SemaRef.Diag(FnDecl->getLocation(),
9223                        diag::err_operator_new_default_arg)
9224      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9225
9226  return false;
9227}
9228
9229static bool
9230CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9231  // C++ [basic.stc.dynamic.deallocation]p1:
9232  //   A program is ill-formed if deallocation functions are declared in a
9233  //   namespace scope other than global scope or declared static in global
9234  //   scope.
9235  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9236    return true;
9237
9238  // C++ [basic.stc.dynamic.deallocation]p2:
9239  //   Each deallocation function shall return void and its first parameter
9240  //   shall be void*.
9241  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9242                                  SemaRef.Context.VoidPtrTy,
9243                                 diag::err_operator_delete_dependent_param_type,
9244                                 diag::err_operator_delete_param_type))
9245    return true;
9246
9247  return false;
9248}
9249
9250/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9251/// of this overloaded operator is well-formed. If so, returns false;
9252/// otherwise, emits appropriate diagnostics and returns true.
9253bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9254  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9255         "Expected an overloaded operator declaration");
9256
9257  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9258
9259  // C++ [over.oper]p5:
9260  //   The allocation and deallocation functions, operator new,
9261  //   operator new[], operator delete and operator delete[], are
9262  //   described completely in 3.7.3. The attributes and restrictions
9263  //   found in the rest of this subclause do not apply to them unless
9264  //   explicitly stated in 3.7.3.
9265  if (Op == OO_Delete || Op == OO_Array_Delete)
9266    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9267
9268  if (Op == OO_New || Op == OO_Array_New)
9269    return CheckOperatorNewDeclaration(*this, FnDecl);
9270
9271  // C++ [over.oper]p6:
9272  //   An operator function shall either be a non-static member
9273  //   function or be a non-member function and have at least one
9274  //   parameter whose type is a class, a reference to a class, an
9275  //   enumeration, or a reference to an enumeration.
9276  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9277    if (MethodDecl->isStatic())
9278      return Diag(FnDecl->getLocation(),
9279                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9280  } else {
9281    bool ClassOrEnumParam = false;
9282    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9283                                   ParamEnd = FnDecl->param_end();
9284         Param != ParamEnd; ++Param) {
9285      QualType ParamType = (*Param)->getType().getNonReferenceType();
9286      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9287          ParamType->isEnumeralType()) {
9288        ClassOrEnumParam = true;
9289        break;
9290      }
9291    }
9292
9293    if (!ClassOrEnumParam)
9294      return Diag(FnDecl->getLocation(),
9295                  diag::err_operator_overload_needs_class_or_enum)
9296        << FnDecl->getDeclName();
9297  }
9298
9299  // C++ [over.oper]p8:
9300  //   An operator function cannot have default arguments (8.3.6),
9301  //   except where explicitly stated below.
9302  //
9303  // Only the function-call operator allows default arguments
9304  // (C++ [over.call]p1).
9305  if (Op != OO_Call) {
9306    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9307         Param != FnDecl->param_end(); ++Param) {
9308      if ((*Param)->hasDefaultArg())
9309        return Diag((*Param)->getLocation(),
9310                    diag::err_operator_overload_default_arg)
9311          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9312    }
9313  }
9314
9315  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9316    { false, false, false }
9317#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9318    , { Unary, Binary, MemberOnly }
9319#include "clang/Basic/OperatorKinds.def"
9320  };
9321
9322  bool CanBeUnaryOperator = OperatorUses[Op][0];
9323  bool CanBeBinaryOperator = OperatorUses[Op][1];
9324  bool MustBeMemberOperator = OperatorUses[Op][2];
9325
9326  // C++ [over.oper]p8:
9327  //   [...] Operator functions cannot have more or fewer parameters
9328  //   than the number required for the corresponding operator, as
9329  //   described in the rest of this subclause.
9330  unsigned NumParams = FnDecl->getNumParams()
9331                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9332  if (Op != OO_Call &&
9333      ((NumParams == 1 && !CanBeUnaryOperator) ||
9334       (NumParams == 2 && !CanBeBinaryOperator) ||
9335       (NumParams < 1) || (NumParams > 2))) {
9336    // We have the wrong number of parameters.
9337    unsigned ErrorKind;
9338    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9339      ErrorKind = 2;  // 2 -> unary or binary.
9340    } else if (CanBeUnaryOperator) {
9341      ErrorKind = 0;  // 0 -> unary
9342    } else {
9343      assert(CanBeBinaryOperator &&
9344             "All non-call overloaded operators are unary or binary!");
9345      ErrorKind = 1;  // 1 -> binary
9346    }
9347
9348    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9349      << FnDecl->getDeclName() << NumParams << ErrorKind;
9350  }
9351
9352  // Overloaded operators other than operator() cannot be variadic.
9353  if (Op != OO_Call &&
9354      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9355    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9356      << FnDecl->getDeclName();
9357  }
9358
9359  // Some operators must be non-static member functions.
9360  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9361    return Diag(FnDecl->getLocation(),
9362                diag::err_operator_overload_must_be_member)
9363      << FnDecl->getDeclName();
9364  }
9365
9366  // C++ [over.inc]p1:
9367  //   The user-defined function called operator++ implements the
9368  //   prefix and postfix ++ operator. If this function is a member
9369  //   function with no parameters, or a non-member function with one
9370  //   parameter of class or enumeration type, it defines the prefix
9371  //   increment operator ++ for objects of that type. If the function
9372  //   is a member function with one parameter (which shall be of type
9373  //   int) or a non-member function with two parameters (the second
9374  //   of which shall be of type int), it defines the postfix
9375  //   increment operator ++ for objects of that type.
9376  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9377    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9378    bool ParamIsInt = false;
9379    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9380      ParamIsInt = BT->getKind() == BuiltinType::Int;
9381
9382    if (!ParamIsInt)
9383      return Diag(LastParam->getLocation(),
9384                  diag::err_operator_overload_post_incdec_must_be_int)
9385        << LastParam->getType() << (Op == OO_MinusMinus);
9386  }
9387
9388  return false;
9389}
9390
9391/// CheckLiteralOperatorDeclaration - Check whether the declaration
9392/// of this literal operator function is well-formed. If so, returns
9393/// false; otherwise, emits appropriate diagnostics and returns true.
9394bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9395  if (isa<CXXMethodDecl>(FnDecl)) {
9396    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9397      << FnDecl->getDeclName();
9398    return true;
9399  }
9400
9401  if (FnDecl->isExternC()) {
9402    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9403    return true;
9404  }
9405
9406  bool Valid = false;
9407
9408  // This might be the definition of a literal operator template.
9409  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9410  // This might be a specialization of a literal operator template.
9411  if (!TpDecl)
9412    TpDecl = FnDecl->getPrimaryTemplate();
9413
9414  // template <char...> type operator "" name() is the only valid template
9415  // signature, and the only valid signature with no parameters.
9416  if (TpDecl) {
9417    if (FnDecl->param_size() == 0) {
9418      // Must have only one template parameter
9419      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9420      if (Params->size() == 1) {
9421        NonTypeTemplateParmDecl *PmDecl =
9422          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9423
9424        // The template parameter must be a char parameter pack.
9425        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9426            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9427          Valid = true;
9428      }
9429    }
9430  } else if (FnDecl->param_size()) {
9431    // Check the first parameter
9432    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9433
9434    QualType T = (*Param)->getType().getUnqualifiedType();
9435
9436    // unsigned long long int, long double, and any character type are allowed
9437    // as the only parameters.
9438    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9439        Context.hasSameType(T, Context.LongDoubleTy) ||
9440        Context.hasSameType(T, Context.CharTy) ||
9441        Context.hasSameType(T, Context.WCharTy) ||
9442        Context.hasSameType(T, Context.Char16Ty) ||
9443        Context.hasSameType(T, Context.Char32Ty)) {
9444      if (++Param == FnDecl->param_end())
9445        Valid = true;
9446      goto FinishedParams;
9447    }
9448
9449    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9450    const PointerType *PT = T->getAs<PointerType>();
9451    if (!PT)
9452      goto FinishedParams;
9453    T = PT->getPointeeType();
9454    if (!T.isConstQualified() || T.isVolatileQualified())
9455      goto FinishedParams;
9456    T = T.getUnqualifiedType();
9457
9458    // Move on to the second parameter;
9459    ++Param;
9460
9461    // If there is no second parameter, the first must be a const char *
9462    if (Param == FnDecl->param_end()) {
9463      if (Context.hasSameType(T, Context.CharTy))
9464        Valid = true;
9465      goto FinishedParams;
9466    }
9467
9468    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9469    // are allowed as the first parameter to a two-parameter function
9470    if (!(Context.hasSameType(T, Context.CharTy) ||
9471          Context.hasSameType(T, Context.WCharTy) ||
9472          Context.hasSameType(T, Context.Char16Ty) ||
9473          Context.hasSameType(T, Context.Char32Ty)))
9474      goto FinishedParams;
9475
9476    // The second and final parameter must be an std::size_t
9477    T = (*Param)->getType().getUnqualifiedType();
9478    if (Context.hasSameType(T, Context.getSizeType()) &&
9479        ++Param == FnDecl->param_end())
9480      Valid = true;
9481  }
9482
9483  // FIXME: This diagnostic is absolutely terrible.
9484FinishedParams:
9485  if (!Valid) {
9486    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9487      << FnDecl->getDeclName();
9488    return true;
9489  }
9490
9491  // A parameter-declaration-clause containing a default argument is not
9492  // equivalent to any of the permitted forms.
9493  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9494                                    ParamEnd = FnDecl->param_end();
9495       Param != ParamEnd; ++Param) {
9496    if ((*Param)->hasDefaultArg()) {
9497      Diag((*Param)->getDefaultArgRange().getBegin(),
9498           diag::err_literal_operator_default_argument)
9499        << (*Param)->getDefaultArgRange();
9500      break;
9501    }
9502  }
9503
9504  StringRef LiteralName
9505    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9506  if (LiteralName[0] != '_') {
9507    // C++11 [usrlit.suffix]p1:
9508    //   Literal suffix identifiers that do not start with an underscore
9509    //   are reserved for future standardization.
9510    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9511  }
9512
9513  return false;
9514}
9515
9516/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9517/// linkage specification, including the language and (if present)
9518/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9519/// the location of the language string literal, which is provided
9520/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9521/// the '{' brace. Otherwise, this linkage specification does not
9522/// have any braces.
9523Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9524                                           SourceLocation LangLoc,
9525                                           StringRef Lang,
9526                                           SourceLocation LBraceLoc) {
9527  LinkageSpecDecl::LanguageIDs Language;
9528  if (Lang == "\"C\"")
9529    Language = LinkageSpecDecl::lang_c;
9530  else if (Lang == "\"C++\"")
9531    Language = LinkageSpecDecl::lang_cxx;
9532  else {
9533    Diag(LangLoc, diag::err_bad_language);
9534    return 0;
9535  }
9536
9537  // FIXME: Add all the various semantics of linkage specifications
9538
9539  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9540                                               ExternLoc, LangLoc, Language);
9541  CurContext->addDecl(D);
9542  PushDeclContext(S, D);
9543  return D;
9544}
9545
9546/// ActOnFinishLinkageSpecification - Complete the definition of
9547/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9548/// valid, it's the position of the closing '}' brace in a linkage
9549/// specification that uses braces.
9550Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9551                                            Decl *LinkageSpec,
9552                                            SourceLocation RBraceLoc) {
9553  if (LinkageSpec) {
9554    if (RBraceLoc.isValid()) {
9555      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9556      LSDecl->setRBraceLoc(RBraceLoc);
9557    }
9558    PopDeclContext();
9559  }
9560  return LinkageSpec;
9561}
9562
9563/// \brief Perform semantic analysis for the variable declaration that
9564/// occurs within a C++ catch clause, returning the newly-created
9565/// variable.
9566VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9567                                         TypeSourceInfo *TInfo,
9568                                         SourceLocation StartLoc,
9569                                         SourceLocation Loc,
9570                                         IdentifierInfo *Name) {
9571  bool Invalid = false;
9572  QualType ExDeclType = TInfo->getType();
9573
9574  // Arrays and functions decay.
9575  if (ExDeclType->isArrayType())
9576    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9577  else if (ExDeclType->isFunctionType())
9578    ExDeclType = Context.getPointerType(ExDeclType);
9579
9580  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9581  // The exception-declaration shall not denote a pointer or reference to an
9582  // incomplete type, other than [cv] void*.
9583  // N2844 forbids rvalue references.
9584  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9585    Diag(Loc, diag::err_catch_rvalue_ref);
9586    Invalid = true;
9587  }
9588
9589  QualType BaseType = ExDeclType;
9590  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9591  unsigned DK = diag::err_catch_incomplete;
9592  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9593    BaseType = Ptr->getPointeeType();
9594    Mode = 1;
9595    DK = diag::err_catch_incomplete_ptr;
9596  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9597    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9598    BaseType = Ref->getPointeeType();
9599    Mode = 2;
9600    DK = diag::err_catch_incomplete_ref;
9601  }
9602  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9603      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9604    Invalid = true;
9605
9606  if (!Invalid && !ExDeclType->isDependentType() &&
9607      RequireNonAbstractType(Loc, ExDeclType,
9608                             diag::err_abstract_type_in_decl,
9609                             AbstractVariableType))
9610    Invalid = true;
9611
9612  // Only the non-fragile NeXT runtime currently supports C++ catches
9613  // of ObjC types, and no runtime supports catching ObjC types by value.
9614  if (!Invalid && getLangOpts().ObjC1) {
9615    QualType T = ExDeclType;
9616    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9617      T = RT->getPointeeType();
9618
9619    if (T->isObjCObjectType()) {
9620      Diag(Loc, diag::err_objc_object_catch);
9621      Invalid = true;
9622    } else if (T->isObjCObjectPointerType()) {
9623      // FIXME: should this be a test for macosx-fragile specifically?
9624      if (getLangOpts().ObjCRuntime.isFragile())
9625        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9626    }
9627  }
9628
9629  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9630                                    ExDeclType, TInfo, SC_None, SC_None);
9631  ExDecl->setExceptionVariable(true);
9632
9633  // In ARC, infer 'retaining' for variables of retainable type.
9634  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9635    Invalid = true;
9636
9637  if (!Invalid && !ExDeclType->isDependentType()) {
9638    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9639      // C++ [except.handle]p16:
9640      //   The object declared in an exception-declaration or, if the
9641      //   exception-declaration does not specify a name, a temporary (12.2) is
9642      //   copy-initialized (8.5) from the exception object. [...]
9643      //   The object is destroyed when the handler exits, after the destruction
9644      //   of any automatic objects initialized within the handler.
9645      //
9646      // We just pretend to initialize the object with itself, then make sure
9647      // it can be destroyed later.
9648      QualType initType = ExDeclType;
9649
9650      InitializedEntity entity =
9651        InitializedEntity::InitializeVariable(ExDecl);
9652      InitializationKind initKind =
9653        InitializationKind::CreateCopy(Loc, SourceLocation());
9654
9655      Expr *opaqueValue =
9656        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9657      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9658      ExprResult result = sequence.Perform(*this, entity, initKind,
9659                                           MultiExprArg(&opaqueValue, 1));
9660      if (result.isInvalid())
9661        Invalid = true;
9662      else {
9663        // If the constructor used was non-trivial, set this as the
9664        // "initializer".
9665        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9666        if (!construct->getConstructor()->isTrivial()) {
9667          Expr *init = MaybeCreateExprWithCleanups(construct);
9668          ExDecl->setInit(init);
9669        }
9670
9671        // And make sure it's destructable.
9672        FinalizeVarWithDestructor(ExDecl, recordType);
9673      }
9674    }
9675  }
9676
9677  if (Invalid)
9678    ExDecl->setInvalidDecl();
9679
9680  return ExDecl;
9681}
9682
9683/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9684/// handler.
9685Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9686  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9687  bool Invalid = D.isInvalidType();
9688
9689  // Check for unexpanded parameter packs.
9690  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9691                                               UPPC_ExceptionType)) {
9692    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9693                                             D.getIdentifierLoc());
9694    Invalid = true;
9695  }
9696
9697  IdentifierInfo *II = D.getIdentifier();
9698  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9699                                             LookupOrdinaryName,
9700                                             ForRedeclaration)) {
9701    // The scope should be freshly made just for us. There is just no way
9702    // it contains any previous declaration.
9703    assert(!S->isDeclScope(PrevDecl));
9704    if (PrevDecl->isTemplateParameter()) {
9705      // Maybe we will complain about the shadowed template parameter.
9706      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9707      PrevDecl = 0;
9708    }
9709  }
9710
9711  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9712    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9713      << D.getCXXScopeSpec().getRange();
9714    Invalid = true;
9715  }
9716
9717  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9718                                              D.getLocStart(),
9719                                              D.getIdentifierLoc(),
9720                                              D.getIdentifier());
9721  if (Invalid)
9722    ExDecl->setInvalidDecl();
9723
9724  // Add the exception declaration into this scope.
9725  if (II)
9726    PushOnScopeChains(ExDecl, S);
9727  else
9728    CurContext->addDecl(ExDecl);
9729
9730  ProcessDeclAttributes(S, ExDecl, D);
9731  return ExDecl;
9732}
9733
9734Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9735                                         Expr *AssertExpr,
9736                                         Expr *AssertMessageExpr_,
9737                                         SourceLocation RParenLoc) {
9738  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
9739
9740  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9741    // In a static_assert-declaration, the constant-expression shall be a
9742    // constant expression that can be contextually converted to bool.
9743    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9744    if (Converted.isInvalid())
9745      return 0;
9746
9747    llvm::APSInt Cond;
9748    if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9749          diag::err_static_assert_expression_is_not_constant,
9750          /*AllowFold=*/false).isInvalid())
9751      return 0;
9752
9753    if (!Cond) {
9754      llvm::SmallString<256> MsgBuffer;
9755      llvm::raw_svector_ostream Msg(MsgBuffer);
9756      AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
9757      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9758        << Msg.str() << AssertExpr->getSourceRange();
9759    }
9760  }
9761
9762  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9763    return 0;
9764
9765  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9766                                        AssertExpr, AssertMessage, RParenLoc);
9767
9768  CurContext->addDecl(Decl);
9769  return Decl;
9770}
9771
9772/// \brief Perform semantic analysis of the given friend type declaration.
9773///
9774/// \returns A friend declaration that.
9775FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9776                                      SourceLocation FriendLoc,
9777                                      TypeSourceInfo *TSInfo) {
9778  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9779
9780  QualType T = TSInfo->getType();
9781  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9782
9783  // C++03 [class.friend]p2:
9784  //   An elaborated-type-specifier shall be used in a friend declaration
9785  //   for a class.*
9786  //
9787  //   * The class-key of the elaborated-type-specifier is required.
9788  if (!ActiveTemplateInstantiations.empty()) {
9789    // Do not complain about the form of friend template types during
9790    // template instantiation; we will already have complained when the
9791    // template was declared.
9792  } else if (!T->isElaboratedTypeSpecifier()) {
9793    // If we evaluated the type to a record type, suggest putting
9794    // a tag in front.
9795    if (const RecordType *RT = T->getAs<RecordType>()) {
9796      RecordDecl *RD = RT->getDecl();
9797
9798      std::string InsertionText = std::string(" ") + RD->getKindName();
9799
9800      Diag(TypeRange.getBegin(),
9801           getLangOpts().CPlusPlus0x ?
9802             diag::warn_cxx98_compat_unelaborated_friend_type :
9803             diag::ext_unelaborated_friend_type)
9804        << (unsigned) RD->getTagKind()
9805        << T
9806        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9807                                      InsertionText);
9808    } else {
9809      Diag(FriendLoc,
9810           getLangOpts().CPlusPlus0x ?
9811             diag::warn_cxx98_compat_nonclass_type_friend :
9812             diag::ext_nonclass_type_friend)
9813        << T
9814        << SourceRange(FriendLoc, TypeRange.getEnd());
9815    }
9816  } else if (T->getAs<EnumType>()) {
9817    Diag(FriendLoc,
9818         getLangOpts().CPlusPlus0x ?
9819           diag::warn_cxx98_compat_enum_friend :
9820           diag::ext_enum_friend)
9821      << T
9822      << SourceRange(FriendLoc, TypeRange.getEnd());
9823  }
9824
9825  // C++0x [class.friend]p3:
9826  //   If the type specifier in a friend declaration designates a (possibly
9827  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9828  //   the friend declaration is ignored.
9829
9830  // FIXME: C++0x has some syntactic restrictions on friend type declarations
9831  // in [class.friend]p3 that we do not implement.
9832
9833  return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
9834}
9835
9836/// Handle a friend tag declaration where the scope specifier was
9837/// templated.
9838Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9839                                    unsigned TagSpec, SourceLocation TagLoc,
9840                                    CXXScopeSpec &SS,
9841                                    IdentifierInfo *Name, SourceLocation NameLoc,
9842                                    AttributeList *Attr,
9843                                    MultiTemplateParamsArg TempParamLists) {
9844  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9845
9846  bool isExplicitSpecialization = false;
9847  bool Invalid = false;
9848
9849  if (TemplateParameterList *TemplateParams
9850        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9851                                                  TempParamLists.get(),
9852                                                  TempParamLists.size(),
9853                                                  /*friend*/ true,
9854                                                  isExplicitSpecialization,
9855                                                  Invalid)) {
9856    if (TemplateParams->size() > 0) {
9857      // This is a declaration of a class template.
9858      if (Invalid)
9859        return 0;
9860
9861      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9862                                SS, Name, NameLoc, Attr,
9863                                TemplateParams, AS_public,
9864                                /*ModulePrivateLoc=*/SourceLocation(),
9865                                TempParamLists.size() - 1,
9866                   (TemplateParameterList**) TempParamLists.release()).take();
9867    } else {
9868      // The "template<>" header is extraneous.
9869      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9870        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9871      isExplicitSpecialization = true;
9872    }
9873  }
9874
9875  if (Invalid) return 0;
9876
9877  bool isAllExplicitSpecializations = true;
9878  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9879    if (TempParamLists.get()[I]->size()) {
9880      isAllExplicitSpecializations = false;
9881      break;
9882    }
9883  }
9884
9885  // FIXME: don't ignore attributes.
9886
9887  // If it's explicit specializations all the way down, just forget
9888  // about the template header and build an appropriate non-templated
9889  // friend.  TODO: for source fidelity, remember the headers.
9890  if (isAllExplicitSpecializations) {
9891    if (SS.isEmpty()) {
9892      bool Owned = false;
9893      bool IsDependent = false;
9894      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9895                      Attr, AS_public,
9896                      /*ModulePrivateLoc=*/SourceLocation(),
9897                      MultiTemplateParamsArg(), Owned, IsDependent,
9898                      /*ScopedEnumKWLoc=*/SourceLocation(),
9899                      /*ScopedEnumUsesClassTag=*/false,
9900                      /*UnderlyingType=*/TypeResult());
9901    }
9902
9903    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9904    ElaboratedTypeKeyword Keyword
9905      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9906    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9907                                   *Name, NameLoc);
9908    if (T.isNull())
9909      return 0;
9910
9911    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9912    if (isa<DependentNameType>(T)) {
9913      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9914      TL.setElaboratedKeywordLoc(TagLoc);
9915      TL.setQualifierLoc(QualifierLoc);
9916      TL.setNameLoc(NameLoc);
9917    } else {
9918      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9919      TL.setElaboratedKeywordLoc(TagLoc);
9920      TL.setQualifierLoc(QualifierLoc);
9921      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9922    }
9923
9924    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9925                                            TSI, FriendLoc);
9926    Friend->setAccess(AS_public);
9927    CurContext->addDecl(Friend);
9928    return Friend;
9929  }
9930
9931  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9932
9933
9934
9935  // Handle the case of a templated-scope friend class.  e.g.
9936  //   template <class T> class A<T>::B;
9937  // FIXME: we don't support these right now.
9938  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9939  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9940  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9941  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9942  TL.setElaboratedKeywordLoc(TagLoc);
9943  TL.setQualifierLoc(SS.getWithLocInContext(Context));
9944  TL.setNameLoc(NameLoc);
9945
9946  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9947                                          TSI, FriendLoc);
9948  Friend->setAccess(AS_public);
9949  Friend->setUnsupportedFriend(true);
9950  CurContext->addDecl(Friend);
9951  return Friend;
9952}
9953
9954
9955/// Handle a friend type declaration.  This works in tandem with
9956/// ActOnTag.
9957///
9958/// Notes on friend class templates:
9959///
9960/// We generally treat friend class declarations as if they were
9961/// declaring a class.  So, for example, the elaborated type specifier
9962/// in a friend declaration is required to obey the restrictions of a
9963/// class-head (i.e. no typedefs in the scope chain), template
9964/// parameters are required to match up with simple template-ids, &c.
9965/// However, unlike when declaring a template specialization, it's
9966/// okay to refer to a template specialization without an empty
9967/// template parameter declaration, e.g.
9968///   friend class A<T>::B<unsigned>;
9969/// We permit this as a special case; if there are any template
9970/// parameters present at all, require proper matching, i.e.
9971///   template <> template \<class T> friend class A<int>::B;
9972Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
9973                                MultiTemplateParamsArg TempParams) {
9974  SourceLocation Loc = DS.getLocStart();
9975
9976  assert(DS.isFriendSpecified());
9977  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9978
9979  // Try to convert the decl specifier to a type.  This works for
9980  // friend templates because ActOnTag never produces a ClassTemplateDecl
9981  // for a TUK_Friend.
9982  Declarator TheDeclarator(DS, Declarator::MemberContext);
9983  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9984  QualType T = TSI->getType();
9985  if (TheDeclarator.isInvalidType())
9986    return 0;
9987
9988  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9989    return 0;
9990
9991  // This is definitely an error in C++98.  It's probably meant to
9992  // be forbidden in C++0x, too, but the specification is just
9993  // poorly written.
9994  //
9995  // The problem is with declarations like the following:
9996  //   template <T> friend A<T>::foo;
9997  // where deciding whether a class C is a friend or not now hinges
9998  // on whether there exists an instantiation of A that causes
9999  // 'foo' to equal C.  There are restrictions on class-heads
10000  // (which we declare (by fiat) elaborated friend declarations to
10001  // be) that makes this tractable.
10002  //
10003  // FIXME: handle "template <> friend class A<T>;", which
10004  // is possibly well-formed?  Who even knows?
10005  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10006    Diag(Loc, diag::err_tagless_friend_type_template)
10007      << DS.getSourceRange();
10008    return 0;
10009  }
10010
10011  // C++98 [class.friend]p1: A friend of a class is a function
10012  //   or class that is not a member of the class . . .
10013  // This is fixed in DR77, which just barely didn't make the C++03
10014  // deadline.  It's also a very silly restriction that seriously
10015  // affects inner classes and which nobody else seems to implement;
10016  // thus we never diagnose it, not even in -pedantic.
10017  //
10018  // But note that we could warn about it: it's always useless to
10019  // friend one of your own members (it's not, however, worthless to
10020  // friend a member of an arbitrary specialization of your template).
10021
10022  Decl *D;
10023  if (unsigned NumTempParamLists = TempParams.size())
10024    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10025                                   NumTempParamLists,
10026                                   TempParams.release(),
10027                                   TSI,
10028                                   DS.getFriendSpecLoc());
10029  else
10030    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10031
10032  if (!D)
10033    return 0;
10034
10035  D->setAccess(AS_public);
10036  CurContext->addDecl(D);
10037
10038  return D;
10039}
10040
10041Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10042                                    MultiTemplateParamsArg TemplateParams) {
10043  const DeclSpec &DS = D.getDeclSpec();
10044
10045  assert(DS.isFriendSpecified());
10046  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10047
10048  SourceLocation Loc = D.getIdentifierLoc();
10049  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10050
10051  // C++ [class.friend]p1
10052  //   A friend of a class is a function or class....
10053  // Note that this sees through typedefs, which is intended.
10054  // It *doesn't* see through dependent types, which is correct
10055  // according to [temp.arg.type]p3:
10056  //   If a declaration acquires a function type through a
10057  //   type dependent on a template-parameter and this causes
10058  //   a declaration that does not use the syntactic form of a
10059  //   function declarator to have a function type, the program
10060  //   is ill-formed.
10061  if (!TInfo->getType()->isFunctionType()) {
10062    Diag(Loc, diag::err_unexpected_friend);
10063
10064    // It might be worthwhile to try to recover by creating an
10065    // appropriate declaration.
10066    return 0;
10067  }
10068
10069  // C++ [namespace.memdef]p3
10070  //  - If a friend declaration in a non-local class first declares a
10071  //    class or function, the friend class or function is a member
10072  //    of the innermost enclosing namespace.
10073  //  - The name of the friend is not found by simple name lookup
10074  //    until a matching declaration is provided in that namespace
10075  //    scope (either before or after the class declaration granting
10076  //    friendship).
10077  //  - If a friend function is called, its name may be found by the
10078  //    name lookup that considers functions from namespaces and
10079  //    classes associated with the types of the function arguments.
10080  //  - When looking for a prior declaration of a class or a function
10081  //    declared as a friend, scopes outside the innermost enclosing
10082  //    namespace scope are not considered.
10083
10084  CXXScopeSpec &SS = D.getCXXScopeSpec();
10085  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10086  DeclarationName Name = NameInfo.getName();
10087  assert(Name);
10088
10089  // Check for unexpanded parameter packs.
10090  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10091      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10092      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10093    return 0;
10094
10095  // The context we found the declaration in, or in which we should
10096  // create the declaration.
10097  DeclContext *DC;
10098  Scope *DCScope = S;
10099  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10100                        ForRedeclaration);
10101
10102  // FIXME: there are different rules in local classes
10103
10104  // There are four cases here.
10105  //   - There's no scope specifier, in which case we just go to the
10106  //     appropriate scope and look for a function or function template
10107  //     there as appropriate.
10108  // Recover from invalid scope qualifiers as if they just weren't there.
10109  if (SS.isInvalid() || !SS.isSet()) {
10110    // C++0x [namespace.memdef]p3:
10111    //   If the name in a friend declaration is neither qualified nor
10112    //   a template-id and the declaration is a function or an
10113    //   elaborated-type-specifier, the lookup to determine whether
10114    //   the entity has been previously declared shall not consider
10115    //   any scopes outside the innermost enclosing namespace.
10116    // C++0x [class.friend]p11:
10117    //   If a friend declaration appears in a local class and the name
10118    //   specified is an unqualified name, a prior declaration is
10119    //   looked up without considering scopes that are outside the
10120    //   innermost enclosing non-class scope. For a friend function
10121    //   declaration, if there is no prior declaration, the program is
10122    //   ill-formed.
10123    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10124    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10125
10126    // Find the appropriate context according to the above.
10127    DC = CurContext;
10128    while (true) {
10129      // Skip class contexts.  If someone can cite chapter and verse
10130      // for this behavior, that would be nice --- it's what GCC and
10131      // EDG do, and it seems like a reasonable intent, but the spec
10132      // really only says that checks for unqualified existing
10133      // declarations should stop at the nearest enclosing namespace,
10134      // not that they should only consider the nearest enclosing
10135      // namespace.
10136      while (DC->isRecord() || DC->isTransparentContext())
10137        DC = DC->getParent();
10138
10139      LookupQualifiedName(Previous, DC);
10140
10141      // TODO: decide what we think about using declarations.
10142      if (isLocal || !Previous.empty())
10143        break;
10144
10145      if (isTemplateId) {
10146        if (isa<TranslationUnitDecl>(DC)) break;
10147      } else {
10148        if (DC->isFileContext()) break;
10149      }
10150      DC = DC->getParent();
10151    }
10152
10153    // C++ [class.friend]p1: A friend of a class is a function or
10154    //   class that is not a member of the class . . .
10155    // C++11 changes this for both friend types and functions.
10156    // Most C++ 98 compilers do seem to give an error here, so
10157    // we do, too.
10158    if (!Previous.empty() && DC->Equals(CurContext))
10159      Diag(DS.getFriendSpecLoc(),
10160           getLangOpts().CPlusPlus0x ?
10161             diag::warn_cxx98_compat_friend_is_member :
10162             diag::err_friend_is_member);
10163
10164    DCScope = getScopeForDeclContext(S, DC);
10165
10166    // C++ [class.friend]p6:
10167    //   A function can be defined in a friend declaration of a class if and
10168    //   only if the class is a non-local class (9.8), the function name is
10169    //   unqualified, and the function has namespace scope.
10170    if (isLocal && D.isFunctionDefinition()) {
10171      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10172    }
10173
10174  //   - There's a non-dependent scope specifier, in which case we
10175  //     compute it and do a previous lookup there for a function
10176  //     or function template.
10177  } else if (!SS.getScopeRep()->isDependent()) {
10178    DC = computeDeclContext(SS);
10179    if (!DC) return 0;
10180
10181    if (RequireCompleteDeclContext(SS, DC)) return 0;
10182
10183    LookupQualifiedName(Previous, DC);
10184
10185    // Ignore things found implicitly in the wrong scope.
10186    // TODO: better diagnostics for this case.  Suggesting the right
10187    // qualified scope would be nice...
10188    LookupResult::Filter F = Previous.makeFilter();
10189    while (F.hasNext()) {
10190      NamedDecl *D = F.next();
10191      if (!DC->InEnclosingNamespaceSetOf(
10192              D->getDeclContext()->getRedeclContext()))
10193        F.erase();
10194    }
10195    F.done();
10196
10197    if (Previous.empty()) {
10198      D.setInvalidType();
10199      Diag(Loc, diag::err_qualified_friend_not_found)
10200          << Name << TInfo->getType();
10201      return 0;
10202    }
10203
10204    // C++ [class.friend]p1: A friend of a class is a function or
10205    //   class that is not a member of the class . . .
10206    if (DC->Equals(CurContext))
10207      Diag(DS.getFriendSpecLoc(),
10208           getLangOpts().CPlusPlus0x ?
10209             diag::warn_cxx98_compat_friend_is_member :
10210             diag::err_friend_is_member);
10211
10212    if (D.isFunctionDefinition()) {
10213      // C++ [class.friend]p6:
10214      //   A function can be defined in a friend declaration of a class if and
10215      //   only if the class is a non-local class (9.8), the function name is
10216      //   unqualified, and the function has namespace scope.
10217      SemaDiagnosticBuilder DB
10218        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10219
10220      DB << SS.getScopeRep();
10221      if (DC->isFileContext())
10222        DB << FixItHint::CreateRemoval(SS.getRange());
10223      SS.clear();
10224    }
10225
10226  //   - There's a scope specifier that does not match any template
10227  //     parameter lists, in which case we use some arbitrary context,
10228  //     create a method or method template, and wait for instantiation.
10229  //   - There's a scope specifier that does match some template
10230  //     parameter lists, which we don't handle right now.
10231  } else {
10232    if (D.isFunctionDefinition()) {
10233      // C++ [class.friend]p6:
10234      //   A function can be defined in a friend declaration of a class if and
10235      //   only if the class is a non-local class (9.8), the function name is
10236      //   unqualified, and the function has namespace scope.
10237      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10238        << SS.getScopeRep();
10239    }
10240
10241    DC = CurContext;
10242    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10243  }
10244
10245  if (!DC->isRecord()) {
10246    // This implies that it has to be an operator or function.
10247    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10248        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10249        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10250      Diag(Loc, diag::err_introducing_special_friend) <<
10251        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10252         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10253      return 0;
10254    }
10255  }
10256
10257  // FIXME: This is an egregious hack to cope with cases where the scope stack
10258  // does not contain the declaration context, i.e., in an out-of-line
10259  // definition of a class.
10260  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10261  if (!DCScope) {
10262    FakeDCScope.setEntity(DC);
10263    DCScope = &FakeDCScope;
10264  }
10265
10266  bool AddToScope = true;
10267  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10268                                          move(TemplateParams), AddToScope);
10269  if (!ND) return 0;
10270
10271  assert(ND->getDeclContext() == DC);
10272  assert(ND->getLexicalDeclContext() == CurContext);
10273
10274  // Add the function declaration to the appropriate lookup tables,
10275  // adjusting the redeclarations list as necessary.  We don't
10276  // want to do this yet if the friending class is dependent.
10277  //
10278  // Also update the scope-based lookup if the target context's
10279  // lookup context is in lexical scope.
10280  if (!CurContext->isDependentContext()) {
10281    DC = DC->getRedeclContext();
10282    DC->makeDeclVisibleInContext(ND);
10283    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10284      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10285  }
10286
10287  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10288                                       D.getIdentifierLoc(), ND,
10289                                       DS.getFriendSpecLoc());
10290  FrD->setAccess(AS_public);
10291  CurContext->addDecl(FrD);
10292
10293  if (ND->isInvalidDecl())
10294    FrD->setInvalidDecl();
10295  else {
10296    FunctionDecl *FD;
10297    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10298      FD = FTD->getTemplatedDecl();
10299    else
10300      FD = cast<FunctionDecl>(ND);
10301
10302    // Mark templated-scope function declarations as unsupported.
10303    if (FD->getNumTemplateParameterLists())
10304      FrD->setUnsupportedFriend(true);
10305  }
10306
10307  return ND;
10308}
10309
10310void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10311  AdjustDeclIfTemplate(Dcl);
10312
10313  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10314  if (!Fn) {
10315    Diag(DelLoc, diag::err_deleted_non_function);
10316    return;
10317  }
10318  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10319    Diag(DelLoc, diag::err_deleted_decl_not_first);
10320    Diag(Prev->getLocation(), diag::note_previous_declaration);
10321    // If the declaration wasn't the first, we delete the function anyway for
10322    // recovery.
10323  }
10324  Fn->setDeletedAsWritten();
10325
10326  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10327  if (!MD)
10328    return;
10329
10330  // A deleted special member function is trivial if the corresponding
10331  // implicitly-declared function would have been.
10332  switch (getSpecialMember(MD)) {
10333  case CXXInvalid:
10334    break;
10335  case CXXDefaultConstructor:
10336    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10337    break;
10338  case CXXCopyConstructor:
10339    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10340    break;
10341  case CXXMoveConstructor:
10342    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10343    break;
10344  case CXXCopyAssignment:
10345    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10346    break;
10347  case CXXMoveAssignment:
10348    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10349    break;
10350  case CXXDestructor:
10351    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10352    break;
10353  }
10354}
10355
10356void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10357  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10358
10359  if (MD) {
10360    if (MD->getParent()->isDependentType()) {
10361      MD->setDefaulted();
10362      MD->setExplicitlyDefaulted();
10363      return;
10364    }
10365
10366    CXXSpecialMember Member = getSpecialMember(MD);
10367    if (Member == CXXInvalid) {
10368      Diag(DefaultLoc, diag::err_default_special_members);
10369      return;
10370    }
10371
10372    MD->setDefaulted();
10373    MD->setExplicitlyDefaulted();
10374
10375    // If this definition appears within the record, do the checking when
10376    // the record is complete.
10377    const FunctionDecl *Primary = MD;
10378    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10379      // Find the uninstantiated declaration that actually had the '= default'
10380      // on it.
10381      MD->getTemplateInstantiationPattern()->isDefined(Primary);
10382
10383    if (Primary == Primary->getCanonicalDecl())
10384      return;
10385
10386    switch (Member) {
10387    case CXXDefaultConstructor: {
10388      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10389      CheckExplicitlyDefaultedSpecialMember(CD);
10390      if (!CD->isInvalidDecl())
10391        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10392      break;
10393    }
10394
10395    case CXXCopyConstructor: {
10396      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10397      CheckExplicitlyDefaultedSpecialMember(CD);
10398      if (!CD->isInvalidDecl())
10399        DefineImplicitCopyConstructor(DefaultLoc, CD);
10400      break;
10401    }
10402
10403    case CXXCopyAssignment: {
10404      CheckExplicitlyDefaultedSpecialMember(MD);
10405      if (!MD->isInvalidDecl())
10406        DefineImplicitCopyAssignment(DefaultLoc, MD);
10407      break;
10408    }
10409
10410    case CXXDestructor: {
10411      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10412      CheckExplicitlyDefaultedSpecialMember(DD);
10413      if (!DD->isInvalidDecl())
10414        DefineImplicitDestructor(DefaultLoc, DD);
10415      break;
10416    }
10417
10418    case CXXMoveConstructor: {
10419      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10420      CheckExplicitlyDefaultedSpecialMember(CD);
10421      if (!CD->isInvalidDecl())
10422        DefineImplicitMoveConstructor(DefaultLoc, CD);
10423      break;
10424    }
10425
10426    case CXXMoveAssignment: {
10427      CheckExplicitlyDefaultedSpecialMember(MD);
10428      if (!MD->isInvalidDecl())
10429        DefineImplicitMoveAssignment(DefaultLoc, MD);
10430      break;
10431    }
10432
10433    case CXXInvalid:
10434      llvm_unreachable("Invalid special member.");
10435    }
10436  } else {
10437    Diag(DefaultLoc, diag::err_default_special_members);
10438  }
10439}
10440
10441static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10442  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10443    Stmt *SubStmt = *CI;
10444    if (!SubStmt)
10445      continue;
10446    if (isa<ReturnStmt>(SubStmt))
10447      Self.Diag(SubStmt->getLocStart(),
10448           diag::err_return_in_constructor_handler);
10449    if (!isa<Expr>(SubStmt))
10450      SearchForReturnInStmt(Self, SubStmt);
10451  }
10452}
10453
10454void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10455  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10456    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10457    SearchForReturnInStmt(*this, Handler);
10458  }
10459}
10460
10461bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10462                                             const CXXMethodDecl *Old) {
10463  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10464  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10465
10466  if (Context.hasSameType(NewTy, OldTy) ||
10467      NewTy->isDependentType() || OldTy->isDependentType())
10468    return false;
10469
10470  // Check if the return types are covariant
10471  QualType NewClassTy, OldClassTy;
10472
10473  /// Both types must be pointers or references to classes.
10474  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10475    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10476      NewClassTy = NewPT->getPointeeType();
10477      OldClassTy = OldPT->getPointeeType();
10478    }
10479  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10480    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10481      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10482        NewClassTy = NewRT->getPointeeType();
10483        OldClassTy = OldRT->getPointeeType();
10484      }
10485    }
10486  }
10487
10488  // The return types aren't either both pointers or references to a class type.
10489  if (NewClassTy.isNull()) {
10490    Diag(New->getLocation(),
10491         diag::err_different_return_type_for_overriding_virtual_function)
10492      << New->getDeclName() << NewTy << OldTy;
10493    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10494
10495    return true;
10496  }
10497
10498  // C++ [class.virtual]p6:
10499  //   If the return type of D::f differs from the return type of B::f, the
10500  //   class type in the return type of D::f shall be complete at the point of
10501  //   declaration of D::f or shall be the class type D.
10502  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10503    if (!RT->isBeingDefined() &&
10504        RequireCompleteType(New->getLocation(), NewClassTy,
10505                            diag::err_covariant_return_incomplete,
10506                            New->getDeclName()))
10507    return true;
10508  }
10509
10510  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10511    // Check if the new class derives from the old class.
10512    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10513      Diag(New->getLocation(),
10514           diag::err_covariant_return_not_derived)
10515      << New->getDeclName() << NewTy << OldTy;
10516      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10517      return true;
10518    }
10519
10520    // Check if we the conversion from derived to base is valid.
10521    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10522                    diag::err_covariant_return_inaccessible_base,
10523                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10524                    // FIXME: Should this point to the return type?
10525                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10526      // FIXME: this note won't trigger for delayed access control
10527      // diagnostics, and it's impossible to get an undelayed error
10528      // here from access control during the original parse because
10529      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10530      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10531      return true;
10532    }
10533  }
10534
10535  // The qualifiers of the return types must be the same.
10536  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10537    Diag(New->getLocation(),
10538         diag::err_covariant_return_type_different_qualifications)
10539    << New->getDeclName() << NewTy << OldTy;
10540    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10541    return true;
10542  };
10543
10544
10545  // The new class type must have the same or less qualifiers as the old type.
10546  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10547    Diag(New->getLocation(),
10548         diag::err_covariant_return_type_class_type_more_qualified)
10549    << New->getDeclName() << NewTy << OldTy;
10550    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10551    return true;
10552  };
10553
10554  return false;
10555}
10556
10557/// \brief Mark the given method pure.
10558///
10559/// \param Method the method to be marked pure.
10560///
10561/// \param InitRange the source range that covers the "0" initializer.
10562bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10563  SourceLocation EndLoc = InitRange.getEnd();
10564  if (EndLoc.isValid())
10565    Method->setRangeEnd(EndLoc);
10566
10567  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10568    Method->setPure();
10569    return false;
10570  }
10571
10572  if (!Method->isInvalidDecl())
10573    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10574      << Method->getDeclName() << InitRange;
10575  return true;
10576}
10577
10578/// \brief Determine whether the given declaration is a static data member.
10579static bool isStaticDataMember(Decl *D) {
10580  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10581  if (!Var)
10582    return false;
10583
10584  return Var->isStaticDataMember();
10585}
10586/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10587/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10588/// is a fresh scope pushed for just this purpose.
10589///
10590/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10591/// static data member of class X, names should be looked up in the scope of
10592/// class X.
10593void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10594  // If there is no declaration, there was an error parsing it.
10595  if (D == 0 || D->isInvalidDecl()) return;
10596
10597  // We should only get called for declarations with scope specifiers, like:
10598  //   int foo::bar;
10599  assert(D->isOutOfLine());
10600  EnterDeclaratorContext(S, D->getDeclContext());
10601
10602  // If we are parsing the initializer for a static data member, push a
10603  // new expression evaluation context that is associated with this static
10604  // data member.
10605  if (isStaticDataMember(D))
10606    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10607}
10608
10609/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10610/// initializer for the out-of-line declaration 'D'.
10611void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10612  // If there is no declaration, there was an error parsing it.
10613  if (D == 0 || D->isInvalidDecl()) return;
10614
10615  if (isStaticDataMember(D))
10616    PopExpressionEvaluationContext();
10617
10618  assert(D->isOutOfLine());
10619  ExitDeclaratorContext(S);
10620}
10621
10622/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10623/// C++ if/switch/while/for statement.
10624/// e.g: "if (int x = f()) {...}"
10625DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10626  // C++ 6.4p2:
10627  // The declarator shall not specify a function or an array.
10628  // The type-specifier-seq shall not contain typedef and shall not declare a
10629  // new class or enumeration.
10630  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10631         "Parser allowed 'typedef' as storage class of condition decl.");
10632
10633  Decl *Dcl = ActOnDeclarator(S, D);
10634  if (!Dcl)
10635    return true;
10636
10637  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10638    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10639      << D.getSourceRange();
10640    return true;
10641  }
10642
10643  return Dcl;
10644}
10645
10646void Sema::LoadExternalVTableUses() {
10647  if (!ExternalSource)
10648    return;
10649
10650  SmallVector<ExternalVTableUse, 4> VTables;
10651  ExternalSource->ReadUsedVTables(VTables);
10652  SmallVector<VTableUse, 4> NewUses;
10653  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10654    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10655      = VTablesUsed.find(VTables[I].Record);
10656    // Even if a definition wasn't required before, it may be required now.
10657    if (Pos != VTablesUsed.end()) {
10658      if (!Pos->second && VTables[I].DefinitionRequired)
10659        Pos->second = true;
10660      continue;
10661    }
10662
10663    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10664    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10665  }
10666
10667  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10668}
10669
10670void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10671                          bool DefinitionRequired) {
10672  // Ignore any vtable uses in unevaluated operands or for classes that do
10673  // not have a vtable.
10674  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10675      CurContext->isDependentContext() ||
10676      ExprEvalContexts.back().Context == Unevaluated)
10677    return;
10678
10679  // Try to insert this class into the map.
10680  LoadExternalVTableUses();
10681  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10682  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10683    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10684  if (!Pos.second) {
10685    // If we already had an entry, check to see if we are promoting this vtable
10686    // to required a definition. If so, we need to reappend to the VTableUses
10687    // list, since we may have already processed the first entry.
10688    if (DefinitionRequired && !Pos.first->second) {
10689      Pos.first->second = true;
10690    } else {
10691      // Otherwise, we can early exit.
10692      return;
10693    }
10694  }
10695
10696  // Local classes need to have their virtual members marked
10697  // immediately. For all other classes, we mark their virtual members
10698  // at the end of the translation unit.
10699  if (Class->isLocalClass())
10700    MarkVirtualMembersReferenced(Loc, Class);
10701  else
10702    VTableUses.push_back(std::make_pair(Class, Loc));
10703}
10704
10705bool Sema::DefineUsedVTables() {
10706  LoadExternalVTableUses();
10707  if (VTableUses.empty())
10708    return false;
10709
10710  // Note: The VTableUses vector could grow as a result of marking
10711  // the members of a class as "used", so we check the size each
10712  // time through the loop and prefer indices (with are stable) to
10713  // iterators (which are not).
10714  bool DefinedAnything = false;
10715  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10716    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10717    if (!Class)
10718      continue;
10719
10720    SourceLocation Loc = VTableUses[I].second;
10721
10722    // If this class has a key function, but that key function is
10723    // defined in another translation unit, we don't need to emit the
10724    // vtable even though we're using it.
10725    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10726    if (KeyFunction && !KeyFunction->hasBody()) {
10727      switch (KeyFunction->getTemplateSpecializationKind()) {
10728      case TSK_Undeclared:
10729      case TSK_ExplicitSpecialization:
10730      case TSK_ExplicitInstantiationDeclaration:
10731        // The key function is in another translation unit.
10732        continue;
10733
10734      case TSK_ExplicitInstantiationDefinition:
10735      case TSK_ImplicitInstantiation:
10736        // We will be instantiating the key function.
10737        break;
10738      }
10739    } else if (!KeyFunction) {
10740      // If we have a class with no key function that is the subject
10741      // of an explicit instantiation declaration, suppress the
10742      // vtable; it will live with the explicit instantiation
10743      // definition.
10744      bool IsExplicitInstantiationDeclaration
10745        = Class->getTemplateSpecializationKind()
10746                                      == TSK_ExplicitInstantiationDeclaration;
10747      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10748                                 REnd = Class->redecls_end();
10749           R != REnd; ++R) {
10750        TemplateSpecializationKind TSK
10751          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10752        if (TSK == TSK_ExplicitInstantiationDeclaration)
10753          IsExplicitInstantiationDeclaration = true;
10754        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10755          IsExplicitInstantiationDeclaration = false;
10756          break;
10757        }
10758      }
10759
10760      if (IsExplicitInstantiationDeclaration)
10761        continue;
10762    }
10763
10764    // Mark all of the virtual members of this class as referenced, so
10765    // that we can build a vtable. Then, tell the AST consumer that a
10766    // vtable for this class is required.
10767    DefinedAnything = true;
10768    MarkVirtualMembersReferenced(Loc, Class);
10769    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10770    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10771
10772    // Optionally warn if we're emitting a weak vtable.
10773    if (Class->getLinkage() == ExternalLinkage &&
10774        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10775      const FunctionDecl *KeyFunctionDef = 0;
10776      if (!KeyFunction ||
10777          (KeyFunction->hasBody(KeyFunctionDef) &&
10778           KeyFunctionDef->isInlined()))
10779        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10780             TSK_ExplicitInstantiationDefinition
10781             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10782          << Class;
10783    }
10784  }
10785  VTableUses.clear();
10786
10787  return DefinedAnything;
10788}
10789
10790void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10791                                        const CXXRecordDecl *RD) {
10792  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10793       e = RD->method_end(); i != e; ++i) {
10794    CXXMethodDecl *MD = *i;
10795
10796    // C++ [basic.def.odr]p2:
10797    //   [...] A virtual member function is used if it is not pure. [...]
10798    if (MD->isVirtual() && !MD->isPure())
10799      MarkFunctionReferenced(Loc, MD);
10800  }
10801
10802  // Only classes that have virtual bases need a VTT.
10803  if (RD->getNumVBases() == 0)
10804    return;
10805
10806  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10807           e = RD->bases_end(); i != e; ++i) {
10808    const CXXRecordDecl *Base =
10809        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10810    if (Base->getNumVBases() == 0)
10811      continue;
10812    MarkVirtualMembersReferenced(Loc, Base);
10813  }
10814}
10815
10816/// SetIvarInitializers - This routine builds initialization ASTs for the
10817/// Objective-C implementation whose ivars need be initialized.
10818void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10819  if (!getLangOpts().CPlusPlus)
10820    return;
10821  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10822    SmallVector<ObjCIvarDecl*, 8> ivars;
10823    CollectIvarsToConstructOrDestruct(OID, ivars);
10824    if (ivars.empty())
10825      return;
10826    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10827    for (unsigned i = 0; i < ivars.size(); i++) {
10828      FieldDecl *Field = ivars[i];
10829      if (Field->isInvalidDecl())
10830        continue;
10831
10832      CXXCtorInitializer *Member;
10833      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10834      InitializationKind InitKind =
10835        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10836
10837      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10838      ExprResult MemberInit =
10839        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10840      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10841      // Note, MemberInit could actually come back empty if no initialization
10842      // is required (e.g., because it would call a trivial default constructor)
10843      if (!MemberInit.get() || MemberInit.isInvalid())
10844        continue;
10845
10846      Member =
10847        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10848                                         SourceLocation(),
10849                                         MemberInit.takeAs<Expr>(),
10850                                         SourceLocation());
10851      AllToInit.push_back(Member);
10852
10853      // Be sure that the destructor is accessible and is marked as referenced.
10854      if (const RecordType *RecordTy
10855                  = Context.getBaseElementType(Field->getType())
10856                                                        ->getAs<RecordType>()) {
10857                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10858        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10859          MarkFunctionReferenced(Field->getLocation(), Destructor);
10860          CheckDestructorAccess(Field->getLocation(), Destructor,
10861                            PDiag(diag::err_access_dtor_ivar)
10862                              << Context.getBaseElementType(Field->getType()));
10863        }
10864      }
10865    }
10866    ObjCImplementation->setIvarInitializers(Context,
10867                                            AllToInit.data(), AllToInit.size());
10868  }
10869}
10870
10871static
10872void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10873                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10874                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10875                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10876                           Sema &S) {
10877  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10878                                                   CE = Current.end();
10879  if (Ctor->isInvalidDecl())
10880    return;
10881
10882  const FunctionDecl *FNTarget = 0;
10883  CXXConstructorDecl *Target;
10884
10885  // We ignore the result here since if we don't have a body, Target will be
10886  // null below.
10887  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10888  Target
10889= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10890
10891  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10892                     // Avoid dereferencing a null pointer here.
10893                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10894
10895  if (!Current.insert(Canonical))
10896    return;
10897
10898  // We know that beyond here, we aren't chaining into a cycle.
10899  if (!Target || !Target->isDelegatingConstructor() ||
10900      Target->isInvalidDecl() || Valid.count(TCanonical)) {
10901    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10902      Valid.insert(*CI);
10903    Current.clear();
10904  // We've hit a cycle.
10905  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10906             Current.count(TCanonical)) {
10907    // If we haven't diagnosed this cycle yet, do so now.
10908    if (!Invalid.count(TCanonical)) {
10909      S.Diag((*Ctor->init_begin())->getSourceLocation(),
10910             diag::warn_delegating_ctor_cycle)
10911        << Ctor;
10912
10913      // Don't add a note for a function delegating directo to itself.
10914      if (TCanonical != Canonical)
10915        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10916
10917      CXXConstructorDecl *C = Target;
10918      while (C->getCanonicalDecl() != Canonical) {
10919        (void)C->getTargetConstructor()->hasBody(FNTarget);
10920        assert(FNTarget && "Ctor cycle through bodiless function");
10921
10922        C
10923       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10924        S.Diag(C->getLocation(), diag::note_which_delegates_to);
10925      }
10926    }
10927
10928    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10929      Invalid.insert(*CI);
10930    Current.clear();
10931  } else {
10932    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10933  }
10934}
10935
10936
10937void Sema::CheckDelegatingCtorCycles() {
10938  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10939
10940  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10941                                                   CE = Current.end();
10942
10943  for (DelegatingCtorDeclsType::iterator
10944         I = DelegatingCtorDecls.begin(ExternalSource),
10945         E = DelegatingCtorDecls.end();
10946       I != E; ++I) {
10947   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
10948  }
10949
10950  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10951    (*CI)->setInvalidDecl();
10952}
10953
10954namespace {
10955  /// \brief AST visitor that finds references to the 'this' expression.
10956  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
10957    Sema &S;
10958
10959  public:
10960    explicit FindCXXThisExpr(Sema &S) : S(S) { }
10961
10962    bool VisitCXXThisExpr(CXXThisExpr *E) {
10963      S.Diag(E->getLocation(), diag::err_this_static_member_func)
10964        << E->isImplicit();
10965      return false;
10966    }
10967  };
10968}
10969
10970bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
10971  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
10972  if (!TSInfo)
10973    return false;
10974
10975  TypeLoc TL = TSInfo->getTypeLoc();
10976  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
10977  if (!ProtoTL)
10978    return false;
10979
10980  // C++11 [expr.prim.general]p3:
10981  //   [The expression this] shall not appear before the optional
10982  //   cv-qualifier-seq and it shall not appear within the declaration of a
10983  //   static member function (although its type and value category are defined
10984  //   within a static member function as they are within a non-static member
10985  //   function). [ Note: this is because declaration matching does not occur
10986  //  until the complete declarator is known. - end note ]
10987  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
10988  FindCXXThisExpr Finder(*this);
10989
10990  // If the return type came after the cv-qualifier-seq, check it now.
10991  if (Proto->hasTrailingReturn() &&
10992      !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
10993    return true;
10994
10995  // Check the exception specification.
10996  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
10997    return true;
10998
10999  return checkThisInStaticMemberFunctionAttributes(Method);
11000}
11001
11002bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
11003  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11004  if (!TSInfo)
11005    return false;
11006
11007  TypeLoc TL = TSInfo->getTypeLoc();
11008  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11009  if (!ProtoTL)
11010    return false;
11011
11012  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11013  FindCXXThisExpr Finder(*this);
11014
11015  switch (Proto->getExceptionSpecType()) {
11016  case EST_Uninstantiated:
11017  case EST_BasicNoexcept:
11018  case EST_Delayed:
11019  case EST_DynamicNone:
11020  case EST_MSAny:
11021  case EST_None:
11022    break;
11023
11024  case EST_ComputedNoexcept:
11025    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11026      return true;
11027
11028  case EST_Dynamic:
11029    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11030         EEnd = Proto->exception_end();
11031         E != EEnd; ++E) {
11032      if (!Finder.TraverseType(*E))
11033        return true;
11034    }
11035    break;
11036  }
11037
11038  return false;
11039}
11040
11041bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11042  FindCXXThisExpr Finder(*this);
11043
11044  // Check attributes.
11045  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11046       A != AEnd; ++A) {
11047    // FIXME: This should be emitted by tblgen.
11048    Expr *Arg = 0;
11049    ArrayRef<Expr *> Args;
11050    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11051      Arg = G->getArg();
11052    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11053      Arg = G->getArg();
11054    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11055      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11056    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11057      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11058    else if (ExclusiveLockFunctionAttr *ELF
11059               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11060      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11061    else if (SharedLockFunctionAttr *SLF
11062               = dyn_cast<SharedLockFunctionAttr>(*A))
11063      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11064    else if (ExclusiveTrylockFunctionAttr *ETLF
11065               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11066      Arg = ETLF->getSuccessValue();
11067      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11068    } else if (SharedTrylockFunctionAttr *STLF
11069                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11070      Arg = STLF->getSuccessValue();
11071      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11072    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11073      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11074    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11075      Arg = LR->getArg();
11076    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11077      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11078    else if (ExclusiveLocksRequiredAttr *ELR
11079               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11080      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11081    else if (SharedLocksRequiredAttr *SLR
11082               = dyn_cast<SharedLocksRequiredAttr>(*A))
11083      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11084
11085    if (Arg && !Finder.TraverseStmt(Arg))
11086      return true;
11087
11088    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11089      if (!Finder.TraverseStmt(Args[I]))
11090        return true;
11091    }
11092  }
11093
11094  return false;
11095}
11096
11097void
11098Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
11099                                  ArrayRef<ParsedType> DynamicExceptions,
11100                                  ArrayRef<SourceRange> DynamicExceptionRanges,
11101                                  Expr *NoexceptExpr,
11102                                  llvm::SmallVectorImpl<QualType> &Exceptions,
11103                                  FunctionProtoType::ExtProtoInfo &EPI) {
11104  Exceptions.clear();
11105  EPI.ExceptionSpecType = EST;
11106  if (EST == EST_Dynamic) {
11107    Exceptions.reserve(DynamicExceptions.size());
11108    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
11109      // FIXME: Preserve type source info.
11110      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
11111
11112      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
11113      collectUnexpandedParameterPacks(ET, Unexpanded);
11114      if (!Unexpanded.empty()) {
11115        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
11116                                         UPPC_ExceptionType,
11117                                         Unexpanded);
11118        continue;
11119      }
11120
11121      // Check that the type is valid for an exception spec, and
11122      // drop it if not.
11123      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
11124        Exceptions.push_back(ET);
11125    }
11126    EPI.NumExceptions = Exceptions.size();
11127    EPI.Exceptions = Exceptions.data();
11128    return;
11129  }
11130
11131  if (EST == EST_ComputedNoexcept) {
11132    // If an error occurred, there's no expression here.
11133    if (NoexceptExpr) {
11134      assert((NoexceptExpr->isTypeDependent() ||
11135              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
11136              Context.BoolTy) &&
11137             "Parser should have made sure that the expression is boolean");
11138      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
11139        EPI.ExceptionSpecType = EST_BasicNoexcept;
11140        return;
11141      }
11142
11143      if (!NoexceptExpr->isValueDependent())
11144        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
11145                         diag::err_noexcept_needs_constant_expression,
11146                         /*AllowFold*/ false).take();
11147      EPI.NoexceptExpr = NoexceptExpr;
11148    }
11149    return;
11150  }
11151}
11152
11153/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11154Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11155  // Implicitly declared functions (e.g. copy constructors) are
11156  // __host__ __device__
11157  if (D->isImplicit())
11158    return CFT_HostDevice;
11159
11160  if (D->hasAttr<CUDAGlobalAttr>())
11161    return CFT_Global;
11162
11163  if (D->hasAttr<CUDADeviceAttr>()) {
11164    if (D->hasAttr<CUDAHostAttr>())
11165      return CFT_HostDevice;
11166    else
11167      return CFT_Device;
11168  }
11169
11170  return CFT_Host;
11171}
11172
11173bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11174                           CUDAFunctionTarget CalleeTarget) {
11175  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11176  // Callable from the device only."
11177  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11178    return true;
11179
11180  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11181  // Callable from the host only."
11182  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11183  // Callable from the host only."
11184  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11185      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11186    return true;
11187
11188  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11189    return true;
11190
11191  return false;
11192}
11193