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