SemaDeclCXX.cpp revision 858d2ba136c8dcdc051fe20b3190c40bc25de189
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/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/DeclVisitor.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/AST/TypeOrdering.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/LiteralSupport.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/CXXFieldCollector.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/ADT/SmallString.h"
42#include <map>
43#include <set>
44
45using namespace clang;
46
47//===----------------------------------------------------------------------===//
48// CheckDefaultArgumentVisitor
49//===----------------------------------------------------------------------===//
50
51namespace {
52  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
53  /// the default argument of a parameter to determine whether it
54  /// contains any ill-formed subexpressions. For example, this will
55  /// diagnose the use of local variables or parameters within the
56  /// default argument expression.
57  class CheckDefaultArgumentVisitor
58    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
59    Expr *DefaultArg;
60    Sema *S;
61
62  public:
63    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
64      : DefaultArg(defarg), S(s) {}
65
66    bool VisitExpr(Expr *Node);
67    bool VisitDeclRefExpr(DeclRefExpr *DRE);
68    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
69    bool VisitLambdaExpr(LambdaExpr *Lambda);
70    bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
71  };
72
73  /// VisitExpr - Visit all of the children of this expression.
74  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
75    bool IsInvalid = false;
76    for (Stmt::child_range I = Node->children(); I; ++I)
77      IsInvalid |= Visit(*I);
78    return IsInvalid;
79  }
80
81  /// VisitDeclRefExpr - Visit a reference to a declaration, to
82  /// determine whether this declaration can be used in the default
83  /// argument expression.
84  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
85    NamedDecl *Decl = DRE->getDecl();
86    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
87      // C++ [dcl.fct.default]p9
88      //   Default arguments are evaluated each time the function is
89      //   called. The order of evaluation of function arguments is
90      //   unspecified. Consequently, parameters of a function shall not
91      //   be used in default argument expressions, even if they are not
92      //   evaluated. Parameters of a function declared before a default
93      //   argument expression are in scope and can hide namespace and
94      //   class member names.
95      return S->Diag(DRE->getLocStart(),
96                     diag::err_param_default_argument_references_param)
97         << Param->getDeclName() << DefaultArg->getSourceRange();
98    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
99      // C++ [dcl.fct.default]p7
100      //   Local variables shall not be used in default argument
101      //   expressions.
102      if (VDecl->isLocalVarDecl())
103        return S->Diag(DRE->getLocStart(),
104                       diag::err_param_default_argument_references_local)
105          << VDecl->getDeclName() << DefaultArg->getSourceRange();
106    }
107
108    return false;
109  }
110
111  /// VisitCXXThisExpr - Visit a C++ "this" expression.
112  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
113    // C++ [dcl.fct.default]p8:
114    //   The keyword this shall not be used in a default argument of a
115    //   member function.
116    return S->Diag(ThisE->getLocStart(),
117                   diag::err_param_default_argument_references_this)
118               << ThisE->getSourceRange();
119  }
120
121  bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
122    bool Invalid = false;
123    for (PseudoObjectExpr::semantics_iterator
124           i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
125      Expr *E = *i;
126
127      // Look through bindings.
128      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
129        E = OVE->getSourceExpr();
130        assert(E && "pseudo-object binding without source expression?");
131      }
132
133      Invalid |= Visit(E);
134    }
135    return Invalid;
136  }
137
138  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
139    // C++11 [expr.lambda.prim]p13:
140    //   A lambda-expression appearing in a default argument shall not
141    //   implicitly or explicitly capture any entity.
142    if (Lambda->capture_begin() == Lambda->capture_end())
143      return false;
144
145    return S->Diag(Lambda->getLocStart(),
146                   diag::err_lambda_capture_default_arg);
147  }
148}
149
150void
151Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152                                                 const CXXMethodDecl *Method) {
153  // If we have an MSAny spec already, don't bother.
154  if (!Method || ComputedEST == EST_MSAny)
155    return;
156
157  const FunctionProtoType *Proto
158    = Method->getType()->getAs<FunctionProtoType>();
159  Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
160  if (!Proto)
161    return;
162
163  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
164
165  // If this function can throw any exceptions, make a note of that.
166  if (EST == EST_MSAny || EST == EST_None) {
167    ClearExceptions();
168    ComputedEST = EST;
169    return;
170  }
171
172  // FIXME: If the call to this decl is using any of its default arguments, we
173  // need to search them for potentially-throwing calls.
174
175  // If this function has a basic noexcept, it doesn't affect the outcome.
176  if (EST == EST_BasicNoexcept)
177    return;
178
179  // If we have a throw-all spec at this point, ignore the function.
180  if (ComputedEST == EST_None)
181    return;
182
183  // If we're still at noexcept(true) and there's a nothrow() callee,
184  // change to that specification.
185  if (EST == EST_DynamicNone) {
186    if (ComputedEST == EST_BasicNoexcept)
187      ComputedEST = EST_DynamicNone;
188    return;
189  }
190
191  // Check out noexcept specs.
192  if (EST == EST_ComputedNoexcept) {
193    FunctionProtoType::NoexceptResult NR =
194        Proto->getNoexceptSpec(Self->Context);
195    assert(NR != FunctionProtoType::NR_NoNoexcept &&
196           "Must have noexcept result for EST_ComputedNoexcept.");
197    assert(NR != FunctionProtoType::NR_Dependent &&
198           "Should not generate implicit declarations for dependent cases, "
199           "and don't know how to handle them anyway.");
200
201    // noexcept(false) -> no spec on the new function
202    if (NR == FunctionProtoType::NR_Throw) {
203      ClearExceptions();
204      ComputedEST = EST_None;
205    }
206    // noexcept(true) won't change anything either.
207    return;
208  }
209
210  assert(EST == EST_Dynamic && "EST case not considered earlier.");
211  assert(ComputedEST != EST_None &&
212         "Shouldn't collect exceptions when throw-all is guaranteed.");
213  ComputedEST = EST_Dynamic;
214  // Record the exceptions in this function's exception specification.
215  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
216                                          EEnd = Proto->exception_end();
217       E != EEnd; ++E)
218    if (ExceptionsSeen.insert(Self->Context.getCanonicalType(*E)))
219      Exceptions.push_back(*E);
220}
221
222void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
223  if (!E || ComputedEST == EST_MSAny)
224    return;
225
226  // FIXME:
227  //
228  // C++0x [except.spec]p14:
229  //   [An] implicit exception-specification specifies the type-id T if and
230  // only if T is allowed by the exception-specification of a function directly
231  // invoked by f's implicit definition; f shall allow all exceptions if any
232  // function it directly invokes allows all exceptions, and f shall allow no
233  // exceptions if every function it directly invokes allows no exceptions.
234  //
235  // Note in particular that if an implicit exception-specification is generated
236  // for a function containing a throw-expression, that specification can still
237  // be noexcept(true).
238  //
239  // Note also that 'directly invoked' is not defined in the standard, and there
240  // is no indication that we should only consider potentially-evaluated calls.
241  //
242  // Ultimately we should implement the intent of the standard: the exception
243  // specification should be the set of exceptions which can be thrown by the
244  // implicit definition. For now, we assume that any non-nothrow expression can
245  // throw any exception.
246
247  if (Self->canThrow(E))
248    ComputedEST = EST_None;
249}
250
251bool
252Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
253                              SourceLocation EqualLoc) {
254  if (RequireCompleteType(Param->getLocation(), Param->getType(),
255                          diag::err_typecheck_decl_incomplete_type)) {
256    Param->setInvalidDecl();
257    return true;
258  }
259
260  // C++ [dcl.fct.default]p5
261  //   A default argument expression is implicitly converted (clause
262  //   4) to the parameter type. The default argument expression has
263  //   the same semantic constraints as the initializer expression in
264  //   a declaration of a variable of the parameter type, using the
265  //   copy-initialization semantics (8.5).
266  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
267                                                                    Param);
268  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
269                                                           EqualLoc);
270  InitializationSequence InitSeq(*this, Entity, Kind, Arg);
271  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
272  if (Result.isInvalid())
273    return true;
274  Arg = Result.takeAs<Expr>();
275
276  CheckCompletedExpr(Arg, EqualLoc);
277  Arg = MaybeCreateExprWithCleanups(Arg);
278
279  // Okay: add the default argument to the parameter
280  Param->setDefaultArg(Arg);
281
282  // We have already instantiated this parameter; provide each of the
283  // instantiations with the uninstantiated default argument.
284  UnparsedDefaultArgInstantiationsMap::iterator InstPos
285    = UnparsedDefaultArgInstantiations.find(Param);
286  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
289
290    // We're done tracking this parameter's instantiations.
291    UnparsedDefaultArgInstantiations.erase(InstPos);
292  }
293
294  return false;
295}
296
297/// ActOnParamDefaultArgument - Check whether the default argument
298/// provided for a function parameter is well-formed. If so, attach it
299/// to the parameter declaration.
300void
301Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
302                                Expr *DefaultArg) {
303  if (!param || !DefaultArg)
304    return;
305
306  ParmVarDecl *Param = cast<ParmVarDecl>(param);
307  UnparsedDefaultArgLocs.erase(Param);
308
309  // Default arguments are only permitted in C++
310  if (!getLangOpts().CPlusPlus) {
311    Diag(EqualLoc, diag::err_param_default_argument)
312      << DefaultArg->getSourceRange();
313    Param->setInvalidDecl();
314    return;
315  }
316
317  // Check for unexpanded parameter packs.
318  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319    Param->setInvalidDecl();
320    return;
321  }
322
323  // Check that the default argument is well-formed
324  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
325  if (DefaultArgChecker.Visit(DefaultArg)) {
326    Param->setInvalidDecl();
327    return;
328  }
329
330  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
331}
332
333/// ActOnParamUnparsedDefaultArgument - We've seen a default
334/// argument for a function parameter, but we can't parse it yet
335/// because we're inside a class definition. Note that this default
336/// argument will be parsed later.
337void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
338                                             SourceLocation EqualLoc,
339                                             SourceLocation ArgLoc) {
340  if (!param)
341    return;
342
343  ParmVarDecl *Param = cast<ParmVarDecl>(param);
344  Param->setUnparsedDefaultArg();
345  UnparsedDefaultArgLocs[Param] = ArgLoc;
346}
347
348/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
349/// the default argument for the parameter param failed.
350void Sema::ActOnParamDefaultArgumentError(Decl *param) {
351  if (!param)
352    return;
353
354  ParmVarDecl *Param = cast<ParmVarDecl>(param);
355  Param->setInvalidDecl();
356  UnparsedDefaultArgLocs.erase(Param);
357}
358
359/// CheckExtraCXXDefaultArguments - Check for any extra default
360/// arguments in the declarator, which is not a function declaration
361/// or definition and therefore is not permitted to have default
362/// arguments. This routine should be invoked for every declarator
363/// that is not a function declaration or definition.
364void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
365  // C++ [dcl.fct.default]p3
366  //   A default argument expression shall be specified only in the
367  //   parameter-declaration-clause of a function declaration or in a
368  //   template-parameter (14.1). It shall not be specified for a
369  //   parameter pack. If it is specified in a
370  //   parameter-declaration-clause, it shall not occur within a
371  //   declarator or abstract-declarator of a parameter-declaration.
372  bool MightBeFunction = D.isFunctionDeclarationContext();
373  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
374    DeclaratorChunk &chunk = D.getTypeObject(i);
375    if (chunk.Kind == DeclaratorChunk::Function) {
376      if (MightBeFunction) {
377        // This is a function declaration. It can have default arguments, but
378        // keep looking in case its return type is a function type with default
379        // arguments.
380        MightBeFunction = false;
381        continue;
382      }
383      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
384        ParmVarDecl *Param =
385          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
386        if (Param->hasUnparsedDefaultArg()) {
387          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
388          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
389            << SourceRange((*Toks)[1].getLocation(),
390                           Toks->back().getLocation());
391          delete Toks;
392          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
393        } else if (Param->getDefaultArg()) {
394          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
395            << Param->getDefaultArg()->getSourceRange();
396          Param->setDefaultArg(0);
397        }
398      }
399    } else if (chunk.Kind != DeclaratorChunk::Paren) {
400      MightBeFunction = false;
401    }
402  }
403}
404
405static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
406  for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
407    const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
408    if (!PVD->hasDefaultArg())
409      return false;
410    if (!PVD->hasInheritedDefaultArg())
411      return true;
412  }
413  return false;
414}
415
416/// MergeCXXFunctionDecl - Merge two declarations of the same C++
417/// function, once we already know that they have the same
418/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
419/// error, false otherwise.
420bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
421                                Scope *S) {
422  bool Invalid = false;
423
424  // C++ [dcl.fct.default]p4:
425  //   For non-template functions, default arguments can be added in
426  //   later declarations of a function in the same
427  //   scope. Declarations in different scopes have completely
428  //   distinct sets of default arguments. That is, declarations in
429  //   inner scopes do not acquire default arguments from
430  //   declarations in outer scopes, and vice versa. In a given
431  //   function declaration, all parameters subsequent to a
432  //   parameter with a default argument shall have default
433  //   arguments supplied in this or previous declarations. A
434  //   default argument shall not be redefined by a later
435  //   declaration (not even to the same value).
436  //
437  // C++ [dcl.fct.default]p6:
438  //   Except for member functions of class templates, the default arguments
439  //   in a member function definition that appears outside of the class
440  //   definition are added to the set of default arguments provided by the
441  //   member function declaration in the class definition.
442  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
443    ParmVarDecl *OldParam = Old->getParamDecl(p);
444    ParmVarDecl *NewParam = New->getParamDecl(p);
445
446    bool OldParamHasDfl = OldParam->hasDefaultArg();
447    bool NewParamHasDfl = NewParam->hasDefaultArg();
448
449    NamedDecl *ND = Old;
450
451    // The declaration context corresponding to the scope is the semantic
452    // parent, unless this is a local function declaration, in which case
453    // it is that surrounding function.
454    DeclContext *ScopeDC = New->getLexicalDeclContext();
455    if (!ScopeDC->isFunctionOrMethod())
456      ScopeDC = New->getDeclContext();
457    if (S && !isDeclInScope(ND, ScopeDC, S) &&
458        !New->getDeclContext()->isRecord())
459      // Ignore default parameters of old decl if they are not in
460      // the same scope and this is not an out-of-line definition of
461      // a member function.
462      OldParamHasDfl = false;
463
464    if (OldParamHasDfl && NewParamHasDfl) {
465
466      unsigned DiagDefaultParamID =
467        diag::err_param_default_argument_redefinition;
468
469      // MSVC accepts that default parameters be redefined for member functions
470      // of template class. The new default parameter's value is ignored.
471      Invalid = true;
472      if (getLangOpts().MicrosoftExt) {
473        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
474        if (MD && MD->getParent()->getDescribedClassTemplate()) {
475          // Merge the old default argument into the new parameter.
476          NewParam->setHasInheritedDefaultArg();
477          if (OldParam->hasUninstantiatedDefaultArg())
478            NewParam->setUninstantiatedDefaultArg(
479                                      OldParam->getUninstantiatedDefaultArg());
480          else
481            NewParam->setDefaultArg(OldParam->getInit());
482          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
483          Invalid = false;
484        }
485      }
486
487      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
488      // hint here. Alternatively, we could walk the type-source information
489      // for NewParam to find the last source location in the type... but it
490      // isn't worth the effort right now. This is the kind of test case that
491      // is hard to get right:
492      //   int f(int);
493      //   void g(int (*fp)(int) = f);
494      //   void g(int (*fp)(int) = &f);
495      Diag(NewParam->getLocation(), DiagDefaultParamID)
496        << NewParam->getDefaultArgRange();
497
498      // Look for the function declaration where the default argument was
499      // actually written, which may be a declaration prior to Old.
500      for (FunctionDecl *Older = Old->getPreviousDecl();
501           Older; Older = Older->getPreviousDecl()) {
502        if (!Older->getParamDecl(p)->hasDefaultArg())
503          break;
504
505        OldParam = Older->getParamDecl(p);
506      }
507
508      Diag(OldParam->getLocation(), diag::note_previous_definition)
509        << OldParam->getDefaultArgRange();
510    } else if (OldParamHasDfl) {
511      // Merge the old default argument into the new parameter.
512      // It's important to use getInit() here;  getDefaultArg()
513      // strips off any top-level ExprWithCleanups.
514      NewParam->setHasInheritedDefaultArg();
515      if (OldParam->hasUninstantiatedDefaultArg())
516        NewParam->setUninstantiatedDefaultArg(
517                                      OldParam->getUninstantiatedDefaultArg());
518      else
519        NewParam->setDefaultArg(OldParam->getInit());
520    } else if (NewParamHasDfl) {
521      if (New->getDescribedFunctionTemplate()) {
522        // Paragraph 4, quoted above, only applies to non-template functions.
523        Diag(NewParam->getLocation(),
524             diag::err_param_default_argument_template_redecl)
525          << NewParam->getDefaultArgRange();
526        Diag(Old->getLocation(), diag::note_template_prev_declaration)
527          << false;
528      } else if (New->getTemplateSpecializationKind()
529                   != TSK_ImplicitInstantiation &&
530                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
531        // C++ [temp.expr.spec]p21:
532        //   Default function arguments shall not be specified in a declaration
533        //   or a definition for one of the following explicit specializations:
534        //     - the explicit specialization of a function template;
535        //     - the explicit specialization of a member function template;
536        //     - the explicit specialization of a member function of a class
537        //       template where the class template specialization to which the
538        //       member function specialization belongs is implicitly
539        //       instantiated.
540        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
541          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
542          << New->getDeclName()
543          << NewParam->getDefaultArgRange();
544      } else if (New->getDeclContext()->isDependentContext()) {
545        // C++ [dcl.fct.default]p6 (DR217):
546        //   Default arguments for a member function of a class template shall
547        //   be specified on the initial declaration of the member function
548        //   within the class template.
549        //
550        // Reading the tea leaves a bit in DR217 and its reference to DR205
551        // leads me to the conclusion that one cannot add default function
552        // arguments for an out-of-line definition of a member function of a
553        // dependent type.
554        int WhichKind = 2;
555        if (CXXRecordDecl *Record
556              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
557          if (Record->getDescribedClassTemplate())
558            WhichKind = 0;
559          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
560            WhichKind = 1;
561          else
562            WhichKind = 2;
563        }
564
565        Diag(NewParam->getLocation(),
566             diag::err_param_default_argument_member_template_redecl)
567          << WhichKind
568          << NewParam->getDefaultArgRange();
569      }
570    }
571  }
572
573  // DR1344: If a default argument is added outside a class definition and that
574  // default argument makes the function a special member function, the program
575  // is ill-formed. This can only happen for constructors.
576  if (isa<CXXConstructorDecl>(New) &&
577      New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
578    CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
579                     OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
580    if (NewSM != OldSM) {
581      ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
582      assert(NewParam->hasDefaultArg());
583      Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
584        << NewParam->getDefaultArgRange() << NewSM;
585      Diag(Old->getLocation(), diag::note_previous_declaration);
586    }
587  }
588
589  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
590  // template has a constexpr specifier then all its declarations shall
591  // contain the constexpr specifier.
592  if (New->isConstexpr() != Old->isConstexpr()) {
593    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
594      << New << New->isConstexpr();
595    Diag(Old->getLocation(), diag::note_previous_declaration);
596    Invalid = true;
597  }
598
599  // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
600  // argument expression, that declaration shall be a definition and shall be
601  // the only declaration of the function or function template in the
602  // translation unit.
603  if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
604      functionDeclHasDefaultArgument(Old)) {
605    Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
606    Diag(Old->getLocation(), diag::note_previous_declaration);
607    Invalid = true;
608  }
609
610  if (CheckEquivalentExceptionSpec(Old, New))
611    Invalid = true;
612
613  return Invalid;
614}
615
616/// \brief Merge the exception specifications of two variable declarations.
617///
618/// This is called when there's a redeclaration of a VarDecl. The function
619/// checks if the redeclaration might have an exception specification and
620/// validates compatibility and merges the specs if necessary.
621void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
622  // Shortcut if exceptions are disabled.
623  if (!getLangOpts().CXXExceptions)
624    return;
625
626  assert(Context.hasSameType(New->getType(), Old->getType()) &&
627         "Should only be called if types are otherwise the same.");
628
629  QualType NewType = New->getType();
630  QualType OldType = Old->getType();
631
632  // We're only interested in pointers and references to functions, as well
633  // as pointers to member functions.
634  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
635    NewType = R->getPointeeType();
636    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
637  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
638    NewType = P->getPointeeType();
639    OldType = OldType->getAs<PointerType>()->getPointeeType();
640  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
641    NewType = M->getPointeeType();
642    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
643  }
644
645  if (!NewType->isFunctionProtoType())
646    return;
647
648  // There's lots of special cases for functions. For function pointers, system
649  // libraries are hopefully not as broken so that we don't need these
650  // workarounds.
651  if (CheckEquivalentExceptionSpec(
652        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
653        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
654    New->setInvalidDecl();
655  }
656}
657
658/// CheckCXXDefaultArguments - Verify that the default arguments for a
659/// function declaration are well-formed according to C++
660/// [dcl.fct.default].
661void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
662  unsigned NumParams = FD->getNumParams();
663  unsigned p;
664
665  // Find first parameter with a default argument
666  for (p = 0; p < NumParams; ++p) {
667    ParmVarDecl *Param = FD->getParamDecl(p);
668    if (Param->hasDefaultArg())
669      break;
670  }
671
672  // C++ [dcl.fct.default]p4:
673  //   In a given function declaration, all parameters
674  //   subsequent to a parameter with a default argument shall
675  //   have default arguments supplied in this or previous
676  //   declarations. A default argument shall not be redefined
677  //   by a later declaration (not even to the same value).
678  unsigned LastMissingDefaultArg = 0;
679  for (; p < NumParams; ++p) {
680    ParmVarDecl *Param = FD->getParamDecl(p);
681    if (!Param->hasDefaultArg()) {
682      if (Param->isInvalidDecl())
683        /* We already complained about this parameter. */;
684      else if (Param->getIdentifier())
685        Diag(Param->getLocation(),
686             diag::err_param_default_argument_missing_name)
687          << Param->getIdentifier();
688      else
689        Diag(Param->getLocation(),
690             diag::err_param_default_argument_missing);
691
692      LastMissingDefaultArg = p;
693    }
694  }
695
696  if (LastMissingDefaultArg > 0) {
697    // Some default arguments were missing. Clear out all of the
698    // default arguments up to (and including) the last missing
699    // default argument, so that we leave the function parameters
700    // in a semantically valid state.
701    for (p = 0; p <= LastMissingDefaultArg; ++p) {
702      ParmVarDecl *Param = FD->getParamDecl(p);
703      if (Param->hasDefaultArg()) {
704        Param->setDefaultArg(0);
705      }
706    }
707  }
708}
709
710// CheckConstexprParameterTypes - Check whether a function's parameter types
711// are all literal types. If so, return true. If not, produce a suitable
712// diagnostic and return false.
713static bool CheckConstexprParameterTypes(Sema &SemaRef,
714                                         const FunctionDecl *FD) {
715  unsigned ArgIndex = 0;
716  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
717  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
718       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
719    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
720    SourceLocation ParamLoc = PD->getLocation();
721    if (!(*i)->isDependentType() &&
722        SemaRef.RequireLiteralType(ParamLoc, *i,
723                                   diag::err_constexpr_non_literal_param,
724                                   ArgIndex+1, PD->getSourceRange(),
725                                   isa<CXXConstructorDecl>(FD)))
726      return false;
727  }
728  return true;
729}
730
731/// \brief Get diagnostic %select index for tag kind for
732/// record diagnostic message.
733/// WARNING: Indexes apply to particular diagnostics only!
734///
735/// \returns diagnostic %select index.
736static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
737  switch (Tag) {
738  case TTK_Struct: return 0;
739  case TTK_Interface: return 1;
740  case TTK_Class:  return 2;
741  default: llvm_unreachable("Invalid tag kind for record diagnostic!");
742  }
743}
744
745// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
746// the requirements of a constexpr function definition or a constexpr
747// constructor definition. If so, return true. If not, produce appropriate
748// diagnostics and return false.
749//
750// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
751bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
752  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
753  if (MD && MD->isInstance()) {
754    // C++11 [dcl.constexpr]p4:
755    //  The definition of a constexpr constructor shall satisfy the following
756    //  constraints:
757    //  - the class shall not have any virtual base classes;
758    const CXXRecordDecl *RD = MD->getParent();
759    if (RD->getNumVBases()) {
760      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
761        << isa<CXXConstructorDecl>(NewFD)
762        << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
763      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
764             E = RD->vbases_end(); I != E; ++I)
765        Diag(I->getLocStart(),
766             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
767      return false;
768    }
769  }
770
771  if (!isa<CXXConstructorDecl>(NewFD)) {
772    // C++11 [dcl.constexpr]p3:
773    //  The definition of a constexpr function shall satisfy the following
774    //  constraints:
775    // - it shall not be virtual;
776    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
777    if (Method && Method->isVirtual()) {
778      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
779
780      // If it's not obvious why this function is virtual, find an overridden
781      // function which uses the 'virtual' keyword.
782      const CXXMethodDecl *WrittenVirtual = Method;
783      while (!WrittenVirtual->isVirtualAsWritten())
784        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
785      if (WrittenVirtual != Method)
786        Diag(WrittenVirtual->getLocation(),
787             diag::note_overridden_virtual_function);
788      return false;
789    }
790
791    // - its return type shall be a literal type;
792    QualType RT = NewFD->getResultType();
793    if (!RT->isDependentType() &&
794        RequireLiteralType(NewFD->getLocation(), RT,
795                           diag::err_constexpr_non_literal_return))
796      return false;
797  }
798
799  // - each of its parameter types shall be a literal type;
800  if (!CheckConstexprParameterTypes(*this, NewFD))
801    return false;
802
803  return true;
804}
805
806/// Check the given declaration statement is legal within a constexpr function
807/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
808///
809/// \return true if the body is OK (maybe only as an extension), false if we
810///         have diagnosed a problem.
811static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
812                                   DeclStmt *DS, SourceLocation &Cxx1yLoc) {
813  // C++11 [dcl.constexpr]p3 and p4:
814  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
815  //  contain only
816  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
817         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
818    switch ((*DclIt)->getKind()) {
819    case Decl::StaticAssert:
820    case Decl::Using:
821    case Decl::UsingShadow:
822    case Decl::UsingDirective:
823    case Decl::UnresolvedUsingTypename:
824    case Decl::UnresolvedUsingValue:
825      //   - static_assert-declarations
826      //   - using-declarations,
827      //   - using-directives,
828      continue;
829
830    case Decl::Typedef:
831    case Decl::TypeAlias: {
832      //   - typedef declarations and alias-declarations that do not define
833      //     classes or enumerations,
834      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
835      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
836        // Don't allow variably-modified types in constexpr functions.
837        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
838        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
839          << TL.getSourceRange() << TL.getType()
840          << isa<CXXConstructorDecl>(Dcl);
841        return false;
842      }
843      continue;
844    }
845
846    case Decl::Enum:
847    case Decl::CXXRecord:
848      // C++1y allows types to be defined, not just declared.
849      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition())
850        SemaRef.Diag(DS->getLocStart(),
851                     SemaRef.getLangOpts().CPlusPlus1y
852                       ? diag::warn_cxx11_compat_constexpr_type_definition
853                       : diag::ext_constexpr_type_definition)
854          << isa<CXXConstructorDecl>(Dcl);
855      continue;
856
857    case Decl::EnumConstant:
858    case Decl::IndirectField:
859    case Decl::ParmVar:
860      // These can only appear with other declarations which are banned in
861      // C++11 and permitted in C++1y, so ignore them.
862      continue;
863
864    case Decl::Var: {
865      // C++1y [dcl.constexpr]p3 allows anything except:
866      //   a definition of a variable of non-literal type or of static or
867      //   thread storage duration or for which no initialization is performed.
868      VarDecl *VD = cast<VarDecl>(*DclIt);
869      if (VD->isThisDeclarationADefinition()) {
870        if (VD->isStaticLocal()) {
871          SemaRef.Diag(VD->getLocation(),
872                       diag::err_constexpr_local_var_static)
873            << isa<CXXConstructorDecl>(Dcl)
874            << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
875          return false;
876        }
877        if (!VD->getType()->isDependentType() &&
878            SemaRef.RequireLiteralType(
879              VD->getLocation(), VD->getType(),
880              diag::err_constexpr_local_var_non_literal_type,
881              isa<CXXConstructorDecl>(Dcl)))
882          return false;
883        if (!VD->hasInit()) {
884          SemaRef.Diag(VD->getLocation(),
885                       diag::err_constexpr_local_var_no_init)
886            << isa<CXXConstructorDecl>(Dcl);
887          return false;
888        }
889      }
890      SemaRef.Diag(VD->getLocation(),
891                   SemaRef.getLangOpts().CPlusPlus1y
892                    ? diag::warn_cxx11_compat_constexpr_local_var
893                    : diag::ext_constexpr_local_var)
894        << isa<CXXConstructorDecl>(Dcl);
895      continue;
896    }
897
898    case Decl::NamespaceAlias:
899    case Decl::Function:
900      // These are disallowed in C++11 and permitted in C++1y. Allow them
901      // everywhere as an extension.
902      if (!Cxx1yLoc.isValid())
903        Cxx1yLoc = DS->getLocStart();
904      continue;
905
906    default:
907      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
908        << isa<CXXConstructorDecl>(Dcl);
909      return false;
910    }
911  }
912
913  return true;
914}
915
916/// Check that the given field is initialized within a constexpr constructor.
917///
918/// \param Dcl The constexpr constructor being checked.
919/// \param Field The field being checked. This may be a member of an anonymous
920///        struct or union nested within the class being checked.
921/// \param Inits All declarations, including anonymous struct/union members and
922///        indirect members, for which any initialization was provided.
923/// \param Diagnosed Set to true if an error is produced.
924static void CheckConstexprCtorInitializer(Sema &SemaRef,
925                                          const FunctionDecl *Dcl,
926                                          FieldDecl *Field,
927                                          llvm::SmallSet<Decl*, 16> &Inits,
928                                          bool &Diagnosed) {
929  if (Field->isInvalidDecl())
930    return;
931
932  if (Field->isUnnamedBitfield())
933    return;
934
935  if (Field->isAnonymousStructOrUnion() &&
936      Field->getType()->getAsCXXRecordDecl()->isEmpty())
937    return;
938
939  if (!Inits.count(Field)) {
940    if (!Diagnosed) {
941      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
942      Diagnosed = true;
943    }
944    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
945  } else if (Field->isAnonymousStructOrUnion()) {
946    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
947    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
948         I != E; ++I)
949      // If an anonymous union contains an anonymous struct of which any member
950      // is initialized, all members must be initialized.
951      if (!RD->isUnion() || Inits.count(*I))
952        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
953  }
954}
955
956/// Check the provided statement is allowed in a constexpr function
957/// definition.
958static bool
959CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
960                           SmallVectorImpl<SourceLocation> &ReturnStmts,
961                           SourceLocation &Cxx1yLoc) {
962  // - its function-body shall be [...] a compound-statement that contains only
963  switch (S->getStmtClass()) {
964  case Stmt::NullStmtClass:
965    //   - null statements,
966    return true;
967
968  case Stmt::DeclStmtClass:
969    //   - static_assert-declarations
970    //   - using-declarations,
971    //   - using-directives,
972    //   - typedef declarations and alias-declarations that do not define
973    //     classes or enumerations,
974    if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
975      return false;
976    return true;
977
978  case Stmt::ReturnStmtClass:
979    //   - and exactly one return statement;
980    if (isa<CXXConstructorDecl>(Dcl)) {
981      // C++1y allows return statements in constexpr constructors.
982      if (!Cxx1yLoc.isValid())
983        Cxx1yLoc = S->getLocStart();
984      return true;
985    }
986
987    ReturnStmts.push_back(S->getLocStart());
988    return true;
989
990  case Stmt::CompoundStmtClass: {
991    // C++1y allows compound-statements.
992    if (!Cxx1yLoc.isValid())
993      Cxx1yLoc = S->getLocStart();
994
995    CompoundStmt *CompStmt = cast<CompoundStmt>(S);
996    for (CompoundStmt::body_iterator BodyIt = CompStmt->body_begin(),
997           BodyEnd = CompStmt->body_end(); BodyIt != BodyEnd; ++BodyIt) {
998      if (!CheckConstexprFunctionStmt(SemaRef, Dcl, *BodyIt, ReturnStmts,
999                                      Cxx1yLoc))
1000        return false;
1001    }
1002    return true;
1003  }
1004
1005  case Stmt::AttributedStmtClass:
1006    if (!Cxx1yLoc.isValid())
1007      Cxx1yLoc = S->getLocStart();
1008    return true;
1009
1010  case Stmt::IfStmtClass: {
1011    // C++1y allows if-statements.
1012    if (!Cxx1yLoc.isValid())
1013      Cxx1yLoc = S->getLocStart();
1014
1015    IfStmt *If = cast<IfStmt>(S);
1016    if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1017                                    Cxx1yLoc))
1018      return false;
1019    if (If->getElse() &&
1020        !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1021                                    Cxx1yLoc))
1022      return false;
1023    return true;
1024  }
1025
1026  case Stmt::WhileStmtClass:
1027  case Stmt::DoStmtClass:
1028  case Stmt::ForStmtClass:
1029  case Stmt::CXXForRangeStmtClass:
1030  case Stmt::ContinueStmtClass:
1031    // C++1y allows all of these. We don't allow them as extensions in C++11,
1032    // because they don't make sense without variable mutation.
1033    if (!SemaRef.getLangOpts().CPlusPlus1y)
1034      break;
1035    if (!Cxx1yLoc.isValid())
1036      Cxx1yLoc = S->getLocStart();
1037    for (Stmt::child_range Children = S->children(); Children; ++Children)
1038      if (*Children &&
1039          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1040                                      Cxx1yLoc))
1041        return false;
1042    return true;
1043
1044  case Stmt::SwitchStmtClass:
1045  case Stmt::CaseStmtClass:
1046  case Stmt::DefaultStmtClass:
1047  case Stmt::BreakStmtClass:
1048    // C++1y allows switch-statements, and since they don't need variable
1049    // mutation, we can reasonably allow them in C++11 as an extension.
1050    if (!Cxx1yLoc.isValid())
1051      Cxx1yLoc = S->getLocStart();
1052    for (Stmt::child_range Children = S->children(); Children; ++Children)
1053      if (*Children &&
1054          !CheckConstexprFunctionStmt(SemaRef, Dcl, *Children, ReturnStmts,
1055                                      Cxx1yLoc))
1056        return false;
1057    return true;
1058
1059  default:
1060    if (!isa<Expr>(S))
1061      break;
1062
1063    // C++1y allows expression-statements.
1064    if (!Cxx1yLoc.isValid())
1065      Cxx1yLoc = S->getLocStart();
1066    return true;
1067  }
1068
1069  SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1070    << isa<CXXConstructorDecl>(Dcl);
1071  return false;
1072}
1073
1074/// Check the body for the given constexpr function declaration only contains
1075/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1076///
1077/// \return true if the body is OK, false if we have diagnosed a problem.
1078bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1079  if (isa<CXXTryStmt>(Body)) {
1080    // C++11 [dcl.constexpr]p3:
1081    //  The definition of a constexpr function shall satisfy the following
1082    //  constraints: [...]
1083    // - its function-body shall be = delete, = default, or a
1084    //   compound-statement
1085    //
1086    // C++11 [dcl.constexpr]p4:
1087    //  In the definition of a constexpr constructor, [...]
1088    // - its function-body shall not be a function-try-block;
1089    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1090      << isa<CXXConstructorDecl>(Dcl);
1091    return false;
1092  }
1093
1094  SmallVector<SourceLocation, 4> ReturnStmts;
1095
1096  // - its function-body shall be [...] a compound-statement that contains only
1097  //   [... list of cases ...]
1098  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1099  SourceLocation Cxx1yLoc;
1100  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
1101         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
1102    if (!CheckConstexprFunctionStmt(*this, Dcl, *BodyIt, ReturnStmts, Cxx1yLoc))
1103      return false;
1104  }
1105
1106  if (Cxx1yLoc.isValid())
1107    Diag(Cxx1yLoc,
1108         getLangOpts().CPlusPlus1y
1109           ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1110           : diag::ext_constexpr_body_invalid_stmt)
1111      << isa<CXXConstructorDecl>(Dcl);
1112
1113  if (const CXXConstructorDecl *Constructor
1114        = dyn_cast<CXXConstructorDecl>(Dcl)) {
1115    const CXXRecordDecl *RD = Constructor->getParent();
1116    // DR1359:
1117    // - every non-variant non-static data member and base class sub-object
1118    //   shall be initialized;
1119    // - if the class is a non-empty union, or for each non-empty anonymous
1120    //   union member of a non-union class, exactly one non-static data member
1121    //   shall be initialized;
1122    if (RD->isUnion()) {
1123      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
1124        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1125        return false;
1126      }
1127    } else if (!Constructor->isDependentContext() &&
1128               !Constructor->isDelegatingConstructor()) {
1129      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1130
1131      // Skip detailed checking if we have enough initializers, and we would
1132      // allow at most one initializer per member.
1133      bool AnyAnonStructUnionMembers = false;
1134      unsigned Fields = 0;
1135      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1136           E = RD->field_end(); I != E; ++I, ++Fields) {
1137        if (I->isAnonymousStructOrUnion()) {
1138          AnyAnonStructUnionMembers = true;
1139          break;
1140        }
1141      }
1142      if (AnyAnonStructUnionMembers ||
1143          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1144        // Check initialization of non-static data members. Base classes are
1145        // always initialized so do not need to be checked. Dependent bases
1146        // might not have initializers in the member initializer list.
1147        llvm::SmallSet<Decl*, 16> Inits;
1148        for (CXXConstructorDecl::init_const_iterator
1149               I = Constructor->init_begin(), E = Constructor->init_end();
1150             I != E; ++I) {
1151          if (FieldDecl *FD = (*I)->getMember())
1152            Inits.insert(FD);
1153          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
1154            Inits.insert(ID->chain_begin(), ID->chain_end());
1155        }
1156
1157        bool Diagnosed = false;
1158        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1159             E = RD->field_end(); I != E; ++I)
1160          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
1161        if (Diagnosed)
1162          return false;
1163      }
1164    }
1165  } else {
1166    if (ReturnStmts.empty()) {
1167      // C++1y doesn't require constexpr functions to contain a 'return'
1168      // statement. We still do, unless the return type is void, because
1169      // otherwise if there's no return statement, the function cannot
1170      // be used in a core constant expression.
1171      bool OK = getLangOpts().CPlusPlus1y && Dcl->getResultType()->isVoidType();
1172      Diag(Dcl->getLocation(),
1173           OK ? diag::warn_cxx11_compat_constexpr_body_no_return
1174              : diag::err_constexpr_body_no_return);
1175      return OK;
1176    }
1177    if (ReturnStmts.size() > 1) {
1178      Diag(ReturnStmts.back(),
1179           getLangOpts().CPlusPlus1y
1180             ? diag::warn_cxx11_compat_constexpr_body_multiple_return
1181             : diag::ext_constexpr_body_multiple_return);
1182      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
1183        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
1184    }
1185  }
1186
1187  // C++11 [dcl.constexpr]p5:
1188  //   if no function argument values exist such that the function invocation
1189  //   substitution would produce a constant expression, the program is
1190  //   ill-formed; no diagnostic required.
1191  // C++11 [dcl.constexpr]p3:
1192  //   - every constructor call and implicit conversion used in initializing the
1193  //     return value shall be one of those allowed in a constant expression.
1194  // C++11 [dcl.constexpr]p4:
1195  //   - every constructor involved in initializing non-static data members and
1196  //     base class sub-objects shall be a constexpr constructor.
1197  SmallVector<PartialDiagnosticAt, 8> Diags;
1198  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
1199    Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
1200      << isa<CXXConstructorDecl>(Dcl);
1201    for (size_t I = 0, N = Diags.size(); I != N; ++I)
1202      Diag(Diags[I].first, Diags[I].second);
1203    // Don't return false here: we allow this for compatibility in
1204    // system headers.
1205  }
1206
1207  return true;
1208}
1209
1210/// isCurrentClassName - Determine whether the identifier II is the
1211/// name of the class type currently being defined. In the case of
1212/// nested classes, this will only return true if II is the name of
1213/// the innermost class.
1214bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1215                              const CXXScopeSpec *SS) {
1216  assert(getLangOpts().CPlusPlus && "No class names in C!");
1217
1218  CXXRecordDecl *CurDecl;
1219  if (SS && SS->isSet() && !SS->isInvalid()) {
1220    DeclContext *DC = computeDeclContext(*SS, true);
1221    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1222  } else
1223    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1224
1225  if (CurDecl && CurDecl->getIdentifier())
1226    return &II == CurDecl->getIdentifier();
1227  return false;
1228}
1229
1230/// \brief Determine whether the identifier II is a typo for the name of
1231/// the class type currently being defined. If so, update it to the identifier
1232/// that should have been used.
1233bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
1234  assert(getLangOpts().CPlusPlus && "No class names in C!");
1235
1236  if (!getLangOpts().SpellChecking)
1237    return false;
1238
1239  CXXRecordDecl *CurDecl;
1240  if (SS && SS->isSet() && !SS->isInvalid()) {
1241    DeclContext *DC = computeDeclContext(*SS, true);
1242    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1243  } else
1244    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1245
1246  if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
1247      3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
1248          < II->getLength()) {
1249    II = CurDecl->getIdentifier();
1250    return true;
1251  }
1252
1253  return false;
1254}
1255
1256/// \brief Determine whether the given class is a base class of the given
1257/// class, including looking at dependent bases.
1258static bool findCircularInheritance(const CXXRecordDecl *Class,
1259                                    const CXXRecordDecl *Current) {
1260  SmallVector<const CXXRecordDecl*, 8> Queue;
1261
1262  Class = Class->getCanonicalDecl();
1263  while (true) {
1264    for (CXXRecordDecl::base_class_const_iterator I = Current->bases_begin(),
1265                                                  E = Current->bases_end();
1266         I != E; ++I) {
1267      CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
1268      if (!Base)
1269        continue;
1270
1271      Base = Base->getDefinition();
1272      if (!Base)
1273        continue;
1274
1275      if (Base->getCanonicalDecl() == Class)
1276        return true;
1277
1278      Queue.push_back(Base);
1279    }
1280
1281    if (Queue.empty())
1282      return false;
1283
1284    Current = Queue.pop_back_val();
1285  }
1286
1287  return false;
1288}
1289
1290/// \brief Check the validity of a C++ base class specifier.
1291///
1292/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1293/// and returns NULL otherwise.
1294CXXBaseSpecifier *
1295Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1296                         SourceRange SpecifierRange,
1297                         bool Virtual, AccessSpecifier Access,
1298                         TypeSourceInfo *TInfo,
1299                         SourceLocation EllipsisLoc) {
1300  QualType BaseType = TInfo->getType();
1301
1302  // C++ [class.union]p1:
1303  //   A union shall not have base classes.
1304  if (Class->isUnion()) {
1305    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1306      << SpecifierRange;
1307    return 0;
1308  }
1309
1310  if (EllipsisLoc.isValid() &&
1311      !TInfo->getType()->containsUnexpandedParameterPack()) {
1312    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1313      << TInfo->getTypeLoc().getSourceRange();
1314    EllipsisLoc = SourceLocation();
1315  }
1316
1317  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1318
1319  if (BaseType->isDependentType()) {
1320    // Make sure that we don't have circular inheritance among our dependent
1321    // bases. For non-dependent bases, the check for completeness below handles
1322    // this.
1323    if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
1324      if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
1325          ((BaseDecl = BaseDecl->getDefinition()) &&
1326           findCircularInheritance(Class, BaseDecl))) {
1327        Diag(BaseLoc, diag::err_circular_inheritance)
1328          << BaseType << Context.getTypeDeclType(Class);
1329
1330        if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
1331          Diag(BaseDecl->getLocation(), diag::note_previous_decl)
1332            << BaseType;
1333
1334        return 0;
1335      }
1336    }
1337
1338    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1339                                          Class->getTagKind() == TTK_Class,
1340                                          Access, TInfo, EllipsisLoc);
1341  }
1342
1343  // Base specifiers must be record types.
1344  if (!BaseType->isRecordType()) {
1345    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1346    return 0;
1347  }
1348
1349  // C++ [class.union]p1:
1350  //   A union shall not be used as a base class.
1351  if (BaseType->isUnionType()) {
1352    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1353    return 0;
1354  }
1355
1356  // C++ [class.derived]p2:
1357  //   The class-name in a base-specifier shall not be an incompletely
1358  //   defined class.
1359  if (RequireCompleteType(BaseLoc, BaseType,
1360                          diag::err_incomplete_base_class, SpecifierRange)) {
1361    Class->setInvalidDecl();
1362    return 0;
1363  }
1364
1365  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1366  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1367  assert(BaseDecl && "Record type has no declaration");
1368  BaseDecl = BaseDecl->getDefinition();
1369  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1370  CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1371  assert(CXXBaseDecl && "Base type is not a C++ type");
1372
1373  // C++ [class]p3:
1374  //   If a class is marked final and it appears as a base-type-specifier in
1375  //   base-clause, the program is ill-formed.
1376  if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
1377    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1378      << CXXBaseDecl->getDeclName()
1379      << FA->isSpelledAsSealed();
1380    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1381      << CXXBaseDecl->getDeclName();
1382    return 0;
1383  }
1384
1385  if (BaseDecl->isInvalidDecl())
1386    Class->setInvalidDecl();
1387
1388  // Create the base specifier.
1389  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1390                                        Class->getTagKind() == TTK_Class,
1391                                        Access, TInfo, EllipsisLoc);
1392}
1393
1394/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1395/// one entry in the base class list of a class specifier, for
1396/// example:
1397///    class foo : public bar, virtual private baz {
1398/// 'public bar' and 'virtual private baz' are each base-specifiers.
1399BaseResult
1400Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1401                         ParsedAttributes &Attributes,
1402                         bool Virtual, AccessSpecifier Access,
1403                         ParsedType basetype, SourceLocation BaseLoc,
1404                         SourceLocation EllipsisLoc) {
1405  if (!classdecl)
1406    return true;
1407
1408  AdjustDeclIfTemplate(classdecl);
1409  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1410  if (!Class)
1411    return true;
1412
1413  // We do not support any C++11 attributes on base-specifiers yet.
1414  // Diagnose any attributes we see.
1415  if (!Attributes.empty()) {
1416    for (AttributeList *Attr = Attributes.getList(); Attr;
1417         Attr = Attr->getNext()) {
1418      if (Attr->isInvalid() ||
1419          Attr->getKind() == AttributeList::IgnoredAttribute)
1420        continue;
1421      Diag(Attr->getLoc(),
1422           Attr->getKind() == AttributeList::UnknownAttribute
1423             ? diag::warn_unknown_attribute_ignored
1424             : diag::err_base_specifier_attribute)
1425        << Attr->getName();
1426    }
1427  }
1428
1429  TypeSourceInfo *TInfo = 0;
1430  GetTypeFromParser(basetype, &TInfo);
1431
1432  if (EllipsisLoc.isInvalid() &&
1433      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1434                                      UPPC_BaseType))
1435    return true;
1436
1437  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1438                                                      Virtual, Access, TInfo,
1439                                                      EllipsisLoc))
1440    return BaseSpec;
1441  else
1442    Class->setInvalidDecl();
1443
1444  return true;
1445}
1446
1447/// \brief Performs the actual work of attaching the given base class
1448/// specifiers to a C++ class.
1449bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1450                                unsigned NumBases) {
1451 if (NumBases == 0)
1452    return false;
1453
1454  // Used to keep track of which base types we have already seen, so
1455  // that we can properly diagnose redundant direct base types. Note
1456  // that the key is always the unqualified canonical type of the base
1457  // class.
1458  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1459
1460  // Copy non-redundant base specifiers into permanent storage.
1461  unsigned NumGoodBases = 0;
1462  bool Invalid = false;
1463  for (unsigned idx = 0; idx < NumBases; ++idx) {
1464    QualType NewBaseType
1465      = Context.getCanonicalType(Bases[idx]->getType());
1466    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1467
1468    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1469    if (KnownBase) {
1470      // C++ [class.mi]p3:
1471      //   A class shall not be specified as a direct base class of a
1472      //   derived class more than once.
1473      Diag(Bases[idx]->getLocStart(),
1474           diag::err_duplicate_base_class)
1475        << KnownBase->getType()
1476        << Bases[idx]->getSourceRange();
1477
1478      // Delete the duplicate base class specifier; we're going to
1479      // overwrite its pointer later.
1480      Context.Deallocate(Bases[idx]);
1481
1482      Invalid = true;
1483    } else {
1484      // Okay, add this new base class.
1485      KnownBase = Bases[idx];
1486      Bases[NumGoodBases++] = Bases[idx];
1487      if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
1488        const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
1489        if (Class->isInterface() &&
1490              (!RD->isInterface() ||
1491               KnownBase->getAccessSpecifier() != AS_public)) {
1492          // The Microsoft extension __interface does not permit bases that
1493          // are not themselves public interfaces.
1494          Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
1495            << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
1496            << RD->getSourceRange();
1497          Invalid = true;
1498        }
1499        if (RD->hasAttr<WeakAttr>())
1500          Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1501      }
1502    }
1503  }
1504
1505  // Attach the remaining base class specifiers to the derived class.
1506  Class->setBases(Bases, NumGoodBases);
1507
1508  // Delete the remaining (good) base class specifiers, since their
1509  // data has been copied into the CXXRecordDecl.
1510  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1511    Context.Deallocate(Bases[idx]);
1512
1513  return Invalid;
1514}
1515
1516/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1517/// class, after checking whether there are any duplicate base
1518/// classes.
1519void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1520                               unsigned NumBases) {
1521  if (!ClassDecl || !Bases || !NumBases)
1522    return;
1523
1524  AdjustDeclIfTemplate(ClassDecl);
1525  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases, NumBases);
1526}
1527
1528/// \brief Determine whether the type \p Derived is a C++ class that is
1529/// derived from the type \p Base.
1530bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1531  if (!getLangOpts().CPlusPlus)
1532    return false;
1533
1534  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1535  if (!DerivedRD)
1536    return false;
1537
1538  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1539  if (!BaseRD)
1540    return false;
1541
1542  // If either the base or the derived type is invalid, don't try to
1543  // check whether one is derived from the other.
1544  if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
1545    return false;
1546
1547  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1548  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1549}
1550
1551/// \brief Determine whether the type \p Derived is a C++ class that is
1552/// derived from the type \p Base.
1553bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1554  if (!getLangOpts().CPlusPlus)
1555    return false;
1556
1557  CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
1558  if (!DerivedRD)
1559    return false;
1560
1561  CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
1562  if (!BaseRD)
1563    return false;
1564
1565  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1566}
1567
1568void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1569                              CXXCastPath &BasePathArray) {
1570  assert(BasePathArray.empty() && "Base path array must be empty!");
1571  assert(Paths.isRecordingPaths() && "Must record paths!");
1572
1573  const CXXBasePath &Path = Paths.front();
1574
1575  // We first go backward and check if we have a virtual base.
1576  // FIXME: It would be better if CXXBasePath had the base specifier for
1577  // the nearest virtual base.
1578  unsigned Start = 0;
1579  for (unsigned I = Path.size(); I != 0; --I) {
1580    if (Path[I - 1].Base->isVirtual()) {
1581      Start = I - 1;
1582      break;
1583    }
1584  }
1585
1586  // Now add all bases.
1587  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1588    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1589}
1590
1591/// \brief Determine whether the given base path includes a virtual
1592/// base class.
1593bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1594  for (CXXCastPath::const_iterator B = BasePath.begin(),
1595                                BEnd = BasePath.end();
1596       B != BEnd; ++B)
1597    if ((*B)->isVirtual())
1598      return true;
1599
1600  return false;
1601}
1602
1603/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1604/// conversion (where Derived and Base are class types) is
1605/// well-formed, meaning that the conversion is unambiguous (and
1606/// that all of the base classes are accessible). Returns true
1607/// and emits a diagnostic if the code is ill-formed, returns false
1608/// otherwise. Loc is the location where this routine should point to
1609/// if there is an error, and Range is the source range to highlight
1610/// if there is an error.
1611bool
1612Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1613                                   unsigned InaccessibleBaseID,
1614                                   unsigned AmbigiousBaseConvID,
1615                                   SourceLocation Loc, SourceRange Range,
1616                                   DeclarationName Name,
1617                                   CXXCastPath *BasePath) {
1618  // First, determine whether the path from Derived to Base is
1619  // ambiguous. This is slightly more expensive than checking whether
1620  // the Derived to Base conversion exists, because here we need to
1621  // explore multiple paths to determine if there is an ambiguity.
1622  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1623                     /*DetectVirtual=*/false);
1624  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1625  assert(DerivationOkay &&
1626         "Can only be used with a derived-to-base conversion");
1627  (void)DerivationOkay;
1628
1629  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1630    if (InaccessibleBaseID) {
1631      // Check that the base class can be accessed.
1632      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1633                                   InaccessibleBaseID)) {
1634        case AR_inaccessible:
1635          return true;
1636        case AR_accessible:
1637        case AR_dependent:
1638        case AR_delayed:
1639          break;
1640      }
1641    }
1642
1643    // Build a base path if necessary.
1644    if (BasePath)
1645      BuildBasePathArray(Paths, *BasePath);
1646    return false;
1647  }
1648
1649  if (AmbigiousBaseConvID) {
1650    // We know that the derived-to-base conversion is ambiguous, and
1651    // we're going to produce a diagnostic. Perform the derived-to-base
1652    // search just one more time to compute all of the possible paths so
1653    // that we can print them out. This is more expensive than any of
1654    // the previous derived-to-base checks we've done, but at this point
1655    // performance isn't as much of an issue.
1656    Paths.clear();
1657    Paths.setRecordingPaths(true);
1658    bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1659    assert(StillOkay && "Can only be used with a derived-to-base conversion");
1660    (void)StillOkay;
1661
1662    // Build up a textual representation of the ambiguous paths, e.g.,
1663    // D -> B -> A, that will be used to illustrate the ambiguous
1664    // conversions in the diagnostic. We only print one of the paths
1665    // to each base class subobject.
1666    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1667
1668    Diag(Loc, AmbigiousBaseConvID)
1669    << Derived << Base << PathDisplayStr << Range << Name;
1670  }
1671  return true;
1672}
1673
1674bool
1675Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1676                                   SourceLocation Loc, SourceRange Range,
1677                                   CXXCastPath *BasePath,
1678                                   bool IgnoreAccess) {
1679  return CheckDerivedToBaseConversion(Derived, Base,
1680                                      IgnoreAccess ? 0
1681                                       : diag::err_upcast_to_inaccessible_base,
1682                                      diag::err_ambiguous_derived_to_base_conv,
1683                                      Loc, Range, DeclarationName(),
1684                                      BasePath);
1685}
1686
1687
1688/// @brief Builds a string representing ambiguous paths from a
1689/// specific derived class to different subobjects of the same base
1690/// class.
1691///
1692/// This function builds a string that can be used in error messages
1693/// to show the different paths that one can take through the
1694/// inheritance hierarchy to go from the derived class to different
1695/// subobjects of a base class. The result looks something like this:
1696/// @code
1697/// struct D -> struct B -> struct A
1698/// struct D -> struct C -> struct A
1699/// @endcode
1700std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1701  std::string PathDisplayStr;
1702  std::set<unsigned> DisplayedPaths;
1703  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1704       Path != Paths.end(); ++Path) {
1705    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1706      // We haven't displayed a path to this particular base
1707      // class subobject yet.
1708      PathDisplayStr += "\n    ";
1709      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1710      for (CXXBasePath::const_iterator Element = Path->begin();
1711           Element != Path->end(); ++Element)
1712        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1713    }
1714  }
1715
1716  return PathDisplayStr;
1717}
1718
1719//===----------------------------------------------------------------------===//
1720// C++ class member Handling
1721//===----------------------------------------------------------------------===//
1722
1723/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1724bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1725                                SourceLocation ASLoc,
1726                                SourceLocation ColonLoc,
1727                                AttributeList *Attrs) {
1728  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1729  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1730                                                  ASLoc, ColonLoc);
1731  CurContext->addHiddenDecl(ASDecl);
1732  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1733}
1734
1735/// CheckOverrideControl - Check C++11 override control semantics.
1736void Sema::CheckOverrideControl(NamedDecl *D) {
1737  if (D->isInvalidDecl())
1738    return;
1739
1740  // We only care about "override" and "final" declarations.
1741  if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
1742    return;
1743
1744  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1745
1746  // We can't check dependent instance methods.
1747  if (MD && MD->isInstance() &&
1748      (MD->getParent()->hasAnyDependentBases() ||
1749       MD->getType()->isDependentType()))
1750    return;
1751
1752  if (MD && !MD->isVirtual()) {
1753    // If we have a non-virtual method, check if if hides a virtual method.
1754    // (In that case, it's most likely the method has the wrong type.)
1755    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
1756    FindHiddenVirtualMethods(MD, OverloadedMethods);
1757
1758    if (!OverloadedMethods.empty()) {
1759      if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1760        Diag(OA->getLocation(),
1761             diag::override_keyword_hides_virtual_member_function)
1762          << "override" << (OverloadedMethods.size() > 1);
1763      } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1764        Diag(FA->getLocation(),
1765             diag::override_keyword_hides_virtual_member_function)
1766          << (FA->isSpelledAsSealed() ? "sealed" : "final")
1767          << (OverloadedMethods.size() > 1);
1768      }
1769      NoteHiddenVirtualMethods(MD, OverloadedMethods);
1770      MD->setInvalidDecl();
1771      return;
1772    }
1773    // Fall through into the general case diagnostic.
1774    // FIXME: We might want to attempt typo correction here.
1775  }
1776
1777  if (!MD || !MD->isVirtual()) {
1778    if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
1779      Diag(OA->getLocation(),
1780           diag::override_keyword_only_allowed_on_virtual_member_functions)
1781        << "override" << FixItHint::CreateRemoval(OA->getLocation());
1782      D->dropAttr<OverrideAttr>();
1783    }
1784    if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
1785      Diag(FA->getLocation(),
1786           diag::override_keyword_only_allowed_on_virtual_member_functions)
1787        << (FA->isSpelledAsSealed() ? "sealed" : "final")
1788        << FixItHint::CreateRemoval(FA->getLocation());
1789      D->dropAttr<FinalAttr>();
1790    }
1791    return;
1792  }
1793
1794  // C++11 [class.virtual]p5:
1795  //   If a virtual function is marked with the virt-specifier override and
1796  //   does not override a member function of a base class, the program is
1797  //   ill-formed.
1798  bool HasOverriddenMethods =
1799    MD->begin_overridden_methods() != MD->end_overridden_methods();
1800  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
1801    Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
1802      << MD->getDeclName();
1803}
1804
1805/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1806/// function overrides a virtual member function marked 'final', according to
1807/// C++11 [class.virtual]p4.
1808bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1809                                                  const CXXMethodDecl *Old) {
1810  FinalAttr *FA = Old->getAttr<FinalAttr>();
1811  if (!FA)
1812    return false;
1813
1814  Diag(New->getLocation(), diag::err_final_function_overridden)
1815    << New->getDeclName()
1816    << FA->isSpelledAsSealed();
1817  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1818  return true;
1819}
1820
1821static bool InitializationHasSideEffects(const FieldDecl &FD) {
1822  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
1823  // FIXME: Destruction of ObjC lifetime types has side-effects.
1824  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1825    return !RD->isCompleteDefinition() ||
1826           !RD->hasTrivialDefaultConstructor() ||
1827           !RD->hasTrivialDestructor();
1828  return false;
1829}
1830
1831static AttributeList *getMSPropertyAttr(AttributeList *list) {
1832  for (AttributeList* it = list; it != 0; it = it->getNext())
1833    if (it->isDeclspecPropertyAttribute())
1834      return it;
1835  return 0;
1836}
1837
1838/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1839/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1840/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1841/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
1842/// present (but parsing it has been deferred).
1843NamedDecl *
1844Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1845                               MultiTemplateParamsArg TemplateParameterLists,
1846                               Expr *BW, const VirtSpecifiers &VS,
1847                               InClassInitStyle InitStyle) {
1848  const DeclSpec &DS = D.getDeclSpec();
1849  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1850  DeclarationName Name = NameInfo.getName();
1851  SourceLocation Loc = NameInfo.getLoc();
1852
1853  // For anonymous bitfields, the location should point to the type.
1854  if (Loc.isInvalid())
1855    Loc = D.getLocStart();
1856
1857  Expr *BitWidth = static_cast<Expr*>(BW);
1858
1859  assert(isa<CXXRecordDecl>(CurContext));
1860  assert(!DS.isFriendSpecified());
1861
1862  bool isFunc = D.isDeclarationOfFunction();
1863
1864  if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
1865    // The Microsoft extension __interface only permits public member functions
1866    // and prohibits constructors, destructors, operators, non-public member
1867    // functions, static methods and data members.
1868    unsigned InvalidDecl;
1869    bool ShowDeclName = true;
1870    if (!isFunc)
1871      InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
1872    else if (AS != AS_public)
1873      InvalidDecl = 2;
1874    else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
1875      InvalidDecl = 3;
1876    else switch (Name.getNameKind()) {
1877      case DeclarationName::CXXConstructorName:
1878        InvalidDecl = 4;
1879        ShowDeclName = false;
1880        break;
1881
1882      case DeclarationName::CXXDestructorName:
1883        InvalidDecl = 5;
1884        ShowDeclName = false;
1885        break;
1886
1887      case DeclarationName::CXXOperatorName:
1888      case DeclarationName::CXXConversionFunctionName:
1889        InvalidDecl = 6;
1890        break;
1891
1892      default:
1893        InvalidDecl = 0;
1894        break;
1895    }
1896
1897    if (InvalidDecl) {
1898      if (ShowDeclName)
1899        Diag(Loc, diag::err_invalid_member_in_interface)
1900          << (InvalidDecl-1) << Name;
1901      else
1902        Diag(Loc, diag::err_invalid_member_in_interface)
1903          << (InvalidDecl-1) << "";
1904      return 0;
1905    }
1906  }
1907
1908  // C++ 9.2p6: A member shall not be declared to have automatic storage
1909  // duration (auto, register) or with the extern storage-class-specifier.
1910  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1911  // data members and cannot be applied to names declared const or static,
1912  // and cannot be applied to reference members.
1913  switch (DS.getStorageClassSpec()) {
1914  case DeclSpec::SCS_unspecified:
1915  case DeclSpec::SCS_typedef:
1916  case DeclSpec::SCS_static:
1917    break;
1918  case DeclSpec::SCS_mutable:
1919    if (isFunc) {
1920      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1921
1922      // FIXME: It would be nicer if the keyword was ignored only for this
1923      // declarator. Otherwise we could get follow-up errors.
1924      D.getMutableDeclSpec().ClearStorageClassSpecs();
1925    }
1926    break;
1927  default:
1928    Diag(DS.getStorageClassSpecLoc(),
1929         diag::err_storageclass_invalid_for_member);
1930    D.getMutableDeclSpec().ClearStorageClassSpecs();
1931    break;
1932  }
1933
1934  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1935                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1936                      !isFunc);
1937
1938  if (DS.isConstexprSpecified() && isInstField) {
1939    SemaDiagnosticBuilder B =
1940        Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
1941    SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
1942    if (InitStyle == ICIS_NoInit) {
1943      B << 0 << 0 << FixItHint::CreateReplacement(ConstexprLoc, "const");
1944      D.getMutableDeclSpec().ClearConstexprSpec();
1945      const char *PrevSpec;
1946      unsigned DiagID;
1947      bool Failed = D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, ConstexprLoc,
1948                                         PrevSpec, DiagID, getLangOpts());
1949      (void)Failed;
1950      assert(!Failed && "Making a constexpr member const shouldn't fail");
1951    } else {
1952      B << 1;
1953      const char *PrevSpec;
1954      unsigned DiagID;
1955      if (D.getMutableDeclSpec().SetStorageClassSpec(
1956          *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID)) {
1957        assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
1958               "This is the only DeclSpec that should fail to be applied");
1959        B << 1;
1960      } else {
1961        B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
1962        isInstField = false;
1963      }
1964    }
1965  }
1966
1967  NamedDecl *Member;
1968  if (isInstField) {
1969    CXXScopeSpec &SS = D.getCXXScopeSpec();
1970
1971    // Data members must have identifiers for names.
1972    if (!Name.isIdentifier()) {
1973      Diag(Loc, diag::err_bad_variable_name)
1974        << Name;
1975      return 0;
1976    }
1977
1978    IdentifierInfo *II = Name.getAsIdentifierInfo();
1979
1980    // Member field could not be with "template" keyword.
1981    // So TemplateParameterLists should be empty in this case.
1982    if (TemplateParameterLists.size()) {
1983      TemplateParameterList* TemplateParams = TemplateParameterLists[0];
1984      if (TemplateParams->size()) {
1985        // There is no such thing as a member field template.
1986        Diag(D.getIdentifierLoc(), diag::err_template_member)
1987            << II
1988            << SourceRange(TemplateParams->getTemplateLoc(),
1989                TemplateParams->getRAngleLoc());
1990      } else {
1991        // There is an extraneous 'template<>' for this member.
1992        Diag(TemplateParams->getTemplateLoc(),
1993            diag::err_template_member_noparams)
1994            << II
1995            << SourceRange(TemplateParams->getTemplateLoc(),
1996                TemplateParams->getRAngleLoc());
1997      }
1998      return 0;
1999    }
2000
2001    if (SS.isSet() && !SS.isInvalid()) {
2002      // The user provided a superfluous scope specifier inside a class
2003      // definition:
2004      //
2005      // class X {
2006      //   int X::member;
2007      // };
2008      if (DeclContext *DC = computeDeclContext(SS, false))
2009        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
2010      else
2011        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
2012          << Name << SS.getRange();
2013
2014      SS.clear();
2015    }
2016
2017    AttributeList *MSPropertyAttr =
2018      getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2019    if (MSPropertyAttr) {
2020      Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2021                                BitWidth, InitStyle, AS, MSPropertyAttr);
2022      if (!Member)
2023        return 0;
2024      isInstField = false;
2025    } else {
2026      Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
2027                                BitWidth, InitStyle, AS);
2028      assert(Member && "HandleField never returns null");
2029    }
2030  } else {
2031    assert(InitStyle == ICIS_NoInit || D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static);
2032
2033    Member = HandleDeclarator(S, D, TemplateParameterLists);
2034    if (!Member)
2035      return 0;
2036
2037    // Non-instance-fields can't have a bitfield.
2038    if (BitWidth) {
2039      if (Member->isInvalidDecl()) {
2040        // don't emit another diagnostic.
2041      } else if (isa<VarDecl>(Member)) {
2042        // C++ 9.6p3: A bit-field shall not be a static member.
2043        // "static member 'A' cannot be a bit-field"
2044        Diag(Loc, diag::err_static_not_bitfield)
2045          << Name << BitWidth->getSourceRange();
2046      } else if (isa<TypedefDecl>(Member)) {
2047        // "typedef member 'x' cannot be a bit-field"
2048        Diag(Loc, diag::err_typedef_not_bitfield)
2049          << Name << BitWidth->getSourceRange();
2050      } else {
2051        // A function typedef ("typedef int f(); f a;").
2052        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
2053        Diag(Loc, diag::err_not_integral_type_bitfield)
2054          << Name << cast<ValueDecl>(Member)->getType()
2055          << BitWidth->getSourceRange();
2056      }
2057
2058      BitWidth = 0;
2059      Member->setInvalidDecl();
2060    }
2061
2062    Member->setAccess(AS);
2063
2064    // If we have declared a member function template or static data member
2065    // template, set the access of the templated declaration as well.
2066    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
2067      FunTmpl->getTemplatedDecl()->setAccess(AS);
2068    else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
2069      VarTmpl->getTemplatedDecl()->setAccess(AS);
2070  }
2071
2072  if (VS.isOverrideSpecified())
2073    Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
2074  if (VS.isFinalSpecified())
2075    Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
2076                                            VS.isFinalSpelledSealed()));
2077
2078  if (VS.getLastLocation().isValid()) {
2079    // Update the end location of a method that has a virt-specifiers.
2080    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
2081      MD->setRangeEnd(VS.getLastLocation());
2082  }
2083
2084  CheckOverrideControl(Member);
2085
2086  assert((Name || isInstField) && "No identifier for non-field ?");
2087
2088  if (isInstField) {
2089    FieldDecl *FD = cast<FieldDecl>(Member);
2090    FieldCollector->Add(FD);
2091
2092    if (Diags.getDiagnosticLevel(diag::warn_unused_private_field,
2093                                 FD->getLocation())
2094          != DiagnosticsEngine::Ignored) {
2095      // Remember all explicit private FieldDecls that have a name, no side
2096      // effects and are not part of a dependent type declaration.
2097      if (!FD->isImplicit() && FD->getDeclName() &&
2098          FD->getAccess() == AS_private &&
2099          !FD->hasAttr<UnusedAttr>() &&
2100          !FD->getParent()->isDependentContext() &&
2101          !InitializationHasSideEffects(*FD))
2102        UnusedPrivateFields.insert(FD);
2103    }
2104  }
2105
2106  return Member;
2107}
2108
2109namespace {
2110  class UninitializedFieldVisitor
2111      : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
2112    Sema &S;
2113    // List of Decls to generate a warning on.  Also remove Decls that become
2114    // initialized.
2115    llvm::SmallPtrSet<ValueDecl*, 4> &Decls;
2116    // If non-null, add a note to the warning pointing back to the constructor.
2117    const CXXConstructorDecl *Constructor;
2118  public:
2119    typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
2120    UninitializedFieldVisitor(Sema &S,
2121                              llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2122                              const CXXConstructorDecl *Constructor)
2123      : Inherited(S.Context), S(S), Decls(Decls),
2124        Constructor(Constructor) { }
2125
2126    void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly) {
2127      if (isa<EnumConstantDecl>(ME->getMemberDecl()))
2128        return;
2129
2130      // FieldME is the inner-most MemberExpr that is not an anonymous struct
2131      // or union.
2132      MemberExpr *FieldME = ME;
2133
2134      Expr *Base = ME;
2135      while (isa<MemberExpr>(Base)) {
2136        ME = cast<MemberExpr>(Base);
2137
2138        if (isa<VarDecl>(ME->getMemberDecl()))
2139          return;
2140
2141        if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2142          if (!FD->isAnonymousStructOrUnion())
2143            FieldME = ME;
2144
2145        Base = ME->getBase();
2146      }
2147
2148      if (!isa<CXXThisExpr>(Base))
2149        return;
2150
2151      ValueDecl* FoundVD = FieldME->getMemberDecl();
2152
2153      if (!Decls.count(FoundVD))
2154        return;
2155
2156      const bool IsReference = FoundVD->getType()->isReferenceType();
2157
2158      // Prevent double warnings on use of unbounded references.
2159      if (IsReference != CheckReferenceOnly)
2160        return;
2161
2162      unsigned diag = IsReference
2163          ? diag::warn_reference_field_is_uninit
2164          : diag::warn_field_is_uninit;
2165      S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
2166      if (Constructor)
2167        S.Diag(Constructor->getLocation(),
2168               diag::note_uninit_in_this_constructor)
2169          << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
2170
2171    }
2172
2173    void HandleValue(Expr *E) {
2174      E = E->IgnoreParens();
2175
2176      if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
2177        HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2178        return;
2179      }
2180
2181      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2182        HandleValue(CO->getTrueExpr());
2183        HandleValue(CO->getFalseExpr());
2184        return;
2185      }
2186
2187      if (BinaryConditionalOperator *BCO =
2188              dyn_cast<BinaryConditionalOperator>(E)) {
2189        HandleValue(BCO->getCommon());
2190        HandleValue(BCO->getFalseExpr());
2191        return;
2192      }
2193
2194      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2195        switch (BO->getOpcode()) {
2196        default:
2197          return;
2198        case(BO_PtrMemD):
2199        case(BO_PtrMemI):
2200          HandleValue(BO->getLHS());
2201          return;
2202        case(BO_Comma):
2203          HandleValue(BO->getRHS());
2204          return;
2205        }
2206      }
2207    }
2208
2209    void VisitMemberExpr(MemberExpr *ME) {
2210      // All uses of unbounded reference fields will warn.
2211      HandleMemberExpr(ME, true /*CheckReferenceOnly*/);
2212
2213      Inherited::VisitMemberExpr(ME);
2214    }
2215
2216    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
2217      if (E->getCastKind() == CK_LValueToRValue)
2218        HandleValue(E->getSubExpr());
2219
2220      Inherited::VisitImplicitCastExpr(E);
2221    }
2222
2223    void VisitCXXConstructExpr(CXXConstructExpr *E) {
2224      if (E->getConstructor()->isCopyConstructor())
2225        if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E->getArg(0)))
2226          if (ICE->getCastKind() == CK_NoOp)
2227            if (MemberExpr *ME = dyn_cast<MemberExpr>(ICE->getSubExpr()))
2228              HandleMemberExpr(ME, false /*CheckReferenceOnly*/);
2229
2230      Inherited::VisitCXXConstructExpr(E);
2231    }
2232
2233    void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2234      Expr *Callee = E->getCallee();
2235      if (isa<MemberExpr>(Callee))
2236        HandleValue(Callee);
2237
2238      Inherited::VisitCXXMemberCallExpr(E);
2239    }
2240
2241    void VisitBinaryOperator(BinaryOperator *E) {
2242      // If a field assignment is detected, remove the field from the
2243      // uninitiailized field set.
2244      if (E->getOpcode() == BO_Assign)
2245        if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
2246          if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2247            if (!FD->getType()->isReferenceType())
2248              Decls.erase(FD);
2249
2250      Inherited::VisitBinaryOperator(E);
2251    }
2252  };
2253  static void CheckInitExprContainsUninitializedFields(
2254      Sema &S, Expr *E, llvm::SmallPtrSet<ValueDecl*, 4> &Decls,
2255      const CXXConstructorDecl *Constructor) {
2256    if (Decls.size() == 0)
2257      return;
2258
2259    if (!E)
2260      return;
2261
2262    if (CXXDefaultInitExpr *Default = dyn_cast<CXXDefaultInitExpr>(E)) {
2263      E = Default->getExpr();
2264      if (!E)
2265        return;
2266      // In class initializers will point to the constructor.
2267      UninitializedFieldVisitor(S, Decls, Constructor).Visit(E);
2268    } else {
2269      UninitializedFieldVisitor(S, Decls, 0).Visit(E);
2270    }
2271  }
2272
2273  // Diagnose value-uses of fields to initialize themselves, e.g.
2274  //   foo(foo)
2275  // where foo is not also a parameter to the constructor.
2276  // Also diagnose across field uninitialized use such as
2277  //   x(y), y(x)
2278  // TODO: implement -Wuninitialized and fold this into that framework.
2279  static void DiagnoseUninitializedFields(
2280      Sema &SemaRef, const CXXConstructorDecl *Constructor) {
2281
2282    if (SemaRef.getDiagnostics().getDiagnosticLevel(diag::warn_field_is_uninit,
2283                                                    Constructor->getLocation())
2284        == DiagnosticsEngine::Ignored) {
2285      return;
2286    }
2287
2288    if (Constructor->isInvalidDecl())
2289      return;
2290
2291    const CXXRecordDecl *RD = Constructor->getParent();
2292
2293    // Holds fields that are uninitialized.
2294    llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
2295
2296    // At the beginning, all fields are uninitialized.
2297    for (DeclContext::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
2298         I != E; ++I) {
2299      if (FieldDecl *FD = dyn_cast<FieldDecl>(*I)) {
2300        UninitializedFields.insert(FD);
2301      } else if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I)) {
2302        UninitializedFields.insert(IFD->getAnonField());
2303      }
2304    }
2305
2306    for (CXXConstructorDecl::init_const_iterator FieldInit =
2307             Constructor->init_begin(),
2308             FieldInitEnd = Constructor->init_end();
2309         FieldInit != FieldInitEnd; ++FieldInit) {
2310
2311      Expr *InitExpr = (*FieldInit)->getInit();
2312
2313      CheckInitExprContainsUninitializedFields(
2314          SemaRef, InitExpr, UninitializedFields, Constructor);
2315
2316      if (FieldDecl *Field = (*FieldInit)->getAnyMember())
2317        UninitializedFields.erase(Field);
2318    }
2319  }
2320} // namespace
2321
2322/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
2323/// in-class initializer for a non-static C++ class member, and after
2324/// instantiating an in-class initializer in a class template. Such actions
2325/// are deferred until the class is complete.
2326void
2327Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation InitLoc,
2328                                       Expr *InitExpr) {
2329  FieldDecl *FD = cast<FieldDecl>(D);
2330  assert(FD->getInClassInitStyle() != ICIS_NoInit &&
2331         "must set init style when field is created");
2332
2333  if (!InitExpr) {
2334    FD->setInvalidDecl();
2335    FD->removeInClassInitializer();
2336    return;
2337  }
2338
2339  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
2340    FD->setInvalidDecl();
2341    FD->removeInClassInitializer();
2342    return;
2343  }
2344
2345  ExprResult Init = InitExpr;
2346  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
2347    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
2348    InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
2349        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
2350        : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
2351    InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2352    Init = Seq.Perform(*this, Entity, Kind, InitExpr);
2353    if (Init.isInvalid()) {
2354      FD->setInvalidDecl();
2355      return;
2356    }
2357  }
2358
2359  // C++11 [class.base.init]p7:
2360  //   The initialization of each base and member constitutes a
2361  //   full-expression.
2362  Init = ActOnFinishFullExpr(Init.take(), InitLoc);
2363  if (Init.isInvalid()) {
2364    FD->setInvalidDecl();
2365    return;
2366  }
2367
2368  InitExpr = Init.release();
2369
2370  FD->setInClassInitializer(InitExpr);
2371}
2372
2373/// \brief Find the direct and/or virtual base specifiers that
2374/// correspond to the given base type, for use in base initialization
2375/// within a constructor.
2376static bool FindBaseInitializer(Sema &SemaRef,
2377                                CXXRecordDecl *ClassDecl,
2378                                QualType BaseType,
2379                                const CXXBaseSpecifier *&DirectBaseSpec,
2380                                const CXXBaseSpecifier *&VirtualBaseSpec) {
2381  // First, check for a direct base class.
2382  DirectBaseSpec = 0;
2383  for (CXXRecordDecl::base_class_const_iterator Base
2384         = ClassDecl->bases_begin();
2385       Base != ClassDecl->bases_end(); ++Base) {
2386    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
2387      // We found a direct base of this type. That's what we're
2388      // initializing.
2389      DirectBaseSpec = &*Base;
2390      break;
2391    }
2392  }
2393
2394  // Check for a virtual base class.
2395  // FIXME: We might be able to short-circuit this if we know in advance that
2396  // there are no virtual bases.
2397  VirtualBaseSpec = 0;
2398  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
2399    // We haven't found a base yet; search the class hierarchy for a
2400    // virtual base class.
2401    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2402                       /*DetectVirtual=*/false);
2403    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
2404                              BaseType, Paths)) {
2405      for (CXXBasePaths::paths_iterator Path = Paths.begin();
2406           Path != Paths.end(); ++Path) {
2407        if (Path->back().Base->isVirtual()) {
2408          VirtualBaseSpec = Path->back().Base;
2409          break;
2410        }
2411      }
2412    }
2413  }
2414
2415  return DirectBaseSpec || VirtualBaseSpec;
2416}
2417
2418/// \brief Handle a C++ member initializer using braced-init-list syntax.
2419MemInitResult
2420Sema::ActOnMemInitializer(Decl *ConstructorD,
2421                          Scope *S,
2422                          CXXScopeSpec &SS,
2423                          IdentifierInfo *MemberOrBase,
2424                          ParsedType TemplateTypeTy,
2425                          const DeclSpec &DS,
2426                          SourceLocation IdLoc,
2427                          Expr *InitList,
2428                          SourceLocation EllipsisLoc) {
2429  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2430                             DS, IdLoc, InitList,
2431                             EllipsisLoc);
2432}
2433
2434/// \brief Handle a C++ member initializer using parentheses syntax.
2435MemInitResult
2436Sema::ActOnMemInitializer(Decl *ConstructorD,
2437                          Scope *S,
2438                          CXXScopeSpec &SS,
2439                          IdentifierInfo *MemberOrBase,
2440                          ParsedType TemplateTypeTy,
2441                          const DeclSpec &DS,
2442                          SourceLocation IdLoc,
2443                          SourceLocation LParenLoc,
2444                          ArrayRef<Expr *> Args,
2445                          SourceLocation RParenLoc,
2446                          SourceLocation EllipsisLoc) {
2447  Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
2448                                           Args, RParenLoc);
2449  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
2450                             DS, IdLoc, List, EllipsisLoc);
2451}
2452
2453namespace {
2454
2455// Callback to only accept typo corrections that can be a valid C++ member
2456// intializer: either a non-static field member or a base class.
2457class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
2458public:
2459  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
2460      : ClassDecl(ClassDecl) {}
2461
2462  bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
2463    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
2464      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
2465        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
2466      return isa<TypeDecl>(ND);
2467    }
2468    return false;
2469  }
2470
2471private:
2472  CXXRecordDecl *ClassDecl;
2473};
2474
2475}
2476
2477/// \brief Handle a C++ member initializer.
2478MemInitResult
2479Sema::BuildMemInitializer(Decl *ConstructorD,
2480                          Scope *S,
2481                          CXXScopeSpec &SS,
2482                          IdentifierInfo *MemberOrBase,
2483                          ParsedType TemplateTypeTy,
2484                          const DeclSpec &DS,
2485                          SourceLocation IdLoc,
2486                          Expr *Init,
2487                          SourceLocation EllipsisLoc) {
2488  if (!ConstructorD)
2489    return true;
2490
2491  AdjustDeclIfTemplate(ConstructorD);
2492
2493  CXXConstructorDecl *Constructor
2494    = dyn_cast<CXXConstructorDecl>(ConstructorD);
2495  if (!Constructor) {
2496    // The user wrote a constructor initializer on a function that is
2497    // not a C++ constructor. Ignore the error for now, because we may
2498    // have more member initializers coming; we'll diagnose it just
2499    // once in ActOnMemInitializers.
2500    return true;
2501  }
2502
2503  CXXRecordDecl *ClassDecl = Constructor->getParent();
2504
2505  // C++ [class.base.init]p2:
2506  //   Names in a mem-initializer-id are looked up in the scope of the
2507  //   constructor's class and, if not found in that scope, are looked
2508  //   up in the scope containing the constructor's definition.
2509  //   [Note: if the constructor's class contains a member with the
2510  //   same name as a direct or virtual base class of the class, a
2511  //   mem-initializer-id naming the member or base class and composed
2512  //   of a single identifier refers to the class member. A
2513  //   mem-initializer-id for the hidden base class may be specified
2514  //   using a qualified name. ]
2515  if (!SS.getScopeRep() && !TemplateTypeTy) {
2516    // Look for a member, first.
2517    DeclContext::lookup_result Result
2518      = ClassDecl->lookup(MemberOrBase);
2519    if (!Result.empty()) {
2520      ValueDecl *Member;
2521      if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
2522          (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
2523        if (EllipsisLoc.isValid())
2524          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
2525            << MemberOrBase
2526            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
2527
2528        return BuildMemberInitializer(Member, Init, IdLoc);
2529      }
2530    }
2531  }
2532  // It didn't name a member, so see if it names a class.
2533  QualType BaseType;
2534  TypeSourceInfo *TInfo = 0;
2535
2536  if (TemplateTypeTy) {
2537    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
2538  } else if (DS.getTypeSpecType() == TST_decltype) {
2539    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
2540  } else {
2541    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
2542    LookupParsedName(R, S, &SS);
2543
2544    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
2545    if (!TyD) {
2546      if (R.isAmbiguous()) return true;
2547
2548      // We don't want access-control diagnostics here.
2549      R.suppressDiagnostics();
2550
2551      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
2552        bool NotUnknownSpecialization = false;
2553        DeclContext *DC = computeDeclContext(SS, false);
2554        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
2555          NotUnknownSpecialization = !Record->hasAnyDependentBases();
2556
2557        if (!NotUnknownSpecialization) {
2558          // When the scope specifier can refer to a member of an unknown
2559          // specialization, we take it as a type name.
2560          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
2561                                       SS.getWithLocInContext(Context),
2562                                       *MemberOrBase, IdLoc);
2563          if (BaseType.isNull())
2564            return true;
2565
2566          R.clear();
2567          R.setLookupName(MemberOrBase);
2568        }
2569      }
2570
2571      // If no results were found, try to correct typos.
2572      TypoCorrection Corr;
2573      MemInitializerValidatorCCC Validator(ClassDecl);
2574      if (R.empty() && BaseType.isNull() &&
2575          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2576                              Validator, ClassDecl))) {
2577        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
2578          // We have found a non-static data member with a similar
2579          // name to what was typed; complain and initialize that
2580          // member.
2581          diagnoseTypo(Corr,
2582                       PDiag(diag::err_mem_init_not_member_or_class_suggest)
2583                         << MemberOrBase << true);
2584          return BuildMemberInitializer(Member, Init, IdLoc);
2585        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
2586          const CXXBaseSpecifier *DirectBaseSpec;
2587          const CXXBaseSpecifier *VirtualBaseSpec;
2588          if (FindBaseInitializer(*this, ClassDecl,
2589                                  Context.getTypeDeclType(Type),
2590                                  DirectBaseSpec, VirtualBaseSpec)) {
2591            // We have found a direct or virtual base class with a
2592            // similar name to what was typed; complain and initialize
2593            // that base class.
2594            diagnoseTypo(Corr,
2595                         PDiag(diag::err_mem_init_not_member_or_class_suggest)
2596                           << MemberOrBase << false,
2597                         PDiag() /*Suppress note, we provide our own.*/);
2598
2599            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
2600                                                              : VirtualBaseSpec;
2601            Diag(BaseSpec->getLocStart(),
2602                 diag::note_base_class_specified_here)
2603              << BaseSpec->getType()
2604              << BaseSpec->getSourceRange();
2605
2606            TyD = Type;
2607          }
2608        }
2609      }
2610
2611      if (!TyD && BaseType.isNull()) {
2612        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
2613          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
2614        return true;
2615      }
2616    }
2617
2618    if (BaseType.isNull()) {
2619      BaseType = Context.getTypeDeclType(TyD);
2620      if (SS.isSet()) {
2621        NestedNameSpecifier *Qualifier =
2622          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2623
2624        // FIXME: preserve source range information
2625        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
2626      }
2627    }
2628  }
2629
2630  if (!TInfo)
2631    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
2632
2633  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
2634}
2635
2636/// Checks a member initializer expression for cases where reference (or
2637/// pointer) members are bound to by-value parameters (or their addresses).
2638static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
2639                                               Expr *Init,
2640                                               SourceLocation IdLoc) {
2641  QualType MemberTy = Member->getType();
2642
2643  // We only handle pointers and references currently.
2644  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
2645  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
2646    return;
2647
2648  const bool IsPointer = MemberTy->isPointerType();
2649  if (IsPointer) {
2650    if (const UnaryOperator *Op
2651          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
2652      // The only case we're worried about with pointers requires taking the
2653      // address.
2654      if (Op->getOpcode() != UO_AddrOf)
2655        return;
2656
2657      Init = Op->getSubExpr();
2658    } else {
2659      // We only handle address-of expression initializers for pointers.
2660      return;
2661    }
2662  }
2663
2664  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
2665    // We only warn when referring to a non-reference parameter declaration.
2666    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2667    if (!Parameter || Parameter->getType()->isReferenceType())
2668      return;
2669
2670    S.Diag(Init->getExprLoc(),
2671           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2672                     : diag::warn_bind_ref_member_to_parameter)
2673      << Member << Parameter << Init->getSourceRange();
2674  } else {
2675    // Other initializers are fine.
2676    return;
2677  }
2678
2679  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2680    << (unsigned)IsPointer;
2681}
2682
2683MemInitResult
2684Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2685                             SourceLocation IdLoc) {
2686  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2687  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2688  assert((DirectMember || IndirectMember) &&
2689         "Member must be a FieldDecl or IndirectFieldDecl");
2690
2691  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2692    return true;
2693
2694  if (Member->isInvalidDecl())
2695    return true;
2696
2697  MultiExprArg Args;
2698  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2699    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2700  } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2701    Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
2702  } else {
2703    // Template instantiation doesn't reconstruct ParenListExprs for us.
2704    Args = Init;
2705  }
2706
2707  SourceRange InitRange = Init->getSourceRange();
2708
2709  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2710    // Can't check initialization for a member of dependent type or when
2711    // any of the arguments are type-dependent expressions.
2712    DiscardCleanupsInEvaluationContext();
2713  } else {
2714    bool InitList = false;
2715    if (isa<InitListExpr>(Init)) {
2716      InitList = true;
2717      Args = Init;
2718    }
2719
2720    // Initialize the member.
2721    InitializedEntity MemberEntity =
2722      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2723                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2724    InitializationKind Kind =
2725      InitList ? InitializationKind::CreateDirectList(IdLoc)
2726               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2727                                                  InitRange.getEnd());
2728
2729    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
2730    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 0);
2731    if (MemberInit.isInvalid())
2732      return true;
2733
2734    CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
2735
2736    // C++11 [class.base.init]p7:
2737    //   The initialization of each base and member constitutes a
2738    //   full-expression.
2739    MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
2740    if (MemberInit.isInvalid())
2741      return true;
2742
2743    Init = MemberInit.get();
2744  }
2745
2746  if (DirectMember) {
2747    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2748                                            InitRange.getBegin(), Init,
2749                                            InitRange.getEnd());
2750  } else {
2751    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2752                                            InitRange.getBegin(), Init,
2753                                            InitRange.getEnd());
2754  }
2755}
2756
2757MemInitResult
2758Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2759                                 CXXRecordDecl *ClassDecl) {
2760  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2761  if (!LangOpts.CPlusPlus11)
2762    return Diag(NameLoc, diag::err_delegating_ctor)
2763      << TInfo->getTypeLoc().getLocalSourceRange();
2764  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2765
2766  bool InitList = true;
2767  MultiExprArg Args = Init;
2768  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2769    InitList = false;
2770    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2771  }
2772
2773  SourceRange InitRange = Init->getSourceRange();
2774  // Initialize the object.
2775  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2776                                     QualType(ClassDecl->getTypeForDecl(), 0));
2777  InitializationKind Kind =
2778    InitList ? InitializationKind::CreateDirectList(NameLoc)
2779             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2780                                                InitRange.getEnd());
2781  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
2782  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2783                                              Args, 0);
2784  if (DelegationInit.isInvalid())
2785    return true;
2786
2787  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2788         "Delegating constructor with no target?");
2789
2790  // C++11 [class.base.init]p7:
2791  //   The initialization of each base and member constitutes a
2792  //   full-expression.
2793  DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
2794                                       InitRange.getBegin());
2795  if (DelegationInit.isInvalid())
2796    return true;
2797
2798  // If we are in a dependent context, template instantiation will
2799  // perform this type-checking again. Just save the arguments that we
2800  // received in a ParenListExpr.
2801  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2802  // of the information that we have about the base
2803  // initializer. However, deconstructing the ASTs is a dicey process,
2804  // and this approach is far more likely to get the corner cases right.
2805  if (CurContext->isDependentContext())
2806    DelegationInit = Owned(Init);
2807
2808  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2809                                          DelegationInit.takeAs<Expr>(),
2810                                          InitRange.getEnd());
2811}
2812
2813MemInitResult
2814Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2815                           Expr *Init, CXXRecordDecl *ClassDecl,
2816                           SourceLocation EllipsisLoc) {
2817  SourceLocation BaseLoc
2818    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2819
2820  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2821    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2822             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2823
2824  // C++ [class.base.init]p2:
2825  //   [...] Unless the mem-initializer-id names a nonstatic data
2826  //   member of the constructor's class or a direct or virtual base
2827  //   of that class, the mem-initializer is ill-formed. A
2828  //   mem-initializer-list can initialize a base class using any
2829  //   name that denotes that base class type.
2830  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2831
2832  SourceRange InitRange = Init->getSourceRange();
2833  if (EllipsisLoc.isValid()) {
2834    // This is a pack expansion.
2835    if (!BaseType->containsUnexpandedParameterPack())  {
2836      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2837        << SourceRange(BaseLoc, InitRange.getEnd());
2838
2839      EllipsisLoc = SourceLocation();
2840    }
2841  } else {
2842    // Check for any unexpanded parameter packs.
2843    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2844      return true;
2845
2846    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2847      return true;
2848  }
2849
2850  // Check for direct and virtual base classes.
2851  const CXXBaseSpecifier *DirectBaseSpec = 0;
2852  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2853  if (!Dependent) {
2854    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2855                                       BaseType))
2856      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2857
2858    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2859                        VirtualBaseSpec);
2860
2861    // C++ [base.class.init]p2:
2862    // Unless the mem-initializer-id names a nonstatic data member of the
2863    // constructor's class or a direct or virtual base of that class, the
2864    // mem-initializer is ill-formed.
2865    if (!DirectBaseSpec && !VirtualBaseSpec) {
2866      // If the class has any dependent bases, then it's possible that
2867      // one of those types will resolve to the same type as
2868      // BaseType. Therefore, just treat this as a dependent base
2869      // class initialization.  FIXME: Should we try to check the
2870      // initialization anyway? It seems odd.
2871      if (ClassDecl->hasAnyDependentBases())
2872        Dependent = true;
2873      else
2874        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2875          << BaseType << Context.getTypeDeclType(ClassDecl)
2876          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2877    }
2878  }
2879
2880  if (Dependent) {
2881    DiscardCleanupsInEvaluationContext();
2882
2883    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2884                                            /*IsVirtual=*/false,
2885                                            InitRange.getBegin(), Init,
2886                                            InitRange.getEnd(), EllipsisLoc);
2887  }
2888
2889  // C++ [base.class.init]p2:
2890  //   If a mem-initializer-id is ambiguous because it designates both
2891  //   a direct non-virtual base class and an inherited virtual base
2892  //   class, the mem-initializer is ill-formed.
2893  if (DirectBaseSpec && VirtualBaseSpec)
2894    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2895      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2896
2897  const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
2898  if (!BaseSpec)
2899    BaseSpec = VirtualBaseSpec;
2900
2901  // Initialize the base.
2902  bool InitList = true;
2903  MultiExprArg Args = Init;
2904  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2905    InitList = false;
2906    Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
2907  }
2908
2909  InitializedEntity BaseEntity =
2910    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2911  InitializationKind Kind =
2912    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2913             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2914                                                InitRange.getEnd());
2915  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
2916  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, 0);
2917  if (BaseInit.isInvalid())
2918    return true;
2919
2920  // C++11 [class.base.init]p7:
2921  //   The initialization of each base and member constitutes a
2922  //   full-expression.
2923  BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
2924  if (BaseInit.isInvalid())
2925    return true;
2926
2927  // If we are in a dependent context, template instantiation will
2928  // perform this type-checking again. Just save the arguments that we
2929  // received in a ParenListExpr.
2930  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2931  // of the information that we have about the base
2932  // initializer. However, deconstructing the ASTs is a dicey process,
2933  // and this approach is far more likely to get the corner cases right.
2934  if (CurContext->isDependentContext())
2935    BaseInit = Owned(Init);
2936
2937  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2938                                          BaseSpec->isVirtual(),
2939                                          InitRange.getBegin(),
2940                                          BaseInit.takeAs<Expr>(),
2941                                          InitRange.getEnd(), EllipsisLoc);
2942}
2943
2944// Create a static_cast\<T&&>(expr).
2945static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
2946  if (T.isNull()) T = E->getType();
2947  QualType TargetType = SemaRef.BuildReferenceType(
2948      T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
2949  SourceLocation ExprLoc = E->getLocStart();
2950  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2951      TargetType, ExprLoc);
2952
2953  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2954                                   SourceRange(ExprLoc, ExprLoc),
2955                                   E->getSourceRange()).take();
2956}
2957
2958/// ImplicitInitializerKind - How an implicit base or member initializer should
2959/// initialize its base or member.
2960enum ImplicitInitializerKind {
2961  IIK_Default,
2962  IIK_Copy,
2963  IIK_Move,
2964  IIK_Inherit
2965};
2966
2967static bool
2968BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2969                             ImplicitInitializerKind ImplicitInitKind,
2970                             CXXBaseSpecifier *BaseSpec,
2971                             bool IsInheritedVirtualBase,
2972                             CXXCtorInitializer *&CXXBaseInit) {
2973  InitializedEntity InitEntity
2974    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2975                                        IsInheritedVirtualBase);
2976
2977  ExprResult BaseInit;
2978
2979  switch (ImplicitInitKind) {
2980  case IIK_Inherit: {
2981    const CXXRecordDecl *Inherited =
2982        Constructor->getInheritedConstructor()->getParent();
2983    const CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
2984    if (Base && Inherited->getCanonicalDecl() == Base->getCanonicalDecl()) {
2985      // C++11 [class.inhctor]p8:
2986      //   Each expression in the expression-list is of the form
2987      //   static_cast<T&&>(p), where p is the name of the corresponding
2988      //   constructor parameter and T is the declared type of p.
2989      SmallVector<Expr*, 16> Args;
2990      for (unsigned I = 0, E = Constructor->getNumParams(); I != E; ++I) {
2991        ParmVarDecl *PD = Constructor->getParamDecl(I);
2992        ExprResult ArgExpr =
2993            SemaRef.BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
2994                                     VK_LValue, SourceLocation());
2995        if (ArgExpr.isInvalid())
2996          return true;
2997        Args.push_back(CastForMoving(SemaRef, ArgExpr.take(), PD->getType()));
2998      }
2999
3000      InitializationKind InitKind = InitializationKind::CreateDirect(
3001          Constructor->getLocation(), SourceLocation(), SourceLocation());
3002      InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, Args);
3003      BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, Args);
3004      break;
3005    }
3006  }
3007  // Fall through.
3008  case IIK_Default: {
3009    InitializationKind InitKind
3010      = InitializationKind::CreateDefault(Constructor->getLocation());
3011    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3012    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3013    break;
3014  }
3015
3016  case IIK_Move:
3017  case IIK_Copy: {
3018    bool Moving = ImplicitInitKind == IIK_Move;
3019    ParmVarDecl *Param = Constructor->getParamDecl(0);
3020    QualType ParamType = Param->getType().getNonReferenceType();
3021
3022    Expr *CopyCtorArg =
3023      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3024                          SourceLocation(), Param, false,
3025                          Constructor->getLocation(), ParamType,
3026                          VK_LValue, 0);
3027
3028    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
3029
3030    // Cast to the base class to avoid ambiguities.
3031    QualType ArgTy =
3032      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
3033                                       ParamType.getQualifiers());
3034
3035    if (Moving) {
3036      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
3037    }
3038
3039    CXXCastPath BasePath;
3040    BasePath.push_back(BaseSpec);
3041    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
3042                                            CK_UncheckedDerivedToBase,
3043                                            Moving ? VK_XValue : VK_LValue,
3044                                            &BasePath).take();
3045
3046    InitializationKind InitKind
3047      = InitializationKind::CreateDirect(Constructor->getLocation(),
3048                                         SourceLocation(), SourceLocation());
3049    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
3050    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
3051    break;
3052  }
3053  }
3054
3055  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
3056  if (BaseInit.isInvalid())
3057    return true;
3058
3059  CXXBaseInit =
3060    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3061               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
3062                                                        SourceLocation()),
3063                                             BaseSpec->isVirtual(),
3064                                             SourceLocation(),
3065                                             BaseInit.takeAs<Expr>(),
3066                                             SourceLocation(),
3067                                             SourceLocation());
3068
3069  return false;
3070}
3071
3072static bool RefersToRValueRef(Expr *MemRef) {
3073  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
3074  return Referenced->getType()->isRValueReferenceType();
3075}
3076
3077static bool
3078BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
3079                               ImplicitInitializerKind ImplicitInitKind,
3080                               FieldDecl *Field, IndirectFieldDecl *Indirect,
3081                               CXXCtorInitializer *&CXXMemberInit) {
3082  if (Field->isInvalidDecl())
3083    return true;
3084
3085  SourceLocation Loc = Constructor->getLocation();
3086
3087  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
3088    bool Moving = ImplicitInitKind == IIK_Move;
3089    ParmVarDecl *Param = Constructor->getParamDecl(0);
3090    QualType ParamType = Param->getType().getNonReferenceType();
3091
3092    // Suppress copying zero-width bitfields.
3093    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
3094      return false;
3095
3096    Expr *MemberExprBase =
3097      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
3098                          SourceLocation(), Param, false,
3099                          Loc, ParamType, VK_LValue, 0);
3100
3101    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
3102
3103    if (Moving) {
3104      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
3105    }
3106
3107    // Build a reference to this field within the parameter.
3108    CXXScopeSpec SS;
3109    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
3110                              Sema::LookupMemberName);
3111    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
3112                                  : cast<ValueDecl>(Field), AS_public);
3113    MemberLookup.resolveKind();
3114    ExprResult CtorArg
3115      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
3116                                         ParamType, Loc,
3117                                         /*IsArrow=*/false,
3118                                         SS,
3119                                         /*TemplateKWLoc=*/SourceLocation(),
3120                                         /*FirstQualifierInScope=*/0,
3121                                         MemberLookup,
3122                                         /*TemplateArgs=*/0);
3123    if (CtorArg.isInvalid())
3124      return true;
3125
3126    // C++11 [class.copy]p15:
3127    //   - if a member m has rvalue reference type T&&, it is direct-initialized
3128    //     with static_cast<T&&>(x.m);
3129    if (RefersToRValueRef(CtorArg.get())) {
3130      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3131    }
3132
3133    // When the field we are copying is an array, create index variables for
3134    // each dimension of the array. We use these index variables to subscript
3135    // the source array, and other clients (e.g., CodeGen) will perform the
3136    // necessary iteration with these index variables.
3137    SmallVector<VarDecl *, 4> IndexVariables;
3138    QualType BaseType = Field->getType();
3139    QualType SizeType = SemaRef.Context.getSizeType();
3140    bool InitializingArray = false;
3141    while (const ConstantArrayType *Array
3142                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
3143      InitializingArray = true;
3144      // Create the iteration variable for this array index.
3145      IdentifierInfo *IterationVarName = 0;
3146      {
3147        SmallString<8> Str;
3148        llvm::raw_svector_ostream OS(Str);
3149        OS << "__i" << IndexVariables.size();
3150        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
3151      }
3152      VarDecl *IterationVar
3153        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
3154                          IterationVarName, SizeType,
3155                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
3156                          SC_None);
3157      IndexVariables.push_back(IterationVar);
3158
3159      // Create a reference to the iteration variable.
3160      ExprResult IterationVarRef
3161        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
3162      assert(!IterationVarRef.isInvalid() &&
3163             "Reference to invented variable cannot fail!");
3164      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
3165      assert(!IterationVarRef.isInvalid() &&
3166             "Conversion of invented variable cannot fail!");
3167
3168      // Subscript the array with this iteration variable.
3169      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
3170                                                        IterationVarRef.take(),
3171                                                        Loc);
3172      if (CtorArg.isInvalid())
3173        return true;
3174
3175      BaseType = Array->getElementType();
3176    }
3177
3178    // The array subscript expression is an lvalue, which is wrong for moving.
3179    if (Moving && InitializingArray)
3180      CtorArg = CastForMoving(SemaRef, CtorArg.take());
3181
3182    // Construct the entity that we will be initializing. For an array, this
3183    // will be first element in the array, which may require several levels
3184    // of array-subscript entities.
3185    SmallVector<InitializedEntity, 4> Entities;
3186    Entities.reserve(1 + IndexVariables.size());
3187    if (Indirect)
3188      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
3189    else
3190      Entities.push_back(InitializedEntity::InitializeMember(Field));
3191    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
3192      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
3193                                                              0,
3194                                                              Entities.back()));
3195
3196    // Direct-initialize to use the copy constructor.
3197    InitializationKind InitKind =
3198      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
3199
3200    Expr *CtorArgE = CtorArg.takeAs<Expr>();
3201    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind, CtorArgE);
3202
3203    ExprResult MemberInit
3204      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
3205                        MultiExprArg(&CtorArgE, 1));
3206    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3207    if (MemberInit.isInvalid())
3208      return true;
3209
3210    if (Indirect) {
3211      assert(IndexVariables.size() == 0 &&
3212             "Indirect field improperly initialized");
3213      CXXMemberInit
3214        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3215                                                   Loc, Loc,
3216                                                   MemberInit.takeAs<Expr>(),
3217                                                   Loc);
3218    } else
3219      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
3220                                                 Loc, MemberInit.takeAs<Expr>(),
3221                                                 Loc,
3222                                                 IndexVariables.data(),
3223                                                 IndexVariables.size());
3224    return false;
3225  }
3226
3227  assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
3228         "Unhandled implicit init kind!");
3229
3230  QualType FieldBaseElementType =
3231    SemaRef.Context.getBaseElementType(Field->getType());
3232
3233  if (FieldBaseElementType->isRecordType()) {
3234    InitializedEntity InitEntity
3235      = Indirect? InitializedEntity::InitializeMember(Indirect)
3236                : InitializedEntity::InitializeMember(Field);
3237    InitializationKind InitKind =
3238      InitializationKind::CreateDefault(Loc);
3239
3240    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
3241    ExprResult MemberInit =
3242      InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
3243
3244    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
3245    if (MemberInit.isInvalid())
3246      return true;
3247
3248    if (Indirect)
3249      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3250                                                               Indirect, Loc,
3251                                                               Loc,
3252                                                               MemberInit.get(),
3253                                                               Loc);
3254    else
3255      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
3256                                                               Field, Loc, Loc,
3257                                                               MemberInit.get(),
3258                                                               Loc);
3259    return false;
3260  }
3261
3262  if (!Field->getParent()->isUnion()) {
3263    if (FieldBaseElementType->isReferenceType()) {
3264      SemaRef.Diag(Constructor->getLocation(),
3265                   diag::err_uninitialized_member_in_ctor)
3266      << (int)Constructor->isImplicit()
3267      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3268      << 0 << Field->getDeclName();
3269      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3270      return true;
3271    }
3272
3273    if (FieldBaseElementType.isConstQualified()) {
3274      SemaRef.Diag(Constructor->getLocation(),
3275                   diag::err_uninitialized_member_in_ctor)
3276      << (int)Constructor->isImplicit()
3277      << SemaRef.Context.getTagDeclType(Constructor->getParent())
3278      << 1 << Field->getDeclName();
3279      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
3280      return true;
3281    }
3282  }
3283
3284  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
3285      FieldBaseElementType->isObjCRetainableType() &&
3286      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
3287      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
3288    // ARC:
3289    //   Default-initialize Objective-C pointers to NULL.
3290    CXXMemberInit
3291      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3292                                                 Loc, Loc,
3293                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
3294                                                 Loc);
3295    return false;
3296  }
3297
3298  // Nothing to initialize.
3299  CXXMemberInit = 0;
3300  return false;
3301}
3302
3303namespace {
3304struct BaseAndFieldInfo {
3305  Sema &S;
3306  CXXConstructorDecl *Ctor;
3307  bool AnyErrorsInInits;
3308  ImplicitInitializerKind IIK;
3309  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
3310  SmallVector<CXXCtorInitializer*, 8> AllToInit;
3311
3312  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
3313    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
3314    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
3315    if (Generated && Ctor->isCopyConstructor())
3316      IIK = IIK_Copy;
3317    else if (Generated && Ctor->isMoveConstructor())
3318      IIK = IIK_Move;
3319    else if (Ctor->getInheritedConstructor())
3320      IIK = IIK_Inherit;
3321    else
3322      IIK = IIK_Default;
3323  }
3324
3325  bool isImplicitCopyOrMove() const {
3326    switch (IIK) {
3327    case IIK_Copy:
3328    case IIK_Move:
3329      return true;
3330
3331    case IIK_Default:
3332    case IIK_Inherit:
3333      return false;
3334    }
3335
3336    llvm_unreachable("Invalid ImplicitInitializerKind!");
3337  }
3338
3339  bool addFieldInitializer(CXXCtorInitializer *Init) {
3340    AllToInit.push_back(Init);
3341
3342    // Check whether this initializer makes the field "used".
3343    if (Init->getInit()->HasSideEffects(S.Context))
3344      S.UnusedPrivateFields.remove(Init->getAnyMember());
3345
3346    return false;
3347  }
3348};
3349}
3350
3351/// \brief Determine whether the given indirect field declaration is somewhere
3352/// within an anonymous union.
3353static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
3354  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
3355                                      CEnd = F->chain_end();
3356       C != CEnd; ++C)
3357    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
3358      if (Record->isUnion())
3359        return true;
3360
3361  return false;
3362}
3363
3364/// \brief Determine whether the given type is an incomplete or zero-lenfgth
3365/// array type.
3366static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
3367  if (T->isIncompleteArrayType())
3368    return true;
3369
3370  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
3371    if (!ArrayT->getSize())
3372      return true;
3373
3374    T = ArrayT->getElementType();
3375  }
3376
3377  return false;
3378}
3379
3380static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
3381                                    FieldDecl *Field,
3382                                    IndirectFieldDecl *Indirect = 0) {
3383  if (Field->isInvalidDecl())
3384    return false;
3385
3386  // Overwhelmingly common case: we have a direct initializer for this field.
3387  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field))
3388    return Info.addFieldInitializer(Init);
3389
3390  // C++11 [class.base.init]p8: if the entity is a non-static data member that
3391  // has a brace-or-equal-initializer, the entity is initialized as specified
3392  // in [dcl.init].
3393  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
3394    Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
3395                                           Info.Ctor->getLocation(), Field);
3396    CXXCtorInitializer *Init;
3397    if (Indirect)
3398      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
3399                                                      SourceLocation(),
3400                                                      SourceLocation(), DIE,
3401                                                      SourceLocation());
3402    else
3403      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
3404                                                      SourceLocation(),
3405                                                      SourceLocation(), DIE,
3406                                                      SourceLocation());
3407    return Info.addFieldInitializer(Init);
3408  }
3409
3410  // Don't build an implicit initializer for union members if none was
3411  // explicitly specified.
3412  if (Field->getParent()->isUnion() ||
3413      (Indirect && isWithinAnonymousUnion(Indirect)))
3414    return false;
3415
3416  // Don't initialize incomplete or zero-length arrays.
3417  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
3418    return false;
3419
3420  // Don't try to build an implicit initializer if there were semantic
3421  // errors in any of the initializers (and therefore we might be
3422  // missing some that the user actually wrote).
3423  if (Info.AnyErrorsInInits)
3424    return false;
3425
3426  CXXCtorInitializer *Init = 0;
3427  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
3428                                     Indirect, Init))
3429    return true;
3430
3431  if (!Init)
3432    return false;
3433
3434  return Info.addFieldInitializer(Init);
3435}
3436
3437bool
3438Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
3439                               CXXCtorInitializer *Initializer) {
3440  assert(Initializer->isDelegatingInitializer());
3441  Constructor->setNumCtorInitializers(1);
3442  CXXCtorInitializer **initializer =
3443    new (Context) CXXCtorInitializer*[1];
3444  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
3445  Constructor->setCtorInitializers(initializer);
3446
3447  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
3448    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
3449    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
3450  }
3451
3452  DelegatingCtorDecls.push_back(Constructor);
3453
3454  return false;
3455}
3456
3457bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
3458                               ArrayRef<CXXCtorInitializer *> Initializers) {
3459  if (Constructor->isDependentContext()) {
3460    // Just store the initializers as written, they will be checked during
3461    // instantiation.
3462    if (!Initializers.empty()) {
3463      Constructor->setNumCtorInitializers(Initializers.size());
3464      CXXCtorInitializer **baseOrMemberInitializers =
3465        new (Context) CXXCtorInitializer*[Initializers.size()];
3466      memcpy(baseOrMemberInitializers, Initializers.data(),
3467             Initializers.size() * sizeof(CXXCtorInitializer*));
3468      Constructor->setCtorInitializers(baseOrMemberInitializers);
3469    }
3470
3471    // Let template instantiation know whether we had errors.
3472    if (AnyErrors)
3473      Constructor->setInvalidDecl();
3474
3475    return false;
3476  }
3477
3478  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
3479
3480  // We need to build the initializer AST according to order of construction
3481  // and not what user specified in the Initializers list.
3482  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
3483  if (!ClassDecl)
3484    return true;
3485
3486  bool HadError = false;
3487
3488  for (unsigned i = 0; i < Initializers.size(); i++) {
3489    CXXCtorInitializer *Member = Initializers[i];
3490
3491    if (Member->isBaseInitializer())
3492      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
3493    else
3494      Info.AllBaseFields[Member->getAnyMember()] = Member;
3495  }
3496
3497  // Keep track of the direct virtual bases.
3498  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
3499  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
3500       E = ClassDecl->bases_end(); I != E; ++I) {
3501    if (I->isVirtual())
3502      DirectVBases.insert(I);
3503  }
3504
3505  // Push virtual bases before others.
3506  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3507       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3508
3509    if (CXXCtorInitializer *Value
3510        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
3511      // [class.base.init]p7, per DR257:
3512      //   A mem-initializer where the mem-initializer-id names a virtual base
3513      //   class is ignored during execution of a constructor of any class that
3514      //   is not the most derived class.
3515      if (ClassDecl->isAbstract()) {
3516        // FIXME: Provide a fixit to remove the base specifier. This requires
3517        // tracking the location of the associated comma for a base specifier.
3518        Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
3519          << VBase->getType() << ClassDecl;
3520        DiagnoseAbstractType(ClassDecl);
3521      }
3522
3523      Info.AllToInit.push_back(Value);
3524    } else if (!AnyErrors && !ClassDecl->isAbstract()) {
3525      // [class.base.init]p8, per DR257:
3526      //   If a given [...] base class is not named by a mem-initializer-id
3527      //   [...] and the entity is not a virtual base class of an abstract
3528      //   class, then [...] the entity is default-initialized.
3529      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
3530      CXXCtorInitializer *CXXBaseInit;
3531      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3532                                       VBase, IsInheritedVirtualBase,
3533                                       CXXBaseInit)) {
3534        HadError = true;
3535        continue;
3536      }
3537
3538      Info.AllToInit.push_back(CXXBaseInit);
3539    }
3540  }
3541
3542  // Non-virtual bases.
3543  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3544       E = ClassDecl->bases_end(); Base != E; ++Base) {
3545    // Virtuals are in the virtual base list and already constructed.
3546    if (Base->isVirtual())
3547      continue;
3548
3549    if (CXXCtorInitializer *Value
3550          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
3551      Info.AllToInit.push_back(Value);
3552    } else if (!AnyErrors) {
3553      CXXCtorInitializer *CXXBaseInit;
3554      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
3555                                       Base, /*IsInheritedVirtualBase=*/false,
3556                                       CXXBaseInit)) {
3557        HadError = true;
3558        continue;
3559      }
3560
3561      Info.AllToInit.push_back(CXXBaseInit);
3562    }
3563  }
3564
3565  // Fields.
3566  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
3567                               MemEnd = ClassDecl->decls_end();
3568       Mem != MemEnd; ++Mem) {
3569    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
3570      // C++ [class.bit]p2:
3571      //   A declaration for a bit-field that omits the identifier declares an
3572      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
3573      //   initialized.
3574      if (F->isUnnamedBitfield())
3575        continue;
3576
3577      // If we're not generating the implicit copy/move constructor, then we'll
3578      // handle anonymous struct/union fields based on their individual
3579      // indirect fields.
3580      if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
3581        continue;
3582
3583      if (CollectFieldInitializer(*this, Info, F))
3584        HadError = true;
3585      continue;
3586    }
3587
3588    // Beyond this point, we only consider default initialization.
3589    if (Info.isImplicitCopyOrMove())
3590      continue;
3591
3592    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
3593      if (F->getType()->isIncompleteArrayType()) {
3594        assert(ClassDecl->hasFlexibleArrayMember() &&
3595               "Incomplete array type is not valid");
3596        continue;
3597      }
3598
3599      // Initialize each field of an anonymous struct individually.
3600      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
3601        HadError = true;
3602
3603      continue;
3604    }
3605  }
3606
3607  unsigned NumInitializers = Info.AllToInit.size();
3608  if (NumInitializers > 0) {
3609    Constructor->setNumCtorInitializers(NumInitializers);
3610    CXXCtorInitializer **baseOrMemberInitializers =
3611      new (Context) CXXCtorInitializer*[NumInitializers];
3612    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
3613           NumInitializers * sizeof(CXXCtorInitializer*));
3614    Constructor->setCtorInitializers(baseOrMemberInitializers);
3615
3616    // Constructors implicitly reference the base and member
3617    // destructors.
3618    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
3619                                           Constructor->getParent());
3620  }
3621
3622  return HadError;
3623}
3624
3625static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
3626  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3627    const RecordDecl *RD = RT->getDecl();
3628    if (RD->isAnonymousStructOrUnion()) {
3629      for (RecordDecl::field_iterator Field = RD->field_begin(),
3630          E = RD->field_end(); Field != E; ++Field)
3631        PopulateKeysForFields(*Field, IdealInits);
3632      return;
3633    }
3634  }
3635  IdealInits.push_back(Field);
3636}
3637
3638static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3639  return Context.getCanonicalType(BaseType).getTypePtr();
3640}
3641
3642static const void *GetKeyForMember(ASTContext &Context,
3643                                   CXXCtorInitializer *Member) {
3644  if (!Member->isAnyMemberInitializer())
3645    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3646
3647  return Member->getAnyMember();
3648}
3649
3650static void DiagnoseBaseOrMemInitializerOrder(
3651    Sema &SemaRef, const CXXConstructorDecl *Constructor,
3652    ArrayRef<CXXCtorInitializer *> Inits) {
3653  if (Constructor->getDeclContext()->isDependentContext())
3654    return;
3655
3656  // Don't check initializers order unless the warning is enabled at the
3657  // location of at least one initializer.
3658  bool ShouldCheckOrder = false;
3659  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3660    CXXCtorInitializer *Init = Inits[InitIndex];
3661    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3662                                         Init->getSourceLocation())
3663          != DiagnosticsEngine::Ignored) {
3664      ShouldCheckOrder = true;
3665      break;
3666    }
3667  }
3668  if (!ShouldCheckOrder)
3669    return;
3670
3671  // Build the list of bases and members in the order that they'll
3672  // actually be initialized.  The explicit initializers should be in
3673  // this same order but may be missing things.
3674  SmallVector<const void*, 32> IdealInitKeys;
3675
3676  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3677
3678  // 1. Virtual bases.
3679  for (CXXRecordDecl::base_class_const_iterator VBase =
3680       ClassDecl->vbases_begin(),
3681       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3682    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3683
3684  // 2. Non-virtual bases.
3685  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3686       E = ClassDecl->bases_end(); Base != E; ++Base) {
3687    if (Base->isVirtual())
3688      continue;
3689    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3690  }
3691
3692  // 3. Direct fields.
3693  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3694       E = ClassDecl->field_end(); Field != E; ++Field) {
3695    if (Field->isUnnamedBitfield())
3696      continue;
3697
3698    PopulateKeysForFields(*Field, IdealInitKeys);
3699  }
3700
3701  unsigned NumIdealInits = IdealInitKeys.size();
3702  unsigned IdealIndex = 0;
3703
3704  CXXCtorInitializer *PrevInit = 0;
3705  for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
3706    CXXCtorInitializer *Init = Inits[InitIndex];
3707    const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3708
3709    // Scan forward to try to find this initializer in the idealized
3710    // initializers list.
3711    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3712      if (InitKey == IdealInitKeys[IdealIndex])
3713        break;
3714
3715    // If we didn't find this initializer, it must be because we
3716    // scanned past it on a previous iteration.  That can only
3717    // happen if we're out of order;  emit a warning.
3718    if (IdealIndex == NumIdealInits && PrevInit) {
3719      Sema::SemaDiagnosticBuilder D =
3720        SemaRef.Diag(PrevInit->getSourceLocation(),
3721                     diag::warn_initializer_out_of_order);
3722
3723      if (PrevInit->isAnyMemberInitializer())
3724        D << 0 << PrevInit->getAnyMember()->getDeclName();
3725      else
3726        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3727
3728      if (Init->isAnyMemberInitializer())
3729        D << 0 << Init->getAnyMember()->getDeclName();
3730      else
3731        D << 1 << Init->getTypeSourceInfo()->getType();
3732
3733      // Move back to the initializer's location in the ideal list.
3734      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3735        if (InitKey == IdealInitKeys[IdealIndex])
3736          break;
3737
3738      assert(IdealIndex != NumIdealInits &&
3739             "initializer not found in initializer list");
3740    }
3741
3742    PrevInit = Init;
3743  }
3744}
3745
3746namespace {
3747bool CheckRedundantInit(Sema &S,
3748                        CXXCtorInitializer *Init,
3749                        CXXCtorInitializer *&PrevInit) {
3750  if (!PrevInit) {
3751    PrevInit = Init;
3752    return false;
3753  }
3754
3755  if (FieldDecl *Field = Init->getAnyMember())
3756    S.Diag(Init->getSourceLocation(),
3757           diag::err_multiple_mem_initialization)
3758      << Field->getDeclName()
3759      << Init->getSourceRange();
3760  else {
3761    const Type *BaseClass = Init->getBaseClass();
3762    assert(BaseClass && "neither field nor base");
3763    S.Diag(Init->getSourceLocation(),
3764           diag::err_multiple_base_initialization)
3765      << QualType(BaseClass, 0)
3766      << Init->getSourceRange();
3767  }
3768  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3769    << 0 << PrevInit->getSourceRange();
3770
3771  return true;
3772}
3773
3774typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3775typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3776
3777bool CheckRedundantUnionInit(Sema &S,
3778                             CXXCtorInitializer *Init,
3779                             RedundantUnionMap &Unions) {
3780  FieldDecl *Field = Init->getAnyMember();
3781  RecordDecl *Parent = Field->getParent();
3782  NamedDecl *Child = Field;
3783
3784  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3785    if (Parent->isUnion()) {
3786      UnionEntry &En = Unions[Parent];
3787      if (En.first && En.first != Child) {
3788        S.Diag(Init->getSourceLocation(),
3789               diag::err_multiple_mem_union_initialization)
3790          << Field->getDeclName()
3791          << Init->getSourceRange();
3792        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3793          << 0 << En.second->getSourceRange();
3794        return true;
3795      }
3796      if (!En.first) {
3797        En.first = Child;
3798        En.second = Init;
3799      }
3800      if (!Parent->isAnonymousStructOrUnion())
3801        return false;
3802    }
3803
3804    Child = Parent;
3805    Parent = cast<RecordDecl>(Parent->getDeclContext());
3806  }
3807
3808  return false;
3809}
3810}
3811
3812/// ActOnMemInitializers - Handle the member initializers for a constructor.
3813void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3814                                SourceLocation ColonLoc,
3815                                ArrayRef<CXXCtorInitializer*> MemInits,
3816                                bool AnyErrors) {
3817  if (!ConstructorDecl)
3818    return;
3819
3820  AdjustDeclIfTemplate(ConstructorDecl);
3821
3822  CXXConstructorDecl *Constructor
3823    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3824
3825  if (!Constructor) {
3826    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3827    return;
3828  }
3829
3830  // Mapping for the duplicate initializers check.
3831  // For member initializers, this is keyed with a FieldDecl*.
3832  // For base initializers, this is keyed with a Type*.
3833  llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
3834
3835  // Mapping for the inconsistent anonymous-union initializers check.
3836  RedundantUnionMap MemberUnions;
3837
3838  bool HadError = false;
3839  for (unsigned i = 0; i < MemInits.size(); i++) {
3840    CXXCtorInitializer *Init = MemInits[i];
3841
3842    // Set the source order index.
3843    Init->setSourceOrder(i);
3844
3845    if (Init->isAnyMemberInitializer()) {
3846      FieldDecl *Field = Init->getAnyMember();
3847      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3848          CheckRedundantUnionInit(*this, Init, MemberUnions))
3849        HadError = true;
3850    } else if (Init->isBaseInitializer()) {
3851      const void *Key =
3852          GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3853      if (CheckRedundantInit(*this, Init, Members[Key]))
3854        HadError = true;
3855    } else {
3856      assert(Init->isDelegatingInitializer());
3857      // This must be the only initializer
3858      if (MemInits.size() != 1) {
3859        Diag(Init->getSourceLocation(),
3860             diag::err_delegating_initializer_alone)
3861          << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
3862        // We will treat this as being the only initializer.
3863      }
3864      SetDelegatingInitializer(Constructor, MemInits[i]);
3865      // Return immediately as the initializer is set.
3866      return;
3867    }
3868  }
3869
3870  if (HadError)
3871    return;
3872
3873  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
3874
3875  SetCtorInitializers(Constructor, AnyErrors, MemInits);
3876
3877  DiagnoseUninitializedFields(*this, Constructor);
3878}
3879
3880void
3881Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3882                                             CXXRecordDecl *ClassDecl) {
3883  // Ignore dependent contexts. Also ignore unions, since their members never
3884  // have destructors implicitly called.
3885  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3886    return;
3887
3888  // FIXME: all the access-control diagnostics are positioned on the
3889  // field/base declaration.  That's probably good; that said, the
3890  // user might reasonably want to know why the destructor is being
3891  // emitted, and we currently don't say.
3892
3893  // Non-static data members.
3894  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3895       E = ClassDecl->field_end(); I != E; ++I) {
3896    FieldDecl *Field = *I;
3897    if (Field->isInvalidDecl())
3898      continue;
3899
3900    // Don't destroy incomplete or zero-length arrays.
3901    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3902      continue;
3903
3904    QualType FieldType = Context.getBaseElementType(Field->getType());
3905
3906    const RecordType* RT = FieldType->getAs<RecordType>();
3907    if (!RT)
3908      continue;
3909
3910    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3911    if (FieldClassDecl->isInvalidDecl())
3912      continue;
3913    if (FieldClassDecl->hasIrrelevantDestructor())
3914      continue;
3915    // The destructor for an implicit anonymous union member is never invoked.
3916    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3917      continue;
3918
3919    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3920    assert(Dtor && "No dtor found for FieldClassDecl!");
3921    CheckDestructorAccess(Field->getLocation(), Dtor,
3922                          PDiag(diag::err_access_dtor_field)
3923                            << Field->getDeclName()
3924                            << FieldType);
3925
3926    MarkFunctionReferenced(Location, Dtor);
3927    DiagnoseUseOfDecl(Dtor, Location);
3928  }
3929
3930  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3931
3932  // Bases.
3933  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3934       E = ClassDecl->bases_end(); Base != E; ++Base) {
3935    // Bases are always records in a well-formed non-dependent class.
3936    const RecordType *RT = Base->getType()->getAs<RecordType>();
3937
3938    // Remember direct virtual bases.
3939    if (Base->isVirtual())
3940      DirectVirtualBases.insert(RT);
3941
3942    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3943    // If our base class is invalid, we probably can't get its dtor anyway.
3944    if (BaseClassDecl->isInvalidDecl())
3945      continue;
3946    if (BaseClassDecl->hasIrrelevantDestructor())
3947      continue;
3948
3949    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3950    assert(Dtor && "No dtor found for BaseClassDecl!");
3951
3952    // FIXME: caret should be on the start of the class name
3953    CheckDestructorAccess(Base->getLocStart(), Dtor,
3954                          PDiag(diag::err_access_dtor_base)
3955                            << Base->getType()
3956                            << Base->getSourceRange(),
3957                          Context.getTypeDeclType(ClassDecl));
3958
3959    MarkFunctionReferenced(Location, Dtor);
3960    DiagnoseUseOfDecl(Dtor, Location);
3961  }
3962
3963  // Virtual bases.
3964  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3965       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3966
3967    // Bases are always records in a well-formed non-dependent class.
3968    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3969
3970    // Ignore direct virtual bases.
3971    if (DirectVirtualBases.count(RT))
3972      continue;
3973
3974    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3975    // If our base class is invalid, we probably can't get its dtor anyway.
3976    if (BaseClassDecl->isInvalidDecl())
3977      continue;
3978    if (BaseClassDecl->hasIrrelevantDestructor())
3979      continue;
3980
3981    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3982    assert(Dtor && "No dtor found for BaseClassDecl!");
3983    if (CheckDestructorAccess(
3984            ClassDecl->getLocation(), Dtor,
3985            PDiag(diag::err_access_dtor_vbase)
3986                << Context.getTypeDeclType(ClassDecl) << VBase->getType(),
3987            Context.getTypeDeclType(ClassDecl)) ==
3988        AR_accessible) {
3989      CheckDerivedToBaseConversion(
3990          Context.getTypeDeclType(ClassDecl), VBase->getType(),
3991          diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
3992          SourceRange(), DeclarationName(), 0);
3993    }
3994
3995    MarkFunctionReferenced(Location, Dtor);
3996    DiagnoseUseOfDecl(Dtor, Location);
3997  }
3998}
3999
4000void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
4001  if (!CDtorDecl)
4002    return;
4003
4004  if (CXXConstructorDecl *Constructor
4005      = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
4006    SetCtorInitializers(Constructor, /*AnyErrors=*/false);
4007    DiagnoseUninitializedFields(*this, Constructor);
4008  }
4009}
4010
4011bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4012                                  unsigned DiagID, AbstractDiagSelID SelID) {
4013  class NonAbstractTypeDiagnoser : public TypeDiagnoser {
4014    unsigned DiagID;
4015    AbstractDiagSelID SelID;
4016
4017  public:
4018    NonAbstractTypeDiagnoser(unsigned DiagID, AbstractDiagSelID SelID)
4019      : TypeDiagnoser(DiagID == 0), DiagID(DiagID), SelID(SelID) { }
4020
4021    void diagnose(Sema &S, SourceLocation Loc, QualType T) LLVM_OVERRIDE {
4022      if (Suppressed) return;
4023      if (SelID == -1)
4024        S.Diag(Loc, DiagID) << T;
4025      else
4026        S.Diag(Loc, DiagID) << SelID << T;
4027    }
4028  } Diagnoser(DiagID, SelID);
4029
4030  return RequireNonAbstractType(Loc, T, Diagnoser);
4031}
4032
4033bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
4034                                  TypeDiagnoser &Diagnoser) {
4035  if (!getLangOpts().CPlusPlus)
4036    return false;
4037
4038  if (const ArrayType *AT = Context.getAsArrayType(T))
4039    return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4040
4041  if (const PointerType *PT = T->getAs<PointerType>()) {
4042    // Find the innermost pointer type.
4043    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
4044      PT = T;
4045
4046    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
4047      return RequireNonAbstractType(Loc, AT->getElementType(), Diagnoser);
4048  }
4049
4050  const RecordType *RT = T->getAs<RecordType>();
4051  if (!RT)
4052    return false;
4053
4054  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4055
4056  // We can't answer whether something is abstract until it has a
4057  // definition.  If it's currently being defined, we'll walk back
4058  // over all the declarations when we have a full definition.
4059  const CXXRecordDecl *Def = RD->getDefinition();
4060  if (!Def || Def->isBeingDefined())
4061    return false;
4062
4063  if (!RD->isAbstract())
4064    return false;
4065
4066  Diagnoser.diagnose(*this, Loc, T);
4067  DiagnoseAbstractType(RD);
4068
4069  return true;
4070}
4071
4072void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
4073  // Check if we've already emitted the list of pure virtual functions
4074  // for this class.
4075  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
4076    return;
4077
4078  // If the diagnostic is suppressed, don't emit the notes. We're only
4079  // going to emit them once, so try to attach them to a diagnostic we're
4080  // actually going to show.
4081  if (Diags.isLastDiagnosticIgnored())
4082    return;
4083
4084  CXXFinalOverriderMap FinalOverriders;
4085  RD->getFinalOverriders(FinalOverriders);
4086
4087  // Keep a set of seen pure methods so we won't diagnose the same method
4088  // more than once.
4089  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
4090
4091  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
4092                                   MEnd = FinalOverriders.end();
4093       M != MEnd;
4094       ++M) {
4095    for (OverridingMethods::iterator SO = M->second.begin(),
4096                                  SOEnd = M->second.end();
4097         SO != SOEnd; ++SO) {
4098      // C++ [class.abstract]p4:
4099      //   A class is abstract if it contains or inherits at least one
4100      //   pure virtual function for which the final overrider is pure
4101      //   virtual.
4102
4103      //
4104      if (SO->second.size() != 1)
4105        continue;
4106
4107      if (!SO->second.front().Method->isPure())
4108        continue;
4109
4110      if (!SeenPureMethods.insert(SO->second.front().Method))
4111        continue;
4112
4113      Diag(SO->second.front().Method->getLocation(),
4114           diag::note_pure_virtual_function)
4115        << SO->second.front().Method->getDeclName() << RD->getDeclName();
4116    }
4117  }
4118
4119  if (!PureVirtualClassDiagSet)
4120    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
4121  PureVirtualClassDiagSet->insert(RD);
4122}
4123
4124namespace {
4125struct AbstractUsageInfo {
4126  Sema &S;
4127  CXXRecordDecl *Record;
4128  CanQualType AbstractType;
4129  bool Invalid;
4130
4131  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
4132    : S(S), Record(Record),
4133      AbstractType(S.Context.getCanonicalType(
4134                   S.Context.getTypeDeclType(Record))),
4135      Invalid(false) {}
4136
4137  void DiagnoseAbstractType() {
4138    if (Invalid) return;
4139    S.DiagnoseAbstractType(Record);
4140    Invalid = true;
4141  }
4142
4143  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
4144};
4145
4146struct CheckAbstractUsage {
4147  AbstractUsageInfo &Info;
4148  const NamedDecl *Ctx;
4149
4150  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
4151    : Info(Info), Ctx(Ctx) {}
4152
4153  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4154    switch (TL.getTypeLocClass()) {
4155#define ABSTRACT_TYPELOC(CLASS, PARENT)
4156#define TYPELOC(CLASS, PARENT) \
4157    case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
4158#include "clang/AST/TypeLocNodes.def"
4159    }
4160  }
4161
4162  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4163    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
4164    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4165      if (!TL.getArg(I))
4166        continue;
4167
4168      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
4169      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
4170    }
4171  }
4172
4173  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4174    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
4175  }
4176
4177  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
4178    // Visit the type parameters from a permissive context.
4179    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
4180      TemplateArgumentLoc TAL = TL.getArgLoc(I);
4181      if (TAL.getArgument().getKind() == TemplateArgument::Type)
4182        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
4183          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
4184      // TODO: other template argument types?
4185    }
4186  }
4187
4188  // Visit pointee types from a permissive context.
4189#define CheckPolymorphic(Type) \
4190  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
4191    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
4192  }
4193  CheckPolymorphic(PointerTypeLoc)
4194  CheckPolymorphic(ReferenceTypeLoc)
4195  CheckPolymorphic(MemberPointerTypeLoc)
4196  CheckPolymorphic(BlockPointerTypeLoc)
4197  CheckPolymorphic(AtomicTypeLoc)
4198
4199  /// Handle all the types we haven't given a more specific
4200  /// implementation for above.
4201  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
4202    // Every other kind of type that we haven't called out already
4203    // that has an inner type is either (1) sugar or (2) contains that
4204    // inner type in some way as a subobject.
4205    if (TypeLoc Next = TL.getNextTypeLoc())
4206      return Visit(Next, Sel);
4207
4208    // If there's no inner type and we're in a permissive context,
4209    // don't diagnose.
4210    if (Sel == Sema::AbstractNone) return;
4211
4212    // Check whether the type matches the abstract type.
4213    QualType T = TL.getType();
4214    if (T->isArrayType()) {
4215      Sel = Sema::AbstractArrayType;
4216      T = Info.S.Context.getBaseElementType(T);
4217    }
4218    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
4219    if (CT != Info.AbstractType) return;
4220
4221    // It matched; do some magic.
4222    if (Sel == Sema::AbstractArrayType) {
4223      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
4224        << T << TL.getSourceRange();
4225    } else {
4226      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
4227        << Sel << T << TL.getSourceRange();
4228    }
4229    Info.DiagnoseAbstractType();
4230  }
4231};
4232
4233void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
4234                                  Sema::AbstractDiagSelID Sel) {
4235  CheckAbstractUsage(*this, D).Visit(TL, Sel);
4236}
4237
4238}
4239
4240/// Check for invalid uses of an abstract type in a method declaration.
4241static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4242                                    CXXMethodDecl *MD) {
4243  // No need to do the check on definitions, which require that
4244  // the return/param types be complete.
4245  if (MD->doesThisDeclarationHaveABody())
4246    return;
4247
4248  // For safety's sake, just ignore it if we don't have type source
4249  // information.  This should never happen for non-implicit methods,
4250  // but...
4251  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
4252    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
4253}
4254
4255/// Check for invalid uses of an abstract type within a class definition.
4256static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
4257                                    CXXRecordDecl *RD) {
4258  for (CXXRecordDecl::decl_iterator
4259         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
4260    Decl *D = *I;
4261    if (D->isImplicit()) continue;
4262
4263    // Methods and method templates.
4264    if (isa<CXXMethodDecl>(D)) {
4265      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
4266    } else if (isa<FunctionTemplateDecl>(D)) {
4267      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
4268      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
4269
4270    // Fields and static variables.
4271    } else if (isa<FieldDecl>(D)) {
4272      FieldDecl *FD = cast<FieldDecl>(D);
4273      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
4274        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
4275    } else if (isa<VarDecl>(D)) {
4276      VarDecl *VD = cast<VarDecl>(D);
4277      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
4278        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
4279
4280    // Nested classes and class templates.
4281    } else if (isa<CXXRecordDecl>(D)) {
4282      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
4283    } else if (isa<ClassTemplateDecl>(D)) {
4284      CheckAbstractClassUsage(Info,
4285                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
4286    }
4287  }
4288}
4289
4290/// \brief Perform semantic checks on a class definition that has been
4291/// completing, introducing implicitly-declared members, checking for
4292/// abstract types, etc.
4293void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
4294  if (!Record)
4295    return;
4296
4297  if (Record->isAbstract() && !Record->isInvalidDecl()) {
4298    AbstractUsageInfo Info(*this, Record);
4299    CheckAbstractClassUsage(Info, Record);
4300  }
4301
4302  // If this is not an aggregate type and has no user-declared constructor,
4303  // complain about any non-static data members of reference or const scalar
4304  // type, since they will never get initializers.
4305  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
4306      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
4307      !Record->isLambda()) {
4308    bool Complained = false;
4309    for (RecordDecl::field_iterator F = Record->field_begin(),
4310                                 FEnd = Record->field_end();
4311         F != FEnd; ++F) {
4312      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
4313        continue;
4314
4315      if (F->getType()->isReferenceType() ||
4316          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
4317        if (!Complained) {
4318          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
4319            << Record->getTagKind() << Record;
4320          Complained = true;
4321        }
4322
4323        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
4324          << F->getType()->isReferenceType()
4325          << F->getDeclName();
4326      }
4327    }
4328  }
4329
4330  if (Record->isDynamicClass() && !Record->isDependentType())
4331    DynamicClasses.push_back(Record);
4332
4333  if (Record->getIdentifier()) {
4334    // C++ [class.mem]p13:
4335    //   If T is the name of a class, then each of the following shall have a
4336    //   name different from T:
4337    //     - every member of every anonymous union that is a member of class T.
4338    //
4339    // C++ [class.mem]p14:
4340    //   In addition, if class T has a user-declared constructor (12.1), every
4341    //   non-static data member of class T shall have a name different from T.
4342    DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
4343    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
4344         ++I) {
4345      NamedDecl *D = *I;
4346      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
4347          isa<IndirectFieldDecl>(D)) {
4348        Diag(D->getLocation(), diag::err_member_name_of_class)
4349          << D->getDeclName();
4350        break;
4351      }
4352    }
4353  }
4354
4355  // Warn if the class has virtual methods but non-virtual public destructor.
4356  if (Record->isPolymorphic() && !Record->isDependentType()) {
4357    CXXDestructorDecl *dtor = Record->getDestructor();
4358    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
4359      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
4360           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
4361  }
4362
4363  if (Record->isAbstract()) {
4364    if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
4365      Diag(Record->getLocation(), diag::warn_abstract_final_class)
4366        << FA->isSpelledAsSealed();
4367      DiagnoseAbstractType(Record);
4368    }
4369  }
4370
4371  if (!Record->isDependentType()) {
4372    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4373                                     MEnd = Record->method_end();
4374         M != MEnd; ++M) {
4375      // See if a method overloads virtual methods in a base
4376      // class without overriding any.
4377      if (!M->isStatic())
4378        DiagnoseHiddenVirtualMethods(*M);
4379
4380      // Check whether the explicitly-defaulted special members are valid.
4381      if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
4382        CheckExplicitlyDefaultedSpecialMember(*M);
4383
4384      // For an explicitly defaulted or deleted special member, we defer
4385      // determining triviality until the class is complete. That time is now!
4386      if (!M->isImplicit() && !M->isUserProvided()) {
4387        CXXSpecialMember CSM = getSpecialMember(*M);
4388        if (CSM != CXXInvalid) {
4389          M->setTrivial(SpecialMemberIsTrivial(*M, CSM));
4390
4391          // Inform the class that we've finished declaring this member.
4392          Record->finishedDefaultedOrDeletedMember(*M);
4393        }
4394      }
4395    }
4396  }
4397
4398  // C++11 [dcl.constexpr]p8: A constexpr specifier for a non-static member
4399  // function that is not a constructor declares that member function to be
4400  // const. [...] The class of which that function is a member shall be
4401  // a literal type.
4402  //
4403  // If the class has virtual bases, any constexpr members will already have
4404  // been diagnosed by the checks performed on the member declaration, so
4405  // suppress this (less useful) diagnostic.
4406  //
4407  // We delay this until we know whether an explicitly-defaulted (or deleted)
4408  // destructor for the class is trivial.
4409  if (LangOpts.CPlusPlus11 && !Record->isDependentType() &&
4410      !Record->isLiteral() && !Record->getNumVBases()) {
4411    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
4412                                     MEnd = Record->method_end();
4413         M != MEnd; ++M) {
4414      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
4415        switch (Record->getTemplateSpecializationKind()) {
4416        case TSK_ImplicitInstantiation:
4417        case TSK_ExplicitInstantiationDeclaration:
4418        case TSK_ExplicitInstantiationDefinition:
4419          // If a template instantiates to a non-literal type, but its members
4420          // instantiate to constexpr functions, the template is technically
4421          // ill-formed, but we allow it for sanity.
4422          continue;
4423
4424        case TSK_Undeclared:
4425        case TSK_ExplicitSpecialization:
4426          RequireLiteralType(M->getLocation(), Context.getRecordType(Record),
4427                             diag::err_constexpr_method_non_literal);
4428          break;
4429        }
4430
4431        // Only produce one error per class.
4432        break;
4433      }
4434    }
4435  }
4436
4437  // Check to see if we're trying to lay out a struct using the ms_struct
4438  // attribute that is dynamic.
4439  if (Record->isMsStruct(Context) && Record->isDynamicClass()) {
4440    Diag(Record->getLocation(), diag::warn_pragma_ms_struct_failed);
4441    Record->dropAttr<MsStructAttr>();
4442  }
4443
4444  // Declare inheriting constructors. We do this eagerly here because:
4445  // - The standard requires an eager diagnostic for conflicting inheriting
4446  //   constructors from different classes.
4447  // - The lazy declaration of the other implicit constructors is so as to not
4448  //   waste space and performance on classes that are not meant to be
4449  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
4450  //   have inheriting constructors.
4451  DeclareInheritingConstructors(Record);
4452}
4453
4454/// Is the special member function which would be selected to perform the
4455/// specified operation on the specified class type a constexpr constructor?
4456static bool specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4457                                     Sema::CXXSpecialMember CSM,
4458                                     bool ConstArg) {
4459  Sema::SpecialMemberOverloadResult *SMOR =
4460      S.LookupSpecialMember(ClassDecl, CSM, ConstArg,
4461                            false, false, false, false);
4462  if (!SMOR || !SMOR->getMethod())
4463    // A constructor we wouldn't select can't be "involved in initializing"
4464    // anything.
4465    return true;
4466  return SMOR->getMethod()->isConstexpr();
4467}
4468
4469/// Determine whether the specified special member function would be constexpr
4470/// if it were implicitly defined.
4471static bool defaultedSpecialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
4472                                              Sema::CXXSpecialMember CSM,
4473                                              bool ConstArg) {
4474  if (!S.getLangOpts().CPlusPlus11)
4475    return false;
4476
4477  // C++11 [dcl.constexpr]p4:
4478  // In the definition of a constexpr constructor [...]
4479  bool Ctor = true;
4480  switch (CSM) {
4481  case Sema::CXXDefaultConstructor:
4482    // Since default constructor lookup is essentially trivial (and cannot
4483    // involve, for instance, template instantiation), we compute whether a
4484    // defaulted default constructor is constexpr directly within CXXRecordDecl.
4485    //
4486    // This is important for performance; we need to know whether the default
4487    // constructor is constexpr to determine whether the type is a literal type.
4488    return ClassDecl->defaultedDefaultConstructorIsConstexpr();
4489
4490  case Sema::CXXCopyConstructor:
4491  case Sema::CXXMoveConstructor:
4492    // For copy or move constructors, we need to perform overload resolution.
4493    break;
4494
4495  case Sema::CXXCopyAssignment:
4496  case Sema::CXXMoveAssignment:
4497    if (!S.getLangOpts().CPlusPlus1y)
4498      return false;
4499    // In C++1y, we need to perform overload resolution.
4500    Ctor = false;
4501    break;
4502
4503  case Sema::CXXDestructor:
4504  case Sema::CXXInvalid:
4505    return false;
4506  }
4507
4508  //   -- if the class is a non-empty union, or for each non-empty anonymous
4509  //      union member of a non-union class, exactly one non-static data member
4510  //      shall be initialized; [DR1359]
4511  //
4512  // If we squint, this is guaranteed, since exactly one non-static data member
4513  // will be initialized (if the constructor isn't deleted), we just don't know
4514  // which one.
4515  if (Ctor && ClassDecl->isUnion())
4516    return true;
4517
4518  //   -- the class shall not have any virtual base classes;
4519  if (Ctor && ClassDecl->getNumVBases())
4520    return false;
4521
4522  // C++1y [class.copy]p26:
4523  //   -- [the class] is a literal type, and
4524  if (!Ctor && !ClassDecl->isLiteral())
4525    return false;
4526
4527  //   -- every constructor involved in initializing [...] base class
4528  //      sub-objects shall be a constexpr constructor;
4529  //   -- the assignment operator selected to copy/move each direct base
4530  //      class is a constexpr function, and
4531  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4532                                       BEnd = ClassDecl->bases_end();
4533       B != BEnd; ++B) {
4534    const RecordType *BaseType = B->getType()->getAs<RecordType>();
4535    if (!BaseType) continue;
4536
4537    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4538    if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, ConstArg))
4539      return false;
4540  }
4541
4542  //   -- every constructor involved in initializing non-static data members
4543  //      [...] shall be a constexpr constructor;
4544  //   -- every non-static data member and base class sub-object shall be
4545  //      initialized
4546  //   -- for each non-stastic data member of X that is of class type (or array
4547  //      thereof), the assignment operator selected to copy/move that member is
4548  //      a constexpr function
4549  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4550                               FEnd = ClassDecl->field_end();
4551       F != FEnd; ++F) {
4552    if (F->isInvalidDecl())
4553      continue;
4554    if (const RecordType *RecordTy =
4555            S.Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4556      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4557      if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, ConstArg))
4558        return false;
4559    }
4560  }
4561
4562  // All OK, it's constexpr!
4563  return true;
4564}
4565
4566static Sema::ImplicitExceptionSpecification
4567computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
4568  switch (S.getSpecialMember(MD)) {
4569  case Sema::CXXDefaultConstructor:
4570    return S.ComputeDefaultedDefaultCtorExceptionSpec(Loc, MD);
4571  case Sema::CXXCopyConstructor:
4572    return S.ComputeDefaultedCopyCtorExceptionSpec(MD);
4573  case Sema::CXXCopyAssignment:
4574    return S.ComputeDefaultedCopyAssignmentExceptionSpec(MD);
4575  case Sema::CXXMoveConstructor:
4576    return S.ComputeDefaultedMoveCtorExceptionSpec(MD);
4577  case Sema::CXXMoveAssignment:
4578    return S.ComputeDefaultedMoveAssignmentExceptionSpec(MD);
4579  case Sema::CXXDestructor:
4580    return S.ComputeDefaultedDtorExceptionSpec(MD);
4581  case Sema::CXXInvalid:
4582    break;
4583  }
4584  assert(cast<CXXConstructorDecl>(MD)->getInheritedConstructor() &&
4585         "only special members have implicit exception specs");
4586  return S.ComputeInheritingCtorExceptionSpec(cast<CXXConstructorDecl>(MD));
4587}
4588
4589static void
4590updateExceptionSpec(Sema &S, FunctionDecl *FD, const FunctionProtoType *FPT,
4591                    const Sema::ImplicitExceptionSpecification &ExceptSpec) {
4592  FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
4593  ExceptSpec.getEPI(EPI);
4594  FD->setType(S.Context.getFunctionType(FPT->getResultType(),
4595                                        FPT->getArgTypes(), EPI));
4596}
4597
4598static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
4599                                                            CXXMethodDecl *MD) {
4600  FunctionProtoType::ExtProtoInfo EPI;
4601
4602  // Build an exception specification pointing back at this member.
4603  EPI.ExceptionSpecType = EST_Unevaluated;
4604  EPI.ExceptionSpecDecl = MD;
4605
4606  // Set the calling convention to the default for C++ instance methods.
4607  EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
4608      S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4609                                            /*IsCXXMethod=*/true));
4610  return EPI;
4611}
4612
4613void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
4614  const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
4615  if (FPT->getExceptionSpecType() != EST_Unevaluated)
4616    return;
4617
4618  // Evaluate the exception specification.
4619  ImplicitExceptionSpecification ExceptSpec =
4620      computeImplicitExceptionSpec(*this, Loc, MD);
4621
4622  // Update the type of the special member to use it.
4623  updateExceptionSpec(*this, MD, FPT, ExceptSpec);
4624
4625  // A user-provided destructor can be defined outside the class. When that
4626  // happens, be sure to update the exception specification on both
4627  // declarations.
4628  const FunctionProtoType *CanonicalFPT =
4629    MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
4630  if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
4631    updateExceptionSpec(*this, MD->getCanonicalDecl(),
4632                        CanonicalFPT, ExceptSpec);
4633}
4634
4635void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
4636  CXXRecordDecl *RD = MD->getParent();
4637  CXXSpecialMember CSM = getSpecialMember(MD);
4638
4639  assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
4640         "not an explicitly-defaulted special member");
4641
4642  // Whether this was the first-declared instance of the constructor.
4643  // This affects whether we implicitly add an exception spec and constexpr.
4644  bool First = MD == MD->getCanonicalDecl();
4645
4646  bool HadError = false;
4647
4648  // C++11 [dcl.fct.def.default]p1:
4649  //   A function that is explicitly defaulted shall
4650  //     -- be a special member function (checked elsewhere),
4651  //     -- have the same type (except for ref-qualifiers, and except that a
4652  //        copy operation can take a non-const reference) as an implicit
4653  //        declaration, and
4654  //     -- not have default arguments.
4655  unsigned ExpectedParams = 1;
4656  if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
4657    ExpectedParams = 0;
4658  if (MD->getNumParams() != ExpectedParams) {
4659    // This also checks for default arguments: a copy or move constructor with a
4660    // default argument is classified as a default constructor, and assignment
4661    // operations and destructors can't have default arguments.
4662    Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
4663      << CSM << MD->getSourceRange();
4664    HadError = true;
4665  } else if (MD->isVariadic()) {
4666    Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
4667      << CSM << MD->getSourceRange();
4668    HadError = true;
4669  }
4670
4671  const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
4672
4673  bool CanHaveConstParam = false;
4674  if (CSM == CXXCopyConstructor)
4675    CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
4676  else if (CSM == CXXCopyAssignment)
4677    CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
4678
4679  QualType ReturnType = Context.VoidTy;
4680  if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
4681    // Check for return type matching.
4682    ReturnType = Type->getResultType();
4683    QualType ExpectedReturnType =
4684        Context.getLValueReferenceType(Context.getTypeDeclType(RD));
4685    if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
4686      Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
4687        << (CSM == CXXMoveAssignment) << ExpectedReturnType;
4688      HadError = true;
4689    }
4690
4691    // A defaulted special member cannot have cv-qualifiers.
4692    if (Type->getTypeQuals()) {
4693      Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
4694        << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus1y;
4695      HadError = true;
4696    }
4697  }
4698
4699  // Check for parameter type matching.
4700  QualType ArgType = ExpectedParams ? Type->getArgType(0) : QualType();
4701  bool HasConstParam = false;
4702  if (ExpectedParams && ArgType->isReferenceType()) {
4703    // Argument must be reference to possibly-const T.
4704    QualType ReferentType = ArgType->getPointeeType();
4705    HasConstParam = ReferentType.isConstQualified();
4706
4707    if (ReferentType.isVolatileQualified()) {
4708      Diag(MD->getLocation(),
4709           diag::err_defaulted_special_member_volatile_param) << CSM;
4710      HadError = true;
4711    }
4712
4713    if (HasConstParam && !CanHaveConstParam) {
4714      if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
4715        Diag(MD->getLocation(),
4716             diag::err_defaulted_special_member_copy_const_param)
4717          << (CSM == CXXCopyAssignment);
4718        // FIXME: Explain why this special member can't be const.
4719      } else {
4720        Diag(MD->getLocation(),
4721             diag::err_defaulted_special_member_move_const_param)
4722          << (CSM == CXXMoveAssignment);
4723      }
4724      HadError = true;
4725    }
4726  } else if (ExpectedParams) {
4727    // A copy assignment operator can take its argument by value, but a
4728    // defaulted one cannot.
4729    assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
4730    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4731    HadError = true;
4732  }
4733
4734  // C++11 [dcl.fct.def.default]p2:
4735  //   An explicitly-defaulted function may be declared constexpr only if it
4736  //   would have been implicitly declared as constexpr,
4737  // Do not apply this rule to members of class templates, since core issue 1358
4738  // makes such functions always instantiate to constexpr functions. For
4739  // functions which cannot be constexpr (for non-constructors in C++11 and for
4740  // destructors in C++1y), this is checked elsewhere.
4741  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
4742                                                     HasConstParam);
4743  if ((getLangOpts().CPlusPlus1y ? !isa<CXXDestructorDecl>(MD)
4744                                 : isa<CXXConstructorDecl>(MD)) &&
4745      MD->isConstexpr() && !Constexpr &&
4746      MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4747    Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
4748    // FIXME: Explain why the special member can't be constexpr.
4749    HadError = true;
4750  }
4751
4752  //   and may have an explicit exception-specification only if it is compatible
4753  //   with the exception-specification on the implicit declaration.
4754  if (Type->hasExceptionSpec()) {
4755    // Delay the check if this is the first declaration of the special member,
4756    // since we may not have parsed some necessary in-class initializers yet.
4757    if (First) {
4758      // If the exception specification needs to be instantiated, do so now,
4759      // before we clobber it with an EST_Unevaluated specification below.
4760      if (Type->getExceptionSpecType() == EST_Uninstantiated) {
4761        InstantiateExceptionSpec(MD->getLocStart(), MD);
4762        Type = MD->getType()->getAs<FunctionProtoType>();
4763      }
4764      DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
4765    } else
4766      CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
4767  }
4768
4769  //   If a function is explicitly defaulted on its first declaration,
4770  if (First) {
4771    //  -- it is implicitly considered to be constexpr if the implicit
4772    //     definition would be,
4773    MD->setConstexpr(Constexpr);
4774
4775    //  -- it is implicitly considered to have the same exception-specification
4776    //     as if it had been implicitly declared,
4777    FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
4778    EPI.ExceptionSpecType = EST_Unevaluated;
4779    EPI.ExceptionSpecDecl = MD;
4780    MD->setType(Context.getFunctionType(ReturnType,
4781                                        ArrayRef<QualType>(&ArgType,
4782                                                           ExpectedParams),
4783                                        EPI));
4784  }
4785
4786  if (ShouldDeleteSpecialMember(MD, CSM)) {
4787    if (First) {
4788      SetDeclDeleted(MD, MD->getLocation());
4789    } else {
4790      // C++11 [dcl.fct.def.default]p4:
4791      //   [For a] user-provided explicitly-defaulted function [...] if such a
4792      //   function is implicitly defined as deleted, the program is ill-formed.
4793      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
4794      HadError = true;
4795    }
4796  }
4797
4798  if (HadError)
4799    MD->setInvalidDecl();
4800}
4801
4802/// Check whether the exception specification provided for an
4803/// explicitly-defaulted special member matches the exception specification
4804/// that would have been generated for an implicit special member, per
4805/// C++11 [dcl.fct.def.default]p2.
4806void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
4807    CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
4808  // Compute the implicit exception specification.
4809  CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
4810                                                       /*IsCXXMethod=*/true);
4811  FunctionProtoType::ExtProtoInfo EPI(CC);
4812  computeImplicitExceptionSpec(*this, MD->getLocation(), MD).getEPI(EPI);
4813  const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
4814    Context.getFunctionType(Context.VoidTy, None, EPI));
4815
4816  // Ensure that it matches.
4817  CheckEquivalentExceptionSpec(
4818    PDiag(diag::err_incorrect_defaulted_exception_spec)
4819      << getSpecialMember(MD), PDiag(),
4820    ImplicitType, SourceLocation(),
4821    SpecifiedType, MD->getLocation());
4822}
4823
4824void Sema::CheckDelayedMemberExceptionSpecs() {
4825  SmallVector<std::pair<const CXXDestructorDecl *, const CXXDestructorDecl *>,
4826              2> Checks;
4827  SmallVector<std::pair<CXXMethodDecl *, const FunctionProtoType *>, 2> Specs;
4828
4829  std::swap(Checks, DelayedDestructorExceptionSpecChecks);
4830  std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
4831
4832  // Perform any deferred checking of exception specifications for virtual
4833  // destructors.
4834  for (unsigned i = 0, e = Checks.size(); i != e; ++i) {
4835    const CXXDestructorDecl *Dtor = Checks[i].first;
4836    assert(!Dtor->getParent()->isDependentType() &&
4837           "Should not ever add destructors of templates into the list.");
4838    CheckOverridingFunctionExceptionSpec(Dtor, Checks[i].second);
4839  }
4840
4841  // Check that any explicitly-defaulted methods have exception specifications
4842  // compatible with their implicit exception specifications.
4843  for (unsigned I = 0, N = Specs.size(); I != N; ++I)
4844    CheckExplicitlyDefaultedMemberExceptionSpec(Specs[I].first,
4845                                                Specs[I].second);
4846}
4847
4848namespace {
4849struct SpecialMemberDeletionInfo {
4850  Sema &S;
4851  CXXMethodDecl *MD;
4852  Sema::CXXSpecialMember CSM;
4853  bool Diagnose;
4854
4855  // Properties of the special member, computed for convenience.
4856  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4857  SourceLocation Loc;
4858
4859  bool AllFieldsAreConst;
4860
4861  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4862                            Sema::CXXSpecialMember CSM, bool Diagnose)
4863    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4864      IsConstructor(false), IsAssignment(false), IsMove(false),
4865      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4866      AllFieldsAreConst(true) {
4867    switch (CSM) {
4868      case Sema::CXXDefaultConstructor:
4869      case Sema::CXXCopyConstructor:
4870        IsConstructor = true;
4871        break;
4872      case Sema::CXXMoveConstructor:
4873        IsConstructor = true;
4874        IsMove = true;
4875        break;
4876      case Sema::CXXCopyAssignment:
4877        IsAssignment = true;
4878        break;
4879      case Sema::CXXMoveAssignment:
4880        IsAssignment = true;
4881        IsMove = true;
4882        break;
4883      case Sema::CXXDestructor:
4884        break;
4885      case Sema::CXXInvalid:
4886        llvm_unreachable("invalid special member kind");
4887    }
4888
4889    if (MD->getNumParams()) {
4890      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4891      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4892    }
4893  }
4894
4895  bool inUnion() const { return MD->getParent()->isUnion(); }
4896
4897  /// Look up the corresponding special member in the given class.
4898  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class,
4899                                              unsigned Quals) {
4900    unsigned TQ = MD->getTypeQualifiers();
4901    // cv-qualifiers on class members don't affect default ctor / dtor calls.
4902    if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
4903      Quals = 0;
4904    return S.LookupSpecialMember(Class, CSM,
4905                                 ConstArg || (Quals & Qualifiers::Const),
4906                                 VolatileArg || (Quals & Qualifiers::Volatile),
4907                                 MD->getRefQualifier() == RQ_RValue,
4908                                 TQ & Qualifiers::Const,
4909                                 TQ & Qualifiers::Volatile);
4910  }
4911
4912  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4913
4914  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4915  bool shouldDeleteForField(FieldDecl *FD);
4916  bool shouldDeleteForAllConstMembers();
4917
4918  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
4919                                     unsigned Quals);
4920  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4921                                    Sema::SpecialMemberOverloadResult *SMOR,
4922                                    bool IsDtorCallInCtor);
4923
4924  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4925};
4926}
4927
4928/// Is the given special member inaccessible when used on the given
4929/// sub-object.
4930bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4931                                             CXXMethodDecl *target) {
4932  /// If we're operating on a base class, the object type is the
4933  /// type of this special member.
4934  QualType objectTy;
4935  AccessSpecifier access = target->getAccess();
4936  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4937    objectTy = S.Context.getTypeDeclType(MD->getParent());
4938    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4939
4940  // If we're operating on a field, the object type is the type of the field.
4941  } else {
4942    objectTy = S.Context.getTypeDeclType(target->getParent());
4943  }
4944
4945  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4946}
4947
4948/// Check whether we should delete a special member due to the implicit
4949/// definition containing a call to a special member of a subobject.
4950bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4951    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4952    bool IsDtorCallInCtor) {
4953  CXXMethodDecl *Decl = SMOR->getMethod();
4954  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4955
4956  int DiagKind = -1;
4957
4958  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4959    DiagKind = !Decl ? 0 : 1;
4960  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4961    DiagKind = 2;
4962  else if (!isAccessible(Subobj, Decl))
4963    DiagKind = 3;
4964  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4965           !Decl->isTrivial()) {
4966    // A member of a union must have a trivial corresponding special member.
4967    // As a weird special case, a destructor call from a union's constructor
4968    // must be accessible and non-deleted, but need not be trivial. Such a
4969    // destructor is never actually called, but is semantically checked as
4970    // if it were.
4971    DiagKind = 4;
4972  }
4973
4974  if (DiagKind == -1)
4975    return false;
4976
4977  if (Diagnose) {
4978    if (Field) {
4979      S.Diag(Field->getLocation(),
4980             diag::note_deleted_special_member_class_subobject)
4981        << CSM << MD->getParent() << /*IsField*/true
4982        << Field << DiagKind << IsDtorCallInCtor;
4983    } else {
4984      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4985      S.Diag(Base->getLocStart(),
4986             diag::note_deleted_special_member_class_subobject)
4987        << CSM << MD->getParent() << /*IsField*/false
4988        << Base->getType() << DiagKind << IsDtorCallInCtor;
4989    }
4990
4991    if (DiagKind == 1)
4992      S.NoteDeletedFunction(Decl);
4993    // FIXME: Explain inaccessibility if DiagKind == 3.
4994  }
4995
4996  return true;
4997}
4998
4999/// Check whether we should delete a special member function due to having a
5000/// direct or virtual base class or non-static data member of class type M.
5001bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
5002    CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
5003  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
5004
5005  // C++11 [class.ctor]p5:
5006  // -- any direct or virtual base class, or non-static data member with no
5007  //    brace-or-equal-initializer, has class type M (or array thereof) and
5008  //    either M has no default constructor or overload resolution as applied
5009  //    to M's default constructor results in an ambiguity or in a function
5010  //    that is deleted or inaccessible
5011  // C++11 [class.copy]p11, C++11 [class.copy]p23:
5012  // -- a direct or virtual base class B that cannot be copied/moved because
5013  //    overload resolution, as applied to B's corresponding special member,
5014  //    results in an ambiguity or a function that is deleted or inaccessible
5015  //    from the defaulted special member
5016  // C++11 [class.dtor]p5:
5017  // -- any direct or virtual base class [...] has a type with a destructor
5018  //    that is deleted or inaccessible
5019  if (!(CSM == Sema::CXXDefaultConstructor &&
5020        Field && Field->hasInClassInitializer()) &&
5021      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals), false))
5022    return true;
5023
5024  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
5025  // -- any direct or virtual base class or non-static data member has a
5026  //    type with a destructor that is deleted or inaccessible
5027  if (IsConstructor) {
5028    Sema::SpecialMemberOverloadResult *SMOR =
5029        S.LookupSpecialMember(Class, Sema::CXXDestructor,
5030                              false, false, false, false, false);
5031    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
5032      return true;
5033  }
5034
5035  return false;
5036}
5037
5038/// Check whether we should delete a special member function due to the class
5039/// having a particular direct or virtual base class.
5040bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
5041  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
5042  return shouldDeleteForClassSubobject(BaseClass, Base, 0);
5043}
5044
5045/// Check whether we should delete a special member function due to the class
5046/// having a particular non-static data member.
5047bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
5048  QualType FieldType = S.Context.getBaseElementType(FD->getType());
5049  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
5050
5051  if (CSM == Sema::CXXDefaultConstructor) {
5052    // For a default constructor, all references must be initialized in-class
5053    // and, if a union, it must have a non-const member.
5054    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
5055      if (Diagnose)
5056        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5057          << MD->getParent() << FD << FieldType << /*Reference*/0;
5058      return true;
5059    }
5060    // C++11 [class.ctor]p5: any non-variant non-static data member of
5061    // const-qualified type (or array thereof) with no
5062    // brace-or-equal-initializer does not have a user-provided default
5063    // constructor.
5064    if (!inUnion() && FieldType.isConstQualified() &&
5065        !FD->hasInClassInitializer() &&
5066        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
5067      if (Diagnose)
5068        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
5069          << MD->getParent() << FD << FD->getType() << /*Const*/1;
5070      return true;
5071    }
5072
5073    if (inUnion() && !FieldType.isConstQualified())
5074      AllFieldsAreConst = false;
5075  } else if (CSM == Sema::CXXCopyConstructor) {
5076    // For a copy constructor, data members must not be of rvalue reference
5077    // type.
5078    if (FieldType->isRValueReferenceType()) {
5079      if (Diagnose)
5080        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
5081          << MD->getParent() << FD << FieldType;
5082      return true;
5083    }
5084  } else if (IsAssignment) {
5085    // For an assignment operator, data members must not be of reference type.
5086    if (FieldType->isReferenceType()) {
5087      if (Diagnose)
5088        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5089          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
5090      return true;
5091    }
5092    if (!FieldRecord && FieldType.isConstQualified()) {
5093      // C++11 [class.copy]p23:
5094      // -- a non-static data member of const non-class type (or array thereof)
5095      if (Diagnose)
5096        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
5097          << IsMove << MD->getParent() << FD << FD->getType() << /*Const*/1;
5098      return true;
5099    }
5100  }
5101
5102  if (FieldRecord) {
5103    // Some additional restrictions exist on the variant members.
5104    if (!inUnion() && FieldRecord->isUnion() &&
5105        FieldRecord->isAnonymousStructOrUnion()) {
5106      bool AllVariantFieldsAreConst = true;
5107
5108      // FIXME: Handle anonymous unions declared within anonymous unions.
5109      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
5110                                         UE = FieldRecord->field_end();
5111           UI != UE; ++UI) {
5112        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
5113
5114        if (!UnionFieldType.isConstQualified())
5115          AllVariantFieldsAreConst = false;
5116
5117        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
5118        if (UnionFieldRecord &&
5119            shouldDeleteForClassSubobject(UnionFieldRecord, *UI,
5120                                          UnionFieldType.getCVRQualifiers()))
5121          return true;
5122      }
5123
5124      // At least one member in each anonymous union must be non-const
5125      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
5126          FieldRecord->field_begin() != FieldRecord->field_end()) {
5127        if (Diagnose)
5128          S.Diag(FieldRecord->getLocation(),
5129                 diag::note_deleted_default_ctor_all_const)
5130            << MD->getParent() << /*anonymous union*/1;
5131        return true;
5132      }
5133
5134      // Don't check the implicit member of the anonymous union type.
5135      // This is technically non-conformant, but sanity demands it.
5136      return false;
5137    }
5138
5139    if (shouldDeleteForClassSubobject(FieldRecord, FD,
5140                                      FieldType.getCVRQualifiers()))
5141      return true;
5142  }
5143
5144  return false;
5145}
5146
5147/// C++11 [class.ctor] p5:
5148///   A defaulted default constructor for a class X is defined as deleted if
5149/// X is a union and all of its variant members are of const-qualified type.
5150bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
5151  // This is a silly definition, because it gives an empty union a deleted
5152  // default constructor. Don't do that.
5153  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
5154      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
5155    if (Diagnose)
5156      S.Diag(MD->getParent()->getLocation(),
5157             diag::note_deleted_default_ctor_all_const)
5158        << MD->getParent() << /*not anonymous union*/0;
5159    return true;
5160  }
5161  return false;
5162}
5163
5164/// Determine whether a defaulted special member function should be defined as
5165/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
5166/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
5167bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
5168                                     bool Diagnose) {
5169  if (MD->isInvalidDecl())
5170    return false;
5171  CXXRecordDecl *RD = MD->getParent();
5172  assert(!RD->isDependentType() && "do deletion after instantiation");
5173  if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
5174    return false;
5175
5176  // C++11 [expr.lambda.prim]p19:
5177  //   The closure type associated with a lambda-expression has a
5178  //   deleted (8.4.3) default constructor and a deleted copy
5179  //   assignment operator.
5180  if (RD->isLambda() &&
5181      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
5182    if (Diagnose)
5183      Diag(RD->getLocation(), diag::note_lambda_decl);
5184    return true;
5185  }
5186
5187  // For an anonymous struct or union, the copy and assignment special members
5188  // will never be used, so skip the check. For an anonymous union declared at
5189  // namespace scope, the constructor and destructor are used.
5190  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
5191      RD->isAnonymousStructOrUnion())
5192    return false;
5193
5194  // C++11 [class.copy]p7, p18:
5195  //   If the class definition declares a move constructor or move assignment
5196  //   operator, an implicitly declared copy constructor or copy assignment
5197  //   operator is defined as deleted.
5198  if (MD->isImplicit() &&
5199      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
5200    CXXMethodDecl *UserDeclaredMove = 0;
5201
5202    // In Microsoft mode, a user-declared move only causes the deletion of the
5203    // corresponding copy operation, not both copy operations.
5204    if (RD->hasUserDeclaredMoveConstructor() &&
5205        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
5206      if (!Diagnose) return true;
5207
5208      // Find any user-declared move constructor.
5209      for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
5210                                        E = RD->ctor_end(); I != E; ++I) {
5211        if (I->isMoveConstructor()) {
5212          UserDeclaredMove = *I;
5213          break;
5214        }
5215      }
5216      assert(UserDeclaredMove);
5217    } else if (RD->hasUserDeclaredMoveAssignment() &&
5218               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
5219      if (!Diagnose) return true;
5220
5221      // Find any user-declared move assignment operator.
5222      for (CXXRecordDecl::method_iterator I = RD->method_begin(),
5223                                          E = RD->method_end(); I != E; ++I) {
5224        if (I->isMoveAssignmentOperator()) {
5225          UserDeclaredMove = *I;
5226          break;
5227        }
5228      }
5229      assert(UserDeclaredMove);
5230    }
5231
5232    if (UserDeclaredMove) {
5233      Diag(UserDeclaredMove->getLocation(),
5234           diag::note_deleted_copy_user_declared_move)
5235        << (CSM == CXXCopyAssignment) << RD
5236        << UserDeclaredMove->isMoveAssignmentOperator();
5237      return true;
5238    }
5239  }
5240
5241  // Do access control from the special member function
5242  ContextRAII MethodContext(*this, MD);
5243
5244  // C++11 [class.dtor]p5:
5245  // -- for a virtual destructor, lookup of the non-array deallocation function
5246  //    results in an ambiguity or in a function that is deleted or inaccessible
5247  if (CSM == CXXDestructor && MD->isVirtual()) {
5248    FunctionDecl *OperatorDelete = 0;
5249    DeclarationName Name =
5250      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5251    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
5252                                 OperatorDelete, false)) {
5253      if (Diagnose)
5254        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
5255      return true;
5256    }
5257  }
5258
5259  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
5260
5261  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5262                                          BE = RD->bases_end(); BI != BE; ++BI)
5263    if (!BI->isVirtual() &&
5264        SMI.shouldDeleteForBase(BI))
5265      return true;
5266
5267  // Per DR1611, do not consider virtual bases of constructors of abstract
5268  // classes, since we are not going to construct them.
5269  if (!RD->isAbstract() || !SMI.IsConstructor) {
5270    for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
5271                                            BE = RD->vbases_end();
5272         BI != BE; ++BI)
5273      if (SMI.shouldDeleteForBase(BI))
5274        return true;
5275  }
5276
5277  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5278                                     FE = RD->field_end(); FI != FE; ++FI)
5279    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
5280        SMI.shouldDeleteForField(*FI))
5281      return true;
5282
5283  if (SMI.shouldDeleteForAllConstMembers())
5284    return true;
5285
5286  return false;
5287}
5288
5289/// Perform lookup for a special member of the specified kind, and determine
5290/// whether it is trivial. If the triviality can be determined without the
5291/// lookup, skip it. This is intended for use when determining whether a
5292/// special member of a containing object is trivial, and thus does not ever
5293/// perform overload resolution for default constructors.
5294///
5295/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
5296/// member that was most likely to be intended to be trivial, if any.
5297static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
5298                                     Sema::CXXSpecialMember CSM, unsigned Quals,
5299                                     CXXMethodDecl **Selected) {
5300  if (Selected)
5301    *Selected = 0;
5302
5303  switch (CSM) {
5304  case Sema::CXXInvalid:
5305    llvm_unreachable("not a special member");
5306
5307  case Sema::CXXDefaultConstructor:
5308    // C++11 [class.ctor]p5:
5309    //   A default constructor is trivial if:
5310    //    - all the [direct subobjects] have trivial default constructors
5311    //
5312    // Note, no overload resolution is performed in this case.
5313    if (RD->hasTrivialDefaultConstructor())
5314      return true;
5315
5316    if (Selected) {
5317      // If there's a default constructor which could have been trivial, dig it
5318      // out. Otherwise, if there's any user-provided default constructor, point
5319      // to that as an example of why there's not a trivial one.
5320      CXXConstructorDecl *DefCtor = 0;
5321      if (RD->needsImplicitDefaultConstructor())
5322        S.DeclareImplicitDefaultConstructor(RD);
5323      for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(),
5324                                        CE = RD->ctor_end(); CI != CE; ++CI) {
5325        if (!CI->isDefaultConstructor())
5326          continue;
5327        DefCtor = *CI;
5328        if (!DefCtor->isUserProvided())
5329          break;
5330      }
5331
5332      *Selected = DefCtor;
5333    }
5334
5335    return false;
5336
5337  case Sema::CXXDestructor:
5338    // C++11 [class.dtor]p5:
5339    //   A destructor is trivial if:
5340    //    - all the direct [subobjects] have trivial destructors
5341    if (RD->hasTrivialDestructor())
5342      return true;
5343
5344    if (Selected) {
5345      if (RD->needsImplicitDestructor())
5346        S.DeclareImplicitDestructor(RD);
5347      *Selected = RD->getDestructor();
5348    }
5349
5350    return false;
5351
5352  case Sema::CXXCopyConstructor:
5353    // C++11 [class.copy]p12:
5354    //   A copy constructor is trivial if:
5355    //    - the constructor selected to copy each direct [subobject] is trivial
5356    if (RD->hasTrivialCopyConstructor()) {
5357      if (Quals == Qualifiers::Const)
5358        // We must either select the trivial copy constructor or reach an
5359        // ambiguity; no need to actually perform overload resolution.
5360        return true;
5361    } else if (!Selected) {
5362      return false;
5363    }
5364    // In C++98, we are not supposed to perform overload resolution here, but we
5365    // treat that as a language defect, as suggested on cxx-abi-dev, to treat
5366    // cases like B as having a non-trivial copy constructor:
5367    //   struct A { template<typename T> A(T&); };
5368    //   struct B { mutable A a; };
5369    goto NeedOverloadResolution;
5370
5371  case Sema::CXXCopyAssignment:
5372    // C++11 [class.copy]p25:
5373    //   A copy assignment operator is trivial if:
5374    //    - the assignment operator selected to copy each direct [subobject] is
5375    //      trivial
5376    if (RD->hasTrivialCopyAssignment()) {
5377      if (Quals == Qualifiers::Const)
5378        return true;
5379    } else if (!Selected) {
5380      return false;
5381    }
5382    // In C++98, we are not supposed to perform overload resolution here, but we
5383    // treat that as a language defect.
5384    goto NeedOverloadResolution;
5385
5386  case Sema::CXXMoveConstructor:
5387  case Sema::CXXMoveAssignment:
5388  NeedOverloadResolution:
5389    Sema::SpecialMemberOverloadResult *SMOR =
5390      S.LookupSpecialMember(RD, CSM,
5391                            Quals & Qualifiers::Const,
5392                            Quals & Qualifiers::Volatile,
5393                            /*RValueThis*/false, /*ConstThis*/false,
5394                            /*VolatileThis*/false);
5395
5396    // The standard doesn't describe how to behave if the lookup is ambiguous.
5397    // We treat it as not making the member non-trivial, just like the standard
5398    // mandates for the default constructor. This should rarely matter, because
5399    // the member will also be deleted.
5400    if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
5401      return true;
5402
5403    if (!SMOR->getMethod()) {
5404      assert(SMOR->getKind() ==
5405             Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
5406      return false;
5407    }
5408
5409    // We deliberately don't check if we found a deleted special member. We're
5410    // not supposed to!
5411    if (Selected)
5412      *Selected = SMOR->getMethod();
5413    return SMOR->getMethod()->isTrivial();
5414  }
5415
5416  llvm_unreachable("unknown special method kind");
5417}
5418
5419static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
5420  for (CXXRecordDecl::ctor_iterator CI = RD->ctor_begin(), CE = RD->ctor_end();
5421       CI != CE; ++CI)
5422    if (!CI->isImplicit())
5423      return *CI;
5424
5425  // Look for constructor templates.
5426  typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
5427  for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
5428    if (CXXConstructorDecl *CD =
5429          dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
5430      return CD;
5431  }
5432
5433  return 0;
5434}
5435
5436/// The kind of subobject we are checking for triviality. The values of this
5437/// enumeration are used in diagnostics.
5438enum TrivialSubobjectKind {
5439  /// The subobject is a base class.
5440  TSK_BaseClass,
5441  /// The subobject is a non-static data member.
5442  TSK_Field,
5443  /// The object is actually the complete object.
5444  TSK_CompleteObject
5445};
5446
5447/// Check whether the special member selected for a given type would be trivial.
5448static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
5449                                      QualType SubType,
5450                                      Sema::CXXSpecialMember CSM,
5451                                      TrivialSubobjectKind Kind,
5452                                      bool Diagnose) {
5453  CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
5454  if (!SubRD)
5455    return true;
5456
5457  CXXMethodDecl *Selected;
5458  if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
5459                               Diagnose ? &Selected : 0))
5460    return true;
5461
5462  if (Diagnose) {
5463    if (!Selected && CSM == Sema::CXXDefaultConstructor) {
5464      S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
5465        << Kind << SubType.getUnqualifiedType();
5466      if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
5467        S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
5468    } else if (!Selected)
5469      S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
5470        << Kind << SubType.getUnqualifiedType() << CSM << SubType;
5471    else if (Selected->isUserProvided()) {
5472      if (Kind == TSK_CompleteObject)
5473        S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
5474          << Kind << SubType.getUnqualifiedType() << CSM;
5475      else {
5476        S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
5477          << Kind << SubType.getUnqualifiedType() << CSM;
5478        S.Diag(Selected->getLocation(), diag::note_declared_at);
5479      }
5480    } else {
5481      if (Kind != TSK_CompleteObject)
5482        S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
5483          << Kind << SubType.getUnqualifiedType() << CSM;
5484
5485      // Explain why the defaulted or deleted special member isn't trivial.
5486      S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
5487    }
5488  }
5489
5490  return false;
5491}
5492
5493/// Check whether the members of a class type allow a special member to be
5494/// trivial.
5495static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
5496                                     Sema::CXXSpecialMember CSM,
5497                                     bool ConstArg, bool Diagnose) {
5498  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
5499                                     FE = RD->field_end(); FI != FE; ++FI) {
5500    if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
5501      continue;
5502
5503    QualType FieldType = S.Context.getBaseElementType(FI->getType());
5504
5505    // Pretend anonymous struct or union members are members of this class.
5506    if (FI->isAnonymousStructOrUnion()) {
5507      if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
5508                                    CSM, ConstArg, Diagnose))
5509        return false;
5510      continue;
5511    }
5512
5513    // C++11 [class.ctor]p5:
5514    //   A default constructor is trivial if [...]
5515    //    -- no non-static data member of its class has a
5516    //       brace-or-equal-initializer
5517    if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
5518      if (Diagnose)
5519        S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << *FI;
5520      return false;
5521    }
5522
5523    // Objective C ARC 4.3.5:
5524    //   [...] nontrivally ownership-qualified types are [...] not trivially
5525    //   default constructible, copy constructible, move constructible, copy
5526    //   assignable, move assignable, or destructible [...]
5527    if (S.getLangOpts().ObjCAutoRefCount &&
5528        FieldType.hasNonTrivialObjCLifetime()) {
5529      if (Diagnose)
5530        S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
5531          << RD << FieldType.getObjCLifetime();
5532      return false;
5533    }
5534
5535    if (ConstArg && !FI->isMutable())
5536      FieldType.addConst();
5537    if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, CSM,
5538                                   TSK_Field, Diagnose))
5539      return false;
5540  }
5541
5542  return true;
5543}
5544
5545/// Diagnose why the specified class does not have a trivial special member of
5546/// the given kind.
5547void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
5548  QualType Ty = Context.getRecordType(RD);
5549  if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)
5550    Ty.addConst();
5551
5552  checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, CSM,
5553                            TSK_CompleteObject, /*Diagnose*/true);
5554}
5555
5556/// Determine whether a defaulted or deleted special member function is trivial,
5557/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
5558/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
5559bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
5560                                  bool Diagnose) {
5561  assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
5562
5563  CXXRecordDecl *RD = MD->getParent();
5564
5565  bool ConstArg = false;
5566
5567  // C++11 [class.copy]p12, p25:
5568  //   A [special member] is trivial if its declared parameter type is the same
5569  //   as if it had been implicitly declared [...]
5570  switch (CSM) {
5571  case CXXDefaultConstructor:
5572  case CXXDestructor:
5573    // Trivial default constructors and destructors cannot have parameters.
5574    break;
5575
5576  case CXXCopyConstructor:
5577  case CXXCopyAssignment: {
5578    // Trivial copy operations always have const, non-volatile parameter types.
5579    ConstArg = true;
5580    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5581    const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
5582    if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
5583      if (Diagnose)
5584        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5585          << Param0->getSourceRange() << Param0->getType()
5586          << Context.getLValueReferenceType(
5587               Context.getRecordType(RD).withConst());
5588      return false;
5589    }
5590    break;
5591  }
5592
5593  case CXXMoveConstructor:
5594  case CXXMoveAssignment: {
5595    // Trivial move operations always have non-cv-qualified parameters.
5596    const ParmVarDecl *Param0 = MD->getParamDecl(0);
5597    const RValueReferenceType *RT =
5598      Param0->getType()->getAs<RValueReferenceType>();
5599    if (!RT || RT->getPointeeType().getCVRQualifiers()) {
5600      if (Diagnose)
5601        Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
5602          << Param0->getSourceRange() << Param0->getType()
5603          << Context.getRValueReferenceType(Context.getRecordType(RD));
5604      return false;
5605    }
5606    break;
5607  }
5608
5609  case CXXInvalid:
5610    llvm_unreachable("not a special member");
5611  }
5612
5613  // FIXME: We require that the parameter-declaration-clause is equivalent to
5614  // that of an implicit declaration, not just that the declared parameter type
5615  // matches, in order to prevent absuridities like a function simultaneously
5616  // being a trivial copy constructor and a non-trivial default constructor.
5617  // This issue has not yet been assigned a core issue number.
5618  if (MD->getMinRequiredArguments() < MD->getNumParams()) {
5619    if (Diagnose)
5620      Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
5621           diag::note_nontrivial_default_arg)
5622        << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
5623    return false;
5624  }
5625  if (MD->isVariadic()) {
5626    if (Diagnose)
5627      Diag(MD->getLocation(), diag::note_nontrivial_variadic);
5628    return false;
5629  }
5630
5631  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5632  //   A copy/move [constructor or assignment operator] is trivial if
5633  //    -- the [member] selected to copy/move each direct base class subobject
5634  //       is trivial
5635  //
5636  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5637  //   A [default constructor or destructor] is trivial if
5638  //    -- all the direct base classes have trivial [default constructors or
5639  //       destructors]
5640  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
5641                                          BE = RD->bases_end(); BI != BE; ++BI)
5642    if (!checkTrivialSubobjectCall(*this, BI->getLocStart(),
5643                                   ConstArg ? BI->getType().withConst()
5644                                            : BI->getType(),
5645                                   CSM, TSK_BaseClass, Diagnose))
5646      return false;
5647
5648  // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
5649  //   A copy/move [constructor or assignment operator] for a class X is
5650  //   trivial if
5651  //    -- for each non-static data member of X that is of class type (or array
5652  //       thereof), the constructor selected to copy/move that member is
5653  //       trivial
5654  //
5655  // C++11 [class.copy]p12, C++11 [class.copy]p25:
5656  //   A [default constructor or destructor] is trivial if
5657  //    -- for all of the non-static data members of its class that are of class
5658  //       type (or array thereof), each such class has a trivial [default
5659  //       constructor or destructor]
5660  if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
5661    return false;
5662
5663  // C++11 [class.dtor]p5:
5664  //   A destructor is trivial if [...]
5665  //    -- the destructor is not virtual
5666  if (CSM == CXXDestructor && MD->isVirtual()) {
5667    if (Diagnose)
5668      Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
5669    return false;
5670  }
5671
5672  // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
5673  //   A [special member] for class X is trivial if [...]
5674  //    -- class X has no virtual functions and no virtual base classes
5675  if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
5676    if (!Diagnose)
5677      return false;
5678
5679    if (RD->getNumVBases()) {
5680      // Check for virtual bases. We already know that the corresponding
5681      // member in all bases is trivial, so vbases must all be direct.
5682      CXXBaseSpecifier &BS = *RD->vbases_begin();
5683      assert(BS.isVirtual());
5684      Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
5685      return false;
5686    }
5687
5688    // Must have a virtual method.
5689    for (CXXRecordDecl::method_iterator MI = RD->method_begin(),
5690                                        ME = RD->method_end(); MI != ME; ++MI) {
5691      if (MI->isVirtual()) {
5692        SourceLocation MLoc = MI->getLocStart();
5693        Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
5694        return false;
5695      }
5696    }
5697
5698    llvm_unreachable("dynamic class with no vbases and no virtual functions");
5699  }
5700
5701  // Looks like it's trivial!
5702  return true;
5703}
5704
5705/// \brief Data used with FindHiddenVirtualMethod
5706namespace {
5707  struct FindHiddenVirtualMethodData {
5708    Sema *S;
5709    CXXMethodDecl *Method;
5710    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
5711    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5712  };
5713}
5714
5715/// \brief Check whether any most overriden method from MD in Methods
5716static bool CheckMostOverridenMethods(const CXXMethodDecl *MD,
5717                   const llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5718  if (MD->size_overridden_methods() == 0)
5719    return Methods.count(MD->getCanonicalDecl());
5720  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5721                                      E = MD->end_overridden_methods();
5722       I != E; ++I)
5723    if (CheckMostOverridenMethods(*I, Methods))
5724      return true;
5725  return false;
5726}
5727
5728/// \brief Member lookup function that determines whether a given C++
5729/// method overloads virtual methods in a base class without overriding any,
5730/// to be used with CXXRecordDecl::lookupInBases().
5731static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
5732                                    CXXBasePath &Path,
5733                                    void *UserData) {
5734  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5735
5736  FindHiddenVirtualMethodData &Data
5737    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
5738
5739  DeclarationName Name = Data.Method->getDeclName();
5740  assert(Name.getNameKind() == DeclarationName::Identifier);
5741
5742  bool foundSameNameMethod = false;
5743  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
5744  for (Path.Decls = BaseRecord->lookup(Name);
5745       !Path.Decls.empty();
5746       Path.Decls = Path.Decls.slice(1)) {
5747    NamedDecl *D = Path.Decls.front();
5748    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5749      MD = MD->getCanonicalDecl();
5750      foundSameNameMethod = true;
5751      // Interested only in hidden virtual methods.
5752      if (!MD->isVirtual())
5753        continue;
5754      // If the method we are checking overrides a method from its base
5755      // don't warn about the other overloaded methods.
5756      if (!Data.S->IsOverload(Data.Method, MD, false))
5757        return true;
5758      // Collect the overload only if its hidden.
5759      if (!CheckMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods))
5760        overloadedMethods.push_back(MD);
5761    }
5762  }
5763
5764  if (foundSameNameMethod)
5765    Data.OverloadedMethods.append(overloadedMethods.begin(),
5766                                   overloadedMethods.end());
5767  return foundSameNameMethod;
5768}
5769
5770/// \brief Add the most overriden methods from MD to Methods
5771static void AddMostOverridenMethods(const CXXMethodDecl *MD,
5772                         llvm::SmallPtrSet<const CXXMethodDecl *, 8>& Methods) {
5773  if (MD->size_overridden_methods() == 0)
5774    Methods.insert(MD->getCanonicalDecl());
5775  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5776                                      E = MD->end_overridden_methods();
5777       I != E; ++I)
5778    AddMostOverridenMethods(*I, Methods);
5779}
5780
5781/// \brief Check if a method overloads virtual methods in a base class without
5782/// overriding any.
5783void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
5784                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5785  if (!MD->getDeclName().isIdentifier())
5786    return;
5787
5788  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
5789                     /*bool RecordPaths=*/false,
5790                     /*bool DetectVirtual=*/false);
5791  FindHiddenVirtualMethodData Data;
5792  Data.Method = MD;
5793  Data.S = this;
5794
5795  // Keep the base methods that were overriden or introduced in the subclass
5796  // by 'using' in a set. A base method not in this set is hidden.
5797  CXXRecordDecl *DC = MD->getParent();
5798  DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
5799  for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
5800    NamedDecl *ND = *I;
5801    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
5802      ND = shad->getTargetDecl();
5803    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5804      AddMostOverridenMethods(MD, Data.OverridenAndUsingBaseMethods);
5805  }
5806
5807  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths))
5808    OverloadedMethods = Data.OverloadedMethods;
5809}
5810
5811void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
5812                          SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
5813  for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
5814    CXXMethodDecl *overloadedMD = OverloadedMethods[i];
5815    PartialDiagnostic PD = PDiag(
5816         diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5817    HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
5818    Diag(overloadedMD->getLocation(), PD);
5819  }
5820}
5821
5822/// \brief Diagnose methods which overload virtual methods in a base class
5823/// without overriding any.
5824void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
5825  if (MD->isInvalidDecl())
5826    return;
5827
5828  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
5829                               MD->getLocation()) == DiagnosticsEngine::Ignored)
5830    return;
5831
5832  SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
5833  FindHiddenVirtualMethods(MD, OverloadedMethods);
5834  if (!OverloadedMethods.empty()) {
5835    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5836      << MD << (OverloadedMethods.size() > 1);
5837
5838    NoteHiddenVirtualMethods(MD, OverloadedMethods);
5839  }
5840}
5841
5842void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
5843                                             Decl *TagDecl,
5844                                             SourceLocation LBrac,
5845                                             SourceLocation RBrac,
5846                                             AttributeList *AttrList) {
5847  if (!TagDecl)
5848    return;
5849
5850  AdjustDeclIfTemplate(TagDecl);
5851
5852  for (const AttributeList* l = AttrList; l; l = l->getNext()) {
5853    if (l->getKind() != AttributeList::AT_Visibility)
5854      continue;
5855    l->setInvalid();
5856    Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
5857      l->getName();
5858  }
5859
5860  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
5861              // strict aliasing violation!
5862              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
5863              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
5864
5865  CheckCompletedCXXClass(
5866                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
5867}
5868
5869/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5870/// special functions, such as the default constructor, copy
5871/// constructor, or destructor, to the given C++ class (C++
5872/// [special]p1).  This routine can only be executed just before the
5873/// definition of the class is complete.
5874void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
5875  if (!ClassDecl->hasUserDeclaredConstructor())
5876    ++ASTContext::NumImplicitDefaultConstructors;
5877
5878  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
5879    ++ASTContext::NumImplicitCopyConstructors;
5880
5881    // If the properties or semantics of the copy constructor couldn't be
5882    // determined while the class was being declared, force a declaration
5883    // of it now.
5884    if (ClassDecl->needsOverloadResolutionForCopyConstructor())
5885      DeclareImplicitCopyConstructor(ClassDecl);
5886  }
5887
5888  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
5889    ++ASTContext::NumImplicitMoveConstructors;
5890
5891    if (ClassDecl->needsOverloadResolutionForMoveConstructor())
5892      DeclareImplicitMoveConstructor(ClassDecl);
5893  }
5894
5895  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5896    ++ASTContext::NumImplicitCopyAssignmentOperators;
5897
5898    // If we have a dynamic class, then the copy assignment operator may be
5899    // virtual, so we have to declare it immediately. This ensures that, e.g.,
5900    // it shows up in the right place in the vtable and that we diagnose
5901    // problems with the implicit exception specification.
5902    if (ClassDecl->isDynamicClass() ||
5903        ClassDecl->needsOverloadResolutionForCopyAssignment())
5904      DeclareImplicitCopyAssignment(ClassDecl);
5905  }
5906
5907  if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
5908    ++ASTContext::NumImplicitMoveAssignmentOperators;
5909
5910    // Likewise for the move assignment operator.
5911    if (ClassDecl->isDynamicClass() ||
5912        ClassDecl->needsOverloadResolutionForMoveAssignment())
5913      DeclareImplicitMoveAssignment(ClassDecl);
5914  }
5915
5916  if (!ClassDecl->hasUserDeclaredDestructor()) {
5917    ++ASTContext::NumImplicitDestructors;
5918
5919    // If we have a dynamic class, then the destructor may be virtual, so we
5920    // have to declare the destructor immediately. This ensures that, e.g., it
5921    // shows up in the right place in the vtable and that we diagnose problems
5922    // with the implicit exception specification.
5923    if (ClassDecl->isDynamicClass() ||
5924        ClassDecl->needsOverloadResolutionForDestructor())
5925      DeclareImplicitDestructor(ClassDecl);
5926  }
5927}
5928
5929void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5930  if (!D)
5931    return;
5932
5933  int NumParamList = D->getNumTemplateParameterLists();
5934  for (int i = 0; i < NumParamList; i++) {
5935    TemplateParameterList* Params = D->getTemplateParameterList(i);
5936    for (TemplateParameterList::iterator Param = Params->begin(),
5937                                      ParamEnd = Params->end();
5938          Param != ParamEnd; ++Param) {
5939      NamedDecl *Named = cast<NamedDecl>(*Param);
5940      if (Named->getDeclName()) {
5941        S->AddDecl(Named);
5942        IdResolver.AddDecl(Named);
5943      }
5944    }
5945  }
5946}
5947
5948void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
5949  if (!D)
5950    return;
5951
5952  TemplateParameterList *Params = 0;
5953  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5954    Params = Template->getTemplateParameters();
5955  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5956           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5957    Params = PartialSpec->getTemplateParameters();
5958  else
5959    return;
5960
5961  for (TemplateParameterList::iterator Param = Params->begin(),
5962                                    ParamEnd = Params->end();
5963       Param != ParamEnd; ++Param) {
5964    NamedDecl *Named = cast<NamedDecl>(*Param);
5965    if (Named->getDeclName()) {
5966      S->AddDecl(Named);
5967      IdResolver.AddDecl(Named);
5968    }
5969  }
5970}
5971
5972void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5973  if (!RecordD) return;
5974  AdjustDeclIfTemplate(RecordD);
5975  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
5976  PushDeclContext(S, Record);
5977}
5978
5979void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
5980  if (!RecordD) return;
5981  PopDeclContext();
5982}
5983
5984/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5985/// parsing a top-level (non-nested) C++ class, and we are now
5986/// parsing those parts of the given Method declaration that could
5987/// not be parsed earlier (C++ [class.mem]p2), such as default
5988/// arguments. This action should enter the scope of the given
5989/// Method declaration as if we had just parsed the qualified method
5990/// name. However, it should not bring the parameters into scope;
5991/// that will be performed by ActOnDelayedCXXMethodParameter.
5992void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
5993}
5994
5995/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5996/// C++ method declaration. We're (re-)introducing the given
5997/// function parameter into scope for use in parsing later parts of
5998/// the method declaration. For example, we could see an
5999/// ActOnParamDefaultArgument event for this parameter.
6000void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
6001  if (!ParamD)
6002    return;
6003
6004  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
6005
6006  // If this parameter has an unparsed default argument, clear it out
6007  // to make way for the parsed default argument.
6008  if (Param->hasUnparsedDefaultArg())
6009    Param->setDefaultArg(0);
6010
6011  S->AddDecl(Param);
6012  if (Param->getDeclName())
6013    IdResolver.AddDecl(Param);
6014}
6015
6016/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
6017/// processing the delayed method declaration for Method. The method
6018/// declaration is now considered finished. There may be a separate
6019/// ActOnStartOfFunctionDef action later (not necessarily
6020/// immediately!) for this method, if it was also defined inside the
6021/// class body.
6022void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
6023  if (!MethodD)
6024    return;
6025
6026  AdjustDeclIfTemplate(MethodD);
6027
6028  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
6029
6030  // Now that we have our default arguments, check the constructor
6031  // again. It could produce additional diagnostics or affect whether
6032  // the class has implicitly-declared destructors, among other
6033  // things.
6034  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
6035    CheckConstructor(Constructor);
6036
6037  // Check the default arguments, which we may have added.
6038  if (!Method->isInvalidDecl())
6039    CheckCXXDefaultArguments(Method);
6040}
6041
6042/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
6043/// the well-formedness of the constructor declarator @p D with type @p
6044/// R. If there are any errors in the declarator, this routine will
6045/// emit diagnostics and set the invalid bit to true.  In any case, the type
6046/// will be updated to reflect a well-formed type for the constructor and
6047/// returned.
6048QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
6049                                          StorageClass &SC) {
6050  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6051
6052  // C++ [class.ctor]p3:
6053  //   A constructor shall not be virtual (10.3) or static (9.4). A
6054  //   constructor can be invoked for a const, volatile or const
6055  //   volatile object. A constructor shall not be declared const,
6056  //   volatile, or const volatile (9.3.2).
6057  if (isVirtual) {
6058    if (!D.isInvalidType())
6059      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6060        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
6061        << SourceRange(D.getIdentifierLoc());
6062    D.setInvalidType();
6063  }
6064  if (SC == SC_Static) {
6065    if (!D.isInvalidType())
6066      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
6067        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6068        << SourceRange(D.getIdentifierLoc());
6069    D.setInvalidType();
6070    SC = SC_None;
6071  }
6072
6073  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6074  if (FTI.TypeQuals != 0) {
6075    if (FTI.TypeQuals & Qualifiers::Const)
6076      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6077        << "const" << SourceRange(D.getIdentifierLoc());
6078    if (FTI.TypeQuals & Qualifiers::Volatile)
6079      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6080        << "volatile" << SourceRange(D.getIdentifierLoc());
6081    if (FTI.TypeQuals & Qualifiers::Restrict)
6082      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
6083        << "restrict" << SourceRange(D.getIdentifierLoc());
6084    D.setInvalidType();
6085  }
6086
6087  // C++0x [class.ctor]p4:
6088  //   A constructor shall not be declared with a ref-qualifier.
6089  if (FTI.hasRefQualifier()) {
6090    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
6091      << FTI.RefQualifierIsLValueRef
6092      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6093    D.setInvalidType();
6094  }
6095
6096  // Rebuild the function type "R" without any type qualifiers (in
6097  // case any of the errors above fired) and with "void" as the
6098  // return type, since constructors don't have return types.
6099  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6100  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
6101    return R;
6102
6103  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6104  EPI.TypeQuals = 0;
6105  EPI.RefQualifier = RQ_None;
6106
6107  return Context.getFunctionType(Context.VoidTy, Proto->getArgTypes(), EPI);
6108}
6109
6110/// CheckConstructor - Checks a fully-formed constructor for
6111/// well-formedness, issuing any diagnostics required. Returns true if
6112/// the constructor declarator is invalid.
6113void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
6114  CXXRecordDecl *ClassDecl
6115    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
6116  if (!ClassDecl)
6117    return Constructor->setInvalidDecl();
6118
6119  // C++ [class.copy]p3:
6120  //   A declaration of a constructor for a class X is ill-formed if
6121  //   its first parameter is of type (optionally cv-qualified) X and
6122  //   either there are no other parameters or else all other
6123  //   parameters have default arguments.
6124  if (!Constructor->isInvalidDecl() &&
6125      ((Constructor->getNumParams() == 1) ||
6126       (Constructor->getNumParams() > 1 &&
6127        Constructor->getParamDecl(1)->hasDefaultArg())) &&
6128      Constructor->getTemplateSpecializationKind()
6129                                              != TSK_ImplicitInstantiation) {
6130    QualType ParamType = Constructor->getParamDecl(0)->getType();
6131    QualType ClassTy = Context.getTagDeclType(ClassDecl);
6132    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
6133      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
6134      const char *ConstRef
6135        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
6136                                                        : " const &";
6137      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
6138        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
6139
6140      // FIXME: Rather that making the constructor invalid, we should endeavor
6141      // to fix the type.
6142      Constructor->setInvalidDecl();
6143    }
6144  }
6145}
6146
6147/// CheckDestructor - Checks a fully-formed destructor definition for
6148/// well-formedness, issuing any diagnostics required.  Returns true
6149/// on error.
6150bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
6151  CXXRecordDecl *RD = Destructor->getParent();
6152
6153  if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
6154    SourceLocation Loc;
6155
6156    if (!Destructor->isImplicit())
6157      Loc = Destructor->getLocation();
6158    else
6159      Loc = RD->getLocation();
6160
6161    // If we have a virtual destructor, look up the deallocation function
6162    FunctionDecl *OperatorDelete = 0;
6163    DeclarationName Name =
6164    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6165    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
6166      return true;
6167
6168    MarkFunctionReferenced(Loc, OperatorDelete);
6169
6170    Destructor->setOperatorDelete(OperatorDelete);
6171  }
6172
6173  return false;
6174}
6175
6176static inline bool
6177FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
6178  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6179          FTI.ArgInfo[0].Param &&
6180          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
6181}
6182
6183/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
6184/// the well-formednes of the destructor declarator @p D with type @p
6185/// R. If there are any errors in the declarator, this routine will
6186/// emit diagnostics and set the declarator to invalid.  Even if this happens,
6187/// will be updated to reflect a well-formed type for the destructor and
6188/// returned.
6189QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
6190                                         StorageClass& SC) {
6191  // C++ [class.dtor]p1:
6192  //   [...] A typedef-name that names a class is a class-name
6193  //   (7.1.3); however, a typedef-name that names a class shall not
6194  //   be used as the identifier in the declarator for a destructor
6195  //   declaration.
6196  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
6197  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
6198    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6199      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
6200  else if (const TemplateSpecializationType *TST =
6201             DeclaratorType->getAs<TemplateSpecializationType>())
6202    if (TST->isTypeAlias())
6203      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
6204        << DeclaratorType << 1;
6205
6206  // C++ [class.dtor]p2:
6207  //   A destructor is used to destroy objects of its class type. A
6208  //   destructor takes no parameters, and no return type can be
6209  //   specified for it (not even void). The address of a destructor
6210  //   shall not be taken. A destructor shall not be static. A
6211  //   destructor can be invoked for a const, volatile or const
6212  //   volatile object. A destructor shall not be declared const,
6213  //   volatile or const volatile (9.3.2).
6214  if (SC == SC_Static) {
6215    if (!D.isInvalidType())
6216      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
6217        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6218        << SourceRange(D.getIdentifierLoc())
6219        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6220
6221    SC = SC_None;
6222  }
6223  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6224    // Destructors don't have return types, but the parser will
6225    // happily parse something like:
6226    //
6227    //   class X {
6228    //     float ~X();
6229    //   };
6230    //
6231    // The return type will be eliminated later.
6232    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
6233      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6234      << SourceRange(D.getIdentifierLoc());
6235  }
6236
6237  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6238  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
6239    if (FTI.TypeQuals & Qualifiers::Const)
6240      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6241        << "const" << SourceRange(D.getIdentifierLoc());
6242    if (FTI.TypeQuals & Qualifiers::Volatile)
6243      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6244        << "volatile" << SourceRange(D.getIdentifierLoc());
6245    if (FTI.TypeQuals & Qualifiers::Restrict)
6246      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
6247        << "restrict" << SourceRange(D.getIdentifierLoc());
6248    D.setInvalidType();
6249  }
6250
6251  // C++0x [class.dtor]p2:
6252  //   A destructor shall not be declared with a ref-qualifier.
6253  if (FTI.hasRefQualifier()) {
6254    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
6255      << FTI.RefQualifierIsLValueRef
6256      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
6257    D.setInvalidType();
6258  }
6259
6260  // Make sure we don't have any parameters.
6261  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
6262    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
6263
6264    // Delete the parameters.
6265    FTI.freeArgs();
6266    D.setInvalidType();
6267  }
6268
6269  // Make sure the destructor isn't variadic.
6270  if (FTI.isVariadic) {
6271    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
6272    D.setInvalidType();
6273  }
6274
6275  // Rebuild the function type "R" without any type qualifiers or
6276  // parameters (in case any of the errors above fired) and with
6277  // "void" as the return type, since destructors don't have return
6278  // types.
6279  if (!D.isInvalidType())
6280    return R;
6281
6282  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6283  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
6284  EPI.Variadic = false;
6285  EPI.TypeQuals = 0;
6286  EPI.RefQualifier = RQ_None;
6287  return Context.getFunctionType(Context.VoidTy, None, EPI);
6288}
6289
6290/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
6291/// well-formednes of the conversion function declarator @p D with
6292/// type @p R. If there are any errors in the declarator, this routine
6293/// will emit diagnostics and return true. Otherwise, it will return
6294/// false. Either way, the type @p R will be updated to reflect a
6295/// well-formed type for the conversion operator.
6296void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
6297                                     StorageClass& SC) {
6298  // C++ [class.conv.fct]p1:
6299  //   Neither parameter types nor return type can be specified. The
6300  //   type of a conversion function (8.3.5) is "function taking no
6301  //   parameter returning conversion-type-id."
6302  if (SC == SC_Static) {
6303    if (!D.isInvalidType())
6304      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
6305        << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
6306        << D.getName().getSourceRange();
6307    D.setInvalidType();
6308    SC = SC_None;
6309  }
6310
6311  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
6312
6313  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
6314    // Conversion functions don't have return types, but the parser will
6315    // happily parse something like:
6316    //
6317    //   class X {
6318    //     float operator bool();
6319    //   };
6320    //
6321    // The return type will be changed later anyway.
6322    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
6323      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6324      << SourceRange(D.getIdentifierLoc());
6325    D.setInvalidType();
6326  }
6327
6328  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
6329
6330  // Make sure we don't have any parameters.
6331  if (Proto->getNumArgs() > 0) {
6332    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
6333
6334    // Delete the parameters.
6335    D.getFunctionTypeInfo().freeArgs();
6336    D.setInvalidType();
6337  } else if (Proto->isVariadic()) {
6338    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
6339    D.setInvalidType();
6340  }
6341
6342  // Diagnose "&operator bool()" and other such nonsense.  This
6343  // is actually a gcc extension which we don't support.
6344  if (Proto->getResultType() != ConvType) {
6345    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
6346      << Proto->getResultType();
6347    D.setInvalidType();
6348    ConvType = Proto->getResultType();
6349  }
6350
6351  // C++ [class.conv.fct]p4:
6352  //   The conversion-type-id shall not represent a function type nor
6353  //   an array type.
6354  if (ConvType->isArrayType()) {
6355    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
6356    ConvType = Context.getPointerType(ConvType);
6357    D.setInvalidType();
6358  } else if (ConvType->isFunctionType()) {
6359    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
6360    ConvType = Context.getPointerType(ConvType);
6361    D.setInvalidType();
6362  }
6363
6364  // Rebuild the function type "R" without any parameters (in case any
6365  // of the errors above fired) and with the conversion type as the
6366  // return type.
6367  if (D.isInvalidType())
6368    R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
6369
6370  // C++0x explicit conversion operators.
6371  if (D.getDeclSpec().isExplicitSpecified())
6372    Diag(D.getDeclSpec().getExplicitSpecLoc(),
6373         getLangOpts().CPlusPlus11 ?
6374           diag::warn_cxx98_compat_explicit_conversion_functions :
6375           diag::ext_explicit_conversion_functions)
6376      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
6377}
6378
6379/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
6380/// the declaration of the given C++ conversion function. This routine
6381/// is responsible for recording the conversion function in the C++
6382/// class, if possible.
6383Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
6384  assert(Conversion && "Expected to receive a conversion function declaration");
6385
6386  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
6387
6388  // Make sure we aren't redeclaring the conversion function.
6389  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
6390
6391  // C++ [class.conv.fct]p1:
6392  //   [...] A conversion function is never used to convert a
6393  //   (possibly cv-qualified) object to the (possibly cv-qualified)
6394  //   same object type (or a reference to it), to a (possibly
6395  //   cv-qualified) base class of that type (or a reference to it),
6396  //   or to (possibly cv-qualified) void.
6397  // FIXME: Suppress this warning if the conversion function ends up being a
6398  // virtual function that overrides a virtual function in a base class.
6399  QualType ClassType
6400    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6401  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
6402    ConvType = ConvTypeRef->getPointeeType();
6403  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
6404      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6405    /* Suppress diagnostics for instantiations. */;
6406  else if (ConvType->isRecordType()) {
6407    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
6408    if (ConvType == ClassType)
6409      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
6410        << ClassType;
6411    else if (IsDerivedFrom(ClassType, ConvType))
6412      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
6413        <<  ClassType << ConvType;
6414  } else if (ConvType->isVoidType()) {
6415    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
6416      << ClassType << ConvType;
6417  }
6418
6419  if (FunctionTemplateDecl *ConversionTemplate
6420                                = Conversion->getDescribedFunctionTemplate())
6421    return ConversionTemplate;
6422
6423  return Conversion;
6424}
6425
6426//===----------------------------------------------------------------------===//
6427// Namespace Handling
6428//===----------------------------------------------------------------------===//
6429
6430/// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
6431/// reopened.
6432static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
6433                                            SourceLocation Loc,
6434                                            IdentifierInfo *II, bool *IsInline,
6435                                            NamespaceDecl *PrevNS) {
6436  assert(*IsInline != PrevNS->isInline());
6437
6438  // HACK: Work around a bug in libstdc++4.6's <atomic>, where
6439  // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
6440  // inline namespaces, with the intention of bringing names into namespace std.
6441  //
6442  // We support this just well enough to get that case working; this is not
6443  // sufficient to support reopening namespaces as inline in general.
6444  if (*IsInline && II && II->getName().startswith("__atomic") &&
6445      S.getSourceManager().isInSystemHeader(Loc)) {
6446    // Mark all prior declarations of the namespace as inline.
6447    for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
6448         NS = NS->getPreviousDecl())
6449      NS->setInline(*IsInline);
6450    // Patch up the lookup table for the containing namespace. This isn't really
6451    // correct, but it's good enough for this particular case.
6452    for (DeclContext::decl_iterator I = PrevNS->decls_begin(),
6453                                    E = PrevNS->decls_end(); I != E; ++I)
6454      if (NamedDecl *ND = dyn_cast<NamedDecl>(*I))
6455        PrevNS->getParent()->makeDeclVisibleInContext(ND);
6456    return;
6457  }
6458
6459  if (PrevNS->isInline())
6460    // The user probably just forgot the 'inline', so suggest that it
6461    // be added back.
6462    S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
6463      << FixItHint::CreateInsertion(KeywordLoc, "inline ");
6464  else
6465    S.Diag(Loc, diag::err_inline_namespace_mismatch)
6466      << IsInline;
6467
6468  S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
6469  *IsInline = PrevNS->isInline();
6470}
6471
6472/// ActOnStartNamespaceDef - This is called at the start of a namespace
6473/// definition.
6474Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
6475                                   SourceLocation InlineLoc,
6476                                   SourceLocation NamespaceLoc,
6477                                   SourceLocation IdentLoc,
6478                                   IdentifierInfo *II,
6479                                   SourceLocation LBrace,
6480                                   AttributeList *AttrList) {
6481  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
6482  // For anonymous namespace, take the location of the left brace.
6483  SourceLocation Loc = II ? IdentLoc : LBrace;
6484  bool IsInline = InlineLoc.isValid();
6485  bool IsInvalid = false;
6486  bool IsStd = false;
6487  bool AddToKnown = false;
6488  Scope *DeclRegionScope = NamespcScope->getParent();
6489
6490  NamespaceDecl *PrevNS = 0;
6491  if (II) {
6492    // C++ [namespace.def]p2:
6493    //   The identifier in an original-namespace-definition shall not
6494    //   have been previously defined in the declarative region in
6495    //   which the original-namespace-definition appears. The
6496    //   identifier in an original-namespace-definition is the name of
6497    //   the namespace. Subsequently in that declarative region, it is
6498    //   treated as an original-namespace-name.
6499    //
6500    // Since namespace names are unique in their scope, and we don't
6501    // look through using directives, just look for any ordinary names.
6502
6503    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
6504    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
6505    Decl::IDNS_Namespace;
6506    NamedDecl *PrevDecl = 0;
6507    DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
6508    for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6509         ++I) {
6510      if ((*I)->getIdentifierNamespace() & IDNS) {
6511        PrevDecl = *I;
6512        break;
6513      }
6514    }
6515
6516    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
6517
6518    if (PrevNS) {
6519      // This is an extended namespace definition.
6520      if (IsInline != PrevNS->isInline())
6521        DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
6522                                        &IsInline, PrevNS);
6523    } else if (PrevDecl) {
6524      // This is an invalid name redefinition.
6525      Diag(Loc, diag::err_redefinition_different_kind)
6526        << II;
6527      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6528      IsInvalid = true;
6529      // Continue on to push Namespc as current DeclContext and return it.
6530    } else if (II->isStr("std") &&
6531               CurContext->getRedeclContext()->isTranslationUnit()) {
6532      // This is the first "real" definition of the namespace "std", so update
6533      // our cache of the "std" namespace to point at this definition.
6534      PrevNS = getStdNamespace();
6535      IsStd = true;
6536      AddToKnown = !IsInline;
6537    } else {
6538      // We've seen this namespace for the first time.
6539      AddToKnown = !IsInline;
6540    }
6541  } else {
6542    // Anonymous namespaces.
6543
6544    // Determine whether the parent already has an anonymous namespace.
6545    DeclContext *Parent = CurContext->getRedeclContext();
6546    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6547      PrevNS = TU->getAnonymousNamespace();
6548    } else {
6549      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
6550      PrevNS = ND->getAnonymousNamespace();
6551    }
6552
6553    if (PrevNS && IsInline != PrevNS->isInline())
6554      DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
6555                                      &IsInline, PrevNS);
6556  }
6557
6558  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
6559                                                 StartLoc, Loc, II, PrevNS);
6560  if (IsInvalid)
6561    Namespc->setInvalidDecl();
6562
6563  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
6564
6565  // FIXME: Should we be merging attributes?
6566  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
6567    PushNamespaceVisibilityAttr(Attr, Loc);
6568
6569  if (IsStd)
6570    StdNamespace = Namespc;
6571  if (AddToKnown)
6572    KnownNamespaces[Namespc] = false;
6573
6574  if (II) {
6575    PushOnScopeChains(Namespc, DeclRegionScope);
6576  } else {
6577    // Link the anonymous namespace into its parent.
6578    DeclContext *Parent = CurContext->getRedeclContext();
6579    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
6580      TU->setAnonymousNamespace(Namespc);
6581    } else {
6582      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
6583    }
6584
6585    CurContext->addDecl(Namespc);
6586
6587    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
6588    //   behaves as if it were replaced by
6589    //     namespace unique { /* empty body */ }
6590    //     using namespace unique;
6591    //     namespace unique { namespace-body }
6592    //   where all occurrences of 'unique' in a translation unit are
6593    //   replaced by the same identifier and this identifier differs
6594    //   from all other identifiers in the entire program.
6595
6596    // We just create the namespace with an empty name and then add an
6597    // implicit using declaration, just like the standard suggests.
6598    //
6599    // CodeGen enforces the "universally unique" aspect by giving all
6600    // declarations semantically contained within an anonymous
6601    // namespace internal linkage.
6602
6603    if (!PrevNS) {
6604      UsingDirectiveDecl* UD
6605        = UsingDirectiveDecl::Create(Context, Parent,
6606                                     /* 'using' */ LBrace,
6607                                     /* 'namespace' */ SourceLocation(),
6608                                     /* qualifier */ NestedNameSpecifierLoc(),
6609                                     /* identifier */ SourceLocation(),
6610                                     Namespc,
6611                                     /* Ancestor */ Parent);
6612      UD->setImplicit();
6613      Parent->addDecl(UD);
6614    }
6615  }
6616
6617  ActOnDocumentableDecl(Namespc);
6618
6619  // Although we could have an invalid decl (i.e. the namespace name is a
6620  // redefinition), push it as current DeclContext and try to continue parsing.
6621  // FIXME: We should be able to push Namespc here, so that the each DeclContext
6622  // for the namespace has the declarations that showed up in that particular
6623  // namespace definition.
6624  PushDeclContext(NamespcScope, Namespc);
6625  return Namespc;
6626}
6627
6628/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
6629/// is a namespace alias, returns the namespace it points to.
6630static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
6631  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
6632    return AD->getNamespace();
6633  return dyn_cast_or_null<NamespaceDecl>(D);
6634}
6635
6636/// ActOnFinishNamespaceDef - This callback is called after a namespace is
6637/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
6638void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
6639  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
6640  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
6641  Namespc->setRBraceLoc(RBrace);
6642  PopDeclContext();
6643  if (Namespc->hasAttr<VisibilityAttr>())
6644    PopPragmaVisibility(true, RBrace);
6645}
6646
6647CXXRecordDecl *Sema::getStdBadAlloc() const {
6648  return cast_or_null<CXXRecordDecl>(
6649                                  StdBadAlloc.get(Context.getExternalSource()));
6650}
6651
6652NamespaceDecl *Sema::getStdNamespace() const {
6653  return cast_or_null<NamespaceDecl>(
6654                                 StdNamespace.get(Context.getExternalSource()));
6655}
6656
6657/// \brief Retrieve the special "std" namespace, which may require us to
6658/// implicitly define the namespace.
6659NamespaceDecl *Sema::getOrCreateStdNamespace() {
6660  if (!StdNamespace) {
6661    // The "std" namespace has not yet been defined, so build one implicitly.
6662    StdNamespace = NamespaceDecl::Create(Context,
6663                                         Context.getTranslationUnitDecl(),
6664                                         /*Inline=*/false,
6665                                         SourceLocation(), SourceLocation(),
6666                                         &PP.getIdentifierTable().get("std"),
6667                                         /*PrevDecl=*/0);
6668    getStdNamespace()->setImplicit(true);
6669  }
6670
6671  return getStdNamespace();
6672}
6673
6674bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
6675  assert(getLangOpts().CPlusPlus &&
6676         "Looking for std::initializer_list outside of C++.");
6677
6678  // We're looking for implicit instantiations of
6679  // template <typename E> class std::initializer_list.
6680
6681  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
6682    return false;
6683
6684  ClassTemplateDecl *Template = 0;
6685  const TemplateArgument *Arguments = 0;
6686
6687  if (const RecordType *RT = Ty->getAs<RecordType>()) {
6688
6689    ClassTemplateSpecializationDecl *Specialization =
6690        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
6691    if (!Specialization)
6692      return false;
6693
6694    Template = Specialization->getSpecializedTemplate();
6695    Arguments = Specialization->getTemplateArgs().data();
6696  } else if (const TemplateSpecializationType *TST =
6697                 Ty->getAs<TemplateSpecializationType>()) {
6698    Template = dyn_cast_or_null<ClassTemplateDecl>(
6699        TST->getTemplateName().getAsTemplateDecl());
6700    Arguments = TST->getArgs();
6701  }
6702  if (!Template)
6703    return false;
6704
6705  if (!StdInitializerList) {
6706    // Haven't recognized std::initializer_list yet, maybe this is it.
6707    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
6708    if (TemplateClass->getIdentifier() !=
6709            &PP.getIdentifierTable().get("initializer_list") ||
6710        !getStdNamespace()->InEnclosingNamespaceSetOf(
6711            TemplateClass->getDeclContext()))
6712      return false;
6713    // This is a template called std::initializer_list, but is it the right
6714    // template?
6715    TemplateParameterList *Params = Template->getTemplateParameters();
6716    if (Params->getMinRequiredArguments() != 1)
6717      return false;
6718    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
6719      return false;
6720
6721    // It's the right template.
6722    StdInitializerList = Template;
6723  }
6724
6725  if (Template != StdInitializerList)
6726    return false;
6727
6728  // This is an instance of std::initializer_list. Find the argument type.
6729  if (Element)
6730    *Element = Arguments[0].getAsType();
6731  return true;
6732}
6733
6734static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
6735  NamespaceDecl *Std = S.getStdNamespace();
6736  if (!Std) {
6737    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6738    return 0;
6739  }
6740
6741  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
6742                      Loc, Sema::LookupOrdinaryName);
6743  if (!S.LookupQualifiedName(Result, Std)) {
6744    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
6745    return 0;
6746  }
6747  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
6748  if (!Template) {
6749    Result.suppressDiagnostics();
6750    // We found something weird. Complain about the first thing we found.
6751    NamedDecl *Found = *Result.begin();
6752    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
6753    return 0;
6754  }
6755
6756  // We found some template called std::initializer_list. Now verify that it's
6757  // correct.
6758  TemplateParameterList *Params = Template->getTemplateParameters();
6759  if (Params->getMinRequiredArguments() != 1 ||
6760      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6761    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
6762    return 0;
6763  }
6764
6765  return Template;
6766}
6767
6768QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
6769  if (!StdInitializerList) {
6770    StdInitializerList = LookupStdInitializerList(*this, Loc);
6771    if (!StdInitializerList)
6772      return QualType();
6773  }
6774
6775  TemplateArgumentListInfo Args(Loc, Loc);
6776  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
6777                                       Context.getTrivialTypeSourceInfo(Element,
6778                                                                        Loc)));
6779  return Context.getCanonicalType(
6780      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
6781}
6782
6783bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
6784  // C++ [dcl.init.list]p2:
6785  //   A constructor is an initializer-list constructor if its first parameter
6786  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
6787  //   std::initializer_list<E> for some type E, and either there are no other
6788  //   parameters or else all other parameters have default arguments.
6789  if (Ctor->getNumParams() < 1 ||
6790      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
6791    return false;
6792
6793  QualType ArgType = Ctor->getParamDecl(0)->getType();
6794  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
6795    ArgType = RT->getPointeeType().getUnqualifiedType();
6796
6797  return isStdInitializerList(ArgType, 0);
6798}
6799
6800/// \brief Determine whether a using statement is in a context where it will be
6801/// apply in all contexts.
6802static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
6803  switch (CurContext->getDeclKind()) {
6804    case Decl::TranslationUnit:
6805      return true;
6806    case Decl::LinkageSpec:
6807      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
6808    default:
6809      return false;
6810  }
6811}
6812
6813namespace {
6814
6815// Callback to only accept typo corrections that are namespaces.
6816class NamespaceValidatorCCC : public CorrectionCandidateCallback {
6817public:
6818  bool ValidateCandidate(const TypoCorrection &candidate) LLVM_OVERRIDE {
6819    if (NamedDecl *ND = candidate.getCorrectionDecl())
6820      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
6821    return false;
6822  }
6823};
6824
6825}
6826
6827static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
6828                                       CXXScopeSpec &SS,
6829                                       SourceLocation IdentLoc,
6830                                       IdentifierInfo *Ident) {
6831  NamespaceValidatorCCC Validator;
6832  R.clear();
6833  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
6834                                               R.getLookupKind(), Sc, &SS,
6835                                               Validator)) {
6836    if (DeclContext *DC = S.computeDeclContext(SS, false)) {
6837      std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
6838      bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
6839                              Ident->getName().equals(CorrectedStr);
6840      S.diagnoseTypo(Corrected,
6841                     S.PDiag(diag::err_using_directive_member_suggest)
6842                       << Ident << DC << DroppedSpecifier << SS.getRange(),
6843                     S.PDiag(diag::note_namespace_defined_here));
6844    } else {
6845      S.diagnoseTypo(Corrected,
6846                     S.PDiag(diag::err_using_directive_suggest) << Ident,
6847                     S.PDiag(diag::note_namespace_defined_here));
6848    }
6849    R.addDecl(Corrected.getCorrectionDecl());
6850    return true;
6851  }
6852  return false;
6853}
6854
6855Decl *Sema::ActOnUsingDirective(Scope *S,
6856                                          SourceLocation UsingLoc,
6857                                          SourceLocation NamespcLoc,
6858                                          CXXScopeSpec &SS,
6859                                          SourceLocation IdentLoc,
6860                                          IdentifierInfo *NamespcName,
6861                                          AttributeList *AttrList) {
6862  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6863  assert(NamespcName && "Invalid NamespcName.");
6864  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
6865
6866  // This can only happen along a recovery path.
6867  while (S->getFlags() & Scope::TemplateParamScope)
6868    S = S->getParent();
6869  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6870
6871  UsingDirectiveDecl *UDir = 0;
6872  NestedNameSpecifier *Qualifier = 0;
6873  if (SS.isSet())
6874    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6875
6876  // Lookup namespace name.
6877  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6878  LookupParsedName(R, S, &SS);
6879  if (R.isAmbiguous())
6880    return 0;
6881
6882  if (R.empty()) {
6883    R.clear();
6884    // Allow "using namespace std;" or "using namespace ::std;" even if
6885    // "std" hasn't been defined yet, for GCC compatibility.
6886    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6887        NamespcName->isStr("std")) {
6888      Diag(IdentLoc, diag::ext_using_undefined_std);
6889      R.addDecl(getOrCreateStdNamespace());
6890      R.resolveKind();
6891    }
6892    // Otherwise, attempt typo correction.
6893    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
6894  }
6895
6896  if (!R.empty()) {
6897    NamedDecl *Named = R.getFoundDecl();
6898    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6899        && "expected namespace decl");
6900    // C++ [namespace.udir]p1:
6901    //   A using-directive specifies that the names in the nominated
6902    //   namespace can be used in the scope in which the
6903    //   using-directive appears after the using-directive. During
6904    //   unqualified name lookup (3.4.1), the names appear as if they
6905    //   were declared in the nearest enclosing namespace which
6906    //   contains both the using-directive and the nominated
6907    //   namespace. [Note: in this context, "contains" means "contains
6908    //   directly or indirectly". ]
6909
6910    // Find enclosing context containing both using-directive and
6911    // nominated namespace.
6912    NamespaceDecl *NS = getNamespaceDecl(Named);
6913    DeclContext *CommonAncestor = cast<DeclContext>(NS);
6914    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6915      CommonAncestor = CommonAncestor->getParent();
6916
6917    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
6918                                      SS.getWithLocInContext(Context),
6919                                      IdentLoc, Named, CommonAncestor);
6920
6921    if (IsUsingDirectiveInToplevelContext(CurContext) &&
6922        !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
6923      Diag(IdentLoc, diag::warn_using_directive_in_header);
6924    }
6925
6926    PushUsingDirective(S, UDir);
6927  } else {
6928    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6929  }
6930
6931  if (UDir)
6932    ProcessDeclAttributeList(S, UDir, AttrList);
6933
6934  return UDir;
6935}
6936
6937void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6938  // If the scope has an associated entity and the using directive is at
6939  // namespace or translation unit scope, add the UsingDirectiveDecl into
6940  // its lookup structure so qualified name lookup can find it.
6941  DeclContext *Ctx = S->getEntity();
6942  if (Ctx && !Ctx->isFunctionOrMethod())
6943    Ctx->addDecl(UDir);
6944  else
6945    // Otherwise, it is at block sope. The using-directives will affect lookup
6946    // only to the end of the scope.
6947    S->PushUsingDirective(UDir);
6948}
6949
6950
6951Decl *Sema::ActOnUsingDeclaration(Scope *S,
6952                                  AccessSpecifier AS,
6953                                  bool HasUsingKeyword,
6954                                  SourceLocation UsingLoc,
6955                                  CXXScopeSpec &SS,
6956                                  UnqualifiedId &Name,
6957                                  AttributeList *AttrList,
6958                                  bool HasTypenameKeyword,
6959                                  SourceLocation TypenameLoc) {
6960  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
6961
6962  switch (Name.getKind()) {
6963  case UnqualifiedId::IK_ImplicitSelfParam:
6964  case UnqualifiedId::IK_Identifier:
6965  case UnqualifiedId::IK_OperatorFunctionId:
6966  case UnqualifiedId::IK_LiteralOperatorId:
6967  case UnqualifiedId::IK_ConversionFunctionId:
6968    break;
6969
6970  case UnqualifiedId::IK_ConstructorName:
6971  case UnqualifiedId::IK_ConstructorTemplateId:
6972    // C++11 inheriting constructors.
6973    Diag(Name.getLocStart(),
6974         getLangOpts().CPlusPlus11 ?
6975           diag::warn_cxx98_compat_using_decl_constructor :
6976           diag::err_using_decl_constructor)
6977      << SS.getRange();
6978
6979    if (getLangOpts().CPlusPlus11) break;
6980
6981    return 0;
6982
6983  case UnqualifiedId::IK_DestructorName:
6984    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
6985      << SS.getRange();
6986    return 0;
6987
6988  case UnqualifiedId::IK_TemplateId:
6989    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
6990      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
6991    return 0;
6992  }
6993
6994  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6995  DeclarationName TargetName = TargetNameInfo.getName();
6996  if (!TargetName)
6997    return 0;
6998
6999  // Warn about access declarations.
7000  if (!HasUsingKeyword) {
7001    Diag(Name.getLocStart(),
7002         getLangOpts().CPlusPlus11 ? diag::err_access_decl
7003                                   : diag::warn_access_decl_deprecated)
7004      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
7005  }
7006
7007  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
7008      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
7009    return 0;
7010
7011  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
7012                                        TargetNameInfo, AttrList,
7013                                        /* IsInstantiation */ false,
7014                                        HasTypenameKeyword, TypenameLoc);
7015  if (UD)
7016    PushOnScopeChains(UD, S, /*AddToContext*/ false);
7017
7018  return UD;
7019}
7020
7021/// \brief Determine whether a using declaration considers the given
7022/// declarations as "equivalent", e.g., if they are redeclarations of
7023/// the same entity or are both typedefs of the same type.
7024static bool
7025IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
7026  if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
7027    return true;
7028
7029  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
7030    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
7031      return Context.hasSameType(TD1->getUnderlyingType(),
7032                                 TD2->getUnderlyingType());
7033
7034  return false;
7035}
7036
7037
7038/// Determines whether to create a using shadow decl for a particular
7039/// decl, given the set of decls existing prior to this using lookup.
7040bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
7041                                const LookupResult &Previous,
7042                                UsingShadowDecl *&PrevShadow) {
7043  // Diagnose finding a decl which is not from a base class of the
7044  // current class.  We do this now because there are cases where this
7045  // function will silently decide not to build a shadow decl, which
7046  // will pre-empt further diagnostics.
7047  //
7048  // We don't need to do this in C++0x because we do the check once on
7049  // the qualifier.
7050  //
7051  // FIXME: diagnose the following if we care enough:
7052  //   struct A { int foo; };
7053  //   struct B : A { using A::foo; };
7054  //   template <class T> struct C : A {};
7055  //   template <class T> struct D : C<T> { using B::foo; } // <---
7056  // This is invalid (during instantiation) in C++03 because B::foo
7057  // resolves to the using decl in B, which is not a base class of D<T>.
7058  // We can't diagnose it immediately because C<T> is an unknown
7059  // specialization.  The UsingShadowDecl in D<T> then points directly
7060  // to A::foo, which will look well-formed when we instantiate.
7061  // The right solution is to not collapse the shadow-decl chain.
7062  if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
7063    DeclContext *OrigDC = Orig->getDeclContext();
7064
7065    // Handle enums and anonymous structs.
7066    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
7067    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
7068    while (OrigRec->isAnonymousStructOrUnion())
7069      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
7070
7071    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
7072      if (OrigDC == CurContext) {
7073        Diag(Using->getLocation(),
7074             diag::err_using_decl_nested_name_specifier_is_current_class)
7075          << Using->getQualifierLoc().getSourceRange();
7076        Diag(Orig->getLocation(), diag::note_using_decl_target);
7077        return true;
7078      }
7079
7080      Diag(Using->getQualifierLoc().getBeginLoc(),
7081           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7082        << Using->getQualifier()
7083        << cast<CXXRecordDecl>(CurContext)
7084        << Using->getQualifierLoc().getSourceRange();
7085      Diag(Orig->getLocation(), diag::note_using_decl_target);
7086      return true;
7087    }
7088  }
7089
7090  if (Previous.empty()) return false;
7091
7092  NamedDecl *Target = Orig;
7093  if (isa<UsingShadowDecl>(Target))
7094    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7095
7096  // If the target happens to be one of the previous declarations, we
7097  // don't have a conflict.
7098  //
7099  // FIXME: but we might be increasing its access, in which case we
7100  // should redeclare it.
7101  NamedDecl *NonTag = 0, *Tag = 0;
7102  bool FoundEquivalentDecl = false;
7103  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7104         I != E; ++I) {
7105    NamedDecl *D = (*I)->getUnderlyingDecl();
7106    if (IsEquivalentForUsingDecl(Context, D, Target)) {
7107      if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
7108        PrevShadow = Shadow;
7109      FoundEquivalentDecl = true;
7110    }
7111
7112    (isa<TagDecl>(D) ? Tag : NonTag) = D;
7113  }
7114
7115  if (FoundEquivalentDecl)
7116    return false;
7117
7118  if (Target->isFunctionOrFunctionTemplate()) {
7119    FunctionDecl *FD;
7120    if (isa<FunctionTemplateDecl>(Target))
7121      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
7122    else
7123      FD = cast<FunctionDecl>(Target);
7124
7125    NamedDecl *OldDecl = 0;
7126    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
7127    case Ovl_Overload:
7128      return false;
7129
7130    case Ovl_NonFunction:
7131      Diag(Using->getLocation(), diag::err_using_decl_conflict);
7132      break;
7133
7134    // We found a decl with the exact signature.
7135    case Ovl_Match:
7136      // If we're in a record, we want to hide the target, so we
7137      // return true (without a diagnostic) to tell the caller not to
7138      // build a shadow decl.
7139      if (CurContext->isRecord())
7140        return true;
7141
7142      // If we're not in a record, this is an error.
7143      Diag(Using->getLocation(), diag::err_using_decl_conflict);
7144      break;
7145    }
7146
7147    Diag(Target->getLocation(), diag::note_using_decl_target);
7148    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
7149    return true;
7150  }
7151
7152  // Target is not a function.
7153
7154  if (isa<TagDecl>(Target)) {
7155    // No conflict between a tag and a non-tag.
7156    if (!Tag) return false;
7157
7158    Diag(Using->getLocation(), diag::err_using_decl_conflict);
7159    Diag(Target->getLocation(), diag::note_using_decl_target);
7160    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
7161    return true;
7162  }
7163
7164  // No conflict between a tag and a non-tag.
7165  if (!NonTag) return false;
7166
7167  Diag(Using->getLocation(), diag::err_using_decl_conflict);
7168  Diag(Target->getLocation(), diag::note_using_decl_target);
7169  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
7170  return true;
7171}
7172
7173/// Builds a shadow declaration corresponding to a 'using' declaration.
7174UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
7175                                            UsingDecl *UD,
7176                                            NamedDecl *Orig,
7177                                            UsingShadowDecl *PrevDecl) {
7178
7179  // If we resolved to another shadow declaration, just coalesce them.
7180  NamedDecl *Target = Orig;
7181  if (isa<UsingShadowDecl>(Target)) {
7182    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
7183    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
7184  }
7185
7186  UsingShadowDecl *Shadow
7187    = UsingShadowDecl::Create(Context, CurContext,
7188                              UD->getLocation(), UD, Target);
7189  UD->addShadowDecl(Shadow);
7190
7191  Shadow->setAccess(UD->getAccess());
7192  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
7193    Shadow->setInvalidDecl();
7194
7195  Shadow->setPreviousDecl(PrevDecl);
7196
7197  if (S)
7198    PushOnScopeChains(Shadow, S);
7199  else
7200    CurContext->addDecl(Shadow);
7201
7202
7203  return Shadow;
7204}
7205
7206/// Hides a using shadow declaration.  This is required by the current
7207/// using-decl implementation when a resolvable using declaration in a
7208/// class is followed by a declaration which would hide or override
7209/// one or more of the using decl's targets; for example:
7210///
7211///   struct Base { void foo(int); };
7212///   struct Derived : Base {
7213///     using Base::foo;
7214///     void foo(int);
7215///   };
7216///
7217/// The governing language is C++03 [namespace.udecl]p12:
7218///
7219///   When a using-declaration brings names from a base class into a
7220///   derived class scope, member functions in the derived class
7221///   override and/or hide member functions with the same name and
7222///   parameter types in a base class (rather than conflicting).
7223///
7224/// There are two ways to implement this:
7225///   (1) optimistically create shadow decls when they're not hidden
7226///       by existing declarations, or
7227///   (2) don't create any shadow decls (or at least don't make them
7228///       visible) until we've fully parsed/instantiated the class.
7229/// The problem with (1) is that we might have to retroactively remove
7230/// a shadow decl, which requires several O(n) operations because the
7231/// decl structures are (very reasonably) not designed for removal.
7232/// (2) avoids this but is very fiddly and phase-dependent.
7233void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
7234  if (Shadow->getDeclName().getNameKind() ==
7235        DeclarationName::CXXConversionFunctionName)
7236    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
7237
7238  // Remove it from the DeclContext...
7239  Shadow->getDeclContext()->removeDecl(Shadow);
7240
7241  // ...and the scope, if applicable...
7242  if (S) {
7243    S->RemoveDecl(Shadow);
7244    IdResolver.RemoveDecl(Shadow);
7245  }
7246
7247  // ...and the using decl.
7248  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
7249
7250  // TODO: complain somehow if Shadow was used.  It shouldn't
7251  // be possible for this to happen, because...?
7252}
7253
7254namespace {
7255class UsingValidatorCCC : public CorrectionCandidateCallback {
7256public:
7257  UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
7258                    bool RequireMember)
7259      : HasTypenameKeyword(HasTypenameKeyword),
7260        IsInstantiation(IsInstantiation), RequireMember(RequireMember) {}
7261
7262  bool ValidateCandidate(const TypoCorrection &Candidate) LLVM_OVERRIDE {
7263    NamedDecl *ND = Candidate.getCorrectionDecl();
7264
7265    // Keywords are not valid here.
7266    if (!ND || isa<NamespaceDecl>(ND))
7267      return false;
7268
7269    if (RequireMember && !isa<FieldDecl>(ND) && !isa<CXXMethodDecl>(ND) &&
7270        !isa<TypeDecl>(ND))
7271      return false;
7272
7273    // Completely unqualified names are invalid for a 'using' declaration.
7274    if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
7275      return false;
7276
7277    if (isa<TypeDecl>(ND))
7278      return HasTypenameKeyword || !IsInstantiation;
7279
7280    return !HasTypenameKeyword;
7281  }
7282
7283private:
7284  bool HasTypenameKeyword;
7285  bool IsInstantiation;
7286  bool RequireMember;
7287};
7288} // end anonymous namespace
7289
7290/// Builds a using declaration.
7291///
7292/// \param IsInstantiation - Whether this call arises from an
7293///   instantiation of an unresolved using declaration.  We treat
7294///   the lookup differently for these declarations.
7295NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
7296                                       SourceLocation UsingLoc,
7297                                       CXXScopeSpec &SS,
7298                                       const DeclarationNameInfo &NameInfo,
7299                                       AttributeList *AttrList,
7300                                       bool IsInstantiation,
7301                                       bool HasTypenameKeyword,
7302                                       SourceLocation TypenameLoc) {
7303  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
7304  SourceLocation IdentLoc = NameInfo.getLoc();
7305  assert(IdentLoc.isValid() && "Invalid TargetName location.");
7306
7307  // FIXME: We ignore attributes for now.
7308
7309  if (SS.isEmpty()) {
7310    Diag(IdentLoc, diag::err_using_requires_qualname);
7311    return 0;
7312  }
7313
7314  // Do the redeclaration lookup in the current scope.
7315  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
7316                        ForRedeclaration);
7317  Previous.setHideTags(false);
7318  if (S) {
7319    LookupName(Previous, S);
7320
7321    // It is really dumb that we have to do this.
7322    LookupResult::Filter F = Previous.makeFilter();
7323    while (F.hasNext()) {
7324      NamedDecl *D = F.next();
7325      if (!isDeclInScope(D, CurContext, S))
7326        F.erase();
7327    }
7328    F.done();
7329  } else {
7330    assert(IsInstantiation && "no scope in non-instantiation");
7331    assert(CurContext->isRecord() && "scope not record in instantiation");
7332    LookupQualifiedName(Previous, CurContext);
7333  }
7334
7335  // Check for invalid redeclarations.
7336  if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
7337                                  SS, IdentLoc, Previous))
7338    return 0;
7339
7340  // Check for bad qualifiers.
7341  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
7342    return 0;
7343
7344  DeclContext *LookupContext = computeDeclContext(SS);
7345  NamedDecl *D;
7346  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7347  if (!LookupContext) {
7348    if (HasTypenameKeyword) {
7349      // FIXME: not all declaration name kinds are legal here
7350      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
7351                                              UsingLoc, TypenameLoc,
7352                                              QualifierLoc,
7353                                              IdentLoc, NameInfo.getName());
7354    } else {
7355      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
7356                                           QualifierLoc, NameInfo);
7357    }
7358  } else {
7359    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
7360                          NameInfo, HasTypenameKeyword);
7361  }
7362  D->setAccess(AS);
7363  CurContext->addDecl(D);
7364
7365  if (!LookupContext) return D;
7366  UsingDecl *UD = cast<UsingDecl>(D);
7367
7368  if (RequireCompleteDeclContext(SS, LookupContext)) {
7369    UD->setInvalidDecl();
7370    return UD;
7371  }
7372
7373  // The normal rules do not apply to inheriting constructor declarations.
7374  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
7375    if (CheckInheritingConstructorUsingDecl(UD))
7376      UD->setInvalidDecl();
7377    return UD;
7378  }
7379
7380  // Otherwise, look up the target name.
7381
7382  LookupResult R(*this, NameInfo, LookupOrdinaryName);
7383
7384  // Unlike most lookups, we don't always want to hide tag
7385  // declarations: tag names are visible through the using declaration
7386  // even if hidden by ordinary names, *except* in a dependent context
7387  // where it's important for the sanity of two-phase lookup.
7388  if (!IsInstantiation)
7389    R.setHideTags(false);
7390
7391  // For the purposes of this lookup, we have a base object type
7392  // equal to that of the current context.
7393  if (CurContext->isRecord()) {
7394    R.setBaseObjectType(
7395                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
7396  }
7397
7398  LookupQualifiedName(R, LookupContext);
7399
7400  // Try to correct typos if possible.
7401  if (R.empty()) {
7402    UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation,
7403                          CurContext->isRecord());
7404    if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
7405                                               R.getLookupKind(), S, &SS, CCC)){
7406      // We reject any correction for which ND would be NULL.
7407      NamedDecl *ND = Corrected.getCorrectionDecl();
7408      R.setLookupName(Corrected.getCorrection());
7409      R.addDecl(ND);
7410      // We reject candidates where DroppedSpecifier == true, hence the
7411      // literal '0' below.
7412      diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
7413                                << NameInfo.getName() << LookupContext << 0
7414                                << SS.getRange());
7415    } else {
7416      Diag(IdentLoc, diag::err_no_member)
7417        << NameInfo.getName() << LookupContext << SS.getRange();
7418      UD->setInvalidDecl();
7419      return UD;
7420    }
7421  }
7422
7423  if (R.isAmbiguous()) {
7424    UD->setInvalidDecl();
7425    return UD;
7426  }
7427
7428  if (HasTypenameKeyword) {
7429    // If we asked for a typename and got a non-type decl, error out.
7430    if (!R.getAsSingle<TypeDecl>()) {
7431      Diag(IdentLoc, diag::err_using_typename_non_type);
7432      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7433        Diag((*I)->getUnderlyingDecl()->getLocation(),
7434             diag::note_using_decl_target);
7435      UD->setInvalidDecl();
7436      return UD;
7437    }
7438  } else {
7439    // If we asked for a non-typename and we got a type, error out,
7440    // but only if this is an instantiation of an unresolved using
7441    // decl.  Otherwise just silently find the type name.
7442    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
7443      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
7444      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
7445      UD->setInvalidDecl();
7446      return UD;
7447    }
7448  }
7449
7450  // C++0x N2914 [namespace.udecl]p6:
7451  // A using-declaration shall not name a namespace.
7452  if (R.getAsSingle<NamespaceDecl>()) {
7453    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
7454      << SS.getRange();
7455    UD->setInvalidDecl();
7456    return UD;
7457  }
7458
7459  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7460    UsingShadowDecl *PrevDecl = 0;
7461    if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
7462      BuildUsingShadowDecl(S, UD, *I, PrevDecl);
7463  }
7464
7465  return UD;
7466}
7467
7468/// Additional checks for a using declaration referring to a constructor name.
7469bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
7470  assert(!UD->hasTypename() && "expecting a constructor name");
7471
7472  const Type *SourceType = UD->getQualifier()->getAsType();
7473  assert(SourceType &&
7474         "Using decl naming constructor doesn't have type in scope spec.");
7475  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
7476
7477  // Check whether the named type is a direct base class.
7478  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
7479  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
7480  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
7481       BaseIt != BaseE; ++BaseIt) {
7482    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
7483    if (CanonicalSourceType == BaseType)
7484      break;
7485    if (BaseIt->getType()->isDependentType())
7486      break;
7487  }
7488
7489  if (BaseIt == BaseE) {
7490    // Did not find SourceType in the bases.
7491    Diag(UD->getUsingLoc(),
7492         diag::err_using_decl_constructor_not_in_direct_base)
7493      << UD->getNameInfo().getSourceRange()
7494      << QualType(SourceType, 0) << TargetClass;
7495    return true;
7496  }
7497
7498  if (!CurContext->isDependentContext())
7499    BaseIt->setInheritConstructors();
7500
7501  return false;
7502}
7503
7504/// Checks that the given using declaration is not an invalid
7505/// redeclaration.  Note that this is checking only for the using decl
7506/// itself, not for any ill-formedness among the UsingShadowDecls.
7507bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
7508                                       bool HasTypenameKeyword,
7509                                       const CXXScopeSpec &SS,
7510                                       SourceLocation NameLoc,
7511                                       const LookupResult &Prev) {
7512  // C++03 [namespace.udecl]p8:
7513  // C++0x [namespace.udecl]p10:
7514  //   A using-declaration is a declaration and can therefore be used
7515  //   repeatedly where (and only where) multiple declarations are
7516  //   allowed.
7517  //
7518  // That's in non-member contexts.
7519  if (!CurContext->getRedeclContext()->isRecord())
7520    return false;
7521
7522  NestedNameSpecifier *Qual
7523    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
7524
7525  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
7526    NamedDecl *D = *I;
7527
7528    bool DTypename;
7529    NestedNameSpecifier *DQual;
7530    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
7531      DTypename = UD->hasTypename();
7532      DQual = UD->getQualifier();
7533    } else if (UnresolvedUsingValueDecl *UD
7534                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
7535      DTypename = false;
7536      DQual = UD->getQualifier();
7537    } else if (UnresolvedUsingTypenameDecl *UD
7538                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
7539      DTypename = true;
7540      DQual = UD->getQualifier();
7541    } else continue;
7542
7543    // using decls differ if one says 'typename' and the other doesn't.
7544    // FIXME: non-dependent using decls?
7545    if (HasTypenameKeyword != DTypename) continue;
7546
7547    // using decls differ if they name different scopes (but note that
7548    // template instantiation can cause this check to trigger when it
7549    // didn't before instantiation).
7550    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
7551        Context.getCanonicalNestedNameSpecifier(DQual))
7552      continue;
7553
7554    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
7555    Diag(D->getLocation(), diag::note_using_decl) << 1;
7556    return true;
7557  }
7558
7559  return false;
7560}
7561
7562
7563/// Checks that the given nested-name qualifier used in a using decl
7564/// in the current context is appropriately related to the current
7565/// scope.  If an error is found, diagnoses it and returns true.
7566bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
7567                                   const CXXScopeSpec &SS,
7568                                   SourceLocation NameLoc) {
7569  DeclContext *NamedContext = computeDeclContext(SS);
7570
7571  if (!CurContext->isRecord()) {
7572    // C++03 [namespace.udecl]p3:
7573    // C++0x [namespace.udecl]p8:
7574    //   A using-declaration for a class member shall be a member-declaration.
7575
7576    // If we weren't able to compute a valid scope, it must be a
7577    // dependent class scope.
7578    if (!NamedContext || NamedContext->isRecord()) {
7579      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
7580        << SS.getRange();
7581      return true;
7582    }
7583
7584    // Otherwise, everything is known to be fine.
7585    return false;
7586  }
7587
7588  // The current scope is a record.
7589
7590  // If the named context is dependent, we can't decide much.
7591  if (!NamedContext) {
7592    // FIXME: in C++0x, we can diagnose if we can prove that the
7593    // nested-name-specifier does not refer to a base class, which is
7594    // still possible in some cases.
7595
7596    // Otherwise we have to conservatively report that things might be
7597    // okay.
7598    return false;
7599  }
7600
7601  if (!NamedContext->isRecord()) {
7602    // Ideally this would point at the last name in the specifier,
7603    // but we don't have that level of source info.
7604    Diag(SS.getRange().getBegin(),
7605         diag::err_using_decl_nested_name_specifier_is_not_class)
7606      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
7607    return true;
7608  }
7609
7610  if (!NamedContext->isDependentContext() &&
7611      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
7612    return true;
7613
7614  if (getLangOpts().CPlusPlus11) {
7615    // C++0x [namespace.udecl]p3:
7616    //   In a using-declaration used as a member-declaration, the
7617    //   nested-name-specifier shall name a base class of the class
7618    //   being defined.
7619
7620    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
7621                                 cast<CXXRecordDecl>(NamedContext))) {
7622      if (CurContext == NamedContext) {
7623        Diag(NameLoc,
7624             diag::err_using_decl_nested_name_specifier_is_current_class)
7625          << SS.getRange();
7626        return true;
7627      }
7628
7629      Diag(SS.getRange().getBegin(),
7630           diag::err_using_decl_nested_name_specifier_is_not_base_class)
7631        << (NestedNameSpecifier*) SS.getScopeRep()
7632        << cast<CXXRecordDecl>(CurContext)
7633        << SS.getRange();
7634      return true;
7635    }
7636
7637    return false;
7638  }
7639
7640  // C++03 [namespace.udecl]p4:
7641  //   A using-declaration used as a member-declaration shall refer
7642  //   to a member of a base class of the class being defined [etc.].
7643
7644  // Salient point: SS doesn't have to name a base class as long as
7645  // lookup only finds members from base classes.  Therefore we can
7646  // diagnose here only if we can prove that that can't happen,
7647  // i.e. if the class hierarchies provably don't intersect.
7648
7649  // TODO: it would be nice if "definitely valid" results were cached
7650  // in the UsingDecl and UsingShadowDecl so that these checks didn't
7651  // need to be repeated.
7652
7653  struct UserData {
7654    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
7655
7656    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
7657      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7658      Data->Bases.insert(Base);
7659      return true;
7660    }
7661
7662    bool hasDependentBases(const CXXRecordDecl *Class) {
7663      return !Class->forallBases(collect, this);
7664    }
7665
7666    /// Returns true if the base is dependent or is one of the
7667    /// accumulated base classes.
7668    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
7669      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
7670      return !Data->Bases.count(Base);
7671    }
7672
7673    bool mightShareBases(const CXXRecordDecl *Class) {
7674      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
7675    }
7676  };
7677
7678  UserData Data;
7679
7680  // Returns false if we find a dependent base.
7681  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
7682    return false;
7683
7684  // Returns false if the class has a dependent base or if it or one
7685  // of its bases is present in the base set of the current context.
7686  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
7687    return false;
7688
7689  Diag(SS.getRange().getBegin(),
7690       diag::err_using_decl_nested_name_specifier_is_not_base_class)
7691    << (NestedNameSpecifier*) SS.getScopeRep()
7692    << cast<CXXRecordDecl>(CurContext)
7693    << SS.getRange();
7694
7695  return true;
7696}
7697
7698Decl *Sema::ActOnAliasDeclaration(Scope *S,
7699                                  AccessSpecifier AS,
7700                                  MultiTemplateParamsArg TemplateParamLists,
7701                                  SourceLocation UsingLoc,
7702                                  UnqualifiedId &Name,
7703                                  AttributeList *AttrList,
7704                                  TypeResult Type) {
7705  // Skip up to the relevant declaration scope.
7706  while (S->getFlags() & Scope::TemplateParamScope)
7707    S = S->getParent();
7708  assert((S->getFlags() & Scope::DeclScope) &&
7709         "got alias-declaration outside of declaration scope");
7710
7711  if (Type.isInvalid())
7712    return 0;
7713
7714  bool Invalid = false;
7715  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
7716  TypeSourceInfo *TInfo = 0;
7717  GetTypeFromParser(Type.get(), &TInfo);
7718
7719  if (DiagnoseClassNameShadow(CurContext, NameInfo))
7720    return 0;
7721
7722  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
7723                                      UPPC_DeclarationType)) {
7724    Invalid = true;
7725    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
7726                                             TInfo->getTypeLoc().getBeginLoc());
7727  }
7728
7729  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
7730  LookupName(Previous, S);
7731
7732  // Warn about shadowing the name of a template parameter.
7733  if (Previous.isSingleResult() &&
7734      Previous.getFoundDecl()->isTemplateParameter()) {
7735    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
7736    Previous.clear();
7737  }
7738
7739  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
7740         "name in alias declaration must be an identifier");
7741  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
7742                                               Name.StartLocation,
7743                                               Name.Identifier, TInfo);
7744
7745  NewTD->setAccess(AS);
7746
7747  if (Invalid)
7748    NewTD->setInvalidDecl();
7749
7750  ProcessDeclAttributeList(S, NewTD, AttrList);
7751
7752  CheckTypedefForVariablyModifiedType(S, NewTD);
7753  Invalid |= NewTD->isInvalidDecl();
7754
7755  bool Redeclaration = false;
7756
7757  NamedDecl *NewND;
7758  if (TemplateParamLists.size()) {
7759    TypeAliasTemplateDecl *OldDecl = 0;
7760    TemplateParameterList *OldTemplateParams = 0;
7761
7762    if (TemplateParamLists.size() != 1) {
7763      Diag(UsingLoc, diag::err_alias_template_extra_headers)
7764        << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
7765         TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
7766    }
7767    TemplateParameterList *TemplateParams = TemplateParamLists[0];
7768
7769    // Only consider previous declarations in the same scope.
7770    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
7771                         /*ExplicitInstantiationOrSpecialization*/false);
7772    if (!Previous.empty()) {
7773      Redeclaration = true;
7774
7775      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
7776      if (!OldDecl && !Invalid) {
7777        Diag(UsingLoc, diag::err_redefinition_different_kind)
7778          << Name.Identifier;
7779
7780        NamedDecl *OldD = Previous.getRepresentativeDecl();
7781        if (OldD->getLocation().isValid())
7782          Diag(OldD->getLocation(), diag::note_previous_definition);
7783
7784        Invalid = true;
7785      }
7786
7787      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
7788        if (TemplateParameterListsAreEqual(TemplateParams,
7789                                           OldDecl->getTemplateParameters(),
7790                                           /*Complain=*/true,
7791                                           TPL_TemplateMatch))
7792          OldTemplateParams = OldDecl->getTemplateParameters();
7793        else
7794          Invalid = true;
7795
7796        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
7797        if (!Invalid &&
7798            !Context.hasSameType(OldTD->getUnderlyingType(),
7799                                 NewTD->getUnderlyingType())) {
7800          // FIXME: The C++0x standard does not clearly say this is ill-formed,
7801          // but we can't reasonably accept it.
7802          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
7803            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
7804          if (OldTD->getLocation().isValid())
7805            Diag(OldTD->getLocation(), diag::note_previous_definition);
7806          Invalid = true;
7807        }
7808      }
7809    }
7810
7811    // Merge any previous default template arguments into our parameters,
7812    // and check the parameter list.
7813    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
7814                                   TPC_TypeAliasTemplate))
7815      return 0;
7816
7817    TypeAliasTemplateDecl *NewDecl =
7818      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
7819                                    Name.Identifier, TemplateParams,
7820                                    NewTD);
7821
7822    NewDecl->setAccess(AS);
7823
7824    if (Invalid)
7825      NewDecl->setInvalidDecl();
7826    else if (OldDecl)
7827      NewDecl->setPreviousDecl(OldDecl);
7828
7829    NewND = NewDecl;
7830  } else {
7831    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
7832    NewND = NewTD;
7833  }
7834
7835  if (!Redeclaration)
7836    PushOnScopeChains(NewND, S);
7837
7838  ActOnDocumentableDecl(NewND);
7839  return NewND;
7840}
7841
7842Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
7843                                             SourceLocation NamespaceLoc,
7844                                             SourceLocation AliasLoc,
7845                                             IdentifierInfo *Alias,
7846                                             CXXScopeSpec &SS,
7847                                             SourceLocation IdentLoc,
7848                                             IdentifierInfo *Ident) {
7849
7850  // Lookup the namespace name.
7851  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
7852  LookupParsedName(R, S, &SS);
7853
7854  // Check if we have a previous declaration with the same name.
7855  NamedDecl *PrevDecl
7856    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
7857                       ForRedeclaration);
7858  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
7859    PrevDecl = 0;
7860
7861  if (PrevDecl) {
7862    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
7863      // We already have an alias with the same name that points to the same
7864      // namespace, so don't create a new one.
7865      // FIXME: At some point, we'll want to create the (redundant)
7866      // declaration to maintain better source information.
7867      if (!R.isAmbiguous() && !R.empty() &&
7868          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
7869        return 0;
7870    }
7871
7872    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
7873      diag::err_redefinition_different_kind;
7874    Diag(AliasLoc, DiagID) << Alias;
7875    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
7876    return 0;
7877  }
7878
7879  if (R.isAmbiguous())
7880    return 0;
7881
7882  if (R.empty()) {
7883    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
7884      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
7885      return 0;
7886    }
7887  }
7888
7889  NamespaceAliasDecl *AliasDecl =
7890    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
7891                               Alias, SS.getWithLocInContext(Context),
7892                               IdentLoc, R.getFoundDecl());
7893
7894  PushOnScopeChains(AliasDecl, S);
7895  return AliasDecl;
7896}
7897
7898Sema::ImplicitExceptionSpecification
7899Sema::ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
7900                                               CXXMethodDecl *MD) {
7901  CXXRecordDecl *ClassDecl = MD->getParent();
7902
7903  // C++ [except.spec]p14:
7904  //   An implicitly declared special member function (Clause 12) shall have an
7905  //   exception-specification. [...]
7906  ImplicitExceptionSpecification ExceptSpec(*this);
7907  if (ClassDecl->isInvalidDecl())
7908    return ExceptSpec;
7909
7910  // Direct base-class constructors.
7911  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7912                                       BEnd = ClassDecl->bases_end();
7913       B != BEnd; ++B) {
7914    if (B->isVirtual()) // Handled below.
7915      continue;
7916
7917    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7918      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7919      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7920      // If this is a deleted function, add it anyway. This might be conformant
7921      // with the standard. This might not. I'm not sure. It might not matter.
7922      if (Constructor)
7923        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7924    }
7925  }
7926
7927  // Virtual base-class constructors.
7928  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7929                                       BEnd = ClassDecl->vbases_end();
7930       B != BEnd; ++B) {
7931    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7932      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7933      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7934      // If this is a deleted function, add it anyway. This might be conformant
7935      // with the standard. This might not. I'm not sure. It might not matter.
7936      if (Constructor)
7937        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
7938    }
7939  }
7940
7941  // Field constructors.
7942  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7943                               FEnd = ClassDecl->field_end();
7944       F != FEnd; ++F) {
7945    if (F->hasInClassInitializer()) {
7946      if (Expr *E = F->getInClassInitializer())
7947        ExceptSpec.CalledExpr(E);
7948      else if (!F->isInvalidDecl())
7949        // DR1351:
7950        //   If the brace-or-equal-initializer of a non-static data member
7951        //   invokes a defaulted default constructor of its class or of an
7952        //   enclosing class in a potentially evaluated subexpression, the
7953        //   program is ill-formed.
7954        //
7955        // This resolution is unworkable: the exception specification of the
7956        // default constructor can be needed in an unevaluated context, in
7957        // particular, in the operand of a noexcept-expression, and we can be
7958        // unable to compute an exception specification for an enclosed class.
7959        //
7960        // We do not allow an in-class initializer to require the evaluation
7961        // of the exception specification for any in-class initializer whose
7962        // definition is not lexically complete.
7963        Diag(Loc, diag::err_in_class_initializer_references_def_ctor) << MD;
7964    } else if (const RecordType *RecordTy
7965              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
7966      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7967      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7968      // If this is a deleted function, add it anyway. This might be conformant
7969      // with the standard. This might not. I'm not sure. It might not matter.
7970      // In particular, the problem is that this function never gets called. It
7971      // might just be ill-formed because this function attempts to refer to
7972      // a deleted function here.
7973      if (Constructor)
7974        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
7975    }
7976  }
7977
7978  return ExceptSpec;
7979}
7980
7981Sema::ImplicitExceptionSpecification
7982Sema::ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD) {
7983  CXXRecordDecl *ClassDecl = CD->getParent();
7984
7985  // C++ [except.spec]p14:
7986  //   An inheriting constructor [...] shall have an exception-specification. [...]
7987  ImplicitExceptionSpecification ExceptSpec(*this);
7988  if (ClassDecl->isInvalidDecl())
7989    return ExceptSpec;
7990
7991  // Inherited constructor.
7992  const CXXConstructorDecl *InheritedCD = CD->getInheritedConstructor();
7993  const CXXRecordDecl *InheritedDecl = InheritedCD->getParent();
7994  // FIXME: Copying or moving the parameters could add extra exceptions to the
7995  // set, as could the default arguments for the inherited constructor. This
7996  // will be addressed when we implement the resolution of core issue 1351.
7997  ExceptSpec.CalledDecl(CD->getLocStart(), InheritedCD);
7998
7999  // Direct base-class constructors.
8000  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8001                                       BEnd = ClassDecl->bases_end();
8002       B != BEnd; ++B) {
8003    if (B->isVirtual()) // Handled below.
8004      continue;
8005
8006    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8007      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8008      if (BaseClassDecl == InheritedDecl)
8009        continue;
8010      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8011      if (Constructor)
8012        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8013    }
8014  }
8015
8016  // Virtual base-class constructors.
8017  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8018                                       BEnd = ClassDecl->vbases_end();
8019       B != BEnd; ++B) {
8020    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8021      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8022      if (BaseClassDecl == InheritedDecl)
8023        continue;
8024      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
8025      if (Constructor)
8026        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
8027    }
8028  }
8029
8030  // Field constructors.
8031  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8032                               FEnd = ClassDecl->field_end();
8033       F != FEnd; ++F) {
8034    if (F->hasInClassInitializer()) {
8035      if (Expr *E = F->getInClassInitializer())
8036        ExceptSpec.CalledExpr(E);
8037      else if (!F->isInvalidDecl())
8038        Diag(CD->getLocation(),
8039             diag::err_in_class_initializer_references_def_ctor) << CD;
8040    } else if (const RecordType *RecordTy
8041              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8042      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8043      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
8044      if (Constructor)
8045        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
8046    }
8047  }
8048
8049  return ExceptSpec;
8050}
8051
8052namespace {
8053/// RAII object to register a special member as being currently declared.
8054struct DeclaringSpecialMember {
8055  Sema &S;
8056  Sema::SpecialMemberDecl D;
8057  bool WasAlreadyBeingDeclared;
8058
8059  DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
8060    : S(S), D(RD, CSM) {
8061    WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D);
8062    if (WasAlreadyBeingDeclared)
8063      // This almost never happens, but if it does, ensure that our cache
8064      // doesn't contain a stale result.
8065      S.SpecialMemberCache.clear();
8066
8067    // FIXME: Register a note to be produced if we encounter an error while
8068    // declaring the special member.
8069  }
8070  ~DeclaringSpecialMember() {
8071    if (!WasAlreadyBeingDeclared)
8072      S.SpecialMembersBeingDeclared.erase(D);
8073  }
8074
8075  /// \brief Are we already trying to declare this special member?
8076  bool isAlreadyBeingDeclared() const {
8077    return WasAlreadyBeingDeclared;
8078  }
8079};
8080}
8081
8082CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
8083                                                     CXXRecordDecl *ClassDecl) {
8084  // C++ [class.ctor]p5:
8085  //   A default constructor for a class X is a constructor of class X
8086  //   that can be called without an argument. If there is no
8087  //   user-declared constructor for class X, a default constructor is
8088  //   implicitly declared. An implicitly-declared default constructor
8089  //   is an inline public member of its class.
8090  assert(ClassDecl->needsImplicitDefaultConstructor() &&
8091         "Should not build implicit default constructor!");
8092
8093  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
8094  if (DSM.isAlreadyBeingDeclared())
8095    return 0;
8096
8097  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
8098                                                     CXXDefaultConstructor,
8099                                                     false);
8100
8101  // Create the actual constructor declaration.
8102  CanQualType ClassType
8103    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8104  SourceLocation ClassLoc = ClassDecl->getLocation();
8105  DeclarationName Name
8106    = Context.DeclarationNames.getCXXConstructorName(ClassType);
8107  DeclarationNameInfo NameInfo(Name, ClassLoc);
8108  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
8109      Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(), /*TInfo=*/0,
8110      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8111      Constexpr);
8112  DefaultCon->setAccess(AS_public);
8113  DefaultCon->setDefaulted();
8114  DefaultCon->setImplicit();
8115
8116  // Build an exception specification pointing back at this constructor.
8117  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
8118  DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8119
8120  // We don't need to use SpecialMemberIsTrivial here; triviality for default
8121  // constructors is easy to compute.
8122  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
8123
8124  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
8125    SetDeclDeleted(DefaultCon, ClassLoc);
8126
8127  // Note that we have declared this constructor.
8128  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
8129
8130  if (Scope *S = getScopeForContext(ClassDecl))
8131    PushOnScopeChains(DefaultCon, S, false);
8132  ClassDecl->addDecl(DefaultCon);
8133
8134  return DefaultCon;
8135}
8136
8137void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
8138                                            CXXConstructorDecl *Constructor) {
8139  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
8140          !Constructor->doesThisDeclarationHaveABody() &&
8141          !Constructor->isDeleted()) &&
8142    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
8143
8144  CXXRecordDecl *ClassDecl = Constructor->getParent();
8145  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
8146
8147  SynthesizedFunctionScope Scope(*this, Constructor);
8148  DiagnosticErrorTrap Trap(Diags);
8149  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8150      Trap.hasErrorOccurred()) {
8151    Diag(CurrentLocation, diag::note_member_synthesized_at)
8152      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
8153    Constructor->setInvalidDecl();
8154    return;
8155  }
8156
8157  SourceLocation Loc = Constructor->getLocation();
8158  Constructor->setBody(new (Context) CompoundStmt(Loc));
8159
8160  Constructor->markUsed(Context);
8161  MarkVTableUsed(CurrentLocation, ClassDecl);
8162
8163  if (ASTMutationListener *L = getASTMutationListener()) {
8164    L->CompletedImplicitDefinition(Constructor);
8165  }
8166
8167  DiagnoseUninitializedFields(*this, Constructor);
8168}
8169
8170void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
8171  // Perform any delayed checks on exception specifications.
8172  CheckDelayedMemberExceptionSpecs();
8173}
8174
8175namespace {
8176/// Information on inheriting constructors to declare.
8177class InheritingConstructorInfo {
8178public:
8179  InheritingConstructorInfo(Sema &SemaRef, CXXRecordDecl *Derived)
8180      : SemaRef(SemaRef), Derived(Derived) {
8181    // Mark the constructors that we already have in the derived class.
8182    //
8183    // C++11 [class.inhctor]p3: [...] a constructor is implicitly declared [...]
8184    //   unless there is a user-declared constructor with the same signature in
8185    //   the class where the using-declaration appears.
8186    visitAll(Derived, &InheritingConstructorInfo::noteDeclaredInDerived);
8187  }
8188
8189  void inheritAll(CXXRecordDecl *RD) {
8190    visitAll(RD, &InheritingConstructorInfo::inherit);
8191  }
8192
8193private:
8194  /// Information about an inheriting constructor.
8195  struct InheritingConstructor {
8196    InheritingConstructor()
8197      : DeclaredInDerived(false), BaseCtor(0), DerivedCtor(0) {}
8198
8199    /// If \c true, a constructor with this signature is already declared
8200    /// in the derived class.
8201    bool DeclaredInDerived;
8202
8203    /// The constructor which is inherited.
8204    const CXXConstructorDecl *BaseCtor;
8205
8206    /// The derived constructor we declared.
8207    CXXConstructorDecl *DerivedCtor;
8208  };
8209
8210  /// Inheriting constructors with a given canonical type. There can be at
8211  /// most one such non-template constructor, and any number of templated
8212  /// constructors.
8213  struct InheritingConstructorsForType {
8214    InheritingConstructor NonTemplate;
8215    SmallVector<std::pair<TemplateParameterList *, InheritingConstructor>, 4>
8216        Templates;
8217
8218    InheritingConstructor &getEntry(Sema &S, const CXXConstructorDecl *Ctor) {
8219      if (FunctionTemplateDecl *FTD = Ctor->getDescribedFunctionTemplate()) {
8220        TemplateParameterList *ParamList = FTD->getTemplateParameters();
8221        for (unsigned I = 0, N = Templates.size(); I != N; ++I)
8222          if (S.TemplateParameterListsAreEqual(ParamList, Templates[I].first,
8223                                               false, S.TPL_TemplateMatch))
8224            return Templates[I].second;
8225        Templates.push_back(std::make_pair(ParamList, InheritingConstructor()));
8226        return Templates.back().second;
8227      }
8228
8229      return NonTemplate;
8230    }
8231  };
8232
8233  /// Get or create the inheriting constructor record for a constructor.
8234  InheritingConstructor &getEntry(const CXXConstructorDecl *Ctor,
8235                                  QualType CtorType) {
8236    return Map[CtorType.getCanonicalType()->castAs<FunctionProtoType>()]
8237        .getEntry(SemaRef, Ctor);
8238  }
8239
8240  typedef void (InheritingConstructorInfo::*VisitFn)(const CXXConstructorDecl*);
8241
8242  /// Process all constructors for a class.
8243  void visitAll(const CXXRecordDecl *RD, VisitFn Callback) {
8244    for (CXXRecordDecl::ctor_iterator CtorIt = RD->ctor_begin(),
8245                                      CtorE = RD->ctor_end();
8246         CtorIt != CtorE; ++CtorIt)
8247      (this->*Callback)(*CtorIt);
8248    for (CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl>
8249             I(RD->decls_begin()), E(RD->decls_end());
8250         I != E; ++I) {
8251      const FunctionDecl *FD = (*I)->getTemplatedDecl();
8252      if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
8253        (this->*Callback)(CD);
8254    }
8255  }
8256
8257  /// Note that a constructor (or constructor template) was declared in Derived.
8258  void noteDeclaredInDerived(const CXXConstructorDecl *Ctor) {
8259    getEntry(Ctor, Ctor->getType()).DeclaredInDerived = true;
8260  }
8261
8262  /// Inherit a single constructor.
8263  void inherit(const CXXConstructorDecl *Ctor) {
8264    const FunctionProtoType *CtorType =
8265        Ctor->getType()->castAs<FunctionProtoType>();
8266    ArrayRef<QualType> ArgTypes(CtorType->getArgTypes());
8267    FunctionProtoType::ExtProtoInfo EPI = CtorType->getExtProtoInfo();
8268
8269    SourceLocation UsingLoc = getUsingLoc(Ctor->getParent());
8270
8271    // Core issue (no number yet): the ellipsis is always discarded.
8272    if (EPI.Variadic) {
8273      SemaRef.Diag(UsingLoc, diag::warn_using_decl_constructor_ellipsis);
8274      SemaRef.Diag(Ctor->getLocation(),
8275                   diag::note_using_decl_constructor_ellipsis);
8276      EPI.Variadic = false;
8277    }
8278
8279    // Declare a constructor for each number of parameters.
8280    //
8281    // C++11 [class.inhctor]p1:
8282    //   The candidate set of inherited constructors from the class X named in
8283    //   the using-declaration consists of [... modulo defects ...] for each
8284    //   constructor or constructor template of X, the set of constructors or
8285    //   constructor templates that results from omitting any ellipsis parameter
8286    //   specification and successively omitting parameters with a default
8287    //   argument from the end of the parameter-type-list
8288    unsigned MinParams = minParamsToInherit(Ctor);
8289    unsigned Params = Ctor->getNumParams();
8290    if (Params >= MinParams) {
8291      do
8292        declareCtor(UsingLoc, Ctor,
8293                    SemaRef.Context.getFunctionType(
8294                        Ctor->getResultType(), ArgTypes.slice(0, Params), EPI));
8295      while (Params > MinParams &&
8296             Ctor->getParamDecl(--Params)->hasDefaultArg());
8297    }
8298  }
8299
8300  /// Find the using-declaration which specified that we should inherit the
8301  /// constructors of \p Base.
8302  SourceLocation getUsingLoc(const CXXRecordDecl *Base) {
8303    // No fancy lookup required; just look for the base constructor name
8304    // directly within the derived class.
8305    ASTContext &Context = SemaRef.Context;
8306    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8307        Context.getCanonicalType(Context.getRecordType(Base)));
8308    DeclContext::lookup_const_result Decls = Derived->lookup(Name);
8309    return Decls.empty() ? Derived->getLocation() : Decls[0]->getLocation();
8310  }
8311
8312  unsigned minParamsToInherit(const CXXConstructorDecl *Ctor) {
8313    // C++11 [class.inhctor]p3:
8314    //   [F]or each constructor template in the candidate set of inherited
8315    //   constructors, a constructor template is implicitly declared
8316    if (Ctor->getDescribedFunctionTemplate())
8317      return 0;
8318
8319    //   For each non-template constructor in the candidate set of inherited
8320    //   constructors other than a constructor having no parameters or a
8321    //   copy/move constructor having a single parameter, a constructor is
8322    //   implicitly declared [...]
8323    if (Ctor->getNumParams() == 0)
8324      return 1;
8325    if (Ctor->isCopyOrMoveConstructor())
8326      return 2;
8327
8328    // Per discussion on core reflector, never inherit a constructor which
8329    // would become a default, copy, or move constructor of Derived either.
8330    const ParmVarDecl *PD = Ctor->getParamDecl(0);
8331    const ReferenceType *RT = PD->getType()->getAs<ReferenceType>();
8332    return (RT && RT->getPointeeCXXRecordDecl() == Derived) ? 2 : 1;
8333  }
8334
8335  /// Declare a single inheriting constructor, inheriting the specified
8336  /// constructor, with the given type.
8337  void declareCtor(SourceLocation UsingLoc, const CXXConstructorDecl *BaseCtor,
8338                   QualType DerivedType) {
8339    InheritingConstructor &Entry = getEntry(BaseCtor, DerivedType);
8340
8341    // C++11 [class.inhctor]p3:
8342    //   ... a constructor is implicitly declared with the same constructor
8343    //   characteristics unless there is a user-declared constructor with
8344    //   the same signature in the class where the using-declaration appears
8345    if (Entry.DeclaredInDerived)
8346      return;
8347
8348    // C++11 [class.inhctor]p7:
8349    //   If two using-declarations declare inheriting constructors with the
8350    //   same signature, the program is ill-formed
8351    if (Entry.DerivedCtor) {
8352      if (BaseCtor->getParent() != Entry.BaseCtor->getParent()) {
8353        // Only diagnose this once per constructor.
8354        if (Entry.DerivedCtor->isInvalidDecl())
8355          return;
8356        Entry.DerivedCtor->setInvalidDecl();
8357
8358        SemaRef.Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
8359        SemaRef.Diag(BaseCtor->getLocation(),
8360                     diag::note_using_decl_constructor_conflict_current_ctor);
8361        SemaRef.Diag(Entry.BaseCtor->getLocation(),
8362                     diag::note_using_decl_constructor_conflict_previous_ctor);
8363        SemaRef.Diag(Entry.DerivedCtor->getLocation(),
8364                     diag::note_using_decl_constructor_conflict_previous_using);
8365      } else {
8366        // Core issue (no number): if the same inheriting constructor is
8367        // produced by multiple base class constructors from the same base
8368        // class, the inheriting constructor is defined as deleted.
8369        SemaRef.SetDeclDeleted(Entry.DerivedCtor, UsingLoc);
8370      }
8371
8372      return;
8373    }
8374
8375    ASTContext &Context = SemaRef.Context;
8376    DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
8377        Context.getCanonicalType(Context.getRecordType(Derived)));
8378    DeclarationNameInfo NameInfo(Name, UsingLoc);
8379
8380    TemplateParameterList *TemplateParams = 0;
8381    if (const FunctionTemplateDecl *FTD =
8382            BaseCtor->getDescribedFunctionTemplate()) {
8383      TemplateParams = FTD->getTemplateParameters();
8384      // We're reusing template parameters from a different DeclContext. This
8385      // is questionable at best, but works out because the template depth in
8386      // both places is guaranteed to be 0.
8387      // FIXME: Rebuild the template parameters in the new context, and
8388      // transform the function type to refer to them.
8389    }
8390
8391    // Build type source info pointing at the using-declaration. This is
8392    // required by template instantiation.
8393    TypeSourceInfo *TInfo =
8394        Context.getTrivialTypeSourceInfo(DerivedType, UsingLoc);
8395    FunctionProtoTypeLoc ProtoLoc =
8396        TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
8397
8398    CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
8399        Context, Derived, UsingLoc, NameInfo, DerivedType,
8400        TInfo, BaseCtor->isExplicit(), /*Inline=*/true,
8401        /*ImplicitlyDeclared=*/true, /*Constexpr=*/BaseCtor->isConstexpr());
8402
8403    // Build an unevaluated exception specification for this constructor.
8404    const FunctionProtoType *FPT = DerivedType->castAs<FunctionProtoType>();
8405    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8406    EPI.ExceptionSpecType = EST_Unevaluated;
8407    EPI.ExceptionSpecDecl = DerivedCtor;
8408    DerivedCtor->setType(Context.getFunctionType(FPT->getResultType(),
8409                                                 FPT->getArgTypes(), EPI));
8410
8411    // Build the parameter declarations.
8412    SmallVector<ParmVarDecl *, 16> ParamDecls;
8413    for (unsigned I = 0, N = FPT->getNumArgs(); I != N; ++I) {
8414      TypeSourceInfo *TInfo =
8415          Context.getTrivialTypeSourceInfo(FPT->getArgType(I), UsingLoc);
8416      ParmVarDecl *PD = ParmVarDecl::Create(
8417          Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/0,
8418          FPT->getArgType(I), TInfo, SC_None, /*DefaultArg=*/0);
8419      PD->setScopeInfo(0, I);
8420      PD->setImplicit();
8421      ParamDecls.push_back(PD);
8422      ProtoLoc.setArg(I, PD);
8423    }
8424
8425    // Set up the new constructor.
8426    DerivedCtor->setAccess(BaseCtor->getAccess());
8427    DerivedCtor->setParams(ParamDecls);
8428    DerivedCtor->setInheritedConstructor(BaseCtor);
8429    if (BaseCtor->isDeleted())
8430      SemaRef.SetDeclDeleted(DerivedCtor, UsingLoc);
8431
8432    // If this is a constructor template, build the template declaration.
8433    if (TemplateParams) {
8434      FunctionTemplateDecl *DerivedTemplate =
8435          FunctionTemplateDecl::Create(SemaRef.Context, Derived, UsingLoc, Name,
8436                                       TemplateParams, DerivedCtor);
8437      DerivedTemplate->setAccess(BaseCtor->getAccess());
8438      DerivedCtor->setDescribedFunctionTemplate(DerivedTemplate);
8439      Derived->addDecl(DerivedTemplate);
8440    } else {
8441      Derived->addDecl(DerivedCtor);
8442    }
8443
8444    Entry.BaseCtor = BaseCtor;
8445    Entry.DerivedCtor = DerivedCtor;
8446  }
8447
8448  Sema &SemaRef;
8449  CXXRecordDecl *Derived;
8450  typedef llvm::DenseMap<const Type *, InheritingConstructorsForType> MapType;
8451  MapType Map;
8452};
8453}
8454
8455void Sema::DeclareInheritingConstructors(CXXRecordDecl *ClassDecl) {
8456  // Defer declaring the inheriting constructors until the class is
8457  // instantiated.
8458  if (ClassDecl->isDependentContext())
8459    return;
8460
8461  // Find base classes from which we might inherit constructors.
8462  SmallVector<CXXRecordDecl*, 4> InheritedBases;
8463  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
8464                                          BaseE = ClassDecl->bases_end();
8465       BaseIt != BaseE; ++BaseIt)
8466    if (BaseIt->getInheritConstructors())
8467      InheritedBases.push_back(BaseIt->getType()->getAsCXXRecordDecl());
8468
8469  // Go no further if we're not inheriting any constructors.
8470  if (InheritedBases.empty())
8471    return;
8472
8473  // Declare the inherited constructors.
8474  InheritingConstructorInfo ICI(*this, ClassDecl);
8475  for (unsigned I = 0, N = InheritedBases.size(); I != N; ++I)
8476    ICI.inheritAll(InheritedBases[I]);
8477}
8478
8479void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
8480                                       CXXConstructorDecl *Constructor) {
8481  CXXRecordDecl *ClassDecl = Constructor->getParent();
8482  assert(Constructor->getInheritedConstructor() &&
8483         !Constructor->doesThisDeclarationHaveABody() &&
8484         !Constructor->isDeleted());
8485
8486  SynthesizedFunctionScope Scope(*this, Constructor);
8487  DiagnosticErrorTrap Trap(Diags);
8488  if (SetCtorInitializers(Constructor, /*AnyErrors=*/false) ||
8489      Trap.hasErrorOccurred()) {
8490    Diag(CurrentLocation, diag::note_inhctor_synthesized_at)
8491      << Context.getTagDeclType(ClassDecl);
8492    Constructor->setInvalidDecl();
8493    return;
8494  }
8495
8496  SourceLocation Loc = Constructor->getLocation();
8497  Constructor->setBody(new (Context) CompoundStmt(Loc));
8498
8499  Constructor->markUsed(Context);
8500  MarkVTableUsed(CurrentLocation, ClassDecl);
8501
8502  if (ASTMutationListener *L = getASTMutationListener()) {
8503    L->CompletedImplicitDefinition(Constructor);
8504  }
8505}
8506
8507
8508Sema::ImplicitExceptionSpecification
8509Sema::ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD) {
8510  CXXRecordDecl *ClassDecl = MD->getParent();
8511
8512  // C++ [except.spec]p14:
8513  //   An implicitly declared special member function (Clause 12) shall have
8514  //   an exception-specification.
8515  ImplicitExceptionSpecification ExceptSpec(*this);
8516  if (ClassDecl->isInvalidDecl())
8517    return ExceptSpec;
8518
8519  // Direct base-class destructors.
8520  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8521                                       BEnd = ClassDecl->bases_end();
8522       B != BEnd; ++B) {
8523    if (B->isVirtual()) // Handled below.
8524      continue;
8525
8526    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8527      ExceptSpec.CalledDecl(B->getLocStart(),
8528                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8529  }
8530
8531  // Virtual base-class destructors.
8532  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8533                                       BEnd = ClassDecl->vbases_end();
8534       B != BEnd; ++B) {
8535    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
8536      ExceptSpec.CalledDecl(B->getLocStart(),
8537                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
8538  }
8539
8540  // Field destructors.
8541  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8542                               FEnd = ClassDecl->field_end();
8543       F != FEnd; ++F) {
8544    if (const RecordType *RecordTy
8545        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
8546      ExceptSpec.CalledDecl(F->getLocation(),
8547                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
8548  }
8549
8550  return ExceptSpec;
8551}
8552
8553CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
8554  // C++ [class.dtor]p2:
8555  //   If a class has no user-declared destructor, a destructor is
8556  //   declared implicitly. An implicitly-declared destructor is an
8557  //   inline public member of its class.
8558  assert(ClassDecl->needsImplicitDestructor());
8559
8560  DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
8561  if (DSM.isAlreadyBeingDeclared())
8562    return 0;
8563
8564  // Create the actual destructor declaration.
8565  CanQualType ClassType
8566    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8567  SourceLocation ClassLoc = ClassDecl->getLocation();
8568  DeclarationName Name
8569    = Context.DeclarationNames.getCXXDestructorName(ClassType);
8570  DeclarationNameInfo NameInfo(Name, ClassLoc);
8571  CXXDestructorDecl *Destructor
8572      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8573                                  QualType(), 0, /*isInline=*/true,
8574                                  /*isImplicitlyDeclared=*/true);
8575  Destructor->setAccess(AS_public);
8576  Destructor->setDefaulted();
8577  Destructor->setImplicit();
8578
8579  // Build an exception specification pointing back at this destructor.
8580  FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
8581  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8582
8583  AddOverriddenMethods(ClassDecl, Destructor);
8584
8585  // We don't need to use SpecialMemberIsTrivial here; triviality for
8586  // destructors is easy to compute.
8587  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
8588
8589  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
8590    SetDeclDeleted(Destructor, ClassLoc);
8591
8592  // Note that we have declared this destructor.
8593  ++ASTContext::NumImplicitDestructorsDeclared;
8594
8595  // Introduce this destructor into its scope.
8596  if (Scope *S = getScopeForContext(ClassDecl))
8597    PushOnScopeChains(Destructor, S, false);
8598  ClassDecl->addDecl(Destructor);
8599
8600  return Destructor;
8601}
8602
8603void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
8604                                    CXXDestructorDecl *Destructor) {
8605  assert((Destructor->isDefaulted() &&
8606          !Destructor->doesThisDeclarationHaveABody() &&
8607          !Destructor->isDeleted()) &&
8608         "DefineImplicitDestructor - call it for implicit default dtor");
8609  CXXRecordDecl *ClassDecl = Destructor->getParent();
8610  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
8611
8612  if (Destructor->isInvalidDecl())
8613    return;
8614
8615  SynthesizedFunctionScope Scope(*this, Destructor);
8616
8617  DiagnosticErrorTrap Trap(Diags);
8618  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
8619                                         Destructor->getParent());
8620
8621  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
8622    Diag(CurrentLocation, diag::note_member_synthesized_at)
8623      << CXXDestructor << Context.getTagDeclType(ClassDecl);
8624
8625    Destructor->setInvalidDecl();
8626    return;
8627  }
8628
8629  SourceLocation Loc = Destructor->getLocation();
8630  Destructor->setBody(new (Context) CompoundStmt(Loc));
8631  Destructor->markUsed(Context);
8632  MarkVTableUsed(CurrentLocation, ClassDecl);
8633
8634  if (ASTMutationListener *L = getASTMutationListener()) {
8635    L->CompletedImplicitDefinition(Destructor);
8636  }
8637}
8638
8639/// \brief Perform any semantic analysis which needs to be delayed until all
8640/// pending class member declarations have been parsed.
8641void Sema::ActOnFinishCXXMemberDecls() {
8642  // If the context is an invalid C++ class, just suppress these checks.
8643  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
8644    if (Record->isInvalidDecl()) {
8645      DelayedDefaultedMemberExceptionSpecs.clear();
8646      DelayedDestructorExceptionSpecChecks.clear();
8647      return;
8648    }
8649  }
8650}
8651
8652void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
8653                                         CXXDestructorDecl *Destructor) {
8654  assert(getLangOpts().CPlusPlus11 &&
8655         "adjusting dtor exception specs was introduced in c++11");
8656
8657  // C++11 [class.dtor]p3:
8658  //   A declaration of a destructor that does not have an exception-
8659  //   specification is implicitly considered to have the same exception-
8660  //   specification as an implicit declaration.
8661  const FunctionProtoType *DtorType = Destructor->getType()->
8662                                        getAs<FunctionProtoType>();
8663  if (DtorType->hasExceptionSpec())
8664    return;
8665
8666  // Replace the destructor's type, building off the existing one. Fortunately,
8667  // the only thing of interest in the destructor type is its extended info.
8668  // The return and arguments are fixed.
8669  FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
8670  EPI.ExceptionSpecType = EST_Unevaluated;
8671  EPI.ExceptionSpecDecl = Destructor;
8672  Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
8673
8674  // FIXME: If the destructor has a body that could throw, and the newly created
8675  // spec doesn't allow exceptions, we should emit a warning, because this
8676  // change in behavior can break conforming C++03 programs at runtime.
8677  // However, we don't have a body or an exception specification yet, so it
8678  // needs to be done somewhere else.
8679}
8680
8681namespace {
8682/// \brief An abstract base class for all helper classes used in building the
8683//  copy/move operators. These classes serve as factory functions and help us
8684//  avoid using the same Expr* in the AST twice.
8685class ExprBuilder {
8686  ExprBuilder(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8687  ExprBuilder &operator=(const ExprBuilder&) LLVM_DELETED_FUNCTION;
8688
8689protected:
8690  static Expr *assertNotNull(Expr *E) {
8691    assert(E && "Expression construction must not fail.");
8692    return E;
8693  }
8694
8695public:
8696  ExprBuilder() {}
8697  virtual ~ExprBuilder() {}
8698
8699  virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
8700};
8701
8702class RefBuilder: public ExprBuilder {
8703  VarDecl *Var;
8704  QualType VarType;
8705
8706public:
8707  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8708    return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).take());
8709  }
8710
8711  RefBuilder(VarDecl *Var, QualType VarType)
8712      : Var(Var), VarType(VarType) {}
8713};
8714
8715class ThisBuilder: public ExprBuilder {
8716public:
8717  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8718    return assertNotNull(S.ActOnCXXThis(Loc).takeAs<Expr>());
8719  }
8720};
8721
8722class CastBuilder: public ExprBuilder {
8723  const ExprBuilder &Builder;
8724  QualType Type;
8725  ExprValueKind Kind;
8726  const CXXCastPath &Path;
8727
8728public:
8729  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8730    return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
8731                                             CK_UncheckedDerivedToBase, Kind,
8732                                             &Path).take());
8733  }
8734
8735  CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
8736              const CXXCastPath &Path)
8737      : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
8738};
8739
8740class DerefBuilder: public ExprBuilder {
8741  const ExprBuilder &Builder;
8742
8743public:
8744  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8745    return assertNotNull(
8746        S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).take());
8747  }
8748
8749  DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8750};
8751
8752class MemberBuilder: public ExprBuilder {
8753  const ExprBuilder &Builder;
8754  QualType Type;
8755  CXXScopeSpec SS;
8756  bool IsArrow;
8757  LookupResult &MemberLookup;
8758
8759public:
8760  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8761    return assertNotNull(S.BuildMemberReferenceExpr(
8762        Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 0,
8763        MemberLookup, 0).take());
8764  }
8765
8766  MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
8767                LookupResult &MemberLookup)
8768      : Builder(Builder), Type(Type), IsArrow(IsArrow),
8769        MemberLookup(MemberLookup) {}
8770};
8771
8772class MoveCastBuilder: public ExprBuilder {
8773  const ExprBuilder &Builder;
8774
8775public:
8776  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8777    return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
8778  }
8779
8780  MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8781};
8782
8783class LvalueConvBuilder: public ExprBuilder {
8784  const ExprBuilder &Builder;
8785
8786public:
8787  virtual Expr *build(Sema &S, SourceLocation Loc) const LLVM_OVERRIDE {
8788    return assertNotNull(
8789        S.DefaultLvalueConversion(Builder.build(S, Loc)).take());
8790  }
8791
8792  LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
8793};
8794
8795class SubscriptBuilder: public ExprBuilder {
8796  const ExprBuilder &Base;
8797  const ExprBuilder &Index;
8798
8799public:
8800  virtual Expr *build(Sema &S, SourceLocation Loc) const
8801      LLVM_OVERRIDE {
8802    return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
8803        Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).take());
8804  }
8805
8806  SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
8807      : Base(Base), Index(Index) {}
8808};
8809
8810} // end anonymous namespace
8811
8812/// When generating a defaulted copy or move assignment operator, if a field
8813/// should be copied with __builtin_memcpy rather than via explicit assignments,
8814/// do so. This optimization only applies for arrays of scalars, and for arrays
8815/// of class type where the selected copy/move-assignment operator is trivial.
8816static StmtResult
8817buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
8818                           const ExprBuilder &ToB, const ExprBuilder &FromB) {
8819  // Compute the size of the memory buffer to be copied.
8820  QualType SizeType = S.Context.getSizeType();
8821  llvm::APInt Size(S.Context.getTypeSize(SizeType),
8822                   S.Context.getTypeSizeInChars(T).getQuantity());
8823
8824  // Take the address of the field references for "from" and "to". We
8825  // directly construct UnaryOperators here because semantic analysis
8826  // does not permit us to take the address of an xvalue.
8827  Expr *From = FromB.build(S, Loc);
8828  From = new (S.Context) UnaryOperator(From, UO_AddrOf,
8829                         S.Context.getPointerType(From->getType()),
8830                         VK_RValue, OK_Ordinary, Loc);
8831  Expr *To = ToB.build(S, Loc);
8832  To = new (S.Context) UnaryOperator(To, UO_AddrOf,
8833                       S.Context.getPointerType(To->getType()),
8834                       VK_RValue, OK_Ordinary, Loc);
8835
8836  const Type *E = T->getBaseElementTypeUnsafe();
8837  bool NeedsCollectableMemCpy =
8838    E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
8839
8840  // Create a reference to the __builtin_objc_memmove_collectable function
8841  StringRef MemCpyName = NeedsCollectableMemCpy ?
8842    "__builtin_objc_memmove_collectable" :
8843    "__builtin_memcpy";
8844  LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
8845                 Sema::LookupOrdinaryName);
8846  S.LookupName(R, S.TUScope, true);
8847
8848  FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
8849  if (!MemCpy)
8850    // Something went horribly wrong earlier, and we will have complained
8851    // about it.
8852    return StmtError();
8853
8854  ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
8855                                            VK_RValue, Loc, 0);
8856  assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
8857
8858  Expr *CallArgs[] = {
8859    To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
8860  };
8861  ExprResult Call = S.ActOnCallExpr(/*Scope=*/0, MemCpyRef.take(),
8862                                    Loc, CallArgs, Loc);
8863
8864  assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8865  return S.Owned(Call.takeAs<Stmt>());
8866}
8867
8868/// \brief Builds a statement that copies/moves the given entity from \p From to
8869/// \c To.
8870///
8871/// This routine is used to copy/move the members of a class with an
8872/// implicitly-declared copy/move assignment operator. When the entities being
8873/// copied are arrays, this routine builds for loops to copy them.
8874///
8875/// \param S The Sema object used for type-checking.
8876///
8877/// \param Loc The location where the implicit copy/move is being generated.
8878///
8879/// \param T The type of the expressions being copied/moved. Both expressions
8880/// must have this type.
8881///
8882/// \param To The expression we are copying/moving to.
8883///
8884/// \param From The expression we are copying/moving from.
8885///
8886/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
8887/// Otherwise, it's a non-static member subobject.
8888///
8889/// \param Copying Whether we're copying or moving.
8890///
8891/// \param Depth Internal parameter recording the depth of the recursion.
8892///
8893/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
8894/// if a memcpy should be used instead.
8895static StmtResult
8896buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
8897                                 const ExprBuilder &To, const ExprBuilder &From,
8898                                 bool CopyingBaseSubobject, bool Copying,
8899                                 unsigned Depth = 0) {
8900  // C++11 [class.copy]p28:
8901  //   Each subobject is assigned in the manner appropriate to its type:
8902  //
8903  //     - if the subobject is of class type, as if by a call to operator= with
8904  //       the subobject as the object expression and the corresponding
8905  //       subobject of x as a single function argument (as if by explicit
8906  //       qualification; that is, ignoring any possible virtual overriding
8907  //       functions in more derived classes);
8908  //
8909  // C++03 [class.copy]p13:
8910  //     - if the subobject is of class type, the copy assignment operator for
8911  //       the class is used (as if by explicit qualification; that is,
8912  //       ignoring any possible virtual overriding functions in more derived
8913  //       classes);
8914  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
8915    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8916
8917    // Look for operator=.
8918    DeclarationName Name
8919      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8920    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
8921    S.LookupQualifiedName(OpLookup, ClassDecl, false);
8922
8923    // Prior to C++11, filter out any result that isn't a copy/move-assignment
8924    // operator.
8925    if (!S.getLangOpts().CPlusPlus11) {
8926      LookupResult::Filter F = OpLookup.makeFilter();
8927      while (F.hasNext()) {
8928        NamedDecl *D = F.next();
8929        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
8930          if (Method->isCopyAssignmentOperator() ||
8931              (!Copying && Method->isMoveAssignmentOperator()))
8932            continue;
8933
8934        F.erase();
8935      }
8936      F.done();
8937    }
8938
8939    // Suppress the protected check (C++ [class.protected]) for each of the
8940    // assignment operators we found. This strange dance is required when
8941    // we're assigning via a base classes's copy-assignment operator. To
8942    // ensure that we're getting the right base class subobject (without
8943    // ambiguities), we need to cast "this" to that subobject type; to
8944    // ensure that we don't go through the virtual call mechanism, we need
8945    // to qualify the operator= name with the base class (see below). However,
8946    // this means that if the base class has a protected copy assignment
8947    // operator, the protected member access check will fail. So, we
8948    // rewrite "protected" access to "public" access in this case, since we
8949    // know by construction that we're calling from a derived class.
8950    if (CopyingBaseSubobject) {
8951      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
8952           L != LEnd; ++L) {
8953        if (L.getAccess() == AS_protected)
8954          L.setAccess(AS_public);
8955      }
8956    }
8957
8958    // Create the nested-name-specifier that will be used to qualify the
8959    // reference to operator=; this is required to suppress the virtual
8960    // call mechanism.
8961    CXXScopeSpec SS;
8962    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
8963    SS.MakeTrivial(S.Context,
8964                   NestedNameSpecifier::Create(S.Context, 0, false,
8965                                               CanonicalT),
8966                   Loc);
8967
8968    // Create the reference to operator=.
8969    ExprResult OpEqualRef
8970      = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
8971                                   SS, /*TemplateKWLoc=*/SourceLocation(),
8972                                   /*FirstQualifierInScope=*/0,
8973                                   OpLookup,
8974                                   /*TemplateArgs=*/0,
8975                                   /*SuppressQualifierCheck=*/true);
8976    if (OpEqualRef.isInvalid())
8977      return StmtError();
8978
8979    // Build the call to the assignment operator.
8980
8981    Expr *FromInst = From.build(S, Loc);
8982    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
8983                                                  OpEqualRef.takeAs<Expr>(),
8984                                                  Loc, FromInst, Loc);
8985    if (Call.isInvalid())
8986      return StmtError();
8987
8988    // If we built a call to a trivial 'operator=' while copying an array,
8989    // bail out. We'll replace the whole shebang with a memcpy.
8990    CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
8991    if (CE && CE->getMethodDecl()->isTrivial() && Depth)
8992      return StmtResult((Stmt*)0);
8993
8994    // Convert to an expression-statement, and clean up any produced
8995    // temporaries.
8996    return S.ActOnExprStmt(Call);
8997  }
8998
8999  //     - if the subobject is of scalar type, the built-in assignment
9000  //       operator is used.
9001  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
9002  if (!ArrayTy) {
9003    ExprResult Assignment = S.CreateBuiltinBinOp(
9004        Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
9005    if (Assignment.isInvalid())
9006      return StmtError();
9007    return S.ActOnExprStmt(Assignment);
9008  }
9009
9010  //     - if the subobject is an array, each element is assigned, in the
9011  //       manner appropriate to the element type;
9012
9013  // Construct a loop over the array bounds, e.g.,
9014  //
9015  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
9016  //
9017  // that will copy each of the array elements.
9018  QualType SizeType = S.Context.getSizeType();
9019
9020  // Create the iteration variable.
9021  IdentifierInfo *IterationVarName = 0;
9022  {
9023    SmallString<8> Str;
9024    llvm::raw_svector_ostream OS(Str);
9025    OS << "__i" << Depth;
9026    IterationVarName = &S.Context.Idents.get(OS.str());
9027  }
9028  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9029                                          IterationVarName, SizeType,
9030                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9031                                          SC_None);
9032
9033  // Initialize the iteration variable to zero.
9034  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
9035  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
9036
9037  // Creates a reference to the iteration variable.
9038  RefBuilder IterationVarRef(IterationVar, SizeType);
9039  LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
9040
9041  // Create the DeclStmt that holds the iteration variable.
9042  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
9043
9044  // Subscript the "from" and "to" expressions with the iteration variable.
9045  SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
9046  MoveCastBuilder FromIndexMove(FromIndexCopy);
9047  const ExprBuilder *FromIndex;
9048  if (Copying)
9049    FromIndex = &FromIndexCopy;
9050  else
9051    FromIndex = &FromIndexMove;
9052
9053  SubscriptBuilder ToIndex(To, IterationVarRefRVal);
9054
9055  // Build the copy/move for an individual element of the array.
9056  StmtResult Copy =
9057    buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
9058                                     ToIndex, *FromIndex, CopyingBaseSubobject,
9059                                     Copying, Depth + 1);
9060  // Bail out if copying fails or if we determined that we should use memcpy.
9061  if (Copy.isInvalid() || !Copy.get())
9062    return Copy;
9063
9064  // Create the comparison against the array bound.
9065  llvm::APInt Upper
9066    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
9067  Expr *Comparison
9068    = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
9069                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
9070                                     BO_NE, S.Context.BoolTy,
9071                                     VK_RValue, OK_Ordinary, Loc, false);
9072
9073  // Create the pre-increment of the iteration variable.
9074  Expr *Increment
9075    = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
9076                                    SizeType, VK_LValue, OK_Ordinary, Loc);
9077
9078  // Construct the loop that copies all elements of this array.
9079  return S.ActOnForStmt(Loc, Loc, InitStmt,
9080                        S.MakeFullExpr(Comparison),
9081                        0, S.MakeFullDiscardedValueExpr(Increment),
9082                        Loc, Copy.take());
9083}
9084
9085static StmtResult
9086buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
9087                      const ExprBuilder &To, const ExprBuilder &From,
9088                      bool CopyingBaseSubobject, bool Copying) {
9089  // Maybe we should use a memcpy?
9090  if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
9091      T.isTriviallyCopyableType(S.Context))
9092    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9093
9094  StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
9095                                                     CopyingBaseSubobject,
9096                                                     Copying, 0));
9097
9098  // If we ended up picking a trivial assignment operator for an array of a
9099  // non-trivially-copyable class type, just emit a memcpy.
9100  if (!Result.isInvalid() && !Result.get())
9101    return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
9102
9103  return Result;
9104}
9105
9106Sema::ImplicitExceptionSpecification
9107Sema::ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD) {
9108  CXXRecordDecl *ClassDecl = MD->getParent();
9109
9110  ImplicitExceptionSpecification ExceptSpec(*this);
9111  if (ClassDecl->isInvalidDecl())
9112    return ExceptSpec;
9113
9114  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9115  assert(T->getNumArgs() == 1 && "not a copy assignment op");
9116  unsigned ArgQuals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9117
9118  // C++ [except.spec]p14:
9119  //   An implicitly declared special member function (Clause 12) shall have an
9120  //   exception-specification. [...]
9121
9122  // It is unspecified whether or not an implicit copy assignment operator
9123  // attempts to deduplicate calls to assignment operators of virtual bases are
9124  // made. As such, this exception specification is effectively unspecified.
9125  // Based on a similar decision made for constness in C++0x, we're erring on
9126  // the side of assuming such calls to be made regardless of whether they
9127  // actually happen.
9128  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9129                                       BaseEnd = ClassDecl->bases_end();
9130       Base != BaseEnd; ++Base) {
9131    if (Base->isVirtual())
9132      continue;
9133
9134    CXXRecordDecl *BaseClassDecl
9135      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9136    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9137                                                            ArgQuals, false, 0))
9138      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9139  }
9140
9141  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9142                                       BaseEnd = ClassDecl->vbases_end();
9143       Base != BaseEnd; ++Base) {
9144    CXXRecordDecl *BaseClassDecl
9145      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9146    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
9147                                                            ArgQuals, false, 0))
9148      ExceptSpec.CalledDecl(Base->getLocStart(), CopyAssign);
9149  }
9150
9151  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9152                                  FieldEnd = ClassDecl->field_end();
9153       Field != FieldEnd;
9154       ++Field) {
9155    QualType FieldType = Context.getBaseElementType(Field->getType());
9156    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9157      if (CXXMethodDecl *CopyAssign =
9158          LookupCopyingAssignment(FieldClassDecl,
9159                                  ArgQuals | FieldType.getCVRQualifiers(),
9160                                  false, 0))
9161        ExceptSpec.CalledDecl(Field->getLocation(), CopyAssign);
9162    }
9163  }
9164
9165  return ExceptSpec;
9166}
9167
9168CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
9169  // Note: The following rules are largely analoguous to the copy
9170  // constructor rules. Note that virtual bases are not taken into account
9171  // for determining the argument type of the operator. Note also that
9172  // operators taking an object instead of a reference are allowed.
9173  assert(ClassDecl->needsImplicitCopyAssignment());
9174
9175  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
9176  if (DSM.isAlreadyBeingDeclared())
9177    return 0;
9178
9179  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9180  QualType RetType = Context.getLValueReferenceType(ArgType);
9181  bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
9182  if (Const)
9183    ArgType = ArgType.withConst();
9184  ArgType = Context.getLValueReferenceType(ArgType);
9185
9186  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9187                                                     CXXCopyAssignment,
9188                                                     Const);
9189
9190  //   An implicitly-declared copy assignment operator is an inline public
9191  //   member of its class.
9192  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9193  SourceLocation ClassLoc = ClassDecl->getLocation();
9194  DeclarationNameInfo NameInfo(Name, ClassLoc);
9195  CXXMethodDecl *CopyAssignment =
9196      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9197                            /*TInfo=*/ 0, /*StorageClass=*/ SC_None,
9198                            /*isInline=*/ true, Constexpr, SourceLocation());
9199  CopyAssignment->setAccess(AS_public);
9200  CopyAssignment->setDefaulted();
9201  CopyAssignment->setImplicit();
9202
9203  // Build an exception specification pointing back at this member.
9204  FunctionProtoType::ExtProtoInfo EPI =
9205      getImplicitMethodEPI(*this, CopyAssignment);
9206  CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9207
9208  // Add the parameter to the operator.
9209  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
9210                                               ClassLoc, ClassLoc, /*Id=*/0,
9211                                               ArgType, /*TInfo=*/0,
9212                                               SC_None, 0);
9213  CopyAssignment->setParams(FromParam);
9214
9215  AddOverriddenMethods(ClassDecl, CopyAssignment);
9216
9217  CopyAssignment->setTrivial(
9218    ClassDecl->needsOverloadResolutionForCopyAssignment()
9219      ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
9220      : ClassDecl->hasTrivialCopyAssignment());
9221
9222  // C++11 [class.copy]p19:
9223  //   ....  If the class definition does not explicitly declare a copy
9224  //   assignment operator, there is no user-declared move constructor, and
9225  //   there is no user-declared move assignment operator, a copy assignment
9226  //   operator is implicitly declared as defaulted.
9227  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
9228    SetDeclDeleted(CopyAssignment, ClassLoc);
9229
9230  // Note that we have added this copy-assignment operator.
9231  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
9232
9233  if (Scope *S = getScopeForContext(ClassDecl))
9234    PushOnScopeChains(CopyAssignment, S, false);
9235  ClassDecl->addDecl(CopyAssignment);
9236
9237  return CopyAssignment;
9238}
9239
9240/// Diagnose an implicit copy operation for a class which is odr-used, but
9241/// which is deprecated because the class has a user-declared copy constructor,
9242/// copy assignment operator, or destructor.
9243static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp,
9244                                            SourceLocation UseLoc) {
9245  assert(CopyOp->isImplicit());
9246
9247  CXXRecordDecl *RD = CopyOp->getParent();
9248  CXXMethodDecl *UserDeclaredOperation = 0;
9249
9250  // In Microsoft mode, assignment operations don't affect constructors and
9251  // vice versa.
9252  if (RD->hasUserDeclaredDestructor()) {
9253    UserDeclaredOperation = RD->getDestructor();
9254  } else if (!isa<CXXConstructorDecl>(CopyOp) &&
9255             RD->hasUserDeclaredCopyConstructor() &&
9256             !S.getLangOpts().MicrosoftMode) {
9257    // Find any user-declared copy constructor.
9258    for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
9259                                      E = RD->ctor_end(); I != E; ++I) {
9260      if (I->isCopyConstructor()) {
9261        UserDeclaredOperation = *I;
9262        break;
9263      }
9264    }
9265    assert(UserDeclaredOperation);
9266  } else if (isa<CXXConstructorDecl>(CopyOp) &&
9267             RD->hasUserDeclaredCopyAssignment() &&
9268             !S.getLangOpts().MicrosoftMode) {
9269    // Find any user-declared move assignment operator.
9270    for (CXXRecordDecl::method_iterator I = RD->method_begin(),
9271                                        E = RD->method_end(); I != E; ++I) {
9272      if (I->isCopyAssignmentOperator()) {
9273        UserDeclaredOperation = *I;
9274        break;
9275      }
9276    }
9277    assert(UserDeclaredOperation);
9278  }
9279
9280  if (UserDeclaredOperation) {
9281    S.Diag(UserDeclaredOperation->getLocation(),
9282         diag::warn_deprecated_copy_operation)
9283      << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
9284      << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
9285    S.Diag(UseLoc, diag::note_member_synthesized_at)
9286      << (isa<CXXConstructorDecl>(CopyOp) ? Sema::CXXCopyConstructor
9287                                          : Sema::CXXCopyAssignment)
9288      << RD;
9289  }
9290}
9291
9292void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
9293                                        CXXMethodDecl *CopyAssignOperator) {
9294  assert((CopyAssignOperator->isDefaulted() &&
9295          CopyAssignOperator->isOverloadedOperator() &&
9296          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
9297          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
9298          !CopyAssignOperator->isDeleted()) &&
9299         "DefineImplicitCopyAssignment called for wrong function");
9300
9301  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
9302
9303  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
9304    CopyAssignOperator->setInvalidDecl();
9305    return;
9306  }
9307
9308  // C++11 [class.copy]p18:
9309  //   The [definition of an implicitly declared copy assignment operator] is
9310  //   deprecated if the class has a user-declared copy constructor or a
9311  //   user-declared destructor.
9312  if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
9313    diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator, CurrentLocation);
9314
9315  CopyAssignOperator->markUsed(Context);
9316
9317  SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
9318  DiagnosticErrorTrap Trap(Diags);
9319
9320  // C++0x [class.copy]p30:
9321  //   The implicitly-defined or explicitly-defaulted copy assignment operator
9322  //   for a non-union class X performs memberwise copy assignment of its
9323  //   subobjects. The direct base classes of X are assigned first, in the
9324  //   order of their declaration in the base-specifier-list, and then the
9325  //   immediate non-static data members of X are assigned, in the order in
9326  //   which they were declared in the class definition.
9327
9328  // The statements that form the synthesized function body.
9329  SmallVector<Stmt*, 8> Statements;
9330
9331  // The parameter for the "other" object, which we are copying from.
9332  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
9333  Qualifiers OtherQuals = Other->getType().getQualifiers();
9334  QualType OtherRefType = Other->getType();
9335  if (const LValueReferenceType *OtherRef
9336                                = OtherRefType->getAs<LValueReferenceType>()) {
9337    OtherRefType = OtherRef->getPointeeType();
9338    OtherQuals = OtherRefType.getQualifiers();
9339  }
9340
9341  // Our location for everything implicitly-generated.
9342  SourceLocation Loc = CopyAssignOperator->getLocation();
9343
9344  // Builds a DeclRefExpr for the "other" object.
9345  RefBuilder OtherRef(Other, OtherRefType);
9346
9347  // Builds the "this" pointer.
9348  ThisBuilder This;
9349
9350  // Assign base classes.
9351  bool Invalid = false;
9352  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9353       E = ClassDecl->bases_end(); Base != E; ++Base) {
9354    // Form the assignment:
9355    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
9356    QualType BaseType = Base->getType().getUnqualifiedType();
9357    if (!BaseType->isRecordType()) {
9358      Invalid = true;
9359      continue;
9360    }
9361
9362    CXXCastPath BasePath;
9363    BasePath.push_back(Base);
9364
9365    // Construct the "from" expression, which is an implicit cast to the
9366    // appropriately-qualified base type.
9367    CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
9368                     VK_LValue, BasePath);
9369
9370    // Dereference "this".
9371    DerefBuilder DerefThis(This);
9372    CastBuilder To(DerefThis,
9373                   Context.getCVRQualifiedType(
9374                       BaseType, CopyAssignOperator->getTypeQualifiers()),
9375                   VK_LValue, BasePath);
9376
9377    // Build the copy.
9378    StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
9379                                            To, From,
9380                                            /*CopyingBaseSubobject=*/true,
9381                                            /*Copying=*/true);
9382    if (Copy.isInvalid()) {
9383      Diag(CurrentLocation, diag::note_member_synthesized_at)
9384        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9385      CopyAssignOperator->setInvalidDecl();
9386      return;
9387    }
9388
9389    // Success! Record the copy.
9390    Statements.push_back(Copy.takeAs<Expr>());
9391  }
9392
9393  // Assign non-static members.
9394  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9395                                  FieldEnd = ClassDecl->field_end();
9396       Field != FieldEnd; ++Field) {
9397    if (Field->isUnnamedBitfield())
9398      continue;
9399
9400    if (Field->isInvalidDecl()) {
9401      Invalid = true;
9402      continue;
9403    }
9404
9405    // Check for members of reference type; we can't copy those.
9406    if (Field->getType()->isReferenceType()) {
9407      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9408        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9409      Diag(Field->getLocation(), diag::note_declared_at);
9410      Diag(CurrentLocation, diag::note_member_synthesized_at)
9411        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9412      Invalid = true;
9413      continue;
9414    }
9415
9416    // Check for members of const-qualified, non-class type.
9417    QualType BaseType = Context.getBaseElementType(Field->getType());
9418    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9419      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9420        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9421      Diag(Field->getLocation(), diag::note_declared_at);
9422      Diag(CurrentLocation, diag::note_member_synthesized_at)
9423        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9424      Invalid = true;
9425      continue;
9426    }
9427
9428    // Suppress assigning zero-width bitfields.
9429    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9430      continue;
9431
9432    QualType FieldType = Field->getType().getNonReferenceType();
9433    if (FieldType->isIncompleteArrayType()) {
9434      assert(ClassDecl->hasFlexibleArrayMember() &&
9435             "Incomplete array type is not valid");
9436      continue;
9437    }
9438
9439    // Build references to the field in the object we're copying from and to.
9440    CXXScopeSpec SS; // Intentionally empty
9441    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9442                              LookupMemberName);
9443    MemberLookup.addDecl(*Field);
9444    MemberLookup.resolveKind();
9445
9446    MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
9447
9448    MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
9449
9450    // Build the copy of this field.
9451    StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
9452                                            To, From,
9453                                            /*CopyingBaseSubobject=*/false,
9454                                            /*Copying=*/true);
9455    if (Copy.isInvalid()) {
9456      Diag(CurrentLocation, diag::note_member_synthesized_at)
9457        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9458      CopyAssignOperator->setInvalidDecl();
9459      return;
9460    }
9461
9462    // Success! Record the copy.
9463    Statements.push_back(Copy.takeAs<Stmt>());
9464  }
9465
9466  if (!Invalid) {
9467    // Add a "return *this;"
9468    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9469
9470    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9471    if (Return.isInvalid())
9472      Invalid = true;
9473    else {
9474      Statements.push_back(Return.takeAs<Stmt>());
9475
9476      if (Trap.hasErrorOccurred()) {
9477        Diag(CurrentLocation, diag::note_member_synthesized_at)
9478          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
9479        Invalid = true;
9480      }
9481    }
9482  }
9483
9484  if (Invalid) {
9485    CopyAssignOperator->setInvalidDecl();
9486    return;
9487  }
9488
9489  StmtResult Body;
9490  {
9491    CompoundScopeRAII CompoundScope(*this);
9492    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9493                             /*isStmtExpr=*/false);
9494    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9495  }
9496  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
9497
9498  if (ASTMutationListener *L = getASTMutationListener()) {
9499    L->CompletedImplicitDefinition(CopyAssignOperator);
9500  }
9501}
9502
9503Sema::ImplicitExceptionSpecification
9504Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD) {
9505  CXXRecordDecl *ClassDecl = MD->getParent();
9506
9507  ImplicitExceptionSpecification ExceptSpec(*this);
9508  if (ClassDecl->isInvalidDecl())
9509    return ExceptSpec;
9510
9511  // C++0x [except.spec]p14:
9512  //   An implicitly declared special member function (Clause 12) shall have an
9513  //   exception-specification. [...]
9514
9515  // It is unspecified whether or not an implicit move assignment operator
9516  // attempts to deduplicate calls to assignment operators of virtual bases are
9517  // made. As such, this exception specification is effectively unspecified.
9518  // Based on a similar decision made for constness in C++0x, we're erring on
9519  // the side of assuming such calls to be made regardless of whether they
9520  // actually happen.
9521  // Note that a move constructor is not implicitly declared when there are
9522  // virtual bases, but it can still be user-declared and explicitly defaulted.
9523  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9524                                       BaseEnd = ClassDecl->bases_end();
9525       Base != BaseEnd; ++Base) {
9526    if (Base->isVirtual())
9527      continue;
9528
9529    CXXRecordDecl *BaseClassDecl
9530      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9531    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9532                                                           0, false, 0))
9533      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9534  }
9535
9536  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9537                                       BaseEnd = ClassDecl->vbases_end();
9538       Base != BaseEnd; ++Base) {
9539    CXXRecordDecl *BaseClassDecl
9540      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9541    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
9542                                                           0, false, 0))
9543      ExceptSpec.CalledDecl(Base->getLocStart(), MoveAssign);
9544  }
9545
9546  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9547                                  FieldEnd = ClassDecl->field_end();
9548       Field != FieldEnd;
9549       ++Field) {
9550    QualType FieldType = Context.getBaseElementType(Field->getType());
9551    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9552      if (CXXMethodDecl *MoveAssign =
9553              LookupMovingAssignment(FieldClassDecl,
9554                                     FieldType.getCVRQualifiers(),
9555                                     false, 0))
9556        ExceptSpec.CalledDecl(Field->getLocation(), MoveAssign);
9557    }
9558  }
9559
9560  return ExceptSpec;
9561}
9562
9563/// Determine whether the class type has any direct or indirect virtual base
9564/// classes which have a non-trivial move assignment operator.
9565static bool
9566hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
9567  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9568                                          BaseEnd = ClassDecl->vbases_end();
9569       Base != BaseEnd; ++Base) {
9570    CXXRecordDecl *BaseClass =
9571        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9572
9573    // Try to declare the move assignment. If it would be deleted, then the
9574    // class does not have a non-trivial move assignment.
9575    if (BaseClass->needsImplicitMoveAssignment())
9576      S.DeclareImplicitMoveAssignment(BaseClass);
9577
9578    if (BaseClass->hasNonTrivialMoveAssignment())
9579      return true;
9580  }
9581
9582  return false;
9583}
9584
9585/// Determine whether the given type either has a move constructor or is
9586/// trivially copyable.
9587static bool
9588hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
9589  Type = S.Context.getBaseElementType(Type);
9590
9591  // FIXME: Technically, non-trivially-copyable non-class types, such as
9592  // reference types, are supposed to return false here, but that appears
9593  // to be a standard defect.
9594  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
9595  if (!ClassDecl || !ClassDecl->getDefinition() || ClassDecl->isInvalidDecl())
9596    return true;
9597
9598  if (Type.isTriviallyCopyableType(S.Context))
9599    return true;
9600
9601  if (IsConstructor) {
9602    // FIXME: Need this because otherwise hasMoveConstructor isn't guaranteed to
9603    // give the right answer.
9604    if (ClassDecl->needsImplicitMoveConstructor())
9605      S.DeclareImplicitMoveConstructor(ClassDecl);
9606    return ClassDecl->hasMoveConstructor();
9607  }
9608
9609  // FIXME: Need this because otherwise hasMoveAssignment isn't guaranteed to
9610  // give the right answer.
9611  if (ClassDecl->needsImplicitMoveAssignment())
9612    S.DeclareImplicitMoveAssignment(ClassDecl);
9613  return ClassDecl->hasMoveAssignment();
9614}
9615
9616/// Determine whether all non-static data members and direct or virtual bases
9617/// of class \p ClassDecl have either a move operation, or are trivially
9618/// copyable.
9619static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
9620                                            bool IsConstructor) {
9621  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9622                                          BaseEnd = ClassDecl->bases_end();
9623       Base != BaseEnd; ++Base) {
9624    if (Base->isVirtual())
9625      continue;
9626
9627    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9628      return false;
9629  }
9630
9631  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9632                                          BaseEnd = ClassDecl->vbases_end();
9633       Base != BaseEnd; ++Base) {
9634    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
9635      return false;
9636  }
9637
9638  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9639                                     FieldEnd = ClassDecl->field_end();
9640       Field != FieldEnd; ++Field) {
9641    if (!hasMoveOrIsTriviallyCopyable(S, Field->getType(), IsConstructor))
9642      return false;
9643  }
9644
9645  return true;
9646}
9647
9648CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
9649  // C++11 [class.copy]p20:
9650  //   If the definition of a class X does not explicitly declare a move
9651  //   assignment operator, one will be implicitly declared as defaulted
9652  //   if and only if:
9653  //
9654  //   - [first 4 bullets]
9655  assert(ClassDecl->needsImplicitMoveAssignment());
9656
9657  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
9658  if (DSM.isAlreadyBeingDeclared())
9659    return 0;
9660
9661  // [Checked after we build the declaration]
9662  //   - the move assignment operator would not be implicitly defined as
9663  //     deleted,
9664
9665  // [DR1402]:
9666  //   - X has no direct or indirect virtual base class with a non-trivial
9667  //     move assignment operator, and
9668  //   - each of X's non-static data members and direct or virtual base classes
9669  //     has a type that either has a move assignment operator or is trivially
9670  //     copyable.
9671  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
9672      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
9673    ClassDecl->setFailedImplicitMoveAssignment();
9674    return 0;
9675  }
9676
9677  // Note: The following rules are largely analoguous to the move
9678  // constructor rules.
9679
9680  QualType ArgType = Context.getTypeDeclType(ClassDecl);
9681  QualType RetType = Context.getLValueReferenceType(ArgType);
9682  ArgType = Context.getRValueReferenceType(ArgType);
9683
9684  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
9685                                                     CXXMoveAssignment,
9686                                                     false);
9687
9688  //   An implicitly-declared move assignment operator is an inline public
9689  //   member of its class.
9690  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
9691  SourceLocation ClassLoc = ClassDecl->getLocation();
9692  DeclarationNameInfo NameInfo(Name, ClassLoc);
9693  CXXMethodDecl *MoveAssignment =
9694      CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
9695                            /*TInfo=*/0, /*StorageClass=*/SC_None,
9696                            /*isInline=*/true, Constexpr, SourceLocation());
9697  MoveAssignment->setAccess(AS_public);
9698  MoveAssignment->setDefaulted();
9699  MoveAssignment->setImplicit();
9700
9701  // Build an exception specification pointing back at this member.
9702  FunctionProtoType::ExtProtoInfo EPI =
9703      getImplicitMethodEPI(*this, MoveAssignment);
9704  MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
9705
9706  // Add the parameter to the operator.
9707  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
9708                                               ClassLoc, ClassLoc, /*Id=*/0,
9709                                               ArgType, /*TInfo=*/0,
9710                                               SC_None, 0);
9711  MoveAssignment->setParams(FromParam);
9712
9713  AddOverriddenMethods(ClassDecl, MoveAssignment);
9714
9715  MoveAssignment->setTrivial(
9716    ClassDecl->needsOverloadResolutionForMoveAssignment()
9717      ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
9718      : ClassDecl->hasTrivialMoveAssignment());
9719
9720  // C++0x [class.copy]p9:
9721  //   If the definition of a class X does not explicitly declare a move
9722  //   assignment operator, one will be implicitly declared as defaulted if and
9723  //   only if:
9724  //   [...]
9725  //   - the move assignment operator would not be implicitly defined as
9726  //     deleted.
9727  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
9728    // Cache this result so that we don't try to generate this over and over
9729    // on every lookup, leaking memory and wasting time.
9730    ClassDecl->setFailedImplicitMoveAssignment();
9731    return 0;
9732  }
9733
9734  // Note that we have added this copy-assignment operator.
9735  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
9736
9737  if (Scope *S = getScopeForContext(ClassDecl))
9738    PushOnScopeChains(MoveAssignment, S, false);
9739  ClassDecl->addDecl(MoveAssignment);
9740
9741  return MoveAssignment;
9742}
9743
9744void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
9745                                        CXXMethodDecl *MoveAssignOperator) {
9746  assert((MoveAssignOperator->isDefaulted() &&
9747          MoveAssignOperator->isOverloadedOperator() &&
9748          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
9749          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
9750          !MoveAssignOperator->isDeleted()) &&
9751         "DefineImplicitMoveAssignment called for wrong function");
9752
9753  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
9754
9755  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
9756    MoveAssignOperator->setInvalidDecl();
9757    return;
9758  }
9759
9760  MoveAssignOperator->markUsed(Context);
9761
9762  SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
9763  DiagnosticErrorTrap Trap(Diags);
9764
9765  // C++0x [class.copy]p28:
9766  //   The implicitly-defined or move assignment operator for a non-union class
9767  //   X performs memberwise move assignment of its subobjects. The direct base
9768  //   classes of X are assigned first, in the order of their declaration in the
9769  //   base-specifier-list, and then the immediate non-static data members of X
9770  //   are assigned, in the order in which they were declared in the class
9771  //   definition.
9772
9773  // The statements that form the synthesized function body.
9774  SmallVector<Stmt*, 8> Statements;
9775
9776  // The parameter for the "other" object, which we are move from.
9777  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
9778  QualType OtherRefType = Other->getType()->
9779      getAs<RValueReferenceType>()->getPointeeType();
9780  assert(!OtherRefType.getQualifiers() &&
9781         "Bad argument type of defaulted move assignment");
9782
9783  // Our location for everything implicitly-generated.
9784  SourceLocation Loc = MoveAssignOperator->getLocation();
9785
9786  // Builds a reference to the "other" object.
9787  RefBuilder OtherRef(Other, OtherRefType);
9788  // Cast to rvalue.
9789  MoveCastBuilder MoveOther(OtherRef);
9790
9791  // Builds the "this" pointer.
9792  ThisBuilder This;
9793
9794  // Assign base classes.
9795  bool Invalid = false;
9796  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9797       E = ClassDecl->bases_end(); Base != E; ++Base) {
9798    // Form the assignment:
9799    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
9800    QualType BaseType = Base->getType().getUnqualifiedType();
9801    if (!BaseType->isRecordType()) {
9802      Invalid = true;
9803      continue;
9804    }
9805
9806    CXXCastPath BasePath;
9807    BasePath.push_back(Base);
9808
9809    // Construct the "from" expression, which is an implicit cast to the
9810    // appropriately-qualified base type.
9811    CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
9812
9813    // Dereference "this".
9814    DerefBuilder DerefThis(This);
9815
9816    // Implicitly cast "this" to the appropriately-qualified base type.
9817    CastBuilder To(DerefThis,
9818                   Context.getCVRQualifiedType(
9819                       BaseType, MoveAssignOperator->getTypeQualifiers()),
9820                   VK_LValue, BasePath);
9821
9822    // Build the move.
9823    StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
9824                                            To, From,
9825                                            /*CopyingBaseSubobject=*/true,
9826                                            /*Copying=*/false);
9827    if (Move.isInvalid()) {
9828      Diag(CurrentLocation, diag::note_member_synthesized_at)
9829        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9830      MoveAssignOperator->setInvalidDecl();
9831      return;
9832    }
9833
9834    // Success! Record the move.
9835    Statements.push_back(Move.takeAs<Expr>());
9836  }
9837
9838  // Assign non-static members.
9839  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9840                                  FieldEnd = ClassDecl->field_end();
9841       Field != FieldEnd; ++Field) {
9842    if (Field->isUnnamedBitfield())
9843      continue;
9844
9845    if (Field->isInvalidDecl()) {
9846      Invalid = true;
9847      continue;
9848    }
9849
9850    // Check for members of reference type; we can't move those.
9851    if (Field->getType()->isReferenceType()) {
9852      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9853        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
9854      Diag(Field->getLocation(), diag::note_declared_at);
9855      Diag(CurrentLocation, diag::note_member_synthesized_at)
9856        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9857      Invalid = true;
9858      continue;
9859    }
9860
9861    // Check for members of const-qualified, non-class type.
9862    QualType BaseType = Context.getBaseElementType(Field->getType());
9863    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
9864      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
9865        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
9866      Diag(Field->getLocation(), diag::note_declared_at);
9867      Diag(CurrentLocation, diag::note_member_synthesized_at)
9868        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9869      Invalid = true;
9870      continue;
9871    }
9872
9873    // Suppress assigning zero-width bitfields.
9874    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
9875      continue;
9876
9877    QualType FieldType = Field->getType().getNonReferenceType();
9878    if (FieldType->isIncompleteArrayType()) {
9879      assert(ClassDecl->hasFlexibleArrayMember() &&
9880             "Incomplete array type is not valid");
9881      continue;
9882    }
9883
9884    // Build references to the field in the object we're copying from and to.
9885    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
9886                              LookupMemberName);
9887    MemberLookup.addDecl(*Field);
9888    MemberLookup.resolveKind();
9889    MemberBuilder From(MoveOther, OtherRefType,
9890                       /*IsArrow=*/false, MemberLookup);
9891    MemberBuilder To(This, getCurrentThisType(),
9892                     /*IsArrow=*/true, MemberLookup);
9893
9894    assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
9895        "Member reference with rvalue base must be rvalue except for reference "
9896        "members, which aren't allowed for move assignment.");
9897
9898    // Build the move of this field.
9899    StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
9900                                            To, From,
9901                                            /*CopyingBaseSubobject=*/false,
9902                                            /*Copying=*/false);
9903    if (Move.isInvalid()) {
9904      Diag(CurrentLocation, diag::note_member_synthesized_at)
9905        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9906      MoveAssignOperator->setInvalidDecl();
9907      return;
9908    }
9909
9910    // Success! Record the copy.
9911    Statements.push_back(Move.takeAs<Stmt>());
9912  }
9913
9914  if (!Invalid) {
9915    // Add a "return *this;"
9916    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
9917
9918    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
9919    if (Return.isInvalid())
9920      Invalid = true;
9921    else {
9922      Statements.push_back(Return.takeAs<Stmt>());
9923
9924      if (Trap.hasErrorOccurred()) {
9925        Diag(CurrentLocation, diag::note_member_synthesized_at)
9926          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
9927        Invalid = true;
9928      }
9929    }
9930  }
9931
9932  if (Invalid) {
9933    MoveAssignOperator->setInvalidDecl();
9934    return;
9935  }
9936
9937  StmtResult Body;
9938  {
9939    CompoundScopeRAII CompoundScope(*this);
9940    Body = ActOnCompoundStmt(Loc, Loc, Statements,
9941                             /*isStmtExpr=*/false);
9942    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
9943  }
9944  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
9945
9946  if (ASTMutationListener *L = getASTMutationListener()) {
9947    L->CompletedImplicitDefinition(MoveAssignOperator);
9948  }
9949}
9950
9951Sema::ImplicitExceptionSpecification
9952Sema::ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD) {
9953  CXXRecordDecl *ClassDecl = MD->getParent();
9954
9955  ImplicitExceptionSpecification ExceptSpec(*this);
9956  if (ClassDecl->isInvalidDecl())
9957    return ExceptSpec;
9958
9959  const FunctionProtoType *T = MD->getType()->castAs<FunctionProtoType>();
9960  assert(T->getNumArgs() >= 1 && "not a copy ctor");
9961  unsigned Quals = T->getArgType(0).getNonReferenceType().getCVRQualifiers();
9962
9963  // C++ [except.spec]p14:
9964  //   An implicitly declared special member function (Clause 12) shall have an
9965  //   exception-specification. [...]
9966  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
9967                                       BaseEnd = ClassDecl->bases_end();
9968       Base != BaseEnd;
9969       ++Base) {
9970    // Virtual bases are handled below.
9971    if (Base->isVirtual())
9972      continue;
9973
9974    CXXRecordDecl *BaseClassDecl
9975      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9976    if (CXXConstructorDecl *CopyConstructor =
9977          LookupCopyingConstructor(BaseClassDecl, Quals))
9978      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9979  }
9980  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
9981                                       BaseEnd = ClassDecl->vbases_end();
9982       Base != BaseEnd;
9983       ++Base) {
9984    CXXRecordDecl *BaseClassDecl
9985      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
9986    if (CXXConstructorDecl *CopyConstructor =
9987          LookupCopyingConstructor(BaseClassDecl, Quals))
9988      ExceptSpec.CalledDecl(Base->getLocStart(), CopyConstructor);
9989  }
9990  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
9991                                  FieldEnd = ClassDecl->field_end();
9992       Field != FieldEnd;
9993       ++Field) {
9994    QualType FieldType = Context.getBaseElementType(Field->getType());
9995    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
9996      if (CXXConstructorDecl *CopyConstructor =
9997              LookupCopyingConstructor(FieldClassDecl,
9998                                       Quals | FieldType.getCVRQualifiers()))
9999      ExceptSpec.CalledDecl(Field->getLocation(), CopyConstructor);
10000    }
10001  }
10002
10003  return ExceptSpec;
10004}
10005
10006CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
10007                                                    CXXRecordDecl *ClassDecl) {
10008  // C++ [class.copy]p4:
10009  //   If the class definition does not explicitly declare a copy
10010  //   constructor, one is declared implicitly.
10011  assert(ClassDecl->needsImplicitCopyConstructor());
10012
10013  DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
10014  if (DSM.isAlreadyBeingDeclared())
10015    return 0;
10016
10017  QualType ClassType = Context.getTypeDeclType(ClassDecl);
10018  QualType ArgType = ClassType;
10019  bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
10020  if (Const)
10021    ArgType = ArgType.withConst();
10022  ArgType = Context.getLValueReferenceType(ArgType);
10023
10024  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10025                                                     CXXCopyConstructor,
10026                                                     Const);
10027
10028  DeclarationName Name
10029    = Context.DeclarationNames.getCXXConstructorName(
10030                                           Context.getCanonicalType(ClassType));
10031  SourceLocation ClassLoc = ClassDecl->getLocation();
10032  DeclarationNameInfo NameInfo(Name, ClassLoc);
10033
10034  //   An implicitly-declared copy constructor is an inline public
10035  //   member of its class.
10036  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
10037      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10038      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10039      Constexpr);
10040  CopyConstructor->setAccess(AS_public);
10041  CopyConstructor->setDefaulted();
10042
10043  // Build an exception specification pointing back at this member.
10044  FunctionProtoType::ExtProtoInfo EPI =
10045      getImplicitMethodEPI(*this, CopyConstructor);
10046  CopyConstructor->setType(
10047      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10048
10049  // Add the parameter to the constructor.
10050  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
10051                                               ClassLoc, ClassLoc,
10052                                               /*IdentifierInfo=*/0,
10053                                               ArgType, /*TInfo=*/0,
10054                                               SC_None, 0);
10055  CopyConstructor->setParams(FromParam);
10056
10057  CopyConstructor->setTrivial(
10058    ClassDecl->needsOverloadResolutionForCopyConstructor()
10059      ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
10060      : ClassDecl->hasTrivialCopyConstructor());
10061
10062  // C++11 [class.copy]p8:
10063  //   ... If the class definition does not explicitly declare a copy
10064  //   constructor, there is no user-declared move constructor, and there is no
10065  //   user-declared move assignment operator, a copy constructor is implicitly
10066  //   declared as defaulted.
10067  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
10068    SetDeclDeleted(CopyConstructor, ClassLoc);
10069
10070  // Note that we have declared this constructor.
10071  ++ASTContext::NumImplicitCopyConstructorsDeclared;
10072
10073  if (Scope *S = getScopeForContext(ClassDecl))
10074    PushOnScopeChains(CopyConstructor, S, false);
10075  ClassDecl->addDecl(CopyConstructor);
10076
10077  return CopyConstructor;
10078}
10079
10080void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
10081                                   CXXConstructorDecl *CopyConstructor) {
10082  assert((CopyConstructor->isDefaulted() &&
10083          CopyConstructor->isCopyConstructor() &&
10084          !CopyConstructor->doesThisDeclarationHaveABody() &&
10085          !CopyConstructor->isDeleted()) &&
10086         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
10087
10088  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
10089  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
10090
10091  // C++11 [class.copy]p7:
10092  //   The [definition of an implicitly declared copy constructor] is
10093  //   deprecated if the class has a user-declared copy assignment operator
10094  //   or a user-declared destructor.
10095  if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
10096    diagnoseDeprecatedCopyOperation(*this, CopyConstructor, CurrentLocation);
10097
10098  SynthesizedFunctionScope Scope(*this, CopyConstructor);
10099  DiagnosticErrorTrap Trap(Diags);
10100
10101  if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false) ||
10102      Trap.hasErrorOccurred()) {
10103    Diag(CurrentLocation, diag::note_member_synthesized_at)
10104      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
10105    CopyConstructor->setInvalidDecl();
10106  }  else {
10107    Sema::CompoundScopeRAII CompoundScope(*this);
10108    CopyConstructor->setBody(ActOnCompoundStmt(
10109        CopyConstructor->getLocation(), CopyConstructor->getLocation(), None,
10110        /*isStmtExpr=*/ false).takeAs<Stmt>());
10111  }
10112
10113  CopyConstructor->markUsed(Context);
10114  if (ASTMutationListener *L = getASTMutationListener()) {
10115    L->CompletedImplicitDefinition(CopyConstructor);
10116  }
10117}
10118
10119Sema::ImplicitExceptionSpecification
10120Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD) {
10121  CXXRecordDecl *ClassDecl = MD->getParent();
10122
10123  // C++ [except.spec]p14:
10124  //   An implicitly declared special member function (Clause 12) shall have an
10125  //   exception-specification. [...]
10126  ImplicitExceptionSpecification ExceptSpec(*this);
10127  if (ClassDecl->isInvalidDecl())
10128    return ExceptSpec;
10129
10130  // Direct base-class constructors.
10131  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
10132                                       BEnd = ClassDecl->bases_end();
10133       B != BEnd; ++B) {
10134    if (B->isVirtual()) // Handled below.
10135      continue;
10136
10137    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10138      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10139      CXXConstructorDecl *Constructor =
10140          LookupMovingConstructor(BaseClassDecl, 0);
10141      // If this is a deleted function, add it anyway. This might be conformant
10142      // with the standard. This might not. I'm not sure. It might not matter.
10143      if (Constructor)
10144        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10145    }
10146  }
10147
10148  // Virtual base-class constructors.
10149  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
10150                                       BEnd = ClassDecl->vbases_end();
10151       B != BEnd; ++B) {
10152    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
10153      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
10154      CXXConstructorDecl *Constructor =
10155          LookupMovingConstructor(BaseClassDecl, 0);
10156      // If this is a deleted function, add it anyway. This might be conformant
10157      // with the standard. This might not. I'm not sure. It might not matter.
10158      if (Constructor)
10159        ExceptSpec.CalledDecl(B->getLocStart(), Constructor);
10160    }
10161  }
10162
10163  // Field constructors.
10164  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
10165                               FEnd = ClassDecl->field_end();
10166       F != FEnd; ++F) {
10167    QualType FieldType = Context.getBaseElementType(F->getType());
10168    if (CXXRecordDecl *FieldRecDecl = FieldType->getAsCXXRecordDecl()) {
10169      CXXConstructorDecl *Constructor =
10170          LookupMovingConstructor(FieldRecDecl, FieldType.getCVRQualifiers());
10171      // If this is a deleted function, add it anyway. This might be conformant
10172      // with the standard. This might not. I'm not sure. It might not matter.
10173      // In particular, the problem is that this function never gets called. It
10174      // might just be ill-formed because this function attempts to refer to
10175      // a deleted function here.
10176      if (Constructor)
10177        ExceptSpec.CalledDecl(F->getLocation(), Constructor);
10178    }
10179  }
10180
10181  return ExceptSpec;
10182}
10183
10184CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
10185                                                    CXXRecordDecl *ClassDecl) {
10186  // C++11 [class.copy]p9:
10187  //   If the definition of a class X does not explicitly declare a move
10188  //   constructor, one will be implicitly declared as defaulted if and only if:
10189  //
10190  //   - [first 4 bullets]
10191  assert(ClassDecl->needsImplicitMoveConstructor());
10192
10193  DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
10194  if (DSM.isAlreadyBeingDeclared())
10195    return 0;
10196
10197  // [Checked after we build the declaration]
10198  //   - the move assignment operator would not be implicitly defined as
10199  //     deleted,
10200
10201  // [DR1402]:
10202  //   - each of X's non-static data members and direct or virtual base classes
10203  //     has a type that either has a move constructor or is trivially copyable.
10204  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
10205    ClassDecl->setFailedImplicitMoveConstructor();
10206    return 0;
10207  }
10208
10209  QualType ClassType = Context.getTypeDeclType(ClassDecl);
10210  QualType ArgType = Context.getRValueReferenceType(ClassType);
10211
10212  bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10213                                                     CXXMoveConstructor,
10214                                                     false);
10215
10216  DeclarationName Name
10217    = Context.DeclarationNames.getCXXConstructorName(
10218                                           Context.getCanonicalType(ClassType));
10219  SourceLocation ClassLoc = ClassDecl->getLocation();
10220  DeclarationNameInfo NameInfo(Name, ClassLoc);
10221
10222  // C++11 [class.copy]p11:
10223  //   An implicitly-declared copy/move constructor is an inline public
10224  //   member of its class.
10225  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
10226      Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/0,
10227      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
10228      Constexpr);
10229  MoveConstructor->setAccess(AS_public);
10230  MoveConstructor->setDefaulted();
10231
10232  // Build an exception specification pointing back at this member.
10233  FunctionProtoType::ExtProtoInfo EPI =
10234      getImplicitMethodEPI(*this, MoveConstructor);
10235  MoveConstructor->setType(
10236      Context.getFunctionType(Context.VoidTy, ArgType, EPI));
10237
10238  // Add the parameter to the constructor.
10239  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
10240                                               ClassLoc, ClassLoc,
10241                                               /*IdentifierInfo=*/0,
10242                                               ArgType, /*TInfo=*/0,
10243                                               SC_None, 0);
10244  MoveConstructor->setParams(FromParam);
10245
10246  MoveConstructor->setTrivial(
10247    ClassDecl->needsOverloadResolutionForMoveConstructor()
10248      ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
10249      : ClassDecl->hasTrivialMoveConstructor());
10250
10251  // C++0x [class.copy]p9:
10252  //   If the definition of a class X does not explicitly declare a move
10253  //   constructor, one will be implicitly declared as defaulted if and only if:
10254  //   [...]
10255  //   - the move constructor would not be implicitly defined as deleted.
10256  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
10257    // Cache this result so that we don't try to generate this over and over
10258    // on every lookup, leaking memory and wasting time.
10259    ClassDecl->setFailedImplicitMoveConstructor();
10260    return 0;
10261  }
10262
10263  // Note that we have declared this constructor.
10264  ++ASTContext::NumImplicitMoveConstructorsDeclared;
10265
10266  if (Scope *S = getScopeForContext(ClassDecl))
10267    PushOnScopeChains(MoveConstructor, S, false);
10268  ClassDecl->addDecl(MoveConstructor);
10269
10270  return MoveConstructor;
10271}
10272
10273void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
10274                                   CXXConstructorDecl *MoveConstructor) {
10275  assert((MoveConstructor->isDefaulted() &&
10276          MoveConstructor->isMoveConstructor() &&
10277          !MoveConstructor->doesThisDeclarationHaveABody() &&
10278          !MoveConstructor->isDeleted()) &&
10279         "DefineImplicitMoveConstructor - call it for implicit move ctor");
10280
10281  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
10282  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
10283
10284  SynthesizedFunctionScope Scope(*this, MoveConstructor);
10285  DiagnosticErrorTrap Trap(Diags);
10286
10287  if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false) ||
10288      Trap.hasErrorOccurred()) {
10289    Diag(CurrentLocation, diag::note_member_synthesized_at)
10290      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
10291    MoveConstructor->setInvalidDecl();
10292  }  else {
10293    Sema::CompoundScopeRAII CompoundScope(*this);
10294    MoveConstructor->setBody(ActOnCompoundStmt(
10295        MoveConstructor->getLocation(), MoveConstructor->getLocation(), None,
10296        /*isStmtExpr=*/ false).takeAs<Stmt>());
10297  }
10298
10299  MoveConstructor->markUsed(Context);
10300
10301  if (ASTMutationListener *L = getASTMutationListener()) {
10302    L->CompletedImplicitDefinition(MoveConstructor);
10303  }
10304}
10305
10306bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
10307  return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
10308}
10309
10310void Sema::DefineImplicitLambdaToFunctionPointerConversion(
10311                            SourceLocation CurrentLocation,
10312                            CXXConversionDecl *Conv) {
10313  CXXRecordDecl *Lambda = Conv->getParent();
10314  CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
10315  // If we are defining a specialization of a conversion to function-ptr
10316  // cache the deduced template arguments for this specialization
10317  // so that we can use them to retrieve the corresponding call-operator
10318  // and static-invoker.
10319  const TemplateArgumentList *DeducedTemplateArgs = 0;
10320
10321
10322  // Retrieve the corresponding call-operator specialization.
10323  if (Lambda->isGenericLambda()) {
10324    assert(Conv->isFunctionTemplateSpecialization());
10325    FunctionTemplateDecl *CallOpTemplate =
10326        CallOp->getDescribedFunctionTemplate();
10327    DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
10328    void *InsertPos = 0;
10329    FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
10330                                                DeducedTemplateArgs->data(),
10331                                                DeducedTemplateArgs->size(),
10332                                                InsertPos);
10333    assert(CallOpSpec &&
10334          "Conversion operator must have a corresponding call operator");
10335    CallOp = cast<CXXMethodDecl>(CallOpSpec);
10336  }
10337  // Mark the call operator referenced (and add to pending instantiations
10338  // if necessary).
10339  // For both the conversion and static-invoker template specializations
10340  // we construct their body's in this function, so no need to add them
10341  // to the PendingInstantiations.
10342  MarkFunctionReferenced(CurrentLocation, CallOp);
10343
10344  SynthesizedFunctionScope Scope(*this, Conv);
10345  DiagnosticErrorTrap Trap(Diags);
10346
10347  // Retreive the static invoker...
10348  CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
10349  // ... and get the corresponding specialization for a generic lambda.
10350  if (Lambda->isGenericLambda()) {
10351    assert(DeducedTemplateArgs &&
10352      "Must have deduced template arguments from Conversion Operator");
10353    FunctionTemplateDecl *InvokeTemplate =
10354                          Invoker->getDescribedFunctionTemplate();
10355    void *InsertPos = 0;
10356    FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
10357                                                DeducedTemplateArgs->data(),
10358                                                DeducedTemplateArgs->size(),
10359                                                InsertPos);
10360    assert(InvokeSpec &&
10361      "Must have a corresponding static invoker specialization");
10362    Invoker = cast<CXXMethodDecl>(InvokeSpec);
10363  }
10364  // Construct the body of the conversion function { return __invoke; }.
10365  Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
10366                                        VK_LValue, Conv->getLocation()).take();
10367   assert(FunctionRef && "Can't refer to __invoke function?");
10368   Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
10369   Conv->setBody(new (Context) CompoundStmt(Context, Return,
10370                                            Conv->getLocation(),
10371                                            Conv->getLocation()));
10372
10373  Conv->markUsed(Context);
10374  Conv->setReferenced();
10375
10376  // Fill in the __invoke function with a dummy implementation. IR generation
10377  // will fill in the actual details.
10378  Invoker->markUsed(Context);
10379  Invoker->setReferenced();
10380  Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
10381
10382  if (ASTMutationListener *L = getASTMutationListener()) {
10383    L->CompletedImplicitDefinition(Conv);
10384    L->CompletedImplicitDefinition(Invoker);
10385   }
10386}
10387
10388
10389
10390void Sema::DefineImplicitLambdaToBlockPointerConversion(
10391       SourceLocation CurrentLocation,
10392       CXXConversionDecl *Conv)
10393{
10394  assert(!Conv->getParent()->isGenericLambda());
10395
10396  Conv->markUsed(Context);
10397
10398  SynthesizedFunctionScope Scope(*this, Conv);
10399  DiagnosticErrorTrap Trap(Diags);
10400
10401  // Copy-initialize the lambda object as needed to capture it.
10402  Expr *This = ActOnCXXThis(CurrentLocation).take();
10403  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
10404
10405  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
10406                                                        Conv->getLocation(),
10407                                                        Conv, DerefThis);
10408
10409  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
10410  // behavior.  Note that only the general conversion function does this
10411  // (since it's unusable otherwise); in the case where we inline the
10412  // block literal, it has block literal lifetime semantics.
10413  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
10414    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
10415                                          CK_CopyAndAutoreleaseBlockObject,
10416                                          BuildBlock.get(), 0, VK_RValue);
10417
10418  if (BuildBlock.isInvalid()) {
10419    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10420    Conv->setInvalidDecl();
10421    return;
10422  }
10423
10424  // Create the return statement that returns the block from the conversion
10425  // function.
10426  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
10427  if (Return.isInvalid()) {
10428    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
10429    Conv->setInvalidDecl();
10430    return;
10431  }
10432
10433  // Set the body of the conversion function.
10434  Stmt *ReturnS = Return.take();
10435  Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
10436                                           Conv->getLocation(),
10437                                           Conv->getLocation()));
10438
10439  // We're done; notify the mutation listener, if any.
10440  if (ASTMutationListener *L = getASTMutationListener()) {
10441    L->CompletedImplicitDefinition(Conv);
10442  }
10443}
10444
10445/// \brief Determine whether the given list arguments contains exactly one
10446/// "real" (non-default) argument.
10447static bool hasOneRealArgument(MultiExprArg Args) {
10448  switch (Args.size()) {
10449  case 0:
10450    return false;
10451
10452  default:
10453    if (!Args[1]->isDefaultArgument())
10454      return false;
10455
10456    // fall through
10457  case 1:
10458    return !Args[0]->isDefaultArgument();
10459  }
10460
10461  return false;
10462}
10463
10464ExprResult
10465Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10466                            CXXConstructorDecl *Constructor,
10467                            MultiExprArg ExprArgs,
10468                            bool HadMultipleCandidates,
10469                            bool IsListInitialization,
10470                            bool RequiresZeroInit,
10471                            unsigned ConstructKind,
10472                            SourceRange ParenRange) {
10473  bool Elidable = false;
10474
10475  // C++0x [class.copy]p34:
10476  //   When certain criteria are met, an implementation is allowed to
10477  //   omit the copy/move construction of a class object, even if the
10478  //   copy/move constructor and/or destructor for the object have
10479  //   side effects. [...]
10480  //     - when a temporary class object that has not been bound to a
10481  //       reference (12.2) would be copied/moved to a class object
10482  //       with the same cv-unqualified type, the copy/move operation
10483  //       can be omitted by constructing the temporary object
10484  //       directly into the target of the omitted copy/move
10485  if (ConstructKind == CXXConstructExpr::CK_Complete &&
10486      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
10487    Expr *SubExpr = ExprArgs[0];
10488    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
10489  }
10490
10491  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
10492                               Elidable, ExprArgs, HadMultipleCandidates,
10493                               IsListInitialization, RequiresZeroInit,
10494                               ConstructKind, ParenRange);
10495}
10496
10497/// BuildCXXConstructExpr - Creates a complete call to a constructor,
10498/// including handling of its default argument expressions.
10499ExprResult
10500Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
10501                            CXXConstructorDecl *Constructor, bool Elidable,
10502                            MultiExprArg ExprArgs,
10503                            bool HadMultipleCandidates,
10504                            bool IsListInitialization,
10505                            bool RequiresZeroInit,
10506                            unsigned ConstructKind,
10507                            SourceRange ParenRange) {
10508  MarkFunctionReferenced(ConstructLoc, Constructor);
10509  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
10510                                        Constructor, Elidable, ExprArgs,
10511                                        HadMultipleCandidates,
10512                                        IsListInitialization, RequiresZeroInit,
10513              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
10514                                        ParenRange));
10515}
10516
10517void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
10518  if (VD->isInvalidDecl()) return;
10519
10520  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
10521  if (ClassDecl->isInvalidDecl()) return;
10522  if (ClassDecl->hasIrrelevantDestructor()) return;
10523  if (ClassDecl->isDependentContext()) return;
10524
10525  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10526  MarkFunctionReferenced(VD->getLocation(), Destructor);
10527  CheckDestructorAccess(VD->getLocation(), Destructor,
10528                        PDiag(diag::err_access_dtor_var)
10529                        << VD->getDeclName()
10530                        << VD->getType());
10531  DiagnoseUseOfDecl(Destructor, VD->getLocation());
10532
10533  if (!VD->hasGlobalStorage()) return;
10534
10535  // Emit warning for non-trivial dtor in global scope (a real global,
10536  // class-static, function-static).
10537  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
10538
10539  // TODO: this should be re-enabled for static locals by !CXAAtExit
10540  if (!VD->isStaticLocal())
10541    Diag(VD->getLocation(), diag::warn_global_destructor);
10542}
10543
10544/// \brief Given a constructor and the set of arguments provided for the
10545/// constructor, convert the arguments and add any required default arguments
10546/// to form a proper call to this constructor.
10547///
10548/// \returns true if an error occurred, false otherwise.
10549bool
10550Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
10551                              MultiExprArg ArgsPtr,
10552                              SourceLocation Loc,
10553                              SmallVectorImpl<Expr*> &ConvertedArgs,
10554                              bool AllowExplicit,
10555                              bool IsListInitialization) {
10556  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
10557  unsigned NumArgs = ArgsPtr.size();
10558  Expr **Args = ArgsPtr.data();
10559
10560  const FunctionProtoType *Proto
10561    = Constructor->getType()->getAs<FunctionProtoType>();
10562  assert(Proto && "Constructor without a prototype?");
10563  unsigned NumArgsInProto = Proto->getNumArgs();
10564
10565  // If too few arguments are available, we'll fill in the rest with defaults.
10566  if (NumArgs < NumArgsInProto)
10567    ConvertedArgs.reserve(NumArgsInProto);
10568  else
10569    ConvertedArgs.reserve(NumArgs);
10570
10571  VariadicCallType CallType =
10572    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
10573  SmallVector<Expr *, 8> AllArgs;
10574  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
10575                                        Proto, 0,
10576                                        llvm::makeArrayRef(Args, NumArgs),
10577                                        AllArgs,
10578                                        CallType, AllowExplicit,
10579                                        IsListInitialization);
10580  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
10581
10582  DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
10583
10584  CheckConstructorCall(Constructor,
10585                       llvm::makeArrayRef<const Expr *>(AllArgs.data(),
10586                                                        AllArgs.size()),
10587                       Proto, Loc);
10588
10589  return Invalid;
10590}
10591
10592static inline bool
10593CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
10594                                       const FunctionDecl *FnDecl) {
10595  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
10596  if (isa<NamespaceDecl>(DC)) {
10597    return SemaRef.Diag(FnDecl->getLocation(),
10598                        diag::err_operator_new_delete_declared_in_namespace)
10599      << FnDecl->getDeclName();
10600  }
10601
10602  if (isa<TranslationUnitDecl>(DC) &&
10603      FnDecl->getStorageClass() == SC_Static) {
10604    return SemaRef.Diag(FnDecl->getLocation(),
10605                        diag::err_operator_new_delete_declared_static)
10606      << FnDecl->getDeclName();
10607  }
10608
10609  return false;
10610}
10611
10612static inline bool
10613CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
10614                            CanQualType ExpectedResultType,
10615                            CanQualType ExpectedFirstParamType,
10616                            unsigned DependentParamTypeDiag,
10617                            unsigned InvalidParamTypeDiag) {
10618  QualType ResultType =
10619    FnDecl->getType()->getAs<FunctionType>()->getResultType();
10620
10621  // Check that the result type is not dependent.
10622  if (ResultType->isDependentType())
10623    return SemaRef.Diag(FnDecl->getLocation(),
10624                        diag::err_operator_new_delete_dependent_result_type)
10625    << FnDecl->getDeclName() << ExpectedResultType;
10626
10627  // Check that the result type is what we expect.
10628  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
10629    return SemaRef.Diag(FnDecl->getLocation(),
10630                        diag::err_operator_new_delete_invalid_result_type)
10631    << FnDecl->getDeclName() << ExpectedResultType;
10632
10633  // A function template must have at least 2 parameters.
10634  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
10635    return SemaRef.Diag(FnDecl->getLocation(),
10636                      diag::err_operator_new_delete_template_too_few_parameters)
10637        << FnDecl->getDeclName();
10638
10639  // The function decl must have at least 1 parameter.
10640  if (FnDecl->getNumParams() == 0)
10641    return SemaRef.Diag(FnDecl->getLocation(),
10642                        diag::err_operator_new_delete_too_few_parameters)
10643      << FnDecl->getDeclName();
10644
10645  // Check the first parameter type is not dependent.
10646  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
10647  if (FirstParamType->isDependentType())
10648    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
10649      << FnDecl->getDeclName() << ExpectedFirstParamType;
10650
10651  // Check that the first parameter type is what we expect.
10652  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
10653      ExpectedFirstParamType)
10654    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
10655    << FnDecl->getDeclName() << ExpectedFirstParamType;
10656
10657  return false;
10658}
10659
10660static bool
10661CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
10662  // C++ [basic.stc.dynamic.allocation]p1:
10663  //   A program is ill-formed if an allocation function is declared in a
10664  //   namespace scope other than global scope or declared static in global
10665  //   scope.
10666  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10667    return true;
10668
10669  CanQualType SizeTy =
10670    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
10671
10672  // C++ [basic.stc.dynamic.allocation]p1:
10673  //  The return type shall be void*. The first parameter shall have type
10674  //  std::size_t.
10675  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
10676                                  SizeTy,
10677                                  diag::err_operator_new_dependent_param_type,
10678                                  diag::err_operator_new_param_type))
10679    return true;
10680
10681  // C++ [basic.stc.dynamic.allocation]p1:
10682  //  The first parameter shall not have an associated default argument.
10683  if (FnDecl->getParamDecl(0)->hasDefaultArg())
10684    return SemaRef.Diag(FnDecl->getLocation(),
10685                        diag::err_operator_new_default_arg)
10686      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
10687
10688  return false;
10689}
10690
10691static bool
10692CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
10693  // C++ [basic.stc.dynamic.deallocation]p1:
10694  //   A program is ill-formed if deallocation functions are declared in a
10695  //   namespace scope other than global scope or declared static in global
10696  //   scope.
10697  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
10698    return true;
10699
10700  // C++ [basic.stc.dynamic.deallocation]p2:
10701  //   Each deallocation function shall return void and its first parameter
10702  //   shall be void*.
10703  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
10704                                  SemaRef.Context.VoidPtrTy,
10705                                 diag::err_operator_delete_dependent_param_type,
10706                                 diag::err_operator_delete_param_type))
10707    return true;
10708
10709  return false;
10710}
10711
10712/// CheckOverloadedOperatorDeclaration - Check whether the declaration
10713/// of this overloaded operator is well-formed. If so, returns false;
10714/// otherwise, emits appropriate diagnostics and returns true.
10715bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
10716  assert(FnDecl && FnDecl->isOverloadedOperator() &&
10717         "Expected an overloaded operator declaration");
10718
10719  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
10720
10721  // C++ [over.oper]p5:
10722  //   The allocation and deallocation functions, operator new,
10723  //   operator new[], operator delete and operator delete[], are
10724  //   described completely in 3.7.3. The attributes and restrictions
10725  //   found in the rest of this subclause do not apply to them unless
10726  //   explicitly stated in 3.7.3.
10727  if (Op == OO_Delete || Op == OO_Array_Delete)
10728    return CheckOperatorDeleteDeclaration(*this, FnDecl);
10729
10730  if (Op == OO_New || Op == OO_Array_New)
10731    return CheckOperatorNewDeclaration(*this, FnDecl);
10732
10733  // C++ [over.oper]p6:
10734  //   An operator function shall either be a non-static member
10735  //   function or be a non-member function and have at least one
10736  //   parameter whose type is a class, a reference to a class, an
10737  //   enumeration, or a reference to an enumeration.
10738  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
10739    if (MethodDecl->isStatic())
10740      return Diag(FnDecl->getLocation(),
10741                  diag::err_operator_overload_static) << FnDecl->getDeclName();
10742  } else {
10743    bool ClassOrEnumParam = false;
10744    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10745                                   ParamEnd = FnDecl->param_end();
10746         Param != ParamEnd; ++Param) {
10747      QualType ParamType = (*Param)->getType().getNonReferenceType();
10748      if (ParamType->isDependentType() || ParamType->isRecordType() ||
10749          ParamType->isEnumeralType()) {
10750        ClassOrEnumParam = true;
10751        break;
10752      }
10753    }
10754
10755    if (!ClassOrEnumParam)
10756      return Diag(FnDecl->getLocation(),
10757                  diag::err_operator_overload_needs_class_or_enum)
10758        << FnDecl->getDeclName();
10759  }
10760
10761  // C++ [over.oper]p8:
10762  //   An operator function cannot have default arguments (8.3.6),
10763  //   except where explicitly stated below.
10764  //
10765  // Only the function-call operator allows default arguments
10766  // (C++ [over.call]p1).
10767  if (Op != OO_Call) {
10768    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
10769         Param != FnDecl->param_end(); ++Param) {
10770      if ((*Param)->hasDefaultArg())
10771        return Diag((*Param)->getLocation(),
10772                    diag::err_operator_overload_default_arg)
10773          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
10774    }
10775  }
10776
10777  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
10778    { false, false, false }
10779#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
10780    , { Unary, Binary, MemberOnly }
10781#include "clang/Basic/OperatorKinds.def"
10782  };
10783
10784  bool CanBeUnaryOperator = OperatorUses[Op][0];
10785  bool CanBeBinaryOperator = OperatorUses[Op][1];
10786  bool MustBeMemberOperator = OperatorUses[Op][2];
10787
10788  // C++ [over.oper]p8:
10789  //   [...] Operator functions cannot have more or fewer parameters
10790  //   than the number required for the corresponding operator, as
10791  //   described in the rest of this subclause.
10792  unsigned NumParams = FnDecl->getNumParams()
10793                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
10794  if (Op != OO_Call &&
10795      ((NumParams == 1 && !CanBeUnaryOperator) ||
10796       (NumParams == 2 && !CanBeBinaryOperator) ||
10797       (NumParams < 1) || (NumParams > 2))) {
10798    // We have the wrong number of parameters.
10799    unsigned ErrorKind;
10800    if (CanBeUnaryOperator && CanBeBinaryOperator) {
10801      ErrorKind = 2;  // 2 -> unary or binary.
10802    } else if (CanBeUnaryOperator) {
10803      ErrorKind = 0;  // 0 -> unary
10804    } else {
10805      assert(CanBeBinaryOperator &&
10806             "All non-call overloaded operators are unary or binary!");
10807      ErrorKind = 1;  // 1 -> binary
10808    }
10809
10810    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
10811      << FnDecl->getDeclName() << NumParams << ErrorKind;
10812  }
10813
10814  // Overloaded operators other than operator() cannot be variadic.
10815  if (Op != OO_Call &&
10816      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
10817    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
10818      << FnDecl->getDeclName();
10819  }
10820
10821  // Some operators must be non-static member functions.
10822  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
10823    return Diag(FnDecl->getLocation(),
10824                diag::err_operator_overload_must_be_member)
10825      << FnDecl->getDeclName();
10826  }
10827
10828  // C++ [over.inc]p1:
10829  //   The user-defined function called operator++ implements the
10830  //   prefix and postfix ++ operator. If this function is a member
10831  //   function with no parameters, or a non-member function with one
10832  //   parameter of class or enumeration type, it defines the prefix
10833  //   increment operator ++ for objects of that type. If the function
10834  //   is a member function with one parameter (which shall be of type
10835  //   int) or a non-member function with two parameters (the second
10836  //   of which shall be of type int), it defines the postfix
10837  //   increment operator ++ for objects of that type.
10838  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
10839    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
10840    bool ParamIsInt = false;
10841    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
10842      ParamIsInt = BT->getKind() == BuiltinType::Int;
10843
10844    if (!ParamIsInt)
10845      return Diag(LastParam->getLocation(),
10846                  diag::err_operator_overload_post_incdec_must_be_int)
10847        << LastParam->getType() << (Op == OO_MinusMinus);
10848  }
10849
10850  return false;
10851}
10852
10853/// CheckLiteralOperatorDeclaration - Check whether the declaration
10854/// of this literal operator function is well-formed. If so, returns
10855/// false; otherwise, emits appropriate diagnostics and returns true.
10856bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
10857  if (isa<CXXMethodDecl>(FnDecl)) {
10858    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
10859      << FnDecl->getDeclName();
10860    return true;
10861  }
10862
10863  if (FnDecl->isExternC()) {
10864    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
10865    return true;
10866  }
10867
10868  bool Valid = false;
10869
10870  // This might be the definition of a literal operator template.
10871  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
10872  // This might be a specialization of a literal operator template.
10873  if (!TpDecl)
10874    TpDecl = FnDecl->getPrimaryTemplate();
10875
10876  // template <char...> type operator "" name() and
10877  // template <class T, T...> type operator "" name() are the only valid
10878  // template signatures, and the only valid signatures with no parameters.
10879  if (TpDecl) {
10880    if (FnDecl->param_size() == 0) {
10881      // Must have one or two template parameters
10882      TemplateParameterList *Params = TpDecl->getTemplateParameters();
10883      if (Params->size() == 1) {
10884        NonTypeTemplateParmDecl *PmDecl =
10885          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(0));
10886
10887        // The template parameter must be a char parameter pack.
10888        if (PmDecl && PmDecl->isTemplateParameterPack() &&
10889            Context.hasSameType(PmDecl->getType(), Context.CharTy))
10890          Valid = true;
10891      } else if (Params->size() == 2) {
10892        TemplateTypeParmDecl *PmType =
10893          dyn_cast<TemplateTypeParmDecl>(Params->getParam(0));
10894        NonTypeTemplateParmDecl *PmArgs =
10895          dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
10896
10897        // The second template parameter must be a parameter pack with the
10898        // first template parameter as its type.
10899        if (PmType && PmArgs &&
10900            !PmType->isTemplateParameterPack() &&
10901            PmArgs->isTemplateParameterPack()) {
10902          const TemplateTypeParmType *TArgs =
10903            PmArgs->getType()->getAs<TemplateTypeParmType>();
10904          if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
10905              TArgs->getIndex() == PmType->getIndex()) {
10906            Valid = true;
10907            if (ActiveTemplateInstantiations.empty())
10908              Diag(FnDecl->getLocation(),
10909                   diag::ext_string_literal_operator_template);
10910          }
10911        }
10912      }
10913    }
10914  } else if (FnDecl->param_size()) {
10915    // Check the first parameter
10916    FunctionDecl::param_iterator Param = FnDecl->param_begin();
10917
10918    QualType T = (*Param)->getType().getUnqualifiedType();
10919
10920    // unsigned long long int, long double, and any character type are allowed
10921    // as the only parameters.
10922    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
10923        Context.hasSameType(T, Context.LongDoubleTy) ||
10924        Context.hasSameType(T, Context.CharTy) ||
10925        Context.hasSameType(T, Context.WideCharTy) ||
10926        Context.hasSameType(T, Context.Char16Ty) ||
10927        Context.hasSameType(T, Context.Char32Ty)) {
10928      if (++Param == FnDecl->param_end())
10929        Valid = true;
10930      goto FinishedParams;
10931    }
10932
10933    // Otherwise it must be a pointer to const; let's strip those qualifiers.
10934    const PointerType *PT = T->getAs<PointerType>();
10935    if (!PT)
10936      goto FinishedParams;
10937    T = PT->getPointeeType();
10938    if (!T.isConstQualified() || T.isVolatileQualified())
10939      goto FinishedParams;
10940    T = T.getUnqualifiedType();
10941
10942    // Move on to the second parameter;
10943    ++Param;
10944
10945    // If there is no second parameter, the first must be a const char *
10946    if (Param == FnDecl->param_end()) {
10947      if (Context.hasSameType(T, Context.CharTy))
10948        Valid = true;
10949      goto FinishedParams;
10950    }
10951
10952    // const char *, const wchar_t*, const char16_t*, and const char32_t*
10953    // are allowed as the first parameter to a two-parameter function
10954    if (!(Context.hasSameType(T, Context.CharTy) ||
10955          Context.hasSameType(T, Context.WideCharTy) ||
10956          Context.hasSameType(T, Context.Char16Ty) ||
10957          Context.hasSameType(T, Context.Char32Ty)))
10958      goto FinishedParams;
10959
10960    // The second and final parameter must be an std::size_t
10961    T = (*Param)->getType().getUnqualifiedType();
10962    if (Context.hasSameType(T, Context.getSizeType()) &&
10963        ++Param == FnDecl->param_end())
10964      Valid = true;
10965  }
10966
10967  // FIXME: This diagnostic is absolutely terrible.
10968FinishedParams:
10969  if (!Valid) {
10970    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
10971      << FnDecl->getDeclName();
10972    return true;
10973  }
10974
10975  // A parameter-declaration-clause containing a default argument is not
10976  // equivalent to any of the permitted forms.
10977  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
10978                                    ParamEnd = FnDecl->param_end();
10979       Param != ParamEnd; ++Param) {
10980    if ((*Param)->hasDefaultArg()) {
10981      Diag((*Param)->getDefaultArgRange().getBegin(),
10982           diag::err_literal_operator_default_argument)
10983        << (*Param)->getDefaultArgRange();
10984      break;
10985    }
10986  }
10987
10988  StringRef LiteralName
10989    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
10990  if (LiteralName[0] != '_') {
10991    // C++11 [usrlit.suffix]p1:
10992    //   Literal suffix identifiers that do not start with an underscore
10993    //   are reserved for future standardization.
10994    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
10995      << NumericLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
10996  }
10997
10998  return false;
10999}
11000
11001/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
11002/// linkage specification, including the language and (if present)
11003/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
11004/// the location of the language string literal, which is provided
11005/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
11006/// the '{' brace. Otherwise, this linkage specification does not
11007/// have any braces.
11008Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
11009                                           SourceLocation LangLoc,
11010                                           StringRef Lang,
11011                                           SourceLocation LBraceLoc) {
11012  LinkageSpecDecl::LanguageIDs Language;
11013  if (Lang == "\"C\"")
11014    Language = LinkageSpecDecl::lang_c;
11015  else if (Lang == "\"C++\"")
11016    Language = LinkageSpecDecl::lang_cxx;
11017  else {
11018    Diag(LangLoc, diag::err_bad_language);
11019    return 0;
11020  }
11021
11022  // FIXME: Add all the various semantics of linkage specifications
11023
11024  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
11025                                               ExternLoc, LangLoc, Language,
11026                                               LBraceLoc.isValid());
11027  CurContext->addDecl(D);
11028  PushDeclContext(S, D);
11029  return D;
11030}
11031
11032/// ActOnFinishLinkageSpecification - Complete the definition of
11033/// the C++ linkage specification LinkageSpec. If RBraceLoc is
11034/// valid, it's the position of the closing '}' brace in a linkage
11035/// specification that uses braces.
11036Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
11037                                            Decl *LinkageSpec,
11038                                            SourceLocation RBraceLoc) {
11039  if (LinkageSpec) {
11040    if (RBraceLoc.isValid()) {
11041      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
11042      LSDecl->setRBraceLoc(RBraceLoc);
11043    }
11044    PopDeclContext();
11045  }
11046  return LinkageSpec;
11047}
11048
11049Decl *Sema::ActOnEmptyDeclaration(Scope *S,
11050                                  AttributeList *AttrList,
11051                                  SourceLocation SemiLoc) {
11052  Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
11053  // Attribute declarations appertain to empty declaration so we handle
11054  // them here.
11055  if (AttrList)
11056    ProcessDeclAttributeList(S, ED, AttrList);
11057
11058  CurContext->addDecl(ED);
11059  return ED;
11060}
11061
11062/// \brief Perform semantic analysis for the variable declaration that
11063/// occurs within a C++ catch clause, returning the newly-created
11064/// variable.
11065VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
11066                                         TypeSourceInfo *TInfo,
11067                                         SourceLocation StartLoc,
11068                                         SourceLocation Loc,
11069                                         IdentifierInfo *Name) {
11070  bool Invalid = false;
11071  QualType ExDeclType = TInfo->getType();
11072
11073  // Arrays and functions decay.
11074  if (ExDeclType->isArrayType())
11075    ExDeclType = Context.getArrayDecayedType(ExDeclType);
11076  else if (ExDeclType->isFunctionType())
11077    ExDeclType = Context.getPointerType(ExDeclType);
11078
11079  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
11080  // The exception-declaration shall not denote a pointer or reference to an
11081  // incomplete type, other than [cv] void*.
11082  // N2844 forbids rvalue references.
11083  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
11084    Diag(Loc, diag::err_catch_rvalue_ref);
11085    Invalid = true;
11086  }
11087
11088  QualType BaseType = ExDeclType;
11089  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
11090  unsigned DK = diag::err_catch_incomplete;
11091  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
11092    BaseType = Ptr->getPointeeType();
11093    Mode = 1;
11094    DK = diag::err_catch_incomplete_ptr;
11095  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
11096    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
11097    BaseType = Ref->getPointeeType();
11098    Mode = 2;
11099    DK = diag::err_catch_incomplete_ref;
11100  }
11101  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
11102      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
11103    Invalid = true;
11104
11105  if (!Invalid && !ExDeclType->isDependentType() &&
11106      RequireNonAbstractType(Loc, ExDeclType,
11107                             diag::err_abstract_type_in_decl,
11108                             AbstractVariableType))
11109    Invalid = true;
11110
11111  // Only the non-fragile NeXT runtime currently supports C++ catches
11112  // of ObjC types, and no runtime supports catching ObjC types by value.
11113  if (!Invalid && getLangOpts().ObjC1) {
11114    QualType T = ExDeclType;
11115    if (const ReferenceType *RT = T->getAs<ReferenceType>())
11116      T = RT->getPointeeType();
11117
11118    if (T->isObjCObjectType()) {
11119      Diag(Loc, diag::err_objc_object_catch);
11120      Invalid = true;
11121    } else if (T->isObjCObjectPointerType()) {
11122      // FIXME: should this be a test for macosx-fragile specifically?
11123      if (getLangOpts().ObjCRuntime.isFragile())
11124        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
11125    }
11126  }
11127
11128  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
11129                                    ExDeclType, TInfo, SC_None);
11130  ExDecl->setExceptionVariable(true);
11131
11132  // In ARC, infer 'retaining' for variables of retainable type.
11133  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
11134    Invalid = true;
11135
11136  if (!Invalid && !ExDeclType->isDependentType()) {
11137    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
11138      // Insulate this from anything else we might currently be parsing.
11139      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11140
11141      // C++ [except.handle]p16:
11142      //   The object declared in an exception-declaration or, if the
11143      //   exception-declaration does not specify a name, a temporary (12.2) is
11144      //   copy-initialized (8.5) from the exception object. [...]
11145      //   The object is destroyed when the handler exits, after the destruction
11146      //   of any automatic objects initialized within the handler.
11147      //
11148      // We just pretend to initialize the object with itself, then make sure
11149      // it can be destroyed later.
11150      QualType initType = ExDeclType;
11151
11152      InitializedEntity entity =
11153        InitializedEntity::InitializeVariable(ExDecl);
11154      InitializationKind initKind =
11155        InitializationKind::CreateCopy(Loc, SourceLocation());
11156
11157      Expr *opaqueValue =
11158        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
11159      InitializationSequence sequence(*this, entity, initKind, opaqueValue);
11160      ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
11161      if (result.isInvalid())
11162        Invalid = true;
11163      else {
11164        // If the constructor used was non-trivial, set this as the
11165        // "initializer".
11166        CXXConstructExpr *construct = result.takeAs<CXXConstructExpr>();
11167        if (!construct->getConstructor()->isTrivial()) {
11168          Expr *init = MaybeCreateExprWithCleanups(construct);
11169          ExDecl->setInit(init);
11170        }
11171
11172        // And make sure it's destructable.
11173        FinalizeVarWithDestructor(ExDecl, recordType);
11174      }
11175    }
11176  }
11177
11178  if (Invalid)
11179    ExDecl->setInvalidDecl();
11180
11181  return ExDecl;
11182}
11183
11184/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
11185/// handler.
11186Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
11187  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11188  bool Invalid = D.isInvalidType();
11189
11190  // Check for unexpanded parameter packs.
11191  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11192                                      UPPC_ExceptionType)) {
11193    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
11194                                             D.getIdentifierLoc());
11195    Invalid = true;
11196  }
11197
11198  IdentifierInfo *II = D.getIdentifier();
11199  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
11200                                             LookupOrdinaryName,
11201                                             ForRedeclaration)) {
11202    // The scope should be freshly made just for us. There is just no way
11203    // it contains any previous declaration.
11204    assert(!S->isDeclScope(PrevDecl));
11205    if (PrevDecl->isTemplateParameter()) {
11206      // Maybe we will complain about the shadowed template parameter.
11207      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11208      PrevDecl = 0;
11209    }
11210  }
11211
11212  if (D.getCXXScopeSpec().isSet() && !Invalid) {
11213    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
11214      << D.getCXXScopeSpec().getRange();
11215    Invalid = true;
11216  }
11217
11218  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
11219                                              D.getLocStart(),
11220                                              D.getIdentifierLoc(),
11221                                              D.getIdentifier());
11222  if (Invalid)
11223    ExDecl->setInvalidDecl();
11224
11225  // Add the exception declaration into this scope.
11226  if (II)
11227    PushOnScopeChains(ExDecl, S);
11228  else
11229    CurContext->addDecl(ExDecl);
11230
11231  ProcessDeclAttributes(S, ExDecl, D);
11232  return ExDecl;
11233}
11234
11235Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11236                                         Expr *AssertExpr,
11237                                         Expr *AssertMessageExpr,
11238                                         SourceLocation RParenLoc) {
11239  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr);
11240
11241  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
11242    return 0;
11243
11244  return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
11245                                      AssertMessage, RParenLoc, false);
11246}
11247
11248Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
11249                                         Expr *AssertExpr,
11250                                         StringLiteral *AssertMessage,
11251                                         SourceLocation RParenLoc,
11252                                         bool Failed) {
11253  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
11254      !Failed) {
11255    // In a static_assert-declaration, the constant-expression shall be a
11256    // constant expression that can be contextually converted to bool.
11257    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
11258    if (Converted.isInvalid())
11259      Failed = true;
11260
11261    llvm::APSInt Cond;
11262    if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
11263          diag::err_static_assert_expression_is_not_constant,
11264          /*AllowFold=*/false).isInvalid())
11265      Failed = true;
11266
11267    if (!Failed && !Cond) {
11268      SmallString<256> MsgBuffer;
11269      llvm::raw_svector_ostream Msg(MsgBuffer);
11270      AssertMessage->printPretty(Msg, 0, getPrintingPolicy());
11271      Diag(StaticAssertLoc, diag::err_static_assert_failed)
11272        << Msg.str() << AssertExpr->getSourceRange();
11273      Failed = true;
11274    }
11275  }
11276
11277  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
11278                                        AssertExpr, AssertMessage, RParenLoc,
11279                                        Failed);
11280
11281  CurContext->addDecl(Decl);
11282  return Decl;
11283}
11284
11285/// \brief Perform semantic analysis of the given friend type declaration.
11286///
11287/// \returns A friend declaration that.
11288FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
11289                                      SourceLocation FriendLoc,
11290                                      TypeSourceInfo *TSInfo) {
11291  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
11292
11293  QualType T = TSInfo->getType();
11294  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
11295
11296  // C++03 [class.friend]p2:
11297  //   An elaborated-type-specifier shall be used in a friend declaration
11298  //   for a class.*
11299  //
11300  //   * The class-key of the elaborated-type-specifier is required.
11301  if (!ActiveTemplateInstantiations.empty()) {
11302    // Do not complain about the form of friend template types during
11303    // template instantiation; we will already have complained when the
11304    // template was declared.
11305  } else {
11306    if (!T->isElaboratedTypeSpecifier()) {
11307      // If we evaluated the type to a record type, suggest putting
11308      // a tag in front.
11309      if (const RecordType *RT = T->getAs<RecordType>()) {
11310        RecordDecl *RD = RT->getDecl();
11311
11312        std::string InsertionText = std::string(" ") + RD->getKindName();
11313
11314        Diag(TypeRange.getBegin(),
11315             getLangOpts().CPlusPlus11 ?
11316               diag::warn_cxx98_compat_unelaborated_friend_type :
11317               diag::ext_unelaborated_friend_type)
11318          << (unsigned) RD->getTagKind()
11319          << T
11320          << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
11321                                        InsertionText);
11322      } else {
11323        Diag(FriendLoc,
11324             getLangOpts().CPlusPlus11 ?
11325               diag::warn_cxx98_compat_nonclass_type_friend :
11326               diag::ext_nonclass_type_friend)
11327          << T
11328          << TypeRange;
11329      }
11330    } else if (T->getAs<EnumType>()) {
11331      Diag(FriendLoc,
11332           getLangOpts().CPlusPlus11 ?
11333             diag::warn_cxx98_compat_enum_friend :
11334             diag::ext_enum_friend)
11335        << T
11336        << TypeRange;
11337    }
11338
11339    // C++11 [class.friend]p3:
11340    //   A friend declaration that does not declare a function shall have one
11341    //   of the following forms:
11342    //     friend elaborated-type-specifier ;
11343    //     friend simple-type-specifier ;
11344    //     friend typename-specifier ;
11345    if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
11346      Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
11347  }
11348
11349  //   If the type specifier in a friend declaration designates a (possibly
11350  //   cv-qualified) class type, that class is declared as a friend; otherwise,
11351  //   the friend declaration is ignored.
11352  return FriendDecl::Create(Context, CurContext, LocStart, TSInfo, FriendLoc);
11353}
11354
11355/// Handle a friend tag declaration where the scope specifier was
11356/// templated.
11357Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
11358                                    unsigned TagSpec, SourceLocation TagLoc,
11359                                    CXXScopeSpec &SS,
11360                                    IdentifierInfo *Name,
11361                                    SourceLocation NameLoc,
11362                                    AttributeList *Attr,
11363                                    MultiTemplateParamsArg TempParamLists) {
11364  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11365
11366  bool isExplicitSpecialization = false;
11367  bool Invalid = false;
11368
11369  if (TemplateParameterList *TemplateParams =
11370          MatchTemplateParametersToScopeSpecifier(
11371              TagLoc, NameLoc, SS, TempParamLists, /*friend*/ true,
11372              isExplicitSpecialization, Invalid)) {
11373    if (TemplateParams->size() > 0) {
11374      // This is a declaration of a class template.
11375      if (Invalid)
11376        return 0;
11377
11378      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
11379                                SS, Name, NameLoc, Attr,
11380                                TemplateParams, AS_public,
11381                                /*ModulePrivateLoc=*/SourceLocation(),
11382                                TempParamLists.size() - 1,
11383                                TempParamLists.data()).take();
11384    } else {
11385      // The "template<>" header is extraneous.
11386      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11387        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11388      isExplicitSpecialization = true;
11389    }
11390  }
11391
11392  if (Invalid) return 0;
11393
11394  bool isAllExplicitSpecializations = true;
11395  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
11396    if (TempParamLists[I]->size()) {
11397      isAllExplicitSpecializations = false;
11398      break;
11399    }
11400  }
11401
11402  // FIXME: don't ignore attributes.
11403
11404  // If it's explicit specializations all the way down, just forget
11405  // about the template header and build an appropriate non-templated
11406  // friend.  TODO: for source fidelity, remember the headers.
11407  if (isAllExplicitSpecializations) {
11408    if (SS.isEmpty()) {
11409      bool Owned = false;
11410      bool IsDependent = false;
11411      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
11412                      Attr, AS_public,
11413                      /*ModulePrivateLoc=*/SourceLocation(),
11414                      MultiTemplateParamsArg(), Owned, IsDependent,
11415                      /*ScopedEnumKWLoc=*/SourceLocation(),
11416                      /*ScopedEnumUsesClassTag=*/false,
11417                      /*UnderlyingType=*/TypeResult());
11418    }
11419
11420    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11421    ElaboratedTypeKeyword Keyword
11422      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11423    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
11424                                   *Name, NameLoc);
11425    if (T.isNull())
11426      return 0;
11427
11428    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11429    if (isa<DependentNameType>(T)) {
11430      DependentNameTypeLoc TL =
11431          TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11432      TL.setElaboratedKeywordLoc(TagLoc);
11433      TL.setQualifierLoc(QualifierLoc);
11434      TL.setNameLoc(NameLoc);
11435    } else {
11436      ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
11437      TL.setElaboratedKeywordLoc(TagLoc);
11438      TL.setQualifierLoc(QualifierLoc);
11439      TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
11440    }
11441
11442    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11443                                            TSI, FriendLoc, TempParamLists);
11444    Friend->setAccess(AS_public);
11445    CurContext->addDecl(Friend);
11446    return Friend;
11447  }
11448
11449  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
11450
11451
11452
11453  // Handle the case of a templated-scope friend class.  e.g.
11454  //   template <class T> class A<T>::B;
11455  // FIXME: we don't support these right now.
11456  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
11457  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
11458  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
11459  DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
11460  TL.setElaboratedKeywordLoc(TagLoc);
11461  TL.setQualifierLoc(SS.getWithLocInContext(Context));
11462  TL.setNameLoc(NameLoc);
11463
11464  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
11465                                          TSI, FriendLoc, TempParamLists);
11466  Friend->setAccess(AS_public);
11467  Friend->setUnsupportedFriend(true);
11468  CurContext->addDecl(Friend);
11469  return Friend;
11470}
11471
11472
11473/// Handle a friend type declaration.  This works in tandem with
11474/// ActOnTag.
11475///
11476/// Notes on friend class templates:
11477///
11478/// We generally treat friend class declarations as if they were
11479/// declaring a class.  So, for example, the elaborated type specifier
11480/// in a friend declaration is required to obey the restrictions of a
11481/// class-head (i.e. no typedefs in the scope chain), template
11482/// parameters are required to match up with simple template-ids, &c.
11483/// However, unlike when declaring a template specialization, it's
11484/// okay to refer to a template specialization without an empty
11485/// template parameter declaration, e.g.
11486///   friend class A<T>::B<unsigned>;
11487/// We permit this as a special case; if there are any template
11488/// parameters present at all, require proper matching, i.e.
11489///   template <> template \<class T> friend class A<int>::B;
11490Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
11491                                MultiTemplateParamsArg TempParams) {
11492  SourceLocation Loc = DS.getLocStart();
11493
11494  assert(DS.isFriendSpecified());
11495  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11496
11497  // Try to convert the decl specifier to a type.  This works for
11498  // friend templates because ActOnTag never produces a ClassTemplateDecl
11499  // for a TUK_Friend.
11500  Declarator TheDeclarator(DS, Declarator::MemberContext);
11501  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
11502  QualType T = TSI->getType();
11503  if (TheDeclarator.isInvalidType())
11504    return 0;
11505
11506  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
11507    return 0;
11508
11509  // This is definitely an error in C++98.  It's probably meant to
11510  // be forbidden in C++0x, too, but the specification is just
11511  // poorly written.
11512  //
11513  // The problem is with declarations like the following:
11514  //   template <T> friend A<T>::foo;
11515  // where deciding whether a class C is a friend or not now hinges
11516  // on whether there exists an instantiation of A that causes
11517  // 'foo' to equal C.  There are restrictions on class-heads
11518  // (which we declare (by fiat) elaborated friend declarations to
11519  // be) that makes this tractable.
11520  //
11521  // FIXME: handle "template <> friend class A<T>;", which
11522  // is possibly well-formed?  Who even knows?
11523  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
11524    Diag(Loc, diag::err_tagless_friend_type_template)
11525      << DS.getSourceRange();
11526    return 0;
11527  }
11528
11529  // C++98 [class.friend]p1: A friend of a class is a function
11530  //   or class that is not a member of the class . . .
11531  // This is fixed in DR77, which just barely didn't make the C++03
11532  // deadline.  It's also a very silly restriction that seriously
11533  // affects inner classes and which nobody else seems to implement;
11534  // thus we never diagnose it, not even in -pedantic.
11535  //
11536  // But note that we could warn about it: it's always useless to
11537  // friend one of your own members (it's not, however, worthless to
11538  // friend a member of an arbitrary specialization of your template).
11539
11540  Decl *D;
11541  if (unsigned NumTempParamLists = TempParams.size())
11542    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
11543                                   NumTempParamLists,
11544                                   TempParams.data(),
11545                                   TSI,
11546                                   DS.getFriendSpecLoc());
11547  else
11548    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
11549
11550  if (!D)
11551    return 0;
11552
11553  D->setAccess(AS_public);
11554  CurContext->addDecl(D);
11555
11556  return D;
11557}
11558
11559NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
11560                                        MultiTemplateParamsArg TemplateParams) {
11561  const DeclSpec &DS = D.getDeclSpec();
11562
11563  assert(DS.isFriendSpecified());
11564  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
11565
11566  SourceLocation Loc = D.getIdentifierLoc();
11567  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11568
11569  // C++ [class.friend]p1
11570  //   A friend of a class is a function or class....
11571  // Note that this sees through typedefs, which is intended.
11572  // It *doesn't* see through dependent types, which is correct
11573  // according to [temp.arg.type]p3:
11574  //   If a declaration acquires a function type through a
11575  //   type dependent on a template-parameter and this causes
11576  //   a declaration that does not use the syntactic form of a
11577  //   function declarator to have a function type, the program
11578  //   is ill-formed.
11579  if (!TInfo->getType()->isFunctionType()) {
11580    Diag(Loc, diag::err_unexpected_friend);
11581
11582    // It might be worthwhile to try to recover by creating an
11583    // appropriate declaration.
11584    return 0;
11585  }
11586
11587  // C++ [namespace.memdef]p3
11588  //  - If a friend declaration in a non-local class first declares a
11589  //    class or function, the friend class or function is a member
11590  //    of the innermost enclosing namespace.
11591  //  - The name of the friend is not found by simple name lookup
11592  //    until a matching declaration is provided in that namespace
11593  //    scope (either before or after the class declaration granting
11594  //    friendship).
11595  //  - If a friend function is called, its name may be found by the
11596  //    name lookup that considers functions from namespaces and
11597  //    classes associated with the types of the function arguments.
11598  //  - When looking for a prior declaration of a class or a function
11599  //    declared as a friend, scopes outside the innermost enclosing
11600  //    namespace scope are not considered.
11601
11602  CXXScopeSpec &SS = D.getCXXScopeSpec();
11603  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11604  DeclarationName Name = NameInfo.getName();
11605  assert(Name);
11606
11607  // Check for unexpanded parameter packs.
11608  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
11609      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
11610      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
11611    return 0;
11612
11613  // The context we found the declaration in, or in which we should
11614  // create the declaration.
11615  DeclContext *DC;
11616  Scope *DCScope = S;
11617  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
11618                        ForRedeclaration);
11619
11620  // There are five cases here.
11621  //   - There's no scope specifier and we're in a local class. Only look
11622  //     for functions declared in the immediately-enclosing block scope.
11623  // We recover from invalid scope qualifiers as if they just weren't there.
11624  FunctionDecl *FunctionContainingLocalClass = 0;
11625  if ((SS.isInvalid() || !SS.isSet()) &&
11626      (FunctionContainingLocalClass =
11627           cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
11628    // C++11 [class.friend]p11:
11629    //   If a friend declaration appears in a local class and the name
11630    //   specified is an unqualified name, a prior declaration is
11631    //   looked up without considering scopes that are outside the
11632    //   innermost enclosing non-class scope. For a friend function
11633    //   declaration, if there is no prior declaration, the program is
11634    //   ill-formed.
11635
11636    // Find the innermost enclosing non-class scope. This is the block
11637    // scope containing the local class definition (or for a nested class,
11638    // the outer local class).
11639    DCScope = S->getFnParent();
11640
11641    // Look up the function name in the scope.
11642    Previous.clear(LookupLocalFriendName);
11643    LookupName(Previous, S, /*AllowBuiltinCreation*/false);
11644
11645    if (!Previous.empty()) {
11646      // All possible previous declarations must have the same context:
11647      // either they were declared at block scope or they are members of
11648      // one of the enclosing local classes.
11649      DC = Previous.getRepresentativeDecl()->getDeclContext();
11650    } else {
11651      // This is ill-formed, but provide the context that we would have
11652      // declared the function in, if we were permitted to, for error recovery.
11653      DC = FunctionContainingLocalClass;
11654    }
11655    adjustContextForLocalExternDecl(DC);
11656
11657    // C++ [class.friend]p6:
11658    //   A function can be defined in a friend declaration of a class if and
11659    //   only if the class is a non-local class (9.8), the function name is
11660    //   unqualified, and the function has namespace scope.
11661    if (D.isFunctionDefinition()) {
11662      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
11663    }
11664
11665  //   - There's no scope specifier, in which case we just go to the
11666  //     appropriate scope and look for a function or function template
11667  //     there as appropriate.
11668  } else if (SS.isInvalid() || !SS.isSet()) {
11669    // C++11 [namespace.memdef]p3:
11670    //   If the name in a friend declaration is neither qualified nor
11671    //   a template-id and the declaration is a function or an
11672    //   elaborated-type-specifier, the lookup to determine whether
11673    //   the entity has been previously declared shall not consider
11674    //   any scopes outside the innermost enclosing namespace.
11675    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
11676
11677    // Find the appropriate context according to the above.
11678    DC = CurContext;
11679
11680    // Skip class contexts.  If someone can cite chapter and verse
11681    // for this behavior, that would be nice --- it's what GCC and
11682    // EDG do, and it seems like a reasonable intent, but the spec
11683    // really only says that checks for unqualified existing
11684    // declarations should stop at the nearest enclosing namespace,
11685    // not that they should only consider the nearest enclosing
11686    // namespace.
11687    while (DC->isRecord())
11688      DC = DC->getParent();
11689
11690    DeclContext *LookupDC = DC;
11691    while (LookupDC->isTransparentContext())
11692      LookupDC = LookupDC->getParent();
11693
11694    while (true) {
11695      LookupQualifiedName(Previous, LookupDC);
11696
11697      if (!Previous.empty()) {
11698        DC = LookupDC;
11699        break;
11700      }
11701
11702      if (isTemplateId) {
11703        if (isa<TranslationUnitDecl>(LookupDC)) break;
11704      } else {
11705        if (LookupDC->isFileContext()) break;
11706      }
11707      LookupDC = LookupDC->getParent();
11708    }
11709
11710    DCScope = getScopeForDeclContext(S, DC);
11711
11712  //   - There's a non-dependent scope specifier, in which case we
11713  //     compute it and do a previous lookup there for a function
11714  //     or function template.
11715  } else if (!SS.getScopeRep()->isDependent()) {
11716    DC = computeDeclContext(SS);
11717    if (!DC) return 0;
11718
11719    if (RequireCompleteDeclContext(SS, DC)) return 0;
11720
11721    LookupQualifiedName(Previous, DC);
11722
11723    // Ignore things found implicitly in the wrong scope.
11724    // TODO: better diagnostics for this case.  Suggesting the right
11725    // qualified scope would be nice...
11726    LookupResult::Filter F = Previous.makeFilter();
11727    while (F.hasNext()) {
11728      NamedDecl *D = F.next();
11729      if (!DC->InEnclosingNamespaceSetOf(
11730              D->getDeclContext()->getRedeclContext()))
11731        F.erase();
11732    }
11733    F.done();
11734
11735    if (Previous.empty()) {
11736      D.setInvalidType();
11737      Diag(Loc, diag::err_qualified_friend_not_found)
11738          << Name << TInfo->getType();
11739      return 0;
11740    }
11741
11742    // C++ [class.friend]p1: A friend of a class is a function or
11743    //   class that is not a member of the class . . .
11744    if (DC->Equals(CurContext))
11745      Diag(DS.getFriendSpecLoc(),
11746           getLangOpts().CPlusPlus11 ?
11747             diag::warn_cxx98_compat_friend_is_member :
11748             diag::err_friend_is_member);
11749
11750    if (D.isFunctionDefinition()) {
11751      // C++ [class.friend]p6:
11752      //   A function can be defined in a friend declaration of a class if and
11753      //   only if the class is a non-local class (9.8), the function name is
11754      //   unqualified, and the function has namespace scope.
11755      SemaDiagnosticBuilder DB
11756        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
11757
11758      DB << SS.getScopeRep();
11759      if (DC->isFileContext())
11760        DB << FixItHint::CreateRemoval(SS.getRange());
11761      SS.clear();
11762    }
11763
11764  //   - There's a scope specifier that does not match any template
11765  //     parameter lists, in which case we use some arbitrary context,
11766  //     create a method or method template, and wait for instantiation.
11767  //   - There's a scope specifier that does match some template
11768  //     parameter lists, which we don't handle right now.
11769  } else {
11770    if (D.isFunctionDefinition()) {
11771      // C++ [class.friend]p6:
11772      //   A function can be defined in a friend declaration of a class if and
11773      //   only if the class is a non-local class (9.8), the function name is
11774      //   unqualified, and the function has namespace scope.
11775      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
11776        << SS.getScopeRep();
11777    }
11778
11779    DC = CurContext;
11780    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
11781  }
11782
11783  if (!DC->isRecord()) {
11784    // This implies that it has to be an operator or function.
11785    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
11786        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
11787        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
11788      Diag(Loc, diag::err_introducing_special_friend) <<
11789        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
11790         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
11791      return 0;
11792    }
11793  }
11794
11795  // FIXME: This is an egregious hack to cope with cases where the scope stack
11796  // does not contain the declaration context, i.e., in an out-of-line
11797  // definition of a class.
11798  Scope FakeDCScope(S, Scope::DeclScope, Diags);
11799  if (!DCScope) {
11800    FakeDCScope.setEntity(DC);
11801    DCScope = &FakeDCScope;
11802  }
11803
11804  bool AddToScope = true;
11805  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
11806                                          TemplateParams, AddToScope);
11807  if (!ND) return 0;
11808
11809  assert(ND->getLexicalDeclContext() == CurContext);
11810
11811  // If we performed typo correction, we might have added a scope specifier
11812  // and changed the decl context.
11813  DC = ND->getDeclContext();
11814
11815  // Add the function declaration to the appropriate lookup tables,
11816  // adjusting the redeclarations list as necessary.  We don't
11817  // want to do this yet if the friending class is dependent.
11818  //
11819  // Also update the scope-based lookup if the target context's
11820  // lookup context is in lexical scope.
11821  if (!CurContext->isDependentContext()) {
11822    DC = DC->getRedeclContext();
11823    DC->makeDeclVisibleInContext(ND);
11824    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11825      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
11826  }
11827
11828  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
11829                                       D.getIdentifierLoc(), ND,
11830                                       DS.getFriendSpecLoc());
11831  FrD->setAccess(AS_public);
11832  CurContext->addDecl(FrD);
11833
11834  if (ND->isInvalidDecl()) {
11835    FrD->setInvalidDecl();
11836  } else {
11837    if (DC->isRecord()) CheckFriendAccess(ND);
11838
11839    FunctionDecl *FD;
11840    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
11841      FD = FTD->getTemplatedDecl();
11842    else
11843      FD = cast<FunctionDecl>(ND);
11844
11845    // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
11846    // default argument expression, that declaration shall be a definition
11847    // and shall be the only declaration of the function or function
11848    // template in the translation unit.
11849    if (functionDeclHasDefaultArgument(FD)) {
11850      if (FunctionDecl *OldFD = FD->getPreviousDecl()) {
11851        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
11852        Diag(OldFD->getLocation(), diag::note_previous_declaration);
11853      } else if (!D.isFunctionDefinition())
11854        Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
11855    }
11856
11857    // Mark templated-scope function declarations as unsupported.
11858    if (FD->getNumTemplateParameterLists())
11859      FrD->setUnsupportedFriend(true);
11860  }
11861
11862  return ND;
11863}
11864
11865void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
11866  AdjustDeclIfTemplate(Dcl);
11867
11868  FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
11869  if (!Fn) {
11870    Diag(DelLoc, diag::err_deleted_non_function);
11871    return;
11872  }
11873
11874  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
11875    // Don't consider the implicit declaration we generate for explicit
11876    // specializations. FIXME: Do not generate these implicit declarations.
11877    if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
11878        || Prev->getPreviousDecl()) && !Prev->isDefined()) {
11879      Diag(DelLoc, diag::err_deleted_decl_not_first);
11880      Diag(Prev->getLocation(), diag::note_previous_declaration);
11881    }
11882    // If the declaration wasn't the first, we delete the function anyway for
11883    // recovery.
11884    Fn = Fn->getCanonicalDecl();
11885  }
11886
11887  if (Fn->isDeleted())
11888    return;
11889
11890  // See if we're deleting a function which is already known to override a
11891  // non-deleted virtual function.
11892  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
11893    bool IssuedDiagnostic = false;
11894    for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
11895                                        E = MD->end_overridden_methods();
11896         I != E; ++I) {
11897      if (!(*MD->begin_overridden_methods())->isDeleted()) {
11898        if (!IssuedDiagnostic) {
11899          Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
11900          IssuedDiagnostic = true;
11901        }
11902        Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
11903      }
11904    }
11905  }
11906
11907  Fn->setDeletedAsWritten();
11908}
11909
11910void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
11911  CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
11912
11913  if (MD) {
11914    if (MD->getParent()->isDependentType()) {
11915      MD->setDefaulted();
11916      MD->setExplicitlyDefaulted();
11917      return;
11918    }
11919
11920    CXXSpecialMember Member = getSpecialMember(MD);
11921    if (Member == CXXInvalid) {
11922      if (!MD->isInvalidDecl())
11923        Diag(DefaultLoc, diag::err_default_special_members);
11924      return;
11925    }
11926
11927    MD->setDefaulted();
11928    MD->setExplicitlyDefaulted();
11929
11930    // If this definition appears within the record, do the checking when
11931    // the record is complete.
11932    const FunctionDecl *Primary = MD;
11933    if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
11934      // Find the uninstantiated declaration that actually had the '= default'
11935      // on it.
11936      Pattern->isDefined(Primary);
11937
11938    // If the method was defaulted on its first declaration, we will have
11939    // already performed the checking in CheckCompletedCXXClass. Such a
11940    // declaration doesn't trigger an implicit definition.
11941    if (Primary == Primary->getCanonicalDecl())
11942      return;
11943
11944    CheckExplicitlyDefaultedSpecialMember(MD);
11945
11946    // The exception specification is needed because we are defining the
11947    // function.
11948    ResolveExceptionSpec(DefaultLoc,
11949                         MD->getType()->castAs<FunctionProtoType>());
11950
11951    if (MD->isInvalidDecl())
11952      return;
11953
11954    switch (Member) {
11955    case CXXDefaultConstructor:
11956      DefineImplicitDefaultConstructor(DefaultLoc,
11957                                       cast<CXXConstructorDecl>(MD));
11958      break;
11959    case CXXCopyConstructor:
11960      DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11961      break;
11962    case CXXCopyAssignment:
11963      DefineImplicitCopyAssignment(DefaultLoc, MD);
11964      break;
11965    case CXXDestructor:
11966      DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
11967      break;
11968    case CXXMoveConstructor:
11969      DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
11970      break;
11971    case CXXMoveAssignment:
11972      DefineImplicitMoveAssignment(DefaultLoc, MD);
11973      break;
11974    case CXXInvalid:
11975      llvm_unreachable("Invalid special member.");
11976    }
11977  } else {
11978    Diag(DefaultLoc, diag::err_default_special_members);
11979  }
11980}
11981
11982static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
11983  for (Stmt::child_range CI = S->children(); CI; ++CI) {
11984    Stmt *SubStmt = *CI;
11985    if (!SubStmt)
11986      continue;
11987    if (isa<ReturnStmt>(SubStmt))
11988      Self.Diag(SubStmt->getLocStart(),
11989           diag::err_return_in_constructor_handler);
11990    if (!isa<Expr>(SubStmt))
11991      SearchForReturnInStmt(Self, SubStmt);
11992  }
11993}
11994
11995void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
11996  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
11997    CXXCatchStmt *Handler = TryBlock->getHandler(I);
11998    SearchForReturnInStmt(*this, Handler);
11999  }
12000}
12001
12002bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
12003                                             const CXXMethodDecl *Old) {
12004  const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
12005  const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
12006
12007  CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
12008
12009  // If the calling conventions match, everything is fine
12010  if (NewCC == OldCC)
12011    return false;
12012
12013  Diag(New->getLocation(),
12014       diag::err_conflicting_overriding_cc_attributes)
12015    << New->getDeclName() << New->getType() << Old->getType();
12016  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12017  return true;
12018}
12019
12020bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
12021                                             const CXXMethodDecl *Old) {
12022  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
12023  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
12024
12025  if (Context.hasSameType(NewTy, OldTy) ||
12026      NewTy->isDependentType() || OldTy->isDependentType())
12027    return false;
12028
12029  // Check if the return types are covariant
12030  QualType NewClassTy, OldClassTy;
12031
12032  /// Both types must be pointers or references to classes.
12033  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
12034    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
12035      NewClassTy = NewPT->getPointeeType();
12036      OldClassTy = OldPT->getPointeeType();
12037    }
12038  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
12039    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
12040      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
12041        NewClassTy = NewRT->getPointeeType();
12042        OldClassTy = OldRT->getPointeeType();
12043      }
12044    }
12045  }
12046
12047  // The return types aren't either both pointers or references to a class type.
12048  if (NewClassTy.isNull()) {
12049    Diag(New->getLocation(),
12050         diag::err_different_return_type_for_overriding_virtual_function)
12051      << New->getDeclName() << NewTy << OldTy;
12052    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12053
12054    return true;
12055  }
12056
12057  // C++ [class.virtual]p6:
12058  //   If the return type of D::f differs from the return type of B::f, the
12059  //   class type in the return type of D::f shall be complete at the point of
12060  //   declaration of D::f or shall be the class type D.
12061  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
12062    if (!RT->isBeingDefined() &&
12063        RequireCompleteType(New->getLocation(), NewClassTy,
12064                            diag::err_covariant_return_incomplete,
12065                            New->getDeclName()))
12066    return true;
12067  }
12068
12069  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
12070    // Check if the new class derives from the old class.
12071    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
12072      Diag(New->getLocation(),
12073           diag::err_covariant_return_not_derived)
12074      << New->getDeclName() << NewTy << OldTy;
12075      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12076      return true;
12077    }
12078
12079    // Check if we the conversion from derived to base is valid.
12080    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
12081                    diag::err_covariant_return_inaccessible_base,
12082                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
12083                    // FIXME: Should this point to the return type?
12084                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
12085      // FIXME: this note won't trigger for delayed access control
12086      // diagnostics, and it's impossible to get an undelayed error
12087      // here from access control during the original parse because
12088      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
12089      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12090      return true;
12091    }
12092  }
12093
12094  // The qualifiers of the return types must be the same.
12095  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
12096    Diag(New->getLocation(),
12097         diag::err_covariant_return_type_different_qualifications)
12098    << New->getDeclName() << NewTy << OldTy;
12099    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12100    return true;
12101  };
12102
12103
12104  // The new class type must have the same or less qualifiers as the old type.
12105  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
12106    Diag(New->getLocation(),
12107         diag::err_covariant_return_type_class_type_more_qualified)
12108    << New->getDeclName() << NewTy << OldTy;
12109    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
12110    return true;
12111  };
12112
12113  return false;
12114}
12115
12116/// \brief Mark the given method pure.
12117///
12118/// \param Method the method to be marked pure.
12119///
12120/// \param InitRange the source range that covers the "0" initializer.
12121bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
12122  SourceLocation EndLoc = InitRange.getEnd();
12123  if (EndLoc.isValid())
12124    Method->setRangeEnd(EndLoc);
12125
12126  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
12127    Method->setPure();
12128    return false;
12129  }
12130
12131  if (!Method->isInvalidDecl())
12132    Diag(Method->getLocation(), diag::err_non_virtual_pure)
12133      << Method->getDeclName() << InitRange;
12134  return true;
12135}
12136
12137/// \brief Determine whether the given declaration is a static data member.
12138static bool isStaticDataMember(const Decl *D) {
12139  if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
12140    return Var->isStaticDataMember();
12141
12142  return false;
12143}
12144
12145/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
12146/// an initializer for the out-of-line declaration 'Dcl'.  The scope
12147/// is a fresh scope pushed for just this purpose.
12148///
12149/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
12150/// static data member of class X, names should be looked up in the scope of
12151/// class X.
12152void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
12153  // If there is no declaration, there was an error parsing it.
12154  if (D == 0 || D->isInvalidDecl()) return;
12155
12156  // We should only get called for declarations with scope specifiers, like:
12157  //   int foo::bar;
12158  assert(D->isOutOfLine());
12159  EnterDeclaratorContext(S, D->getDeclContext());
12160
12161  // If we are parsing the initializer for a static data member, push a
12162  // new expression evaluation context that is associated with this static
12163  // data member.
12164  if (isStaticDataMember(D))
12165    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
12166}
12167
12168/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
12169/// initializer for the out-of-line declaration 'D'.
12170void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
12171  // If there is no declaration, there was an error parsing it.
12172  if (D == 0 || D->isInvalidDecl()) return;
12173
12174  if (isStaticDataMember(D))
12175    PopExpressionEvaluationContext();
12176
12177  assert(D->isOutOfLine());
12178  ExitDeclaratorContext(S);
12179}
12180
12181/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
12182/// C++ if/switch/while/for statement.
12183/// e.g: "if (int x = f()) {...}"
12184DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
12185  // C++ 6.4p2:
12186  // The declarator shall not specify a function or an array.
12187  // The type-specifier-seq shall not contain typedef and shall not declare a
12188  // new class or enumeration.
12189  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
12190         "Parser allowed 'typedef' as storage class of condition decl.");
12191
12192  Decl *Dcl = ActOnDeclarator(S, D);
12193  if (!Dcl)
12194    return true;
12195
12196  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
12197    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
12198      << D.getSourceRange();
12199    return true;
12200  }
12201
12202  return Dcl;
12203}
12204
12205void Sema::LoadExternalVTableUses() {
12206  if (!ExternalSource)
12207    return;
12208
12209  SmallVector<ExternalVTableUse, 4> VTables;
12210  ExternalSource->ReadUsedVTables(VTables);
12211  SmallVector<VTableUse, 4> NewUses;
12212  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
12213    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
12214      = VTablesUsed.find(VTables[I].Record);
12215    // Even if a definition wasn't required before, it may be required now.
12216    if (Pos != VTablesUsed.end()) {
12217      if (!Pos->second && VTables[I].DefinitionRequired)
12218        Pos->second = true;
12219      continue;
12220    }
12221
12222    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
12223    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
12224  }
12225
12226  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
12227}
12228
12229void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
12230                          bool DefinitionRequired) {
12231  // Ignore any vtable uses in unevaluated operands or for classes that do
12232  // not have a vtable.
12233  if (!Class->isDynamicClass() || Class->isDependentContext() ||
12234      CurContext->isDependentContext() || isUnevaluatedContext())
12235    return;
12236
12237  // Try to insert this class into the map.
12238  LoadExternalVTableUses();
12239  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12240  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
12241    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
12242  if (!Pos.second) {
12243    // If we already had an entry, check to see if we are promoting this vtable
12244    // to required a definition. If so, we need to reappend to the VTableUses
12245    // list, since we may have already processed the first entry.
12246    if (DefinitionRequired && !Pos.first->second) {
12247      Pos.first->second = true;
12248    } else {
12249      // Otherwise, we can early exit.
12250      return;
12251    }
12252  }
12253
12254  // Local classes need to have their virtual members marked
12255  // immediately. For all other classes, we mark their virtual members
12256  // at the end of the translation unit.
12257  if (Class->isLocalClass())
12258    MarkVirtualMembersReferenced(Loc, Class);
12259  else
12260    VTableUses.push_back(std::make_pair(Class, Loc));
12261}
12262
12263bool Sema::DefineUsedVTables() {
12264  LoadExternalVTableUses();
12265  if (VTableUses.empty())
12266    return false;
12267
12268  // Note: The VTableUses vector could grow as a result of marking
12269  // the members of a class as "used", so we check the size each
12270  // time through the loop and prefer indices (which are stable) to
12271  // iterators (which are not).
12272  bool DefinedAnything = false;
12273  for (unsigned I = 0; I != VTableUses.size(); ++I) {
12274    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
12275    if (!Class)
12276      continue;
12277
12278    SourceLocation Loc = VTableUses[I].second;
12279
12280    bool DefineVTable = true;
12281
12282    // If this class has a key function, but that key function is
12283    // defined in another translation unit, we don't need to emit the
12284    // vtable even though we're using it.
12285    const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
12286    if (KeyFunction && !KeyFunction->hasBody()) {
12287      // The key function is in another translation unit.
12288      DefineVTable = false;
12289      TemplateSpecializationKind TSK =
12290          KeyFunction->getTemplateSpecializationKind();
12291      assert(TSK != TSK_ExplicitInstantiationDefinition &&
12292             TSK != TSK_ImplicitInstantiation &&
12293             "Instantiations don't have key functions");
12294      (void)TSK;
12295    } else if (!KeyFunction) {
12296      // If we have a class with no key function that is the subject
12297      // of an explicit instantiation declaration, suppress the
12298      // vtable; it will live with the explicit instantiation
12299      // definition.
12300      bool IsExplicitInstantiationDeclaration
12301        = Class->getTemplateSpecializationKind()
12302                                      == TSK_ExplicitInstantiationDeclaration;
12303      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
12304                                 REnd = Class->redecls_end();
12305           R != REnd; ++R) {
12306        TemplateSpecializationKind TSK
12307          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
12308        if (TSK == TSK_ExplicitInstantiationDeclaration)
12309          IsExplicitInstantiationDeclaration = true;
12310        else if (TSK == TSK_ExplicitInstantiationDefinition) {
12311          IsExplicitInstantiationDeclaration = false;
12312          break;
12313        }
12314      }
12315
12316      if (IsExplicitInstantiationDeclaration)
12317        DefineVTable = false;
12318    }
12319
12320    // The exception specifications for all virtual members may be needed even
12321    // if we are not providing an authoritative form of the vtable in this TU.
12322    // We may choose to emit it available_externally anyway.
12323    if (!DefineVTable) {
12324      MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
12325      continue;
12326    }
12327
12328    // Mark all of the virtual members of this class as referenced, so
12329    // that we can build a vtable. Then, tell the AST consumer that a
12330    // vtable for this class is required.
12331    DefinedAnything = true;
12332    MarkVirtualMembersReferenced(Loc, Class);
12333    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
12334    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
12335
12336    // Optionally warn if we're emitting a weak vtable.
12337    if (Class->isExternallyVisible() &&
12338        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
12339      const FunctionDecl *KeyFunctionDef = 0;
12340      if (!KeyFunction ||
12341          (KeyFunction->hasBody(KeyFunctionDef) &&
12342           KeyFunctionDef->isInlined()))
12343        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
12344             TSK_ExplicitInstantiationDefinition
12345             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
12346          << Class;
12347    }
12348  }
12349  VTableUses.clear();
12350
12351  return DefinedAnything;
12352}
12353
12354void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
12355                                                 const CXXRecordDecl *RD) {
12356  for (CXXRecordDecl::method_iterator I = RD->method_begin(),
12357                                      E = RD->method_end(); I != E; ++I)
12358    if ((*I)->isVirtual() && !(*I)->isPure())
12359      ResolveExceptionSpec(Loc, (*I)->getType()->castAs<FunctionProtoType>());
12360}
12361
12362void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
12363                                        const CXXRecordDecl *RD) {
12364  // Mark all functions which will appear in RD's vtable as used.
12365  CXXFinalOverriderMap FinalOverriders;
12366  RD->getFinalOverriders(FinalOverriders);
12367  for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
12368                                            E = FinalOverriders.end();
12369       I != E; ++I) {
12370    for (OverridingMethods::const_iterator OI = I->second.begin(),
12371                                           OE = I->second.end();
12372         OI != OE; ++OI) {
12373      assert(OI->second.size() > 0 && "no final overrider");
12374      CXXMethodDecl *Overrider = OI->second.front().Method;
12375
12376      // C++ [basic.def.odr]p2:
12377      //   [...] A virtual member function is used if it is not pure. [...]
12378      if (!Overrider->isPure())
12379        MarkFunctionReferenced(Loc, Overrider);
12380    }
12381  }
12382
12383  // Only classes that have virtual bases need a VTT.
12384  if (RD->getNumVBases() == 0)
12385    return;
12386
12387  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
12388           e = RD->bases_end(); i != e; ++i) {
12389    const CXXRecordDecl *Base =
12390        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
12391    if (Base->getNumVBases() == 0)
12392      continue;
12393    MarkVirtualMembersReferenced(Loc, Base);
12394  }
12395}
12396
12397/// SetIvarInitializers - This routine builds initialization ASTs for the
12398/// Objective-C implementation whose ivars need be initialized.
12399void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
12400  if (!getLangOpts().CPlusPlus)
12401    return;
12402  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
12403    SmallVector<ObjCIvarDecl*, 8> ivars;
12404    CollectIvarsToConstructOrDestruct(OID, ivars);
12405    if (ivars.empty())
12406      return;
12407    SmallVector<CXXCtorInitializer*, 32> AllToInit;
12408    for (unsigned i = 0; i < ivars.size(); i++) {
12409      FieldDecl *Field = ivars[i];
12410      if (Field->isInvalidDecl())
12411        continue;
12412
12413      CXXCtorInitializer *Member;
12414      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
12415      InitializationKind InitKind =
12416        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
12417
12418      InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
12419      ExprResult MemberInit =
12420        InitSeq.Perform(*this, InitEntity, InitKind, None);
12421      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
12422      // Note, MemberInit could actually come back empty if no initialization
12423      // is required (e.g., because it would call a trivial default constructor)
12424      if (!MemberInit.get() || MemberInit.isInvalid())
12425        continue;
12426
12427      Member =
12428        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
12429                                         SourceLocation(),
12430                                         MemberInit.takeAs<Expr>(),
12431                                         SourceLocation());
12432      AllToInit.push_back(Member);
12433
12434      // Be sure that the destructor is accessible and is marked as referenced.
12435      if (const RecordType *RecordTy
12436                  = Context.getBaseElementType(Field->getType())
12437                                                        ->getAs<RecordType>()) {
12438                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
12439        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
12440          MarkFunctionReferenced(Field->getLocation(), Destructor);
12441          CheckDestructorAccess(Field->getLocation(), Destructor,
12442                            PDiag(diag::err_access_dtor_ivar)
12443                              << Context.getBaseElementType(Field->getType()));
12444        }
12445      }
12446    }
12447    ObjCImplementation->setIvarInitializers(Context,
12448                                            AllToInit.data(), AllToInit.size());
12449  }
12450}
12451
12452static
12453void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
12454                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
12455                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
12456                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
12457                           Sema &S) {
12458  if (Ctor->isInvalidDecl())
12459    return;
12460
12461  CXXConstructorDecl *Target = Ctor->getTargetConstructor();
12462
12463  // Target may not be determinable yet, for instance if this is a dependent
12464  // call in an uninstantiated template.
12465  if (Target) {
12466    const FunctionDecl *FNTarget = 0;
12467    (void)Target->hasBody(FNTarget);
12468    Target = const_cast<CXXConstructorDecl*>(
12469      cast_or_null<CXXConstructorDecl>(FNTarget));
12470  }
12471
12472  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
12473                     // Avoid dereferencing a null pointer here.
12474                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
12475
12476  if (!Current.insert(Canonical))
12477    return;
12478
12479  // We know that beyond here, we aren't chaining into a cycle.
12480  if (!Target || !Target->isDelegatingConstructor() ||
12481      Target->isInvalidDecl() || Valid.count(TCanonical)) {
12482    Valid.insert(Current.begin(), Current.end());
12483    Current.clear();
12484  // We've hit a cycle.
12485  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
12486             Current.count(TCanonical)) {
12487    // If we haven't diagnosed this cycle yet, do so now.
12488    if (!Invalid.count(TCanonical)) {
12489      S.Diag((*Ctor->init_begin())->getSourceLocation(),
12490             diag::warn_delegating_ctor_cycle)
12491        << Ctor;
12492
12493      // Don't add a note for a function delegating directly to itself.
12494      if (TCanonical != Canonical)
12495        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
12496
12497      CXXConstructorDecl *C = Target;
12498      while (C->getCanonicalDecl() != Canonical) {
12499        const FunctionDecl *FNTarget = 0;
12500        (void)C->getTargetConstructor()->hasBody(FNTarget);
12501        assert(FNTarget && "Ctor cycle through bodiless function");
12502
12503        C = const_cast<CXXConstructorDecl*>(
12504          cast<CXXConstructorDecl>(FNTarget));
12505        S.Diag(C->getLocation(), diag::note_which_delegates_to);
12506      }
12507    }
12508
12509    Invalid.insert(Current.begin(), Current.end());
12510    Current.clear();
12511  } else {
12512    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
12513  }
12514}
12515
12516
12517void Sema::CheckDelegatingCtorCycles() {
12518  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
12519
12520  for (DelegatingCtorDeclsType::iterator
12521         I = DelegatingCtorDecls.begin(ExternalSource),
12522         E = DelegatingCtorDecls.end();
12523       I != E; ++I)
12524    DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
12525
12526  for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
12527                                                         CE = Invalid.end();
12528       CI != CE; ++CI)
12529    (*CI)->setInvalidDecl();
12530}
12531
12532namespace {
12533  /// \brief AST visitor that finds references to the 'this' expression.
12534  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
12535    Sema &S;
12536
12537  public:
12538    explicit FindCXXThisExpr(Sema &S) : S(S) { }
12539
12540    bool VisitCXXThisExpr(CXXThisExpr *E) {
12541      S.Diag(E->getLocation(), diag::err_this_static_member_func)
12542        << E->isImplicit();
12543      return false;
12544    }
12545  };
12546}
12547
12548bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
12549  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12550  if (!TSInfo)
12551    return false;
12552
12553  TypeLoc TL = TSInfo->getTypeLoc();
12554  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12555  if (!ProtoTL)
12556    return false;
12557
12558  // C++11 [expr.prim.general]p3:
12559  //   [The expression this] shall not appear before the optional
12560  //   cv-qualifier-seq and it shall not appear within the declaration of a
12561  //   static member function (although its type and value category are defined
12562  //   within a static member function as they are within a non-static member
12563  //   function). [ Note: this is because declaration matching does not occur
12564  //  until the complete declarator is known. - end note ]
12565  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12566  FindCXXThisExpr Finder(*this);
12567
12568  // If the return type came after the cv-qualifier-seq, check it now.
12569  if (Proto->hasTrailingReturn() &&
12570      !Finder.TraverseTypeLoc(ProtoTL.getResultLoc()))
12571    return true;
12572
12573  // Check the exception specification.
12574  if (checkThisInStaticMemberFunctionExceptionSpec(Method))
12575    return true;
12576
12577  return checkThisInStaticMemberFunctionAttributes(Method);
12578}
12579
12580bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
12581  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
12582  if (!TSInfo)
12583    return false;
12584
12585  TypeLoc TL = TSInfo->getTypeLoc();
12586  FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
12587  if (!ProtoTL)
12588    return false;
12589
12590  const FunctionProtoType *Proto = ProtoTL.getTypePtr();
12591  FindCXXThisExpr Finder(*this);
12592
12593  switch (Proto->getExceptionSpecType()) {
12594  case EST_Uninstantiated:
12595  case EST_Unevaluated:
12596  case EST_BasicNoexcept:
12597  case EST_DynamicNone:
12598  case EST_MSAny:
12599  case EST_None:
12600    break;
12601
12602  case EST_ComputedNoexcept:
12603    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
12604      return true;
12605
12606  case EST_Dynamic:
12607    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
12608         EEnd = Proto->exception_end();
12609         E != EEnd; ++E) {
12610      if (!Finder.TraverseType(*E))
12611        return true;
12612    }
12613    break;
12614  }
12615
12616  return false;
12617}
12618
12619bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
12620  FindCXXThisExpr Finder(*this);
12621
12622  // Check attributes.
12623  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
12624       A != AEnd; ++A) {
12625    // FIXME: This should be emitted by tblgen.
12626    Expr *Arg = 0;
12627    ArrayRef<Expr *> Args;
12628    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
12629      Arg = G->getArg();
12630    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
12631      Arg = G->getArg();
12632    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
12633      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
12634    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
12635      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
12636    else if (ExclusiveLockFunctionAttr *ELF
12637               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
12638      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
12639    else if (SharedLockFunctionAttr *SLF
12640               = dyn_cast<SharedLockFunctionAttr>(*A))
12641      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
12642    else if (ExclusiveTrylockFunctionAttr *ETLF
12643               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
12644      Arg = ETLF->getSuccessValue();
12645      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
12646    } else if (SharedTrylockFunctionAttr *STLF
12647                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
12648      Arg = STLF->getSuccessValue();
12649      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
12650    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
12651      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
12652    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
12653      Arg = LR->getArg();
12654    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
12655      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
12656    else if (ExclusiveLocksRequiredAttr *ELR
12657               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
12658      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
12659    else if (SharedLocksRequiredAttr *SLR
12660               = dyn_cast<SharedLocksRequiredAttr>(*A))
12661      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
12662
12663    if (Arg && !Finder.TraverseStmt(Arg))
12664      return true;
12665
12666    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
12667      if (!Finder.TraverseStmt(Args[I]))
12668        return true;
12669    }
12670  }
12671
12672  return false;
12673}
12674
12675void
12676Sema::checkExceptionSpecification(ExceptionSpecificationType EST,
12677                                  ArrayRef<ParsedType> DynamicExceptions,
12678                                  ArrayRef<SourceRange> DynamicExceptionRanges,
12679                                  Expr *NoexceptExpr,
12680                                  SmallVectorImpl<QualType> &Exceptions,
12681                                  FunctionProtoType::ExtProtoInfo &EPI) {
12682  Exceptions.clear();
12683  EPI.ExceptionSpecType = EST;
12684  if (EST == EST_Dynamic) {
12685    Exceptions.reserve(DynamicExceptions.size());
12686    for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
12687      // FIXME: Preserve type source info.
12688      QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
12689
12690      SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12691      collectUnexpandedParameterPacks(ET, Unexpanded);
12692      if (!Unexpanded.empty()) {
12693        DiagnoseUnexpandedParameterPacks(DynamicExceptionRanges[ei].getBegin(),
12694                                         UPPC_ExceptionType,
12695                                         Unexpanded);
12696        continue;
12697      }
12698
12699      // Check that the type is valid for an exception spec, and
12700      // drop it if not.
12701      if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
12702        Exceptions.push_back(ET);
12703    }
12704    EPI.NumExceptions = Exceptions.size();
12705    EPI.Exceptions = Exceptions.data();
12706    return;
12707  }
12708
12709  if (EST == EST_ComputedNoexcept) {
12710    // If an error occurred, there's no expression here.
12711    if (NoexceptExpr) {
12712      assert((NoexceptExpr->isTypeDependent() ||
12713              NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
12714              Context.BoolTy) &&
12715             "Parser should have made sure that the expression is boolean");
12716      if (NoexceptExpr && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
12717        EPI.ExceptionSpecType = EST_BasicNoexcept;
12718        return;
12719      }
12720
12721      if (!NoexceptExpr->isValueDependent())
12722        NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, 0,
12723                         diag::err_noexcept_needs_constant_expression,
12724                         /*AllowFold*/ false).take();
12725      EPI.NoexceptExpr = NoexceptExpr;
12726    }
12727    return;
12728  }
12729}
12730
12731/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
12732Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
12733  // Implicitly declared functions (e.g. copy constructors) are
12734  // __host__ __device__
12735  if (D->isImplicit())
12736    return CFT_HostDevice;
12737
12738  if (D->hasAttr<CUDAGlobalAttr>())
12739    return CFT_Global;
12740
12741  if (D->hasAttr<CUDADeviceAttr>()) {
12742    if (D->hasAttr<CUDAHostAttr>())
12743      return CFT_HostDevice;
12744    return CFT_Device;
12745  }
12746
12747  return CFT_Host;
12748}
12749
12750bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
12751                           CUDAFunctionTarget CalleeTarget) {
12752  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
12753  // Callable from the device only."
12754  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
12755    return true;
12756
12757  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
12758  // Callable from the host only."
12759  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
12760  // Callable from the host only."
12761  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
12762      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
12763    return true;
12764
12765  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
12766    return true;
12767
12768  return false;
12769}
12770
12771/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
12772///
12773MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
12774                                       SourceLocation DeclStart,
12775                                       Declarator &D, Expr *BitWidth,
12776                                       InClassInitStyle InitStyle,
12777                                       AccessSpecifier AS,
12778                                       AttributeList *MSPropertyAttr) {
12779  IdentifierInfo *II = D.getIdentifier();
12780  if (!II) {
12781    Diag(DeclStart, diag::err_anonymous_property);
12782    return NULL;
12783  }
12784  SourceLocation Loc = D.getIdentifierLoc();
12785
12786  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12787  QualType T = TInfo->getType();
12788  if (getLangOpts().CPlusPlus) {
12789    CheckExtraCXXDefaultArguments(D);
12790
12791    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12792                                        UPPC_DataMemberType)) {
12793      D.setInvalidType();
12794      T = Context.IntTy;
12795      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12796    }
12797  }
12798
12799  DiagnoseFunctionSpecifiers(D.getDeclSpec());
12800
12801  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12802    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12803         diag::err_invalid_thread)
12804      << DeclSpec::getSpecifierName(TSCS);
12805
12806  // Check to see if this name was declared as a member previously
12807  NamedDecl *PrevDecl = 0;
12808  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12809  LookupName(Previous, S);
12810  switch (Previous.getResultKind()) {
12811  case LookupResult::Found:
12812  case LookupResult::FoundUnresolvedValue:
12813    PrevDecl = Previous.getAsSingle<NamedDecl>();
12814    break;
12815
12816  case LookupResult::FoundOverloaded:
12817    PrevDecl = Previous.getRepresentativeDecl();
12818    break;
12819
12820  case LookupResult::NotFound:
12821  case LookupResult::NotFoundInCurrentInstantiation:
12822  case LookupResult::Ambiguous:
12823    break;
12824  }
12825
12826  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12827    // Maybe we will complain about the shadowed template parameter.
12828    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12829    // Just pretend that we didn't see the previous declaration.
12830    PrevDecl = 0;
12831  }
12832
12833  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12834    PrevDecl = 0;
12835
12836  SourceLocation TSSL = D.getLocStart();
12837  MSPropertyDecl *NewPD;
12838  const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
12839  NewPD = new (Context) MSPropertyDecl(Record, Loc,
12840                                       II, T, TInfo, TSSL,
12841                                       Data.GetterId, Data.SetterId);
12842  ProcessDeclAttributes(TUScope, NewPD, D);
12843  NewPD->setAccess(AS);
12844
12845  if (NewPD->isInvalidDecl())
12846    Record->setInvalidDecl();
12847
12848  if (D.getDeclSpec().isModulePrivateSpecified())
12849    NewPD->setModulePrivate();
12850
12851  if (NewPD->isInvalidDecl() && PrevDecl) {
12852    // Don't introduce NewFD into scope; there's already something
12853    // with the same name in the same scope.
12854  } else if (II) {
12855    PushOnScopeChains(NewPD, S);
12856  } else
12857    Record->addDecl(NewPD);
12858
12859  return NewPD;
12860}
12861