SemaDeclCXX.cpp revision cefc3afac14d29de5aba7810cc8fe6c858949e9d
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/AST/ASTConsumer.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/ASTMutationListener.h"
23#include "clang/AST/CharUnits.h"
24#include "clang/AST/CXXInheritance.h"
25#include "clang/AST/DeclVisitor.h"
26#include "clang/AST/ExprCXX.h"
27#include "clang/AST/RecordLayout.h"
28#include "clang/AST/RecursiveASTVisitor.h"
29#include "clang/AST/StmtVisitor.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/TypeOrdering.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Lex/Preprocessor.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/STLExtras.h"
38#include <map>
39#include <set>
40
41using namespace clang;
42
43//===----------------------------------------------------------------------===//
44// CheckDefaultArgumentVisitor
45//===----------------------------------------------------------------------===//
46
47namespace {
48  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
49  /// the default argument of a parameter to determine whether it
50  /// contains any ill-formed subexpressions. For example, this will
51  /// diagnose the use of local variables or parameters within the
52  /// default argument expression.
53  class CheckDefaultArgumentVisitor
54    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
55    Expr *DefaultArg;
56    Sema *S;
57
58  public:
59    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
60      : DefaultArg(defarg), S(s) {}
61
62    bool VisitExpr(Expr *Node);
63    bool VisitDeclRefExpr(DeclRefExpr *DRE);
64    bool VisitCXXThisExpr(CXXThisExpr *ThisE);
65    bool VisitLambdaExpr(LambdaExpr *Lambda);
66  };
67
68  /// VisitExpr - Visit all of the children of this expression.
69  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
70    bool IsInvalid = false;
71    for (Stmt::child_range I = Node->children(); I; ++I)
72      IsInvalid |= Visit(*I);
73    return IsInvalid;
74  }
75
76  /// VisitDeclRefExpr - Visit a reference to a declaration, to
77  /// determine whether this declaration can be used in the default
78  /// argument expression.
79  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
80    NamedDecl *Decl = DRE->getDecl();
81    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
82      // C++ [dcl.fct.default]p9
83      //   Default arguments are evaluated each time the function is
84      //   called. The order of evaluation of function arguments is
85      //   unspecified. Consequently, parameters of a function shall not
86      //   be used in default argument expressions, even if they are not
87      //   evaluated. Parameters of a function declared before a default
88      //   argument expression are in scope and can hide namespace and
89      //   class member names.
90      return S->Diag(DRE->getLocStart(),
91                     diag::err_param_default_argument_references_param)
92         << Param->getDeclName() << DefaultArg->getSourceRange();
93    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
94      // C++ [dcl.fct.default]p7
95      //   Local variables shall not be used in default argument
96      //   expressions.
97      if (VDecl->isLocalVarDecl())
98        return S->Diag(DRE->getLocStart(),
99                       diag::err_param_default_argument_references_local)
100          << VDecl->getDeclName() << DefaultArg->getSourceRange();
101    }
102
103    return false;
104  }
105
106  /// VisitCXXThisExpr - Visit a C++ "this" expression.
107  bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
108    // C++ [dcl.fct.default]p8:
109    //   The keyword this shall not be used in a default argument of a
110    //   member function.
111    return S->Diag(ThisE->getLocStart(),
112                   diag::err_param_default_argument_references_this)
113               << ThisE->getSourceRange();
114  }
115
116  bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
117    // C++11 [expr.lambda.prim]p13:
118    //   A lambda-expression appearing in a default argument shall not
119    //   implicitly or explicitly capture any entity.
120    if (Lambda->capture_begin() == Lambda->capture_end())
121      return false;
122
123    return S->Diag(Lambda->getLocStart(),
124                   diag::err_lambda_capture_default_arg);
125  }
126}
127
128void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
129  assert(Context && "ImplicitExceptionSpecification without an ASTContext");
130  // If we have an MSAny or unknown spec already, don't bother.
131  if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
132    return;
133
134  const FunctionProtoType *Proto
135    = Method->getType()->getAs<FunctionProtoType>();
136
137  ExceptionSpecificationType EST = Proto->getExceptionSpecType();
138
139  // If this function can throw any exceptions, make a note of that.
140  if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
141    ClearExceptions();
142    ComputedEST = EST;
143    return;
144  }
145
146  // FIXME: If the call to this decl is using any of its default arguments, we
147  // need to search them for potentially-throwing calls.
148
149  // If this function has a basic noexcept, it doesn't affect the outcome.
150  if (EST == EST_BasicNoexcept)
151    return;
152
153  // If we have a throw-all spec at this point, ignore the function.
154  if (ComputedEST == EST_None)
155    return;
156
157  // If we're still at noexcept(true) and there's a nothrow() callee,
158  // change to that specification.
159  if (EST == EST_DynamicNone) {
160    if (ComputedEST == EST_BasicNoexcept)
161      ComputedEST = EST_DynamicNone;
162    return;
163  }
164
165  // Check out noexcept specs.
166  if (EST == EST_ComputedNoexcept) {
167    FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
168    assert(NR != FunctionProtoType::NR_NoNoexcept &&
169           "Must have noexcept result for EST_ComputedNoexcept.");
170    assert(NR != FunctionProtoType::NR_Dependent &&
171           "Should not generate implicit declarations for dependent cases, "
172           "and don't know how to handle them anyway.");
173
174    // noexcept(false) -> no spec on the new function
175    if (NR == FunctionProtoType::NR_Throw) {
176      ClearExceptions();
177      ComputedEST = EST_None;
178    }
179    // noexcept(true) won't change anything either.
180    return;
181  }
182
183  assert(EST == EST_Dynamic && "EST case not considered earlier.");
184  assert(ComputedEST != EST_None &&
185         "Shouldn't collect exceptions when throw-all is guaranteed.");
186  ComputedEST = EST_Dynamic;
187  // Record the exceptions in this function's exception specification.
188  for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
189                                          EEnd = Proto->exception_end();
190       E != EEnd; ++E)
191    if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
192      Exceptions.push_back(*E);
193}
194
195void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
196  if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
197    return;
198
199  // FIXME:
200  //
201  // C++0x [except.spec]p14:
202  //   [An] implicit exception-specification specifies the type-id T if and
203  // only if T is allowed by the exception-specification of a function directly
204  // invoked by f's implicit definition; f shall allow all exceptions if any
205  // function it directly invokes allows all exceptions, and f shall allow no
206  // exceptions if every function it directly invokes allows no exceptions.
207  //
208  // Note in particular that if an implicit exception-specification is generated
209  // for a function containing a throw-expression, that specification can still
210  // be noexcept(true).
211  //
212  // Note also that 'directly invoked' is not defined in the standard, and there
213  // is no indication that we should only consider potentially-evaluated calls.
214  //
215  // Ultimately we should implement the intent of the standard: the exception
216  // specification should be the set of exceptions which can be thrown by the
217  // implicit definition. For now, we assume that any non-nothrow expression can
218  // throw any exception.
219
220  if (E->CanThrow(*Context))
221    ComputedEST = EST_None;
222}
223
224bool
225Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
226                              SourceLocation EqualLoc) {
227  if (RequireCompleteType(Param->getLocation(), Param->getType(),
228                          diag::err_typecheck_decl_incomplete_type)) {
229    Param->setInvalidDecl();
230    return true;
231  }
232
233  // C++ [dcl.fct.default]p5
234  //   A default argument expression is implicitly converted (clause
235  //   4) to the parameter type. The default argument expression has
236  //   the same semantic constraints as the initializer expression in
237  //   a declaration of a variable of the parameter type, using the
238  //   copy-initialization semantics (8.5).
239  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
240                                                                    Param);
241  InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
242                                                           EqualLoc);
243  InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
244  ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
245                                      MultiExprArg(*this, &Arg, 1));
246  if (Result.isInvalid())
247    return true;
248  Arg = Result.takeAs<Expr>();
249
250  CheckImplicitConversions(Arg, EqualLoc);
251  Arg = MaybeCreateExprWithCleanups(Arg);
252
253  // Okay: add the default argument to the parameter
254  Param->setDefaultArg(Arg);
255
256  // We have already instantiated this parameter; provide each of the
257  // instantiations with the uninstantiated default argument.
258  UnparsedDefaultArgInstantiationsMap::iterator InstPos
259    = UnparsedDefaultArgInstantiations.find(Param);
260  if (InstPos != UnparsedDefaultArgInstantiations.end()) {
261    for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
262      InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
263
264    // We're done tracking this parameter's instantiations.
265    UnparsedDefaultArgInstantiations.erase(InstPos);
266  }
267
268  return false;
269}
270
271/// ActOnParamDefaultArgument - Check whether the default argument
272/// provided for a function parameter is well-formed. If so, attach it
273/// to the parameter declaration.
274void
275Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
276                                Expr *DefaultArg) {
277  if (!param || !DefaultArg)
278    return;
279
280  ParmVarDecl *Param = cast<ParmVarDecl>(param);
281  UnparsedDefaultArgLocs.erase(Param);
282
283  // Default arguments are only permitted in C++
284  if (!getLangOpts().CPlusPlus) {
285    Diag(EqualLoc, diag::err_param_default_argument)
286      << DefaultArg->getSourceRange();
287    Param->setInvalidDecl();
288    return;
289  }
290
291  // Check for unexpanded parameter packs.
292  if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
293    Param->setInvalidDecl();
294    return;
295  }
296
297  // Check that the default argument is well-formed
298  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
299  if (DefaultArgChecker.Visit(DefaultArg)) {
300    Param->setInvalidDecl();
301    return;
302  }
303
304  SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
305}
306
307/// ActOnParamUnparsedDefaultArgument - We've seen a default
308/// argument for a function parameter, but we can't parse it yet
309/// because we're inside a class definition. Note that this default
310/// argument will be parsed later.
311void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
312                                             SourceLocation EqualLoc,
313                                             SourceLocation ArgLoc) {
314  if (!param)
315    return;
316
317  ParmVarDecl *Param = cast<ParmVarDecl>(param);
318  if (Param)
319    Param->setUnparsedDefaultArg();
320
321  UnparsedDefaultArgLocs[Param] = ArgLoc;
322}
323
324/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
325/// the default argument for the parameter param failed.
326void Sema::ActOnParamDefaultArgumentError(Decl *param) {
327  if (!param)
328    return;
329
330  ParmVarDecl *Param = cast<ParmVarDecl>(param);
331
332  Param->setInvalidDecl();
333
334  UnparsedDefaultArgLocs.erase(Param);
335}
336
337/// CheckExtraCXXDefaultArguments - Check for any extra default
338/// arguments in the declarator, which is not a function declaration
339/// or definition and therefore is not permitted to have default
340/// arguments. This routine should be invoked for every declarator
341/// that is not a function declaration or definition.
342void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
343  // C++ [dcl.fct.default]p3
344  //   A default argument expression shall be specified only in the
345  //   parameter-declaration-clause of a function declaration or in a
346  //   template-parameter (14.1). It shall not be specified for a
347  //   parameter pack. If it is specified in a
348  //   parameter-declaration-clause, it shall not occur within a
349  //   declarator or abstract-declarator of a parameter-declaration.
350  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
351    DeclaratorChunk &chunk = D.getTypeObject(i);
352    if (chunk.Kind == DeclaratorChunk::Function) {
353      for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
354        ParmVarDecl *Param =
355          cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
356        if (Param->hasUnparsedDefaultArg()) {
357          CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
358          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
359            << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
360          delete Toks;
361          chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
362        } else if (Param->getDefaultArg()) {
363          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
364            << Param->getDefaultArg()->getSourceRange();
365          Param->setDefaultArg(0);
366        }
367      }
368    }
369  }
370}
371
372// MergeCXXFunctionDecl - Merge two declarations of the same C++
373// function, once we already know that they have the same
374// type. Subroutine of MergeFunctionDecl. Returns true if there was an
375// error, false otherwise.
376bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
377                                Scope *S) {
378  bool Invalid = false;
379
380  // C++ [dcl.fct.default]p4:
381  //   For non-template functions, default arguments can be added in
382  //   later declarations of a function in the same
383  //   scope. Declarations in different scopes have completely
384  //   distinct sets of default arguments. That is, declarations in
385  //   inner scopes do not acquire default arguments from
386  //   declarations in outer scopes, and vice versa. In a given
387  //   function declaration, all parameters subsequent to a
388  //   parameter with a default argument shall have default
389  //   arguments supplied in this or previous declarations. A
390  //   default argument shall not be redefined by a later
391  //   declaration (not even to the same value).
392  //
393  // C++ [dcl.fct.default]p6:
394  //   Except for member functions of class templates, the default arguments
395  //   in a member function definition that appears outside of the class
396  //   definition are added to the set of default arguments provided by the
397  //   member function declaration in the class definition.
398  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
399    ParmVarDecl *OldParam = Old->getParamDecl(p);
400    ParmVarDecl *NewParam = New->getParamDecl(p);
401
402    bool OldParamHasDfl = OldParam->hasDefaultArg();
403    bool NewParamHasDfl = NewParam->hasDefaultArg();
404
405    NamedDecl *ND = Old;
406    if (S && !isDeclInScope(ND, New->getDeclContext(), S))
407      // Ignore default parameters of old decl if they are not in
408      // the same scope.
409      OldParamHasDfl = false;
410
411    if (OldParamHasDfl && NewParamHasDfl) {
412
413      unsigned DiagDefaultParamID =
414        diag::err_param_default_argument_redefinition;
415
416      // MSVC accepts that default parameters be redefined for member functions
417      // of template class. The new default parameter's value is ignored.
418      Invalid = true;
419      if (getLangOpts().MicrosoftExt) {
420        CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
421        if (MD && MD->getParent()->getDescribedClassTemplate()) {
422          // Merge the old default argument into the new parameter.
423          NewParam->setHasInheritedDefaultArg();
424          if (OldParam->hasUninstantiatedDefaultArg())
425            NewParam->setUninstantiatedDefaultArg(
426                                      OldParam->getUninstantiatedDefaultArg());
427          else
428            NewParam->setDefaultArg(OldParam->getInit());
429          DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
430          Invalid = false;
431        }
432      }
433
434      // FIXME: If we knew where the '=' was, we could easily provide a fix-it
435      // hint here. Alternatively, we could walk the type-source information
436      // for NewParam to find the last source location in the type... but it
437      // isn't worth the effort right now. This is the kind of test case that
438      // is hard to get right:
439      //   int f(int);
440      //   void g(int (*fp)(int) = f);
441      //   void g(int (*fp)(int) = &f);
442      Diag(NewParam->getLocation(), DiagDefaultParamID)
443        << NewParam->getDefaultArgRange();
444
445      // Look for the function declaration where the default argument was
446      // actually written, which may be a declaration prior to Old.
447      for (FunctionDecl *Older = Old->getPreviousDecl();
448           Older; Older = Older->getPreviousDecl()) {
449        if (!Older->getParamDecl(p)->hasDefaultArg())
450          break;
451
452        OldParam = Older->getParamDecl(p);
453      }
454
455      Diag(OldParam->getLocation(), diag::note_previous_definition)
456        << OldParam->getDefaultArgRange();
457    } else if (OldParamHasDfl) {
458      // Merge the old default argument into the new parameter.
459      // It's important to use getInit() here;  getDefaultArg()
460      // strips off any top-level ExprWithCleanups.
461      NewParam->setHasInheritedDefaultArg();
462      if (OldParam->hasUninstantiatedDefaultArg())
463        NewParam->setUninstantiatedDefaultArg(
464                                      OldParam->getUninstantiatedDefaultArg());
465      else
466        NewParam->setDefaultArg(OldParam->getInit());
467    } else if (NewParamHasDfl) {
468      if (New->getDescribedFunctionTemplate()) {
469        // Paragraph 4, quoted above, only applies to non-template functions.
470        Diag(NewParam->getLocation(),
471             diag::err_param_default_argument_template_redecl)
472          << NewParam->getDefaultArgRange();
473        Diag(Old->getLocation(), diag::note_template_prev_declaration)
474          << false;
475      } else if (New->getTemplateSpecializationKind()
476                   != TSK_ImplicitInstantiation &&
477                 New->getTemplateSpecializationKind() != TSK_Undeclared) {
478        // C++ [temp.expr.spec]p21:
479        //   Default function arguments shall not be specified in a declaration
480        //   or a definition for one of the following explicit specializations:
481        //     - the explicit specialization of a function template;
482        //     - the explicit specialization of a member function template;
483        //     - the explicit specialization of a member function of a class
484        //       template where the class template specialization to which the
485        //       member function specialization belongs is implicitly
486        //       instantiated.
487        Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
488          << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
489          << New->getDeclName()
490          << NewParam->getDefaultArgRange();
491      } else if (New->getDeclContext()->isDependentContext()) {
492        // C++ [dcl.fct.default]p6 (DR217):
493        //   Default arguments for a member function of a class template shall
494        //   be specified on the initial declaration of the member function
495        //   within the class template.
496        //
497        // Reading the tea leaves a bit in DR217 and its reference to DR205
498        // leads me to the conclusion that one cannot add default function
499        // arguments for an out-of-line definition of a member function of a
500        // dependent type.
501        int WhichKind = 2;
502        if (CXXRecordDecl *Record
503              = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
504          if (Record->getDescribedClassTemplate())
505            WhichKind = 0;
506          else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
507            WhichKind = 1;
508          else
509            WhichKind = 2;
510        }
511
512        Diag(NewParam->getLocation(),
513             diag::err_param_default_argument_member_template_redecl)
514          << WhichKind
515          << NewParam->getDefaultArgRange();
516      } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
517        CXXSpecialMember NewSM = getSpecialMember(Ctor),
518                         OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
519        if (NewSM != OldSM) {
520          Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
521            << NewParam->getDefaultArgRange() << NewSM;
522          Diag(Old->getLocation(), diag::note_previous_declaration_special)
523            << OldSM;
524        }
525      }
526    }
527  }
528
529  // C++11 [dcl.constexpr]p1: If any declaration of a function or function
530  // template has a constexpr specifier then all its declarations shall
531  // contain the constexpr specifier.
532  if (New->isConstexpr() != Old->isConstexpr()) {
533    Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
534      << New << New->isConstexpr();
535    Diag(Old->getLocation(), diag::note_previous_declaration);
536    Invalid = true;
537  }
538
539  if (CheckEquivalentExceptionSpec(Old, New))
540    Invalid = true;
541
542  return Invalid;
543}
544
545/// \brief Merge the exception specifications of two variable declarations.
546///
547/// This is called when there's a redeclaration of a VarDecl. The function
548/// checks if the redeclaration might have an exception specification and
549/// validates compatibility and merges the specs if necessary.
550void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
551  // Shortcut if exceptions are disabled.
552  if (!getLangOpts().CXXExceptions)
553    return;
554
555  assert(Context.hasSameType(New->getType(), Old->getType()) &&
556         "Should only be called if types are otherwise the same.");
557
558  QualType NewType = New->getType();
559  QualType OldType = Old->getType();
560
561  // We're only interested in pointers and references to functions, as well
562  // as pointers to member functions.
563  if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
564    NewType = R->getPointeeType();
565    OldType = OldType->getAs<ReferenceType>()->getPointeeType();
566  } else if (const PointerType *P = NewType->getAs<PointerType>()) {
567    NewType = P->getPointeeType();
568    OldType = OldType->getAs<PointerType>()->getPointeeType();
569  } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
570    NewType = M->getPointeeType();
571    OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
572  }
573
574  if (!NewType->isFunctionProtoType())
575    return;
576
577  // There's lots of special cases for functions. For function pointers, system
578  // libraries are hopefully not as broken so that we don't need these
579  // workarounds.
580  if (CheckEquivalentExceptionSpec(
581        OldType->getAs<FunctionProtoType>(), Old->getLocation(),
582        NewType->getAs<FunctionProtoType>(), New->getLocation())) {
583    New->setInvalidDecl();
584  }
585}
586
587/// CheckCXXDefaultArguments - Verify that the default arguments for a
588/// function declaration are well-formed according to C++
589/// [dcl.fct.default].
590void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
591  unsigned NumParams = FD->getNumParams();
592  unsigned p;
593
594  bool IsLambda = FD->getOverloadedOperator() == OO_Call &&
595                  isa<CXXMethodDecl>(FD) &&
596                  cast<CXXMethodDecl>(FD)->getParent()->isLambda();
597
598  // Find first parameter with a default argument
599  for (p = 0; p < NumParams; ++p) {
600    ParmVarDecl *Param = FD->getParamDecl(p);
601    if (Param->hasDefaultArg()) {
602      // C++11 [expr.prim.lambda]p5:
603      //   [...] Default arguments (8.3.6) shall not be specified in the
604      //   parameter-declaration-clause of a lambda-declarator.
605      //
606      // FIXME: Core issue 974 strikes this sentence, we only provide an
607      // extension warning.
608      if (IsLambda)
609        Diag(Param->getLocation(), diag::ext_lambda_default_arguments)
610          << Param->getDefaultArgRange();
611      break;
612    }
613  }
614
615  // C++ [dcl.fct.default]p4:
616  //   In a given function declaration, all parameters
617  //   subsequent to a parameter with a default argument shall
618  //   have default arguments supplied in this or previous
619  //   declarations. A default argument shall not be redefined
620  //   by a later declaration (not even to the same value).
621  unsigned LastMissingDefaultArg = 0;
622  for (; p < NumParams; ++p) {
623    ParmVarDecl *Param = FD->getParamDecl(p);
624    if (!Param->hasDefaultArg()) {
625      if (Param->isInvalidDecl())
626        /* We already complained about this parameter. */;
627      else if (Param->getIdentifier())
628        Diag(Param->getLocation(),
629             diag::err_param_default_argument_missing_name)
630          << Param->getIdentifier();
631      else
632        Diag(Param->getLocation(),
633             diag::err_param_default_argument_missing);
634
635      LastMissingDefaultArg = p;
636    }
637  }
638
639  if (LastMissingDefaultArg > 0) {
640    // Some default arguments were missing. Clear out all of the
641    // default arguments up to (and including) the last missing
642    // default argument, so that we leave the function parameters
643    // in a semantically valid state.
644    for (p = 0; p <= LastMissingDefaultArg; ++p) {
645      ParmVarDecl *Param = FD->getParamDecl(p);
646      if (Param->hasDefaultArg()) {
647        Param->setDefaultArg(0);
648      }
649    }
650  }
651}
652
653// CheckConstexprParameterTypes - Check whether a function's parameter types
654// are all literal types. If so, return true. If not, produce a suitable
655// diagnostic and return false.
656static bool CheckConstexprParameterTypes(Sema &SemaRef,
657                                         const FunctionDecl *FD) {
658  unsigned ArgIndex = 0;
659  const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
660  for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
661       e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
662    const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
663    SourceLocation ParamLoc = PD->getLocation();
664    if (!(*i)->isDependentType() &&
665        SemaRef.RequireLiteralType(ParamLoc, *i,
666                            SemaRef.PDiag(diag::err_constexpr_non_literal_param)
667                                     << ArgIndex+1 << PD->getSourceRange()
668                                     << isa<CXXConstructorDecl>(FD)))
669      return false;
670  }
671  return true;
672}
673
674// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
675// the requirements of a constexpr function definition or a constexpr
676// constructor definition. If so, return true. If not, produce appropriate
677// diagnostics and return false.
678//
679// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
680bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
681  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
682  if (MD && MD->isInstance()) {
683    // C++11 [dcl.constexpr]p4:
684    //  The definition of a constexpr constructor shall satisfy the following
685    //  constraints:
686    //  - the class shall not have any virtual base classes;
687    const CXXRecordDecl *RD = MD->getParent();
688    if (RD->getNumVBases()) {
689      Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
690        << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
691        << RD->getNumVBases();
692      for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
693             E = RD->vbases_end(); I != E; ++I)
694        Diag(I->getLocStart(),
695             diag::note_constexpr_virtual_base_here) << I->getSourceRange();
696      return false;
697    }
698  }
699
700  if (!isa<CXXConstructorDecl>(NewFD)) {
701    // C++11 [dcl.constexpr]p3:
702    //  The definition of a constexpr function shall satisfy the following
703    //  constraints:
704    // - it shall not be virtual;
705    const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
706    if (Method && Method->isVirtual()) {
707      Diag(NewFD->getLocation(), diag::err_constexpr_virtual);
708
709      // If it's not obvious why this function is virtual, find an overridden
710      // function which uses the 'virtual' keyword.
711      const CXXMethodDecl *WrittenVirtual = Method;
712      while (!WrittenVirtual->isVirtualAsWritten())
713        WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
714      if (WrittenVirtual != Method)
715        Diag(WrittenVirtual->getLocation(),
716             diag::note_overridden_virtual_function);
717      return false;
718    }
719
720    // - its return type shall be a literal type;
721    QualType RT = NewFD->getResultType();
722    if (!RT->isDependentType() &&
723        RequireLiteralType(NewFD->getLocation(), RT,
724                           PDiag(diag::err_constexpr_non_literal_return)))
725      return false;
726  }
727
728  // - each of its parameter types shall be a literal type;
729  if (!CheckConstexprParameterTypes(*this, NewFD))
730    return false;
731
732  return true;
733}
734
735/// Check the given declaration statement is legal within a constexpr function
736/// body. C++0x [dcl.constexpr]p3,p4.
737///
738/// \return true if the body is OK, false if we have diagnosed a problem.
739static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
740                                   DeclStmt *DS) {
741  // C++0x [dcl.constexpr]p3 and p4:
742  //  The definition of a constexpr function(p3) or constructor(p4) [...] shall
743  //  contain only
744  for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
745         DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
746    switch ((*DclIt)->getKind()) {
747    case Decl::StaticAssert:
748    case Decl::Using:
749    case Decl::UsingShadow:
750    case Decl::UsingDirective:
751    case Decl::UnresolvedUsingTypename:
752      //   - static_assert-declarations
753      //   - using-declarations,
754      //   - using-directives,
755      continue;
756
757    case Decl::Typedef:
758    case Decl::TypeAlias: {
759      //   - typedef declarations and alias-declarations that do not define
760      //     classes or enumerations,
761      TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
762      if (TN->getUnderlyingType()->isVariablyModifiedType()) {
763        // Don't allow variably-modified types in constexpr functions.
764        TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
765        SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
766          << TL.getSourceRange() << TL.getType()
767          << isa<CXXConstructorDecl>(Dcl);
768        return false;
769      }
770      continue;
771    }
772
773    case Decl::Enum:
774    case Decl::CXXRecord:
775      // As an extension, we allow the declaration (but not the definition) of
776      // classes and enumerations in all declarations, not just in typedef and
777      // alias declarations.
778      if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
779        SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
780          << isa<CXXConstructorDecl>(Dcl);
781        return false;
782      }
783      continue;
784
785    case Decl::Var:
786      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
787        << isa<CXXConstructorDecl>(Dcl);
788      return false;
789
790    default:
791      SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
792        << isa<CXXConstructorDecl>(Dcl);
793      return false;
794    }
795  }
796
797  return true;
798}
799
800/// Check that the given field is initialized within a constexpr constructor.
801///
802/// \param Dcl The constexpr constructor being checked.
803/// \param Field The field being checked. This may be a member of an anonymous
804///        struct or union nested within the class being checked.
805/// \param Inits All declarations, including anonymous struct/union members and
806///        indirect members, for which any initialization was provided.
807/// \param Diagnosed Set to true if an error is produced.
808static void CheckConstexprCtorInitializer(Sema &SemaRef,
809                                          const FunctionDecl *Dcl,
810                                          FieldDecl *Field,
811                                          llvm::SmallSet<Decl*, 16> &Inits,
812                                          bool &Diagnosed) {
813  if (Field->isUnnamedBitfield())
814    return;
815
816  if (Field->isAnonymousStructOrUnion() &&
817      Field->getType()->getAsCXXRecordDecl()->isEmpty())
818    return;
819
820  if (!Inits.count(Field)) {
821    if (!Diagnosed) {
822      SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
823      Diagnosed = true;
824    }
825    SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
826  } else if (Field->isAnonymousStructOrUnion()) {
827    const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
828    for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
829         I != E; ++I)
830      // If an anonymous union contains an anonymous struct of which any member
831      // is initialized, all members must be initialized.
832      if (!RD->isUnion() || Inits.count(*I))
833        CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
834  }
835}
836
837/// Check the body for the given constexpr function declaration only contains
838/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
839///
840/// \return true if the body is OK, false if we have diagnosed a problem.
841bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
842  if (isa<CXXTryStmt>(Body)) {
843    // C++11 [dcl.constexpr]p3:
844    //  The definition of a constexpr function shall satisfy the following
845    //  constraints: [...]
846    // - its function-body shall be = delete, = default, or a
847    //   compound-statement
848    //
849    // C++11 [dcl.constexpr]p4:
850    //  In the definition of a constexpr constructor, [...]
851    // - its function-body shall not be a function-try-block;
852    Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
853      << isa<CXXConstructorDecl>(Dcl);
854    return false;
855  }
856
857  // - its function-body shall be [...] a compound-statement that contains only
858  CompoundStmt *CompBody = cast<CompoundStmt>(Body);
859
860  llvm::SmallVector<SourceLocation, 4> ReturnStmts;
861  for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
862         BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
863    switch ((*BodyIt)->getStmtClass()) {
864    case Stmt::NullStmtClass:
865      //   - null statements,
866      continue;
867
868    case Stmt::DeclStmtClass:
869      //   - static_assert-declarations
870      //   - using-declarations,
871      //   - using-directives,
872      //   - typedef declarations and alias-declarations that do not define
873      //     classes or enumerations,
874      if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
875        return false;
876      continue;
877
878    case Stmt::ReturnStmtClass:
879      //   - and exactly one return statement;
880      if (isa<CXXConstructorDecl>(Dcl))
881        break;
882
883      ReturnStmts.push_back((*BodyIt)->getLocStart());
884      continue;
885
886    default:
887      break;
888    }
889
890    Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
891      << isa<CXXConstructorDecl>(Dcl);
892    return false;
893  }
894
895  if (const CXXConstructorDecl *Constructor
896        = dyn_cast<CXXConstructorDecl>(Dcl)) {
897    const CXXRecordDecl *RD = Constructor->getParent();
898    // DR1359:
899    // - every non-variant non-static data member and base class sub-object
900    //   shall be initialized;
901    // - if the class is a non-empty union, or for each non-empty anonymous
902    //   union member of a non-union class, exactly one non-static data member
903    //   shall be initialized;
904    if (RD->isUnion()) {
905      if (Constructor->getNumCtorInitializers() == 0 && !RD->isEmpty()) {
906        Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
907        return false;
908      }
909    } else if (!Constructor->isDependentContext() &&
910               !Constructor->isDelegatingConstructor()) {
911      assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
912
913      // Skip detailed checking if we have enough initializers, and we would
914      // allow at most one initializer per member.
915      bool AnyAnonStructUnionMembers = false;
916      unsigned Fields = 0;
917      for (CXXRecordDecl::field_iterator I = RD->field_begin(),
918           E = RD->field_end(); I != E; ++I, ++Fields) {
919        if ((*I)->isAnonymousStructOrUnion()) {
920          AnyAnonStructUnionMembers = true;
921          break;
922        }
923      }
924      if (AnyAnonStructUnionMembers ||
925          Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
926        // Check initialization of non-static data members. Base classes are
927        // always initialized so do not need to be checked. Dependent bases
928        // might not have initializers in the member initializer list.
929        llvm::SmallSet<Decl*, 16> Inits;
930        for (CXXConstructorDecl::init_const_iterator
931               I = Constructor->init_begin(), E = Constructor->init_end();
932             I != E; ++I) {
933          if (FieldDecl *FD = (*I)->getMember())
934            Inits.insert(FD);
935          else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
936            Inits.insert(ID->chain_begin(), ID->chain_end());
937        }
938
939        bool Diagnosed = false;
940        for (CXXRecordDecl::field_iterator I = RD->field_begin(),
941             E = RD->field_end(); I != E; ++I)
942          CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
943        if (Diagnosed)
944          return false;
945      }
946    }
947  } else {
948    if (ReturnStmts.empty()) {
949      Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
950      return false;
951    }
952    if (ReturnStmts.size() > 1) {
953      Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
954      for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
955        Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
956      return false;
957    }
958  }
959
960  // C++11 [dcl.constexpr]p5:
961  //   if no function argument values exist such that the function invocation
962  //   substitution would produce a constant expression, the program is
963  //   ill-formed; no diagnostic required.
964  // C++11 [dcl.constexpr]p3:
965  //   - every constructor call and implicit conversion used in initializing the
966  //     return value shall be one of those allowed in a constant expression.
967  // C++11 [dcl.constexpr]p4:
968  //   - every constructor involved in initializing non-static data members and
969  //     base class sub-objects shall be a constexpr constructor.
970  llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
971  if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
972    Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
973      << isa<CXXConstructorDecl>(Dcl);
974    for (size_t I = 0, N = Diags.size(); I != N; ++I)
975      Diag(Diags[I].first, Diags[I].second);
976    return false;
977  }
978
979  return true;
980}
981
982/// isCurrentClassName - Determine whether the identifier II is the
983/// name of the class type currently being defined. In the case of
984/// nested classes, this will only return true if II is the name of
985/// the innermost class.
986bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
987                              const CXXScopeSpec *SS) {
988  assert(getLangOpts().CPlusPlus && "No class names in C!");
989
990  CXXRecordDecl *CurDecl;
991  if (SS && SS->isSet() && !SS->isInvalid()) {
992    DeclContext *DC = computeDeclContext(*SS, true);
993    CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
994  } else
995    CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
996
997  if (CurDecl && CurDecl->getIdentifier())
998    return &II == CurDecl->getIdentifier();
999  else
1000    return false;
1001}
1002
1003/// \brief Check the validity of a C++ base class specifier.
1004///
1005/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1006/// and returns NULL otherwise.
1007CXXBaseSpecifier *
1008Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1009                         SourceRange SpecifierRange,
1010                         bool Virtual, AccessSpecifier Access,
1011                         TypeSourceInfo *TInfo,
1012                         SourceLocation EllipsisLoc) {
1013  QualType BaseType = TInfo->getType();
1014
1015  // C++ [class.union]p1:
1016  //   A union shall not have base classes.
1017  if (Class->isUnion()) {
1018    Diag(Class->getLocation(), diag::err_base_clause_on_union)
1019      << SpecifierRange;
1020    return 0;
1021  }
1022
1023  if (EllipsisLoc.isValid() &&
1024      !TInfo->getType()->containsUnexpandedParameterPack()) {
1025    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1026      << TInfo->getTypeLoc().getSourceRange();
1027    EllipsisLoc = SourceLocation();
1028  }
1029
1030  if (BaseType->isDependentType())
1031    return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1032                                          Class->getTagKind() == TTK_Class,
1033                                          Access, TInfo, EllipsisLoc);
1034
1035  SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1036
1037  // Base specifiers must be record types.
1038  if (!BaseType->isRecordType()) {
1039    Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1040    return 0;
1041  }
1042
1043  // C++ [class.union]p1:
1044  //   A union shall not be used as a base class.
1045  if (BaseType->isUnionType()) {
1046    Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1047    return 0;
1048  }
1049
1050  // C++ [class.derived]p2:
1051  //   The class-name in a base-specifier shall not be an incompletely
1052  //   defined class.
1053  if (RequireCompleteType(BaseLoc, BaseType,
1054                          PDiag(diag::err_incomplete_base_class)
1055                            << SpecifierRange)) {
1056    Class->setInvalidDecl();
1057    return 0;
1058  }
1059
1060  // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
1061  RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
1062  assert(BaseDecl && "Record type has no declaration");
1063  BaseDecl = BaseDecl->getDefinition();
1064  assert(BaseDecl && "Base type is not incomplete, but has no definition");
1065  CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1066  assert(CXXBaseDecl && "Base type is not a C++ type");
1067
1068  // C++ [class]p3:
1069  //   If a class is marked final and it appears as a base-type-specifier in
1070  //   base-clause, the program is ill-formed.
1071  if (CXXBaseDecl->hasAttr<FinalAttr>()) {
1072    Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1073      << CXXBaseDecl->getDeclName();
1074    Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1075      << CXXBaseDecl->getDeclName();
1076    return 0;
1077  }
1078
1079  if (BaseDecl->isInvalidDecl())
1080    Class->setInvalidDecl();
1081
1082  // Create the base specifier.
1083  return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1084                                        Class->getTagKind() == TTK_Class,
1085                                        Access, TInfo, EllipsisLoc);
1086}
1087
1088/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1089/// one entry in the base class list of a class specifier, for
1090/// example:
1091///    class foo : public bar, virtual private baz {
1092/// 'public bar' and 'virtual private baz' are each base-specifiers.
1093BaseResult
1094Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1095                         bool Virtual, AccessSpecifier Access,
1096                         ParsedType basetype, SourceLocation BaseLoc,
1097                         SourceLocation EllipsisLoc) {
1098  if (!classdecl)
1099    return true;
1100
1101  AdjustDeclIfTemplate(classdecl);
1102  CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1103  if (!Class)
1104    return true;
1105
1106  TypeSourceInfo *TInfo = 0;
1107  GetTypeFromParser(basetype, &TInfo);
1108
1109  if (EllipsisLoc.isInvalid() &&
1110      DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1111                                      UPPC_BaseType))
1112    return true;
1113
1114  if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1115                                                      Virtual, Access, TInfo,
1116                                                      EllipsisLoc))
1117    return BaseSpec;
1118
1119  return true;
1120}
1121
1122/// \brief Performs the actual work of attaching the given base class
1123/// specifiers to a C++ class.
1124bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1125                                unsigned NumBases) {
1126 if (NumBases == 0)
1127    return false;
1128
1129  // Used to keep track of which base types we have already seen, so
1130  // that we can properly diagnose redundant direct base types. Note
1131  // that the key is always the unqualified canonical type of the base
1132  // class.
1133  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1134
1135  // Copy non-redundant base specifiers into permanent storage.
1136  unsigned NumGoodBases = 0;
1137  bool Invalid = false;
1138  for (unsigned idx = 0; idx < NumBases; ++idx) {
1139    QualType NewBaseType
1140      = Context.getCanonicalType(Bases[idx]->getType());
1141    NewBaseType = NewBaseType.getLocalUnqualifiedType();
1142
1143    CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
1144    if (KnownBase) {
1145      // C++ [class.mi]p3:
1146      //   A class shall not be specified as a direct base class of a
1147      //   derived class more than once.
1148      Diag(Bases[idx]->getLocStart(),
1149           diag::err_duplicate_base_class)
1150        << KnownBase->getType()
1151        << Bases[idx]->getSourceRange();
1152
1153      // Delete the duplicate base class specifier; we're going to
1154      // overwrite its pointer later.
1155      Context.Deallocate(Bases[idx]);
1156
1157      Invalid = true;
1158    } else {
1159      // Okay, add this new base class.
1160      KnownBase = Bases[idx];
1161      Bases[NumGoodBases++] = Bases[idx];
1162      if (const RecordType *Record = NewBaseType->getAs<RecordType>())
1163        if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1164          if (RD->hasAttr<WeakAttr>())
1165            Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
1166    }
1167  }
1168
1169  // Attach the remaining base class specifiers to the derived class.
1170  Class->setBases(Bases, NumGoodBases);
1171
1172  // Delete the remaining (good) base class specifiers, since their
1173  // data has been copied into the CXXRecordDecl.
1174  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1175    Context.Deallocate(Bases[idx]);
1176
1177  return Invalid;
1178}
1179
1180/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1181/// class, after checking whether there are any duplicate base
1182/// classes.
1183void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1184                               unsigned NumBases) {
1185  if (!ClassDecl || !Bases || !NumBases)
1186    return;
1187
1188  AdjustDeclIfTemplate(ClassDecl);
1189  AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1190                       (CXXBaseSpecifier**)(Bases), NumBases);
1191}
1192
1193static CXXRecordDecl *GetClassForType(QualType T) {
1194  if (const RecordType *RT = T->getAs<RecordType>())
1195    return cast<CXXRecordDecl>(RT->getDecl());
1196  else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1197    return ICT->getDecl();
1198  else
1199    return 0;
1200}
1201
1202/// \brief Determine whether the type \p Derived is a C++ class that is
1203/// derived from the type \p Base.
1204bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1205  if (!getLangOpts().CPlusPlus)
1206    return false;
1207
1208  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1209  if (!DerivedRD)
1210    return false;
1211
1212  CXXRecordDecl *BaseRD = GetClassForType(Base);
1213  if (!BaseRD)
1214    return false;
1215
1216  // FIXME: instantiate DerivedRD if necessary.  We need a PoI for this.
1217  return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1218}
1219
1220/// \brief Determine whether the type \p Derived is a C++ class that is
1221/// derived from the type \p Base.
1222bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1223  if (!getLangOpts().CPlusPlus)
1224    return false;
1225
1226  CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1227  if (!DerivedRD)
1228    return false;
1229
1230  CXXRecordDecl *BaseRD = GetClassForType(Base);
1231  if (!BaseRD)
1232    return false;
1233
1234  return DerivedRD->isDerivedFrom(BaseRD, Paths);
1235}
1236
1237void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1238                              CXXCastPath &BasePathArray) {
1239  assert(BasePathArray.empty() && "Base path array must be empty!");
1240  assert(Paths.isRecordingPaths() && "Must record paths!");
1241
1242  const CXXBasePath &Path = Paths.front();
1243
1244  // We first go backward and check if we have a virtual base.
1245  // FIXME: It would be better if CXXBasePath had the base specifier for
1246  // the nearest virtual base.
1247  unsigned Start = 0;
1248  for (unsigned I = Path.size(); I != 0; --I) {
1249    if (Path[I - 1].Base->isVirtual()) {
1250      Start = I - 1;
1251      break;
1252    }
1253  }
1254
1255  // Now add all bases.
1256  for (unsigned I = Start, E = Path.size(); I != E; ++I)
1257    BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1258}
1259
1260/// \brief Determine whether the given base path includes a virtual
1261/// base class.
1262bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1263  for (CXXCastPath::const_iterator B = BasePath.begin(),
1264                                BEnd = BasePath.end();
1265       B != BEnd; ++B)
1266    if ((*B)->isVirtual())
1267      return true;
1268
1269  return false;
1270}
1271
1272/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1273/// conversion (where Derived and Base are class types) is
1274/// well-formed, meaning that the conversion is unambiguous (and
1275/// that all of the base classes are accessible). Returns true
1276/// and emits a diagnostic if the code is ill-formed, returns false
1277/// otherwise. Loc is the location where this routine should point to
1278/// if there is an error, and Range is the source range to highlight
1279/// if there is an error.
1280bool
1281Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1282                                   unsigned InaccessibleBaseID,
1283                                   unsigned AmbigiousBaseConvID,
1284                                   SourceLocation Loc, SourceRange Range,
1285                                   DeclarationName Name,
1286                                   CXXCastPath *BasePath) {
1287  // First, determine whether the path from Derived to Base is
1288  // ambiguous. This is slightly more expensive than checking whether
1289  // the Derived to Base conversion exists, because here we need to
1290  // explore multiple paths to determine if there is an ambiguity.
1291  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1292                     /*DetectVirtual=*/false);
1293  bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1294  assert(DerivationOkay &&
1295         "Can only be used with a derived-to-base conversion");
1296  (void)DerivationOkay;
1297
1298  if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1299    if (InaccessibleBaseID) {
1300      // Check that the base class can be accessed.
1301      switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1302                                   InaccessibleBaseID)) {
1303        case AR_inaccessible:
1304          return true;
1305        case AR_accessible:
1306        case AR_dependent:
1307        case AR_delayed:
1308          break;
1309      }
1310    }
1311
1312    // Build a base path if necessary.
1313    if (BasePath)
1314      BuildBasePathArray(Paths, *BasePath);
1315    return false;
1316  }
1317
1318  // We know that the derived-to-base conversion is ambiguous, and
1319  // we're going to produce a diagnostic. Perform the derived-to-base
1320  // search just one more time to compute all of the possible paths so
1321  // that we can print them out. This is more expensive than any of
1322  // the previous derived-to-base checks we've done, but at this point
1323  // performance isn't as much of an issue.
1324  Paths.clear();
1325  Paths.setRecordingPaths(true);
1326  bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1327  assert(StillOkay && "Can only be used with a derived-to-base conversion");
1328  (void)StillOkay;
1329
1330  // Build up a textual representation of the ambiguous paths, e.g.,
1331  // D -> B -> A, that will be used to illustrate the ambiguous
1332  // conversions in the diagnostic. We only print one of the paths
1333  // to each base class subobject.
1334  std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1335
1336  Diag(Loc, AmbigiousBaseConvID)
1337  << Derived << Base << PathDisplayStr << Range << Name;
1338  return true;
1339}
1340
1341bool
1342Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1343                                   SourceLocation Loc, SourceRange Range,
1344                                   CXXCastPath *BasePath,
1345                                   bool IgnoreAccess) {
1346  return CheckDerivedToBaseConversion(Derived, Base,
1347                                      IgnoreAccess ? 0
1348                                       : diag::err_upcast_to_inaccessible_base,
1349                                      diag::err_ambiguous_derived_to_base_conv,
1350                                      Loc, Range, DeclarationName(),
1351                                      BasePath);
1352}
1353
1354
1355/// @brief Builds a string representing ambiguous paths from a
1356/// specific derived class to different subobjects of the same base
1357/// class.
1358///
1359/// This function builds a string that can be used in error messages
1360/// to show the different paths that one can take through the
1361/// inheritance hierarchy to go from the derived class to different
1362/// subobjects of a base class. The result looks something like this:
1363/// @code
1364/// struct D -> struct B -> struct A
1365/// struct D -> struct C -> struct A
1366/// @endcode
1367std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1368  std::string PathDisplayStr;
1369  std::set<unsigned> DisplayedPaths;
1370  for (CXXBasePaths::paths_iterator Path = Paths.begin();
1371       Path != Paths.end(); ++Path) {
1372    if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1373      // We haven't displayed a path to this particular base
1374      // class subobject yet.
1375      PathDisplayStr += "\n    ";
1376      PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1377      for (CXXBasePath::const_iterator Element = Path->begin();
1378           Element != Path->end(); ++Element)
1379        PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1380    }
1381  }
1382
1383  return PathDisplayStr;
1384}
1385
1386//===----------------------------------------------------------------------===//
1387// C++ class member Handling
1388//===----------------------------------------------------------------------===//
1389
1390/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1391bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1392                                SourceLocation ASLoc,
1393                                SourceLocation ColonLoc,
1394                                AttributeList *Attrs) {
1395  assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1396  AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1397                                                  ASLoc, ColonLoc);
1398  CurContext->addHiddenDecl(ASDecl);
1399  return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1400}
1401
1402/// CheckOverrideControl - Check C++0x override control semantics.
1403void Sema::CheckOverrideControl(const Decl *D) {
1404  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1405  if (!MD || !MD->isVirtual())
1406    return;
1407
1408  if (MD->isDependentContext())
1409    return;
1410
1411  // C++0x [class.virtual]p3:
1412  //   If a virtual function is marked with the virt-specifier override and does
1413  //   not override a member function of a base class,
1414  //   the program is ill-formed.
1415  bool HasOverriddenMethods =
1416    MD->begin_overridden_methods() != MD->end_overridden_methods();
1417  if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1418    Diag(MD->getLocation(),
1419                 diag::err_function_marked_override_not_overriding)
1420      << MD->getDeclName();
1421    return;
1422  }
1423}
1424
1425/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1426/// function overrides a virtual member function marked 'final', according to
1427/// C++0x [class.virtual]p3.
1428bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1429                                                  const CXXMethodDecl *Old) {
1430  if (!Old->hasAttr<FinalAttr>())
1431    return false;
1432
1433  Diag(New->getLocation(), diag::err_final_function_overridden)
1434    << New->getDeclName();
1435  Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1436  return true;
1437}
1438
1439/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1440/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1441/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1442/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1443/// present but parsing it has been deferred.
1444Decl *
1445Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1446                               MultiTemplateParamsArg TemplateParameterLists,
1447                               Expr *BW, const VirtSpecifiers &VS,
1448                               bool HasDeferredInit) {
1449  const DeclSpec &DS = D.getDeclSpec();
1450  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1451  DeclarationName Name = NameInfo.getName();
1452  SourceLocation Loc = NameInfo.getLoc();
1453
1454  // For anonymous bitfields, the location should point to the type.
1455  if (Loc.isInvalid())
1456    Loc = D.getLocStart();
1457
1458  Expr *BitWidth = static_cast<Expr*>(BW);
1459
1460  assert(isa<CXXRecordDecl>(CurContext));
1461  assert(!DS.isFriendSpecified());
1462
1463  bool isFunc = D.isDeclarationOfFunction();
1464
1465  // C++ 9.2p6: A member shall not be declared to have automatic storage
1466  // duration (auto, register) or with the extern storage-class-specifier.
1467  // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1468  // data members and cannot be applied to names declared const or static,
1469  // and cannot be applied to reference members.
1470  switch (DS.getStorageClassSpec()) {
1471    case DeclSpec::SCS_unspecified:
1472    case DeclSpec::SCS_typedef:
1473    case DeclSpec::SCS_static:
1474      // FALL THROUGH.
1475      break;
1476    case DeclSpec::SCS_mutable:
1477      if (isFunc) {
1478        if (DS.getStorageClassSpecLoc().isValid())
1479          Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1480        else
1481          Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1482
1483        // FIXME: It would be nicer if the keyword was ignored only for this
1484        // declarator. Otherwise we could get follow-up errors.
1485        D.getMutableDeclSpec().ClearStorageClassSpecs();
1486      }
1487      break;
1488    default:
1489      if (DS.getStorageClassSpecLoc().isValid())
1490        Diag(DS.getStorageClassSpecLoc(),
1491             diag::err_storageclass_invalid_for_member);
1492      else
1493        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1494      D.getMutableDeclSpec().ClearStorageClassSpecs();
1495  }
1496
1497  bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1498                       DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1499                      !isFunc);
1500
1501  Decl *Member;
1502  if (isInstField) {
1503    CXXScopeSpec &SS = D.getCXXScopeSpec();
1504
1505    // Data members must have identifiers for names.
1506    if (Name.getNameKind() != DeclarationName::Identifier) {
1507      Diag(Loc, diag::err_bad_variable_name)
1508        << Name;
1509      return 0;
1510    }
1511
1512    IdentifierInfo *II = Name.getAsIdentifierInfo();
1513
1514    // Member field could not be with "template" keyword.
1515    // So TemplateParameterLists should be empty in this case.
1516    if (TemplateParameterLists.size()) {
1517      TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1518      if (TemplateParams->size()) {
1519        // There is no such thing as a member field template.
1520        Diag(D.getIdentifierLoc(), diag::err_template_member)
1521            << II
1522            << SourceRange(TemplateParams->getTemplateLoc(),
1523                TemplateParams->getRAngleLoc());
1524      } else {
1525        // There is an extraneous 'template<>' for this member.
1526        Diag(TemplateParams->getTemplateLoc(),
1527            diag::err_template_member_noparams)
1528            << II
1529            << SourceRange(TemplateParams->getTemplateLoc(),
1530                TemplateParams->getRAngleLoc());
1531      }
1532      return 0;
1533    }
1534
1535    if (SS.isSet() && !SS.isInvalid()) {
1536      // The user provided a superfluous scope specifier inside a class
1537      // definition:
1538      //
1539      // class X {
1540      //   int X::member;
1541      // };
1542      if (DeclContext *DC = computeDeclContext(SS, false))
1543        diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
1544      else
1545        Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1546          << Name << SS.getRange();
1547
1548      SS.clear();
1549    }
1550
1551    Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1552                         HasDeferredInit, AS);
1553    assert(Member && "HandleField never returns null");
1554  } else {
1555    assert(!HasDeferredInit);
1556
1557    Member = HandleDeclarator(S, D, move(TemplateParameterLists));
1558    if (!Member) {
1559      return 0;
1560    }
1561
1562    // Non-instance-fields can't have a bitfield.
1563    if (BitWidth) {
1564      if (Member->isInvalidDecl()) {
1565        // don't emit another diagnostic.
1566      } else if (isa<VarDecl>(Member)) {
1567        // C++ 9.6p3: A bit-field shall not be a static member.
1568        // "static member 'A' cannot be a bit-field"
1569        Diag(Loc, diag::err_static_not_bitfield)
1570          << Name << BitWidth->getSourceRange();
1571      } else if (isa<TypedefDecl>(Member)) {
1572        // "typedef member 'x' cannot be a bit-field"
1573        Diag(Loc, diag::err_typedef_not_bitfield)
1574          << Name << BitWidth->getSourceRange();
1575      } else {
1576        // A function typedef ("typedef int f(); f a;").
1577        // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1578        Diag(Loc, diag::err_not_integral_type_bitfield)
1579          << Name << cast<ValueDecl>(Member)->getType()
1580          << BitWidth->getSourceRange();
1581      }
1582
1583      BitWidth = 0;
1584      Member->setInvalidDecl();
1585    }
1586
1587    Member->setAccess(AS);
1588
1589    // If we have declared a member function template, set the access of the
1590    // templated declaration as well.
1591    if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1592      FunTmpl->getTemplatedDecl()->setAccess(AS);
1593  }
1594
1595  if (VS.isOverrideSpecified()) {
1596    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1597    if (!MD || !MD->isVirtual()) {
1598      Diag(Member->getLocStart(),
1599           diag::override_keyword_only_allowed_on_virtual_member_functions)
1600        << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1601    } else
1602      MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1603  }
1604  if (VS.isFinalSpecified()) {
1605    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1606    if (!MD || !MD->isVirtual()) {
1607      Diag(Member->getLocStart(),
1608           diag::override_keyword_only_allowed_on_virtual_member_functions)
1609      << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1610    } else
1611      MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1612  }
1613
1614  if (VS.getLastLocation().isValid()) {
1615    // Update the end location of a method that has a virt-specifiers.
1616    if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1617      MD->setRangeEnd(VS.getLastLocation());
1618  }
1619
1620  CheckOverrideControl(Member);
1621
1622  assert((Name || isInstField) && "No identifier for non-field ?");
1623
1624  if (isInstField)
1625    FieldCollector->Add(cast<FieldDecl>(Member));
1626  return Member;
1627}
1628
1629/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1630/// in-class initializer for a non-static C++ class member, and after
1631/// instantiating an in-class initializer in a class template. Such actions
1632/// are deferred until the class is complete.
1633void
1634Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1635                                       Expr *InitExpr) {
1636  FieldDecl *FD = cast<FieldDecl>(D);
1637
1638  if (!InitExpr) {
1639    FD->setInvalidDecl();
1640    FD->removeInClassInitializer();
1641    return;
1642  }
1643
1644  if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1645    FD->setInvalidDecl();
1646    FD->removeInClassInitializer();
1647    return;
1648  }
1649
1650  ExprResult Init = InitExpr;
1651  if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1652    if (isa<InitListExpr>(InitExpr) && isStdInitializerList(FD->getType(), 0)) {
1653      Diag(FD->getLocation(), diag::warn_dangling_std_initializer_list)
1654        << /*at end of ctor*/1 << InitExpr->getSourceRange();
1655    }
1656    Expr **Inits = &InitExpr;
1657    unsigned NumInits = 1;
1658    InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
1659    InitializationKind Kind = EqualLoc.isInvalid()
1660        ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
1661        : InitializationKind::CreateCopy(InitExpr->getLocStart(), EqualLoc);
1662    InitializationSequence Seq(*this, Entity, Kind, Inits, NumInits);
1663    Init = Seq.Perform(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1664    if (Init.isInvalid()) {
1665      FD->setInvalidDecl();
1666      return;
1667    }
1668
1669    CheckImplicitConversions(Init.get(), EqualLoc);
1670  }
1671
1672  // C++0x [class.base.init]p7:
1673  //   The initialization of each base and member constitutes a
1674  //   full-expression.
1675  Init = MaybeCreateExprWithCleanups(Init);
1676  if (Init.isInvalid()) {
1677    FD->setInvalidDecl();
1678    return;
1679  }
1680
1681  InitExpr = Init.release();
1682
1683  FD->setInClassInitializer(InitExpr);
1684}
1685
1686/// \brief Find the direct and/or virtual base specifiers that
1687/// correspond to the given base type, for use in base initialization
1688/// within a constructor.
1689static bool FindBaseInitializer(Sema &SemaRef,
1690                                CXXRecordDecl *ClassDecl,
1691                                QualType BaseType,
1692                                const CXXBaseSpecifier *&DirectBaseSpec,
1693                                const CXXBaseSpecifier *&VirtualBaseSpec) {
1694  // First, check for a direct base class.
1695  DirectBaseSpec = 0;
1696  for (CXXRecordDecl::base_class_const_iterator Base
1697         = ClassDecl->bases_begin();
1698       Base != ClassDecl->bases_end(); ++Base) {
1699    if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1700      // We found a direct base of this type. That's what we're
1701      // initializing.
1702      DirectBaseSpec = &*Base;
1703      break;
1704    }
1705  }
1706
1707  // Check for a virtual base class.
1708  // FIXME: We might be able to short-circuit this if we know in advance that
1709  // there are no virtual bases.
1710  VirtualBaseSpec = 0;
1711  if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1712    // We haven't found a base yet; search the class hierarchy for a
1713    // virtual base class.
1714    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1715                       /*DetectVirtual=*/false);
1716    if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1717                              BaseType, Paths)) {
1718      for (CXXBasePaths::paths_iterator Path = Paths.begin();
1719           Path != Paths.end(); ++Path) {
1720        if (Path->back().Base->isVirtual()) {
1721          VirtualBaseSpec = Path->back().Base;
1722          break;
1723        }
1724      }
1725    }
1726  }
1727
1728  return DirectBaseSpec || VirtualBaseSpec;
1729}
1730
1731/// \brief Handle a C++ member initializer using braced-init-list syntax.
1732MemInitResult
1733Sema::ActOnMemInitializer(Decl *ConstructorD,
1734                          Scope *S,
1735                          CXXScopeSpec &SS,
1736                          IdentifierInfo *MemberOrBase,
1737                          ParsedType TemplateTypeTy,
1738                          const DeclSpec &DS,
1739                          SourceLocation IdLoc,
1740                          Expr *InitList,
1741                          SourceLocation EllipsisLoc) {
1742  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1743                             DS, IdLoc, InitList,
1744                             EllipsisLoc);
1745}
1746
1747/// \brief Handle a C++ member initializer using parentheses syntax.
1748MemInitResult
1749Sema::ActOnMemInitializer(Decl *ConstructorD,
1750                          Scope *S,
1751                          CXXScopeSpec &SS,
1752                          IdentifierInfo *MemberOrBase,
1753                          ParsedType TemplateTypeTy,
1754                          const DeclSpec &DS,
1755                          SourceLocation IdLoc,
1756                          SourceLocation LParenLoc,
1757                          Expr **Args, unsigned NumArgs,
1758                          SourceLocation RParenLoc,
1759                          SourceLocation EllipsisLoc) {
1760  Expr *List = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1761                                           RParenLoc);
1762  return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1763                             DS, IdLoc, List, EllipsisLoc);
1764}
1765
1766namespace {
1767
1768// Callback to only accept typo corrections that can be a valid C++ member
1769// intializer: either a non-static field member or a base class.
1770class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1771 public:
1772  explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1773      : ClassDecl(ClassDecl) {}
1774
1775  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1776    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1777      if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1778        return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1779      else
1780        return isa<TypeDecl>(ND);
1781    }
1782    return false;
1783  }
1784
1785 private:
1786  CXXRecordDecl *ClassDecl;
1787};
1788
1789}
1790
1791/// \brief Handle a C++ member initializer.
1792MemInitResult
1793Sema::BuildMemInitializer(Decl *ConstructorD,
1794                          Scope *S,
1795                          CXXScopeSpec &SS,
1796                          IdentifierInfo *MemberOrBase,
1797                          ParsedType TemplateTypeTy,
1798                          const DeclSpec &DS,
1799                          SourceLocation IdLoc,
1800                          Expr *Init,
1801                          SourceLocation EllipsisLoc) {
1802  if (!ConstructorD)
1803    return true;
1804
1805  AdjustDeclIfTemplate(ConstructorD);
1806
1807  CXXConstructorDecl *Constructor
1808    = dyn_cast<CXXConstructorDecl>(ConstructorD);
1809  if (!Constructor) {
1810    // The user wrote a constructor initializer on a function that is
1811    // not a C++ constructor. Ignore the error for now, because we may
1812    // have more member initializers coming; we'll diagnose it just
1813    // once in ActOnMemInitializers.
1814    return true;
1815  }
1816
1817  CXXRecordDecl *ClassDecl = Constructor->getParent();
1818
1819  // C++ [class.base.init]p2:
1820  //   Names in a mem-initializer-id are looked up in the scope of the
1821  //   constructor's class and, if not found in that scope, are looked
1822  //   up in the scope containing the constructor's definition.
1823  //   [Note: if the constructor's class contains a member with the
1824  //   same name as a direct or virtual base class of the class, a
1825  //   mem-initializer-id naming the member or base class and composed
1826  //   of a single identifier refers to the class member. A
1827  //   mem-initializer-id for the hidden base class may be specified
1828  //   using a qualified name. ]
1829  if (!SS.getScopeRep() && !TemplateTypeTy) {
1830    // Look for a member, first.
1831    DeclContext::lookup_result Result
1832      = ClassDecl->lookup(MemberOrBase);
1833    if (Result.first != Result.second) {
1834      ValueDecl *Member;
1835      if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1836          (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
1837        if (EllipsisLoc.isValid())
1838          Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1839            << MemberOrBase
1840            << SourceRange(IdLoc, Init->getSourceRange().getEnd());
1841
1842        return BuildMemberInitializer(Member, Init, IdLoc);
1843      }
1844    }
1845  }
1846  // It didn't name a member, so see if it names a class.
1847  QualType BaseType;
1848  TypeSourceInfo *TInfo = 0;
1849
1850  if (TemplateTypeTy) {
1851    BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1852  } else if (DS.getTypeSpecType() == TST_decltype) {
1853    BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
1854  } else {
1855    LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1856    LookupParsedName(R, S, &SS);
1857
1858    TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1859    if (!TyD) {
1860      if (R.isAmbiguous()) return true;
1861
1862      // We don't want access-control diagnostics here.
1863      R.suppressDiagnostics();
1864
1865      if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1866        bool NotUnknownSpecialization = false;
1867        DeclContext *DC = computeDeclContext(SS, false);
1868        if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1869          NotUnknownSpecialization = !Record->hasAnyDependentBases();
1870
1871        if (!NotUnknownSpecialization) {
1872          // When the scope specifier can refer to a member of an unknown
1873          // specialization, we take it as a type name.
1874          BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1875                                       SS.getWithLocInContext(Context),
1876                                       *MemberOrBase, IdLoc);
1877          if (BaseType.isNull())
1878            return true;
1879
1880          R.clear();
1881          R.setLookupName(MemberOrBase);
1882        }
1883      }
1884
1885      // If no results were found, try to correct typos.
1886      TypoCorrection Corr;
1887      MemInitializerValidatorCCC Validator(ClassDecl);
1888      if (R.empty() && BaseType.isNull() &&
1889          (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1890                              Validator, ClassDecl))) {
1891        std::string CorrectedStr(Corr.getAsString(getLangOpts()));
1892        std::string CorrectedQuotedStr(Corr.getQuoted(getLangOpts()));
1893        if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1894          // We have found a non-static data member with a similar
1895          // name to what was typed; complain and initialize that
1896          // member.
1897          Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1898            << MemberOrBase << true << CorrectedQuotedStr
1899            << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1900          Diag(Member->getLocation(), diag::note_previous_decl)
1901            << CorrectedQuotedStr;
1902
1903          return BuildMemberInitializer(Member, Init, IdLoc);
1904        } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1905          const CXXBaseSpecifier *DirectBaseSpec;
1906          const CXXBaseSpecifier *VirtualBaseSpec;
1907          if (FindBaseInitializer(*this, ClassDecl,
1908                                  Context.getTypeDeclType(Type),
1909                                  DirectBaseSpec, VirtualBaseSpec)) {
1910            // We have found a direct or virtual base class with a
1911            // similar name to what was typed; complain and initialize
1912            // that base class.
1913            Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1914              << MemberOrBase << false << CorrectedQuotedStr
1915              << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1916
1917            const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1918                                                             : VirtualBaseSpec;
1919            Diag(BaseSpec->getLocStart(),
1920                 diag::note_base_class_specified_here)
1921              << BaseSpec->getType()
1922              << BaseSpec->getSourceRange();
1923
1924            TyD = Type;
1925          }
1926        }
1927      }
1928
1929      if (!TyD && BaseType.isNull()) {
1930        Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1931          << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
1932        return true;
1933      }
1934    }
1935
1936    if (BaseType.isNull()) {
1937      BaseType = Context.getTypeDeclType(TyD);
1938      if (SS.isSet()) {
1939        NestedNameSpecifier *Qualifier =
1940          static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1941
1942        // FIXME: preserve source range information
1943        BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1944      }
1945    }
1946  }
1947
1948  if (!TInfo)
1949    TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1950
1951  return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
1952}
1953
1954/// Checks a member initializer expression for cases where reference (or
1955/// pointer) members are bound to by-value parameters (or their addresses).
1956static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1957                                               Expr *Init,
1958                                               SourceLocation IdLoc) {
1959  QualType MemberTy = Member->getType();
1960
1961  // We only handle pointers and references currently.
1962  // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1963  if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1964    return;
1965
1966  const bool IsPointer = MemberTy->isPointerType();
1967  if (IsPointer) {
1968    if (const UnaryOperator *Op
1969          = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1970      // The only case we're worried about with pointers requires taking the
1971      // address.
1972      if (Op->getOpcode() != UO_AddrOf)
1973        return;
1974
1975      Init = Op->getSubExpr();
1976    } else {
1977      // We only handle address-of expression initializers for pointers.
1978      return;
1979    }
1980  }
1981
1982  if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1983    // Taking the address of a temporary will be diagnosed as a hard error.
1984    if (IsPointer)
1985      return;
1986
1987    S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1988      << Member << Init->getSourceRange();
1989  } else if (const DeclRefExpr *DRE
1990               = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1991    // We only warn when referring to a non-reference parameter declaration.
1992    const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1993    if (!Parameter || Parameter->getType()->isReferenceType())
1994      return;
1995
1996    S.Diag(Init->getExprLoc(),
1997           IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1998                     : diag::warn_bind_ref_member_to_parameter)
1999      << Member << Parameter << Init->getSourceRange();
2000  } else {
2001    // Other initializers are fine.
2002    return;
2003  }
2004
2005  S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2006    << (unsigned)IsPointer;
2007}
2008
2009/// Checks an initializer expression for use of uninitialized fields, such as
2010/// containing the field that is being initialized. Returns true if there is an
2011/// uninitialized field was used an updates the SourceLocation parameter; false
2012/// otherwise.
2013static bool InitExprContainsUninitializedFields(const Stmt *S,
2014                                                const ValueDecl *LhsField,
2015                                                SourceLocation *L) {
2016  assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2017
2018  if (isa<CallExpr>(S)) {
2019    // Do not descend into function calls or constructors, as the use
2020    // of an uninitialized field may be valid. One would have to inspect
2021    // the contents of the function/ctor to determine if it is safe or not.
2022    // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2023    // may be safe, depending on what the function/ctor does.
2024    return false;
2025  }
2026  if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2027    const NamedDecl *RhsField = ME->getMemberDecl();
2028
2029    if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2030      // The member expression points to a static data member.
2031      assert(VD->isStaticDataMember() &&
2032             "Member points to non-static data member!");
2033      (void)VD;
2034      return false;
2035    }
2036
2037    if (isa<EnumConstantDecl>(RhsField)) {
2038      // The member expression points to an enum.
2039      return false;
2040    }
2041
2042    if (RhsField == LhsField) {
2043      // Initializing a field with itself. Throw a warning.
2044      // But wait; there are exceptions!
2045      // Exception #1:  The field may not belong to this record.
2046      // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
2047      const Expr *base = ME->getBase();
2048      if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2049        // Even though the field matches, it does not belong to this record.
2050        return false;
2051      }
2052      // None of the exceptions triggered; return true to indicate an
2053      // uninitialized field was used.
2054      *L = ME->getMemberLoc();
2055      return true;
2056    }
2057  } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
2058    // sizeof/alignof doesn't reference contents, do not warn.
2059    return false;
2060  } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2061    // address-of doesn't reference contents (the pointer may be dereferenced
2062    // in the same expression but it would be rare; and weird).
2063    if (UOE->getOpcode() == UO_AddrOf)
2064      return false;
2065  }
2066  for (Stmt::const_child_range it = S->children(); it; ++it) {
2067    if (!*it) {
2068      // An expression such as 'member(arg ?: "")' may trigger this.
2069      continue;
2070    }
2071    if (InitExprContainsUninitializedFields(*it, LhsField, L))
2072      return true;
2073  }
2074  return false;
2075}
2076
2077MemInitResult
2078Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
2079                             SourceLocation IdLoc) {
2080  FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2081  IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2082  assert((DirectMember || IndirectMember) &&
2083         "Member must be a FieldDecl or IndirectFieldDecl");
2084
2085  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2086    return true;
2087
2088  if (Member->isInvalidDecl())
2089    return true;
2090
2091  // Diagnose value-uses of fields to initialize themselves, e.g.
2092  //   foo(foo)
2093  // where foo is not also a parameter to the constructor.
2094  // TODO: implement -Wuninitialized and fold this into that framework.
2095  Expr **Args;
2096  unsigned NumArgs;
2097  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2098    Args = ParenList->getExprs();
2099    NumArgs = ParenList->getNumExprs();
2100  } else {
2101    InitListExpr *InitList = cast<InitListExpr>(Init);
2102    Args = InitList->getInits();
2103    NumArgs = InitList->getNumInits();
2104  }
2105  for (unsigned i = 0; i < NumArgs; ++i) {
2106    SourceLocation L;
2107    if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
2108      // FIXME: Return true in the case when other fields are used before being
2109      // uninitialized. For example, let this field be the i'th field. When
2110      // initializing the i'th field, throw a warning if any of the >= i'th
2111      // fields are used, as they are not yet initialized.
2112      // Right now we are only handling the case where the i'th field uses
2113      // itself in its initializer.
2114      Diag(L, diag::warn_field_is_uninit);
2115    }
2116  }
2117
2118  SourceRange InitRange = Init->getSourceRange();
2119
2120  if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
2121    // Can't check initialization for a member of dependent type or when
2122    // any of the arguments are type-dependent expressions.
2123    DiscardCleanupsInEvaluationContext();
2124  } else {
2125    bool InitList = false;
2126    if (isa<InitListExpr>(Init)) {
2127      InitList = true;
2128      Args = &Init;
2129      NumArgs = 1;
2130
2131      if (isStdInitializerList(Member->getType(), 0)) {
2132        Diag(IdLoc, diag::warn_dangling_std_initializer_list)
2133            << /*at end of ctor*/1 << InitRange;
2134      }
2135    }
2136
2137    // Initialize the member.
2138    InitializedEntity MemberEntity =
2139      DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2140                   : InitializedEntity::InitializeMember(IndirectMember, 0);
2141    InitializationKind Kind =
2142      InitList ? InitializationKind::CreateDirectList(IdLoc)
2143               : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
2144                                                  InitRange.getEnd());
2145
2146    InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
2147    ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind,
2148                                            MultiExprArg(*this, Args, NumArgs),
2149                                            0);
2150    if (MemberInit.isInvalid())
2151      return true;
2152
2153    CheckImplicitConversions(MemberInit.get(),
2154                             InitRange.getBegin());
2155
2156    // C++0x [class.base.init]p7:
2157    //   The initialization of each base and member constitutes a
2158    //   full-expression.
2159    MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2160    if (MemberInit.isInvalid())
2161      return true;
2162
2163    // If we are in a dependent context, template instantiation will
2164    // perform this type-checking again. Just save the arguments that we
2165    // received.
2166    // FIXME: This isn't quite ideal, since our ASTs don't capture all
2167    // of the information that we have about the member
2168    // initializer. However, deconstructing the ASTs is a dicey process,
2169    // and this approach is far more likely to get the corner cases right.
2170    if (CurContext->isDependentContext()) {
2171      // The existing Init will do fine.
2172    } else {
2173      Init = MemberInit.get();
2174      CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2175    }
2176  }
2177
2178  if (DirectMember) {
2179    return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
2180                                            InitRange.getBegin(), Init,
2181                                            InitRange.getEnd());
2182  } else {
2183    return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
2184                                            InitRange.getBegin(), Init,
2185                                            InitRange.getEnd());
2186  }
2187}
2188
2189MemInitResult
2190Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
2191                                 CXXRecordDecl *ClassDecl) {
2192  SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2193  if (!LangOpts.CPlusPlus0x)
2194    return Diag(NameLoc, diag::err_delegating_ctor)
2195      << TInfo->getTypeLoc().getLocalSourceRange();
2196  Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
2197
2198  bool InitList = true;
2199  Expr **Args = &Init;
2200  unsigned NumArgs = 1;
2201  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2202    InitList = false;
2203    Args = ParenList->getExprs();
2204    NumArgs = ParenList->getNumExprs();
2205  }
2206
2207  SourceRange InitRange = Init->getSourceRange();
2208  // Initialize the object.
2209  InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2210                                     QualType(ClassDecl->getTypeForDecl(), 0));
2211  InitializationKind Kind =
2212    InitList ? InitializationKind::CreateDirectList(NameLoc)
2213             : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
2214                                                InitRange.getEnd());
2215  InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
2216  ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
2217                                              MultiExprArg(*this, Args,NumArgs),
2218                                              0);
2219  if (DelegationInit.isInvalid())
2220    return true;
2221
2222  assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2223         "Delegating constructor with no target?");
2224
2225  CheckImplicitConversions(DelegationInit.get(), InitRange.getBegin());
2226
2227  // C++0x [class.base.init]p7:
2228  //   The initialization of each base and member constitutes a
2229  //   full-expression.
2230  DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2231  if (DelegationInit.isInvalid())
2232    return true;
2233
2234  return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
2235                                          DelegationInit.takeAs<Expr>(),
2236                                          InitRange.getEnd());
2237}
2238
2239MemInitResult
2240Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2241                           Expr *Init, CXXRecordDecl *ClassDecl,
2242                           SourceLocation EllipsisLoc) {
2243  SourceLocation BaseLoc
2244    = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2245
2246  if (!BaseType->isDependentType() && !BaseType->isRecordType())
2247    return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2248             << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2249
2250  // C++ [class.base.init]p2:
2251  //   [...] Unless the mem-initializer-id names a nonstatic data
2252  //   member of the constructor's class or a direct or virtual base
2253  //   of that class, the mem-initializer is ill-formed. A
2254  //   mem-initializer-list can initialize a base class using any
2255  //   name that denotes that base class type.
2256  bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
2257
2258  SourceRange InitRange = Init->getSourceRange();
2259  if (EllipsisLoc.isValid()) {
2260    // This is a pack expansion.
2261    if (!BaseType->containsUnexpandedParameterPack())  {
2262      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2263        << SourceRange(BaseLoc, InitRange.getEnd());
2264
2265      EllipsisLoc = SourceLocation();
2266    }
2267  } else {
2268    // Check for any unexpanded parameter packs.
2269    if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2270      return true;
2271
2272    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
2273      return true;
2274  }
2275
2276  // Check for direct and virtual base classes.
2277  const CXXBaseSpecifier *DirectBaseSpec = 0;
2278  const CXXBaseSpecifier *VirtualBaseSpec = 0;
2279  if (!Dependent) {
2280    if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2281                                       BaseType))
2282      return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
2283
2284    FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2285                        VirtualBaseSpec);
2286
2287    // C++ [base.class.init]p2:
2288    // Unless the mem-initializer-id names a nonstatic data member of the
2289    // constructor's class or a direct or virtual base of that class, the
2290    // mem-initializer is ill-formed.
2291    if (!DirectBaseSpec && !VirtualBaseSpec) {
2292      // If the class has any dependent bases, then it's possible that
2293      // one of those types will resolve to the same type as
2294      // BaseType. Therefore, just treat this as a dependent base
2295      // class initialization.  FIXME: Should we try to check the
2296      // initialization anyway? It seems odd.
2297      if (ClassDecl->hasAnyDependentBases())
2298        Dependent = true;
2299      else
2300        return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2301          << BaseType << Context.getTypeDeclType(ClassDecl)
2302          << BaseTInfo->getTypeLoc().getLocalSourceRange();
2303    }
2304  }
2305
2306  if (Dependent) {
2307    DiscardCleanupsInEvaluationContext();
2308
2309    return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2310                                            /*IsVirtual=*/false,
2311                                            InitRange.getBegin(), Init,
2312                                            InitRange.getEnd(), EllipsisLoc);
2313  }
2314
2315  // C++ [base.class.init]p2:
2316  //   If a mem-initializer-id is ambiguous because it designates both
2317  //   a direct non-virtual base class and an inherited virtual base
2318  //   class, the mem-initializer is ill-formed.
2319  if (DirectBaseSpec && VirtualBaseSpec)
2320    return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2321      << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2322
2323  CXXBaseSpecifier *BaseSpec = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2324  if (!BaseSpec)
2325    BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2326
2327  // Initialize the base.
2328  bool InitList = true;
2329  Expr **Args = &Init;
2330  unsigned NumArgs = 1;
2331  if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
2332    InitList = false;
2333    Args = ParenList->getExprs();
2334    NumArgs = ParenList->getNumExprs();
2335  }
2336
2337  InitializedEntity BaseEntity =
2338    InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2339  InitializationKind Kind =
2340    InitList ? InitializationKind::CreateDirectList(BaseLoc)
2341             : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
2342                                                InitRange.getEnd());
2343  InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
2344  ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind,
2345                                          MultiExprArg(*this, Args, NumArgs),
2346                                          0);
2347  if (BaseInit.isInvalid())
2348    return true;
2349
2350  CheckImplicitConversions(BaseInit.get(), InitRange.getBegin());
2351
2352  // C++0x [class.base.init]p7:
2353  //   The initialization of each base and member constitutes a
2354  //   full-expression.
2355  BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2356  if (BaseInit.isInvalid())
2357    return true;
2358
2359  // If we are in a dependent context, template instantiation will
2360  // perform this type-checking again. Just save the arguments that we
2361  // received in a ParenListExpr.
2362  // FIXME: This isn't quite ideal, since our ASTs don't capture all
2363  // of the information that we have about the base
2364  // initializer. However, deconstructing the ASTs is a dicey process,
2365  // and this approach is far more likely to get the corner cases right.
2366  if (CurContext->isDependentContext())
2367    BaseInit = Owned(Init);
2368
2369  return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2370                                          BaseSpec->isVirtual(),
2371                                          InitRange.getBegin(),
2372                                          BaseInit.takeAs<Expr>(),
2373                                          InitRange.getEnd(), EllipsisLoc);
2374}
2375
2376// Create a static_cast\<T&&>(expr).
2377static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2378  QualType ExprType = E->getType();
2379  QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2380  SourceLocation ExprLoc = E->getLocStart();
2381  TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2382      TargetType, ExprLoc);
2383
2384  return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2385                                   SourceRange(ExprLoc, ExprLoc),
2386                                   E->getSourceRange()).take();
2387}
2388
2389/// ImplicitInitializerKind - How an implicit base or member initializer should
2390/// initialize its base or member.
2391enum ImplicitInitializerKind {
2392  IIK_Default,
2393  IIK_Copy,
2394  IIK_Move
2395};
2396
2397static bool
2398BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2399                             ImplicitInitializerKind ImplicitInitKind,
2400                             CXXBaseSpecifier *BaseSpec,
2401                             bool IsInheritedVirtualBase,
2402                             CXXCtorInitializer *&CXXBaseInit) {
2403  InitializedEntity InitEntity
2404    = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2405                                        IsInheritedVirtualBase);
2406
2407  ExprResult BaseInit;
2408
2409  switch (ImplicitInitKind) {
2410  case IIK_Default: {
2411    InitializationKind InitKind
2412      = InitializationKind::CreateDefault(Constructor->getLocation());
2413    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2414    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2415                               MultiExprArg(SemaRef, 0, 0));
2416    break;
2417  }
2418
2419  case IIK_Move:
2420  case IIK_Copy: {
2421    bool Moving = ImplicitInitKind == IIK_Move;
2422    ParmVarDecl *Param = Constructor->getParamDecl(0);
2423    QualType ParamType = Param->getType().getNonReferenceType();
2424
2425    Expr *CopyCtorArg =
2426      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2427                          SourceLocation(), Param, false,
2428                          Constructor->getLocation(), ParamType,
2429                          VK_LValue, 0);
2430
2431    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2432
2433    // Cast to the base class to avoid ambiguities.
2434    QualType ArgTy =
2435      SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2436                                       ParamType.getQualifiers());
2437
2438    if (Moving) {
2439      CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2440    }
2441
2442    CXXCastPath BasePath;
2443    BasePath.push_back(BaseSpec);
2444    CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2445                                            CK_UncheckedDerivedToBase,
2446                                            Moving ? VK_XValue : VK_LValue,
2447                                            &BasePath).take();
2448
2449    InitializationKind InitKind
2450      = InitializationKind::CreateDirect(Constructor->getLocation(),
2451                                         SourceLocation(), SourceLocation());
2452    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2453                                   &CopyCtorArg, 1);
2454    BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2455                               MultiExprArg(&CopyCtorArg, 1));
2456    break;
2457  }
2458  }
2459
2460  BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2461  if (BaseInit.isInvalid())
2462    return true;
2463
2464  CXXBaseInit =
2465    new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2466               SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2467                                                        SourceLocation()),
2468                                             BaseSpec->isVirtual(),
2469                                             SourceLocation(),
2470                                             BaseInit.takeAs<Expr>(),
2471                                             SourceLocation(),
2472                                             SourceLocation());
2473
2474  return false;
2475}
2476
2477static bool RefersToRValueRef(Expr *MemRef) {
2478  ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2479  return Referenced->getType()->isRValueReferenceType();
2480}
2481
2482static bool
2483BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2484                               ImplicitInitializerKind ImplicitInitKind,
2485                               FieldDecl *Field, IndirectFieldDecl *Indirect,
2486                               CXXCtorInitializer *&CXXMemberInit) {
2487  if (Field->isInvalidDecl())
2488    return true;
2489
2490  SourceLocation Loc = Constructor->getLocation();
2491
2492  if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2493    bool Moving = ImplicitInitKind == IIK_Move;
2494    ParmVarDecl *Param = Constructor->getParamDecl(0);
2495    QualType ParamType = Param->getType().getNonReferenceType();
2496
2497    // Suppress copying zero-width bitfields.
2498    if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2499      return false;
2500
2501    Expr *MemberExprBase =
2502      DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2503                          SourceLocation(), Param, false,
2504                          Loc, ParamType, VK_LValue, 0);
2505
2506    SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2507
2508    if (Moving) {
2509      MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2510    }
2511
2512    // Build a reference to this field within the parameter.
2513    CXXScopeSpec SS;
2514    LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2515                              Sema::LookupMemberName);
2516    MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2517                                  : cast<ValueDecl>(Field), AS_public);
2518    MemberLookup.resolveKind();
2519    ExprResult CtorArg
2520      = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2521                                         ParamType, Loc,
2522                                         /*IsArrow=*/false,
2523                                         SS,
2524                                         /*TemplateKWLoc=*/SourceLocation(),
2525                                         /*FirstQualifierInScope=*/0,
2526                                         MemberLookup,
2527                                         /*TemplateArgs=*/0);
2528    if (CtorArg.isInvalid())
2529      return true;
2530
2531    // C++11 [class.copy]p15:
2532    //   - if a member m has rvalue reference type T&&, it is direct-initialized
2533    //     with static_cast<T&&>(x.m);
2534    if (RefersToRValueRef(CtorArg.get())) {
2535      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2536    }
2537
2538    // When the field we are copying is an array, create index variables for
2539    // each dimension of the array. We use these index variables to subscript
2540    // the source array, and other clients (e.g., CodeGen) will perform the
2541    // necessary iteration with these index variables.
2542    SmallVector<VarDecl *, 4> IndexVariables;
2543    QualType BaseType = Field->getType();
2544    QualType SizeType = SemaRef.Context.getSizeType();
2545    bool InitializingArray = false;
2546    while (const ConstantArrayType *Array
2547                          = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2548      InitializingArray = true;
2549      // Create the iteration variable for this array index.
2550      IdentifierInfo *IterationVarName = 0;
2551      {
2552        SmallString<8> Str;
2553        llvm::raw_svector_ostream OS(Str);
2554        OS << "__i" << IndexVariables.size();
2555        IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2556      }
2557      VarDecl *IterationVar
2558        = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2559                          IterationVarName, SizeType,
2560                        SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2561                          SC_None, SC_None);
2562      IndexVariables.push_back(IterationVar);
2563
2564      // Create a reference to the iteration variable.
2565      ExprResult IterationVarRef
2566        = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
2567      assert(!IterationVarRef.isInvalid() &&
2568             "Reference to invented variable cannot fail!");
2569      IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2570      assert(!IterationVarRef.isInvalid() &&
2571             "Conversion of invented variable cannot fail!");
2572
2573      // Subscript the array with this iteration variable.
2574      CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2575                                                        IterationVarRef.take(),
2576                                                        Loc);
2577      if (CtorArg.isInvalid())
2578        return true;
2579
2580      BaseType = Array->getElementType();
2581    }
2582
2583    // The array subscript expression is an lvalue, which is wrong for moving.
2584    if (Moving && InitializingArray)
2585      CtorArg = CastForMoving(SemaRef, CtorArg.take());
2586
2587    // Construct the entity that we will be initializing. For an array, this
2588    // will be first element in the array, which may require several levels
2589    // of array-subscript entities.
2590    SmallVector<InitializedEntity, 4> Entities;
2591    Entities.reserve(1 + IndexVariables.size());
2592    if (Indirect)
2593      Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2594    else
2595      Entities.push_back(InitializedEntity::InitializeMember(Field));
2596    for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2597      Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2598                                                              0,
2599                                                              Entities.back()));
2600
2601    // Direct-initialize to use the copy constructor.
2602    InitializationKind InitKind =
2603      InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2604
2605    Expr *CtorArgE = CtorArg.takeAs<Expr>();
2606    InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2607                                   &CtorArgE, 1);
2608
2609    ExprResult MemberInit
2610      = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2611                        MultiExprArg(&CtorArgE, 1));
2612    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2613    if (MemberInit.isInvalid())
2614      return true;
2615
2616    if (Indirect) {
2617      assert(IndexVariables.size() == 0 &&
2618             "Indirect field improperly initialized");
2619      CXXMemberInit
2620        = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2621                                                   Loc, Loc,
2622                                                   MemberInit.takeAs<Expr>(),
2623                                                   Loc);
2624    } else
2625      CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2626                                                 Loc, MemberInit.takeAs<Expr>(),
2627                                                 Loc,
2628                                                 IndexVariables.data(),
2629                                                 IndexVariables.size());
2630    return false;
2631  }
2632
2633  assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2634
2635  QualType FieldBaseElementType =
2636    SemaRef.Context.getBaseElementType(Field->getType());
2637
2638  if (FieldBaseElementType->isRecordType()) {
2639    InitializedEntity InitEntity
2640      = Indirect? InitializedEntity::InitializeMember(Indirect)
2641                : InitializedEntity::InitializeMember(Field);
2642    InitializationKind InitKind =
2643      InitializationKind::CreateDefault(Loc);
2644
2645    InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2646    ExprResult MemberInit =
2647      InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2648
2649    MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2650    if (MemberInit.isInvalid())
2651      return true;
2652
2653    if (Indirect)
2654      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2655                                                               Indirect, Loc,
2656                                                               Loc,
2657                                                               MemberInit.get(),
2658                                                               Loc);
2659    else
2660      CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2661                                                               Field, Loc, Loc,
2662                                                               MemberInit.get(),
2663                                                               Loc);
2664    return false;
2665  }
2666
2667  if (!Field->getParent()->isUnion()) {
2668    if (FieldBaseElementType->isReferenceType()) {
2669      SemaRef.Diag(Constructor->getLocation(),
2670                   diag::err_uninitialized_member_in_ctor)
2671      << (int)Constructor->isImplicit()
2672      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2673      << 0 << Field->getDeclName();
2674      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2675      return true;
2676    }
2677
2678    if (FieldBaseElementType.isConstQualified()) {
2679      SemaRef.Diag(Constructor->getLocation(),
2680                   diag::err_uninitialized_member_in_ctor)
2681      << (int)Constructor->isImplicit()
2682      << SemaRef.Context.getTagDeclType(Constructor->getParent())
2683      << 1 << Field->getDeclName();
2684      SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2685      return true;
2686    }
2687  }
2688
2689  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2690      FieldBaseElementType->isObjCRetainableType() &&
2691      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2692      FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2693    // Instant objects:
2694    //   Default-initialize Objective-C pointers to NULL.
2695    CXXMemberInit
2696      = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2697                                                 Loc, Loc,
2698                 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2699                                                 Loc);
2700    return false;
2701  }
2702
2703  // Nothing to initialize.
2704  CXXMemberInit = 0;
2705  return false;
2706}
2707
2708namespace {
2709struct BaseAndFieldInfo {
2710  Sema &S;
2711  CXXConstructorDecl *Ctor;
2712  bool AnyErrorsInInits;
2713  ImplicitInitializerKind IIK;
2714  llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2715  SmallVector<CXXCtorInitializer*, 8> AllToInit;
2716
2717  BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2718    : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2719    bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2720    if (Generated && Ctor->isCopyConstructor())
2721      IIK = IIK_Copy;
2722    else if (Generated && Ctor->isMoveConstructor())
2723      IIK = IIK_Move;
2724    else
2725      IIK = IIK_Default;
2726  }
2727
2728  bool isImplicitCopyOrMove() const {
2729    switch (IIK) {
2730    case IIK_Copy:
2731    case IIK_Move:
2732      return true;
2733
2734    case IIK_Default:
2735      return false;
2736    }
2737
2738    llvm_unreachable("Invalid ImplicitInitializerKind!");
2739  }
2740};
2741}
2742
2743/// \brief Determine whether the given indirect field declaration is somewhere
2744/// within an anonymous union.
2745static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2746  for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2747                                      CEnd = F->chain_end();
2748       C != CEnd; ++C)
2749    if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2750      if (Record->isUnion())
2751        return true;
2752
2753  return false;
2754}
2755
2756/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2757/// array type.
2758static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2759  if (T->isIncompleteArrayType())
2760    return true;
2761
2762  while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2763    if (!ArrayT->getSize())
2764      return true;
2765
2766    T = ArrayT->getElementType();
2767  }
2768
2769  return false;
2770}
2771
2772static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2773                                    FieldDecl *Field,
2774                                    IndirectFieldDecl *Indirect = 0) {
2775
2776  // Overwhelmingly common case: we have a direct initializer for this field.
2777  if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2778    Info.AllToInit.push_back(Init);
2779    return false;
2780  }
2781
2782  // C++0x [class.base.init]p8: if the entity is a non-static data member that
2783  // has a brace-or-equal-initializer, the entity is initialized as specified
2784  // in [dcl.init].
2785  if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
2786    CXXCtorInitializer *Init;
2787    if (Indirect)
2788      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2789                                                      SourceLocation(),
2790                                                      SourceLocation(), 0,
2791                                                      SourceLocation());
2792    else
2793      Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2794                                                      SourceLocation(),
2795                                                      SourceLocation(), 0,
2796                                                      SourceLocation());
2797    Info.AllToInit.push_back(Init);
2798    return false;
2799  }
2800
2801  // Don't build an implicit initializer for union members if none was
2802  // explicitly specified.
2803  if (Field->getParent()->isUnion() ||
2804      (Indirect && isWithinAnonymousUnion(Indirect)))
2805    return false;
2806
2807  // Don't initialize incomplete or zero-length arrays.
2808  if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2809    return false;
2810
2811  // Don't try to build an implicit initializer if there were semantic
2812  // errors in any of the initializers (and therefore we might be
2813  // missing some that the user actually wrote).
2814  if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2815    return false;
2816
2817  CXXCtorInitializer *Init = 0;
2818  if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2819                                     Indirect, Init))
2820    return true;
2821
2822  if (Init)
2823    Info.AllToInit.push_back(Init);
2824
2825  return false;
2826}
2827
2828bool
2829Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2830                               CXXCtorInitializer *Initializer) {
2831  assert(Initializer->isDelegatingInitializer());
2832  Constructor->setNumCtorInitializers(1);
2833  CXXCtorInitializer **initializer =
2834    new (Context) CXXCtorInitializer*[1];
2835  memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2836  Constructor->setCtorInitializers(initializer);
2837
2838  if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2839    MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
2840    DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2841  }
2842
2843  DelegatingCtorDecls.push_back(Constructor);
2844
2845  return false;
2846}
2847
2848bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2849                               CXXCtorInitializer **Initializers,
2850                               unsigned NumInitializers,
2851                               bool AnyErrors) {
2852  if (Constructor->isDependentContext()) {
2853    // Just store the initializers as written, they will be checked during
2854    // instantiation.
2855    if (NumInitializers > 0) {
2856      Constructor->setNumCtorInitializers(NumInitializers);
2857      CXXCtorInitializer **baseOrMemberInitializers =
2858        new (Context) CXXCtorInitializer*[NumInitializers];
2859      memcpy(baseOrMemberInitializers, Initializers,
2860             NumInitializers * sizeof(CXXCtorInitializer*));
2861      Constructor->setCtorInitializers(baseOrMemberInitializers);
2862    }
2863
2864    return false;
2865  }
2866
2867  BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2868
2869  // We need to build the initializer AST according to order of construction
2870  // and not what user specified in the Initializers list.
2871  CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2872  if (!ClassDecl)
2873    return true;
2874
2875  bool HadError = false;
2876
2877  for (unsigned i = 0; i < NumInitializers; i++) {
2878    CXXCtorInitializer *Member = Initializers[i];
2879
2880    if (Member->isBaseInitializer())
2881      Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2882    else
2883      Info.AllBaseFields[Member->getAnyMember()] = Member;
2884  }
2885
2886  // Keep track of the direct virtual bases.
2887  llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2888  for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2889       E = ClassDecl->bases_end(); I != E; ++I) {
2890    if (I->isVirtual())
2891      DirectVBases.insert(I);
2892  }
2893
2894  // Push virtual bases before others.
2895  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2896       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2897
2898    if (CXXCtorInitializer *Value
2899        = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2900      Info.AllToInit.push_back(Value);
2901    } else if (!AnyErrors) {
2902      bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2903      CXXCtorInitializer *CXXBaseInit;
2904      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2905                                       VBase, IsInheritedVirtualBase,
2906                                       CXXBaseInit)) {
2907        HadError = true;
2908        continue;
2909      }
2910
2911      Info.AllToInit.push_back(CXXBaseInit);
2912    }
2913  }
2914
2915  // Non-virtual bases.
2916  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2917       E = ClassDecl->bases_end(); Base != E; ++Base) {
2918    // Virtuals are in the virtual base list and already constructed.
2919    if (Base->isVirtual())
2920      continue;
2921
2922    if (CXXCtorInitializer *Value
2923          = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2924      Info.AllToInit.push_back(Value);
2925    } else if (!AnyErrors) {
2926      CXXCtorInitializer *CXXBaseInit;
2927      if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2928                                       Base, /*IsInheritedVirtualBase=*/false,
2929                                       CXXBaseInit)) {
2930        HadError = true;
2931        continue;
2932      }
2933
2934      Info.AllToInit.push_back(CXXBaseInit);
2935    }
2936  }
2937
2938  // Fields.
2939  for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2940                               MemEnd = ClassDecl->decls_end();
2941       Mem != MemEnd; ++Mem) {
2942    if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2943      // C++ [class.bit]p2:
2944      //   A declaration for a bit-field that omits the identifier declares an
2945      //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
2946      //   initialized.
2947      if (F->isUnnamedBitfield())
2948        continue;
2949
2950      // If we're not generating the implicit copy/move constructor, then we'll
2951      // handle anonymous struct/union fields based on their individual
2952      // indirect fields.
2953      if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2954        continue;
2955
2956      if (CollectFieldInitializer(*this, Info, F))
2957        HadError = true;
2958      continue;
2959    }
2960
2961    // Beyond this point, we only consider default initialization.
2962    if (Info.IIK != IIK_Default)
2963      continue;
2964
2965    if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2966      if (F->getType()->isIncompleteArrayType()) {
2967        assert(ClassDecl->hasFlexibleArrayMember() &&
2968               "Incomplete array type is not valid");
2969        continue;
2970      }
2971
2972      // Initialize each field of an anonymous struct individually.
2973      if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2974        HadError = true;
2975
2976      continue;
2977    }
2978  }
2979
2980  NumInitializers = Info.AllToInit.size();
2981  if (NumInitializers > 0) {
2982    Constructor->setNumCtorInitializers(NumInitializers);
2983    CXXCtorInitializer **baseOrMemberInitializers =
2984      new (Context) CXXCtorInitializer*[NumInitializers];
2985    memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2986           NumInitializers * sizeof(CXXCtorInitializer*));
2987    Constructor->setCtorInitializers(baseOrMemberInitializers);
2988
2989    // Constructors implicitly reference the base and member
2990    // destructors.
2991    MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2992                                           Constructor->getParent());
2993  }
2994
2995  return HadError;
2996}
2997
2998static void *GetKeyForTopLevelField(FieldDecl *Field) {
2999  // For anonymous unions, use the class declaration as the key.
3000  if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
3001    if (RT->getDecl()->isAnonymousStructOrUnion())
3002      return static_cast<void *>(RT->getDecl());
3003  }
3004  return static_cast<void *>(Field);
3005}
3006
3007static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
3008  return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
3009}
3010
3011static void *GetKeyForMember(ASTContext &Context,
3012                             CXXCtorInitializer *Member) {
3013  if (!Member->isAnyMemberInitializer())
3014    return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
3015
3016  // For fields injected into the class via declaration of an anonymous union,
3017  // use its anonymous union class declaration as the unique key.
3018  FieldDecl *Field = Member->getAnyMember();
3019
3020  // If the field is a member of an anonymous struct or union, our key
3021  // is the anonymous record decl that's a direct child of the class.
3022  RecordDecl *RD = Field->getParent();
3023  if (RD->isAnonymousStructOrUnion()) {
3024    while (true) {
3025      RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
3026      if (Parent->isAnonymousStructOrUnion())
3027        RD = Parent;
3028      else
3029        break;
3030    }
3031
3032    return static_cast<void *>(RD);
3033  }
3034
3035  return static_cast<void *>(Field);
3036}
3037
3038static void
3039DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
3040                                  const CXXConstructorDecl *Constructor,
3041                                  CXXCtorInitializer **Inits,
3042                                  unsigned NumInits) {
3043  if (Constructor->getDeclContext()->isDependentContext())
3044    return;
3045
3046  // Don't check initializers order unless the warning is enabled at the
3047  // location of at least one initializer.
3048  bool ShouldCheckOrder = false;
3049  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3050    CXXCtorInitializer *Init = Inits[InitIndex];
3051    if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3052                                         Init->getSourceLocation())
3053          != DiagnosticsEngine::Ignored) {
3054      ShouldCheckOrder = true;
3055      break;
3056    }
3057  }
3058  if (!ShouldCheckOrder)
3059    return;
3060
3061  // Build the list of bases and members in the order that they'll
3062  // actually be initialized.  The explicit initializers should be in
3063  // this same order but may be missing things.
3064  SmallVector<const void*, 32> IdealInitKeys;
3065
3066  const CXXRecordDecl *ClassDecl = Constructor->getParent();
3067
3068  // 1. Virtual bases.
3069  for (CXXRecordDecl::base_class_const_iterator VBase =
3070       ClassDecl->vbases_begin(),
3071       E = ClassDecl->vbases_end(); VBase != E; ++VBase)
3072    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
3073
3074  // 2. Non-virtual bases.
3075  for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
3076       E = ClassDecl->bases_end(); Base != E; ++Base) {
3077    if (Base->isVirtual())
3078      continue;
3079    IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
3080  }
3081
3082  // 3. Direct fields.
3083  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3084       E = ClassDecl->field_end(); Field != E; ++Field) {
3085    if (Field->isUnnamedBitfield())
3086      continue;
3087
3088    IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
3089  }
3090
3091  unsigned NumIdealInits = IdealInitKeys.size();
3092  unsigned IdealIndex = 0;
3093
3094  CXXCtorInitializer *PrevInit = 0;
3095  for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
3096    CXXCtorInitializer *Init = Inits[InitIndex];
3097    void *InitKey = GetKeyForMember(SemaRef.Context, Init);
3098
3099    // Scan forward to try to find this initializer in the idealized
3100    // initializers list.
3101    for (; IdealIndex != NumIdealInits; ++IdealIndex)
3102      if (InitKey == IdealInitKeys[IdealIndex])
3103        break;
3104
3105    // If we didn't find this initializer, it must be because we
3106    // scanned past it on a previous iteration.  That can only
3107    // happen if we're out of order;  emit a warning.
3108    if (IdealIndex == NumIdealInits && PrevInit) {
3109      Sema::SemaDiagnosticBuilder D =
3110        SemaRef.Diag(PrevInit->getSourceLocation(),
3111                     diag::warn_initializer_out_of_order);
3112
3113      if (PrevInit->isAnyMemberInitializer())
3114        D << 0 << PrevInit->getAnyMember()->getDeclName();
3115      else
3116        D << 1 << PrevInit->getTypeSourceInfo()->getType();
3117
3118      if (Init->isAnyMemberInitializer())
3119        D << 0 << Init->getAnyMember()->getDeclName();
3120      else
3121        D << 1 << Init->getTypeSourceInfo()->getType();
3122
3123      // Move back to the initializer's location in the ideal list.
3124      for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3125        if (InitKey == IdealInitKeys[IdealIndex])
3126          break;
3127
3128      assert(IdealIndex != NumIdealInits &&
3129             "initializer not found in initializer list");
3130    }
3131
3132    PrevInit = Init;
3133  }
3134}
3135
3136namespace {
3137bool CheckRedundantInit(Sema &S,
3138                        CXXCtorInitializer *Init,
3139                        CXXCtorInitializer *&PrevInit) {
3140  if (!PrevInit) {
3141    PrevInit = Init;
3142    return false;
3143  }
3144
3145  if (FieldDecl *Field = Init->getMember())
3146    S.Diag(Init->getSourceLocation(),
3147           diag::err_multiple_mem_initialization)
3148      << Field->getDeclName()
3149      << Init->getSourceRange();
3150  else {
3151    const Type *BaseClass = Init->getBaseClass();
3152    assert(BaseClass && "neither field nor base");
3153    S.Diag(Init->getSourceLocation(),
3154           diag::err_multiple_base_initialization)
3155      << QualType(BaseClass, 0)
3156      << Init->getSourceRange();
3157  }
3158  S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3159    << 0 << PrevInit->getSourceRange();
3160
3161  return true;
3162}
3163
3164typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3165typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3166
3167bool CheckRedundantUnionInit(Sema &S,
3168                             CXXCtorInitializer *Init,
3169                             RedundantUnionMap &Unions) {
3170  FieldDecl *Field = Init->getAnyMember();
3171  RecordDecl *Parent = Field->getParent();
3172  NamedDecl *Child = Field;
3173
3174  while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
3175    if (Parent->isUnion()) {
3176      UnionEntry &En = Unions[Parent];
3177      if (En.first && En.first != Child) {
3178        S.Diag(Init->getSourceLocation(),
3179               diag::err_multiple_mem_union_initialization)
3180          << Field->getDeclName()
3181          << Init->getSourceRange();
3182        S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3183          << 0 << En.second->getSourceRange();
3184        return true;
3185      }
3186      if (!En.first) {
3187        En.first = Child;
3188        En.second = Init;
3189      }
3190      if (!Parent->isAnonymousStructOrUnion())
3191        return false;
3192    }
3193
3194    Child = Parent;
3195    Parent = cast<RecordDecl>(Parent->getDeclContext());
3196  }
3197
3198  return false;
3199}
3200}
3201
3202/// ActOnMemInitializers - Handle the member initializers for a constructor.
3203void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3204                                SourceLocation ColonLoc,
3205                                CXXCtorInitializer **meminits,
3206                                unsigned NumMemInits,
3207                                bool AnyErrors) {
3208  if (!ConstructorDecl)
3209    return;
3210
3211  AdjustDeclIfTemplate(ConstructorDecl);
3212
3213  CXXConstructorDecl *Constructor
3214    = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3215
3216  if (!Constructor) {
3217    Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3218    return;
3219  }
3220
3221  CXXCtorInitializer **MemInits =
3222    reinterpret_cast<CXXCtorInitializer **>(meminits);
3223
3224  // Mapping for the duplicate initializers check.
3225  // For member initializers, this is keyed with a FieldDecl*.
3226  // For base initializers, this is keyed with a Type*.
3227  llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3228
3229  // Mapping for the inconsistent anonymous-union initializers check.
3230  RedundantUnionMap MemberUnions;
3231
3232  bool HadError = false;
3233  for (unsigned i = 0; i < NumMemInits; i++) {
3234    CXXCtorInitializer *Init = MemInits[i];
3235
3236    // Set the source order index.
3237    Init->setSourceOrder(i);
3238
3239    if (Init->isAnyMemberInitializer()) {
3240      FieldDecl *Field = Init->getAnyMember();
3241      if (CheckRedundantInit(*this, Init, Members[Field]) ||
3242          CheckRedundantUnionInit(*this, Init, MemberUnions))
3243        HadError = true;
3244    } else if (Init->isBaseInitializer()) {
3245      void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3246      if (CheckRedundantInit(*this, Init, Members[Key]))
3247        HadError = true;
3248    } else {
3249      assert(Init->isDelegatingInitializer());
3250      // This must be the only initializer
3251      if (i != 0 || NumMemInits > 1) {
3252        Diag(MemInits[0]->getSourceLocation(),
3253             diag::err_delegating_initializer_alone)
3254          << MemInits[0]->getSourceRange();
3255        HadError = true;
3256        // We will treat this as being the only initializer.
3257      }
3258      SetDelegatingInitializer(Constructor, MemInits[i]);
3259      // Return immediately as the initializer is set.
3260      return;
3261    }
3262  }
3263
3264  if (HadError)
3265    return;
3266
3267  DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3268
3269  SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3270}
3271
3272void
3273Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3274                                             CXXRecordDecl *ClassDecl) {
3275  // Ignore dependent contexts. Also ignore unions, since their members never
3276  // have destructors implicitly called.
3277  if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3278    return;
3279
3280  // FIXME: all the access-control diagnostics are positioned on the
3281  // field/base declaration.  That's probably good; that said, the
3282  // user might reasonably want to know why the destructor is being
3283  // emitted, and we currently don't say.
3284
3285  // Non-static data members.
3286  for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3287       E = ClassDecl->field_end(); I != E; ++I) {
3288    FieldDecl *Field = *I;
3289    if (Field->isInvalidDecl())
3290      continue;
3291
3292    // Don't destroy incomplete or zero-length arrays.
3293    if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3294      continue;
3295
3296    QualType FieldType = Context.getBaseElementType(Field->getType());
3297
3298    const RecordType* RT = FieldType->getAs<RecordType>();
3299    if (!RT)
3300      continue;
3301
3302    CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3303    if (FieldClassDecl->isInvalidDecl())
3304      continue;
3305    if (FieldClassDecl->hasIrrelevantDestructor())
3306      continue;
3307    // The destructor for an implicit anonymous union member is never invoked.
3308    if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
3309      continue;
3310
3311    CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3312    assert(Dtor && "No dtor found for FieldClassDecl!");
3313    CheckDestructorAccess(Field->getLocation(), Dtor,
3314                          PDiag(diag::err_access_dtor_field)
3315                            << Field->getDeclName()
3316                            << FieldType);
3317
3318    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3319    DiagnoseUseOfDecl(Dtor, Location);
3320  }
3321
3322  llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3323
3324  // Bases.
3325  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3326       E = ClassDecl->bases_end(); Base != E; ++Base) {
3327    // Bases are always records in a well-formed non-dependent class.
3328    const RecordType *RT = Base->getType()->getAs<RecordType>();
3329
3330    // Remember direct virtual bases.
3331    if (Base->isVirtual())
3332      DirectVirtualBases.insert(RT);
3333
3334    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3335    // If our base class is invalid, we probably can't get its dtor anyway.
3336    if (BaseClassDecl->isInvalidDecl())
3337      continue;
3338    if (BaseClassDecl->hasIrrelevantDestructor())
3339      continue;
3340
3341    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3342    assert(Dtor && "No dtor found for BaseClassDecl!");
3343
3344    // FIXME: caret should be on the start of the class name
3345    CheckDestructorAccess(Base->getLocStart(), Dtor,
3346                          PDiag(diag::err_access_dtor_base)
3347                            << Base->getType()
3348                            << Base->getSourceRange(),
3349                          Context.getTypeDeclType(ClassDecl));
3350
3351    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3352    DiagnoseUseOfDecl(Dtor, Location);
3353  }
3354
3355  // Virtual bases.
3356  for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3357       E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3358
3359    // Bases are always records in a well-formed non-dependent class.
3360    const RecordType *RT = VBase->getType()->castAs<RecordType>();
3361
3362    // Ignore direct virtual bases.
3363    if (DirectVirtualBases.count(RT))
3364      continue;
3365
3366    CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3367    // If our base class is invalid, we probably can't get its dtor anyway.
3368    if (BaseClassDecl->isInvalidDecl())
3369      continue;
3370    if (BaseClassDecl->hasIrrelevantDestructor())
3371      continue;
3372
3373    CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3374    assert(Dtor && "No dtor found for BaseClassDecl!");
3375    CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3376                          PDiag(diag::err_access_dtor_vbase)
3377                            << VBase->getType(),
3378                          Context.getTypeDeclType(ClassDecl));
3379
3380    MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3381    DiagnoseUseOfDecl(Dtor, Location);
3382  }
3383}
3384
3385void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3386  if (!CDtorDecl)
3387    return;
3388
3389  if (CXXConstructorDecl *Constructor
3390      = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3391    SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3392}
3393
3394bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3395                                  unsigned DiagID, AbstractDiagSelID SelID) {
3396  if (SelID == -1)
3397    return RequireNonAbstractType(Loc, T, PDiag(DiagID));
3398  else
3399    return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
3400}
3401
3402bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3403                                  const PartialDiagnostic &PD) {
3404  if (!getLangOpts().CPlusPlus)
3405    return false;
3406
3407  if (const ArrayType *AT = Context.getAsArrayType(T))
3408    return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3409
3410  if (const PointerType *PT = T->getAs<PointerType>()) {
3411    // Find the innermost pointer type.
3412    while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3413      PT = T;
3414
3415    if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3416      return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3417  }
3418
3419  const RecordType *RT = T->getAs<RecordType>();
3420  if (!RT)
3421    return false;
3422
3423  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3424
3425  // We can't answer whether something is abstract until it has a
3426  // definition.  If it's currently being defined, we'll walk back
3427  // over all the declarations when we have a full definition.
3428  const CXXRecordDecl *Def = RD->getDefinition();
3429  if (!Def || Def->isBeingDefined())
3430    return false;
3431
3432  if (!RD->isAbstract())
3433    return false;
3434
3435  Diag(Loc, PD) << RD->getDeclName();
3436  DiagnoseAbstractType(RD);
3437
3438  return true;
3439}
3440
3441void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3442  // Check if we've already emitted the list of pure virtual functions
3443  // for this class.
3444  if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3445    return;
3446
3447  CXXFinalOverriderMap FinalOverriders;
3448  RD->getFinalOverriders(FinalOverriders);
3449
3450  // Keep a set of seen pure methods so we won't diagnose the same method
3451  // more than once.
3452  llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3453
3454  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3455                                   MEnd = FinalOverriders.end();
3456       M != MEnd;
3457       ++M) {
3458    for (OverridingMethods::iterator SO = M->second.begin(),
3459                                  SOEnd = M->second.end();
3460         SO != SOEnd; ++SO) {
3461      // C++ [class.abstract]p4:
3462      //   A class is abstract if it contains or inherits at least one
3463      //   pure virtual function for which the final overrider is pure
3464      //   virtual.
3465
3466      //
3467      if (SO->second.size() != 1)
3468        continue;
3469
3470      if (!SO->second.front().Method->isPure())
3471        continue;
3472
3473      if (!SeenPureMethods.insert(SO->second.front().Method))
3474        continue;
3475
3476      Diag(SO->second.front().Method->getLocation(),
3477           diag::note_pure_virtual_function)
3478        << SO->second.front().Method->getDeclName() << RD->getDeclName();
3479    }
3480  }
3481
3482  if (!PureVirtualClassDiagSet)
3483    PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3484  PureVirtualClassDiagSet->insert(RD);
3485}
3486
3487namespace {
3488struct AbstractUsageInfo {
3489  Sema &S;
3490  CXXRecordDecl *Record;
3491  CanQualType AbstractType;
3492  bool Invalid;
3493
3494  AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3495    : S(S), Record(Record),
3496      AbstractType(S.Context.getCanonicalType(
3497                   S.Context.getTypeDeclType(Record))),
3498      Invalid(false) {}
3499
3500  void DiagnoseAbstractType() {
3501    if (Invalid) return;
3502    S.DiagnoseAbstractType(Record);
3503    Invalid = true;
3504  }
3505
3506  void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3507};
3508
3509struct CheckAbstractUsage {
3510  AbstractUsageInfo &Info;
3511  const NamedDecl *Ctx;
3512
3513  CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3514    : Info(Info), Ctx(Ctx) {}
3515
3516  void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3517    switch (TL.getTypeLocClass()) {
3518#define ABSTRACT_TYPELOC(CLASS, PARENT)
3519#define TYPELOC(CLASS, PARENT) \
3520    case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3521#include "clang/AST/TypeLocNodes.def"
3522    }
3523  }
3524
3525  void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3526    Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3527    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3528      if (!TL.getArg(I))
3529        continue;
3530
3531      TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3532      if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3533    }
3534  }
3535
3536  void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3537    Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3538  }
3539
3540  void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3541    // Visit the type parameters from a permissive context.
3542    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3543      TemplateArgumentLoc TAL = TL.getArgLoc(I);
3544      if (TAL.getArgument().getKind() == TemplateArgument::Type)
3545        if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3546          Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3547      // TODO: other template argument types?
3548    }
3549  }
3550
3551  // Visit pointee types from a permissive context.
3552#define CheckPolymorphic(Type) \
3553  void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3554    Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3555  }
3556  CheckPolymorphic(PointerTypeLoc)
3557  CheckPolymorphic(ReferenceTypeLoc)
3558  CheckPolymorphic(MemberPointerTypeLoc)
3559  CheckPolymorphic(BlockPointerTypeLoc)
3560  CheckPolymorphic(AtomicTypeLoc)
3561
3562  /// Handle all the types we haven't given a more specific
3563  /// implementation for above.
3564  void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3565    // Every other kind of type that we haven't called out already
3566    // that has an inner type is either (1) sugar or (2) contains that
3567    // inner type in some way as a subobject.
3568    if (TypeLoc Next = TL.getNextTypeLoc())
3569      return Visit(Next, Sel);
3570
3571    // If there's no inner type and we're in a permissive context,
3572    // don't diagnose.
3573    if (Sel == Sema::AbstractNone) return;
3574
3575    // Check whether the type matches the abstract type.
3576    QualType T = TL.getType();
3577    if (T->isArrayType()) {
3578      Sel = Sema::AbstractArrayType;
3579      T = Info.S.Context.getBaseElementType(T);
3580    }
3581    CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3582    if (CT != Info.AbstractType) return;
3583
3584    // It matched; do some magic.
3585    if (Sel == Sema::AbstractArrayType) {
3586      Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3587        << T << TL.getSourceRange();
3588    } else {
3589      Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3590        << Sel << T << TL.getSourceRange();
3591    }
3592    Info.DiagnoseAbstractType();
3593  }
3594};
3595
3596void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3597                                  Sema::AbstractDiagSelID Sel) {
3598  CheckAbstractUsage(*this, D).Visit(TL, Sel);
3599}
3600
3601}
3602
3603/// Check for invalid uses of an abstract type in a method declaration.
3604static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3605                                    CXXMethodDecl *MD) {
3606  // No need to do the check on definitions, which require that
3607  // the return/param types be complete.
3608  if (MD->doesThisDeclarationHaveABody())
3609    return;
3610
3611  // For safety's sake, just ignore it if we don't have type source
3612  // information.  This should never happen for non-implicit methods,
3613  // but...
3614  if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3615    Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3616}
3617
3618/// Check for invalid uses of an abstract type within a class definition.
3619static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3620                                    CXXRecordDecl *RD) {
3621  for (CXXRecordDecl::decl_iterator
3622         I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3623    Decl *D = *I;
3624    if (D->isImplicit()) continue;
3625
3626    // Methods and method templates.
3627    if (isa<CXXMethodDecl>(D)) {
3628      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3629    } else if (isa<FunctionTemplateDecl>(D)) {
3630      FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3631      CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3632
3633    // Fields and static variables.
3634    } else if (isa<FieldDecl>(D)) {
3635      FieldDecl *FD = cast<FieldDecl>(D);
3636      if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3637        Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3638    } else if (isa<VarDecl>(D)) {
3639      VarDecl *VD = cast<VarDecl>(D);
3640      if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3641        Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3642
3643    // Nested classes and class templates.
3644    } else if (isa<CXXRecordDecl>(D)) {
3645      CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3646    } else if (isa<ClassTemplateDecl>(D)) {
3647      CheckAbstractClassUsage(Info,
3648                             cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3649    }
3650  }
3651}
3652
3653/// \brief Perform semantic checks on a class definition that has been
3654/// completing, introducing implicitly-declared members, checking for
3655/// abstract types, etc.
3656void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3657  if (!Record)
3658    return;
3659
3660  if (Record->isAbstract() && !Record->isInvalidDecl()) {
3661    AbstractUsageInfo Info(*this, Record);
3662    CheckAbstractClassUsage(Info, Record);
3663  }
3664
3665  // If this is not an aggregate type and has no user-declared constructor,
3666  // complain about any non-static data members of reference or const scalar
3667  // type, since they will never get initializers.
3668  if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3669      !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3670      !Record->isLambda()) {
3671    bool Complained = false;
3672    for (RecordDecl::field_iterator F = Record->field_begin(),
3673                                 FEnd = Record->field_end();
3674         F != FEnd; ++F) {
3675      if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3676        continue;
3677
3678      if (F->getType()->isReferenceType() ||
3679          (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3680        if (!Complained) {
3681          Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3682            << Record->getTagKind() << Record;
3683          Complained = true;
3684        }
3685
3686        Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3687          << F->getType()->isReferenceType()
3688          << F->getDeclName();
3689      }
3690    }
3691  }
3692
3693  if (Record->isDynamicClass() && !Record->isDependentType())
3694    DynamicClasses.push_back(Record);
3695
3696  if (Record->getIdentifier()) {
3697    // C++ [class.mem]p13:
3698    //   If T is the name of a class, then each of the following shall have a
3699    //   name different from T:
3700    //     - every member of every anonymous union that is a member of class T.
3701    //
3702    // C++ [class.mem]p14:
3703    //   In addition, if class T has a user-declared constructor (12.1), every
3704    //   non-static data member of class T shall have a name different from T.
3705    for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3706         R.first != R.second; ++R.first) {
3707      NamedDecl *D = *R.first;
3708      if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3709          isa<IndirectFieldDecl>(D)) {
3710        Diag(D->getLocation(), diag::err_member_name_of_class)
3711          << D->getDeclName();
3712        break;
3713      }
3714    }
3715  }
3716
3717  // Warn if the class has virtual methods but non-virtual public destructor.
3718  if (Record->isPolymorphic() && !Record->isDependentType()) {
3719    CXXDestructorDecl *dtor = Record->getDestructor();
3720    if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3721      Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3722           diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3723  }
3724
3725  // See if a method overloads virtual methods in a base
3726  /// class without overriding any.
3727  if (!Record->isDependentType()) {
3728    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3729                                     MEnd = Record->method_end();
3730         M != MEnd; ++M) {
3731      if (!(*M)->isStatic())
3732        DiagnoseHiddenVirtualMethods(Record, *M);
3733    }
3734  }
3735
3736  // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3737  // function that is not a constructor declares that member function to be
3738  // const. [...] The class of which that function is a member shall be
3739  // a literal type.
3740  //
3741  // If the class has virtual bases, any constexpr members will already have
3742  // been diagnosed by the checks performed on the member declaration, so
3743  // suppress this (less useful) diagnostic.
3744  if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3745      !Record->isLiteral() && !Record->getNumVBases()) {
3746    for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3747                                     MEnd = Record->method_end();
3748         M != MEnd; ++M) {
3749      if (M->isConstexpr() && M->isInstance() && !isa<CXXConstructorDecl>(*M)) {
3750        switch (Record->getTemplateSpecializationKind()) {
3751        case TSK_ImplicitInstantiation:
3752        case TSK_ExplicitInstantiationDeclaration:
3753        case TSK_ExplicitInstantiationDefinition:
3754          // If a template instantiates to a non-literal type, but its members
3755          // instantiate to constexpr functions, the template is technically
3756          // ill-formed, but we allow it for sanity.
3757          continue;
3758
3759        case TSK_Undeclared:
3760        case TSK_ExplicitSpecialization:
3761          RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3762                             PDiag(diag::err_constexpr_method_non_literal));
3763          break;
3764        }
3765
3766        // Only produce one error per class.
3767        break;
3768      }
3769    }
3770  }
3771
3772  // Declare inherited constructors. We do this eagerly here because:
3773  // - The standard requires an eager diagnostic for conflicting inherited
3774  //   constructors from different classes.
3775  // - The lazy declaration of the other implicit constructors is so as to not
3776  //   waste space and performance on classes that are not meant to be
3777  //   instantiated (e.g. meta-functions). This doesn't apply to classes that
3778  //   have inherited constructors.
3779  DeclareInheritedConstructors(Record);
3780
3781  if (!Record->isDependentType())
3782    CheckExplicitlyDefaultedMethods(Record);
3783}
3784
3785void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3786  for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3787                                      ME = Record->method_end();
3788       MI != ME; ++MI) {
3789    if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3790      switch (getSpecialMember(*MI)) {
3791      case CXXDefaultConstructor:
3792        CheckExplicitlyDefaultedDefaultConstructor(
3793                                                  cast<CXXConstructorDecl>(*MI));
3794        break;
3795
3796      case CXXDestructor:
3797        CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3798        break;
3799
3800      case CXXCopyConstructor:
3801        CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3802        break;
3803
3804      case CXXCopyAssignment:
3805        CheckExplicitlyDefaultedCopyAssignment(*MI);
3806        break;
3807
3808      case CXXMoveConstructor:
3809        CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
3810        break;
3811
3812      case CXXMoveAssignment:
3813        CheckExplicitlyDefaultedMoveAssignment(*MI);
3814        break;
3815
3816      case CXXInvalid:
3817        llvm_unreachable("non-special member explicitly defaulted!");
3818      }
3819    }
3820  }
3821
3822}
3823
3824void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3825  assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3826
3827  // Whether this was the first-declared instance of the constructor.
3828  // This affects whether we implicitly add an exception spec (and, eventually,
3829  // constexpr). It is also ill-formed to explicitly default a constructor such
3830  // that it would be deleted. (C++0x [decl.fct.def.default])
3831  bool First = CD == CD->getCanonicalDecl();
3832
3833  bool HadError = false;
3834  if (CD->getNumParams() != 0) {
3835    Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3836      << CD->getSourceRange();
3837    HadError = true;
3838  }
3839
3840  ImplicitExceptionSpecification Spec
3841    = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3842  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3843  if (EPI.ExceptionSpecType == EST_Delayed) {
3844    // Exception specification depends on some deferred part of the class. We'll
3845    // try again when the class's definition has been fully processed.
3846    return;
3847  }
3848  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3849                          *ExceptionType = Context.getFunctionType(
3850                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3851
3852  // C++11 [dcl.fct.def.default]p2:
3853  //   An explicitly-defaulted function may be declared constexpr only if it
3854  //   would have been implicitly declared as constexpr,
3855  // Do not apply this rule to templates, since core issue 1358 makes such
3856  // functions always instantiate to constexpr functions.
3857  if (CD->isConstexpr() &&
3858      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
3859    if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3860      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3861        << CXXDefaultConstructor;
3862      HadError = true;
3863    }
3864  }
3865  //   and may have an explicit exception-specification only if it is compatible
3866  //   with the exception-specification on the implicit declaration.
3867  if (CtorType->hasExceptionSpec()) {
3868    if (CheckEquivalentExceptionSpec(
3869          PDiag(diag::err_incorrect_defaulted_exception_spec)
3870            << CXXDefaultConstructor,
3871          PDiag(),
3872          ExceptionType, SourceLocation(),
3873          CtorType, CD->getLocation())) {
3874      HadError = true;
3875    }
3876  }
3877
3878  //   If a function is explicitly defaulted on its first declaration,
3879  if (First) {
3880    //  -- it is implicitly considered to be constexpr if the implicit
3881    //     definition would be,
3882    CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3883
3884    //  -- it is implicitly considered to have the same
3885    //     exception-specification as if it had been implicitly declared
3886    //
3887    // FIXME: a compatible, but different, explicit exception specification
3888    // will be silently overridden. We should issue a warning if this happens.
3889    EPI.ExtInfo = CtorType->getExtInfo();
3890
3891    // Such a function is also trivial if the implicitly-declared function
3892    // would have been.
3893    CD->setTrivial(CD->getParent()->hasTrivialDefaultConstructor());
3894  }
3895
3896  if (HadError) {
3897    CD->setInvalidDecl();
3898    return;
3899  }
3900
3901  if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
3902    if (First) {
3903      CD->setDeletedAsWritten();
3904    } else {
3905      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3906        << CXXDefaultConstructor;
3907      CD->setInvalidDecl();
3908    }
3909  }
3910}
3911
3912void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3913  assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3914
3915  // Whether this was the first-declared instance of the constructor.
3916  bool First = CD == CD->getCanonicalDecl();
3917
3918  bool HadError = false;
3919  if (CD->getNumParams() != 1) {
3920    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3921      << CD->getSourceRange();
3922    HadError = true;
3923  }
3924
3925  ImplicitExceptionSpecification Spec(Context);
3926  bool Const;
3927  llvm::tie(Spec, Const) =
3928    ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3929
3930  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3931  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3932                          *ExceptionType = Context.getFunctionType(
3933                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3934
3935  // Check for parameter type matching.
3936  // This is a copy ctor so we know it's a cv-qualified reference to T.
3937  QualType ArgType = CtorType->getArgType(0);
3938  if (ArgType->getPointeeType().isVolatileQualified()) {
3939    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3940    HadError = true;
3941  }
3942  if (ArgType->getPointeeType().isConstQualified() && !Const) {
3943    Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3944    HadError = true;
3945  }
3946
3947  // C++11 [dcl.fct.def.default]p2:
3948  //   An explicitly-defaulted function may be declared constexpr only if it
3949  //   would have been implicitly declared as constexpr,
3950  // Do not apply this rule to templates, since core issue 1358 makes such
3951  // functions always instantiate to constexpr functions.
3952  if (CD->isConstexpr() &&
3953      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
3954    if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3955      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3956        << CXXCopyConstructor;
3957      HadError = true;
3958    }
3959  }
3960  //   and may have an explicit exception-specification only if it is compatible
3961  //   with the exception-specification on the implicit declaration.
3962  if (CtorType->hasExceptionSpec()) {
3963    if (CheckEquivalentExceptionSpec(
3964          PDiag(diag::err_incorrect_defaulted_exception_spec)
3965            << CXXCopyConstructor,
3966          PDiag(),
3967          ExceptionType, SourceLocation(),
3968          CtorType, CD->getLocation())) {
3969      HadError = true;
3970    }
3971  }
3972
3973  //   If a function is explicitly defaulted on its first declaration,
3974  if (First) {
3975    //  -- it is implicitly considered to be constexpr if the implicit
3976    //     definition would be,
3977    CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3978
3979    //  -- it is implicitly considered to have the same
3980    //     exception-specification as if it had been implicitly declared, and
3981    //
3982    // FIXME: a compatible, but different, explicit exception specification
3983    // will be silently overridden. We should issue a warning if this happens.
3984    EPI.ExtInfo = CtorType->getExtInfo();
3985
3986    //  -- [...] it shall have the same parameter type as if it had been
3987    //     implicitly declared.
3988    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3989
3990    // Such a function is also trivial if the implicitly-declared function
3991    // would have been.
3992    CD->setTrivial(CD->getParent()->hasTrivialCopyConstructor());
3993  }
3994
3995  if (HadError) {
3996    CD->setInvalidDecl();
3997    return;
3998  }
3999
4000  if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
4001    if (First) {
4002      CD->setDeletedAsWritten();
4003    } else {
4004      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4005        << CXXCopyConstructor;
4006      CD->setInvalidDecl();
4007    }
4008  }
4009}
4010
4011void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
4012  assert(MD->isExplicitlyDefaulted());
4013
4014  // Whether this was the first-declared instance of the operator
4015  bool First = MD == MD->getCanonicalDecl();
4016
4017  bool HadError = false;
4018  if (MD->getNumParams() != 1) {
4019    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
4020      << MD->getSourceRange();
4021    HadError = true;
4022  }
4023
4024  QualType ReturnType =
4025    MD->getType()->getAs<FunctionType>()->getResultType();
4026  if (!ReturnType->isLValueReferenceType() ||
4027      !Context.hasSameType(
4028        Context.getCanonicalType(ReturnType->getPointeeType()),
4029        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4030    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
4031    HadError = true;
4032  }
4033
4034  ImplicitExceptionSpecification Spec(Context);
4035  bool Const;
4036  llvm::tie(Spec, Const) =
4037    ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
4038
4039  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4040  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4041                          *ExceptionType = Context.getFunctionType(
4042                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4043
4044  QualType ArgType = OperType->getArgType(0);
4045  if (!ArgType->isLValueReferenceType()) {
4046    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
4047    HadError = true;
4048  } else {
4049    if (ArgType->getPointeeType().isVolatileQualified()) {
4050      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4051      HadError = true;
4052    }
4053    if (ArgType->getPointeeType().isConstQualified() && !Const) {
4054      Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4055      HadError = true;
4056    }
4057  }
4058
4059  if (OperType->getTypeQuals()) {
4060    Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4061    HadError = true;
4062  }
4063
4064  if (OperType->hasExceptionSpec()) {
4065    if (CheckEquivalentExceptionSpec(
4066          PDiag(diag::err_incorrect_defaulted_exception_spec)
4067            << CXXCopyAssignment,
4068          PDiag(),
4069          ExceptionType, SourceLocation(),
4070          OperType, MD->getLocation())) {
4071      HadError = true;
4072    }
4073  }
4074  if (First) {
4075    // We set the declaration to have the computed exception spec here.
4076    // We duplicate the one parameter type.
4077    EPI.RefQualifier = OperType->getRefQualifier();
4078    EPI.ExtInfo = OperType->getExtInfo();
4079    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4080
4081    // Such a function is also trivial if the implicitly-declared function
4082    // would have been.
4083    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
4084  }
4085
4086  if (HadError) {
4087    MD->setInvalidDecl();
4088    return;
4089  }
4090
4091  if (ShouldDeleteSpecialMember(MD, CXXCopyAssignment)) {
4092    if (First) {
4093      MD->setDeletedAsWritten();
4094    } else {
4095      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4096        << CXXCopyAssignment;
4097      MD->setInvalidDecl();
4098    }
4099  }
4100}
4101
4102void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4103  assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4104
4105  // Whether this was the first-declared instance of the constructor.
4106  bool First = CD == CD->getCanonicalDecl();
4107
4108  bool HadError = false;
4109  if (CD->getNumParams() != 1) {
4110    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4111      << CD->getSourceRange();
4112    HadError = true;
4113  }
4114
4115  ImplicitExceptionSpecification Spec(
4116      ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4117
4118  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4119  const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4120                          *ExceptionType = Context.getFunctionType(
4121                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4122
4123  // Check for parameter type matching.
4124  // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4125  QualType ArgType = CtorType->getArgType(0);
4126  if (ArgType->getPointeeType().isVolatileQualified()) {
4127    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4128    HadError = true;
4129  }
4130  if (ArgType->getPointeeType().isConstQualified()) {
4131    Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4132    HadError = true;
4133  }
4134
4135  // C++11 [dcl.fct.def.default]p2:
4136  //   An explicitly-defaulted function may be declared constexpr only if it
4137  //   would have been implicitly declared as constexpr,
4138  // Do not apply this rule to templates, since core issue 1358 makes such
4139  // functions always instantiate to constexpr functions.
4140  if (CD->isConstexpr() &&
4141      CD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
4142    if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4143      Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4144        << CXXMoveConstructor;
4145      HadError = true;
4146    }
4147  }
4148  //   and may have an explicit exception-specification only if it is compatible
4149  //   with the exception-specification on the implicit declaration.
4150  if (CtorType->hasExceptionSpec()) {
4151    if (CheckEquivalentExceptionSpec(
4152          PDiag(diag::err_incorrect_defaulted_exception_spec)
4153            << CXXMoveConstructor,
4154          PDiag(),
4155          ExceptionType, SourceLocation(),
4156          CtorType, CD->getLocation())) {
4157      HadError = true;
4158    }
4159  }
4160
4161  //   If a function is explicitly defaulted on its first declaration,
4162  if (First) {
4163    //  -- it is implicitly considered to be constexpr if the implicit
4164    //     definition would be,
4165    CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4166
4167    //  -- it is implicitly considered to have the same
4168    //     exception-specification as if it had been implicitly declared, and
4169    //
4170    // FIXME: a compatible, but different, explicit exception specification
4171    // will be silently overridden. We should issue a warning if this happens.
4172    EPI.ExtInfo = CtorType->getExtInfo();
4173
4174    //  -- [...] it shall have the same parameter type as if it had been
4175    //     implicitly declared.
4176    CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4177
4178    // Such a function is also trivial if the implicitly-declared function
4179    // would have been.
4180    CD->setTrivial(CD->getParent()->hasTrivialMoveConstructor());
4181  }
4182
4183  if (HadError) {
4184    CD->setInvalidDecl();
4185    return;
4186  }
4187
4188  if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
4189    if (First) {
4190      CD->setDeletedAsWritten();
4191    } else {
4192      Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4193        << CXXMoveConstructor;
4194      CD->setInvalidDecl();
4195    }
4196  }
4197}
4198
4199void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4200  assert(MD->isExplicitlyDefaulted());
4201
4202  // Whether this was the first-declared instance of the operator
4203  bool First = MD == MD->getCanonicalDecl();
4204
4205  bool HadError = false;
4206  if (MD->getNumParams() != 1) {
4207    Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4208      << MD->getSourceRange();
4209    HadError = true;
4210  }
4211
4212  QualType ReturnType =
4213    MD->getType()->getAs<FunctionType>()->getResultType();
4214  if (!ReturnType->isLValueReferenceType() ||
4215      !Context.hasSameType(
4216        Context.getCanonicalType(ReturnType->getPointeeType()),
4217        Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4218    Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4219    HadError = true;
4220  }
4221
4222  ImplicitExceptionSpecification Spec(
4223      ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4224
4225  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4226  const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4227                          *ExceptionType = Context.getFunctionType(
4228                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4229
4230  QualType ArgType = OperType->getArgType(0);
4231  if (!ArgType->isRValueReferenceType()) {
4232    Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4233    HadError = true;
4234  } else {
4235    if (ArgType->getPointeeType().isVolatileQualified()) {
4236      Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4237      HadError = true;
4238    }
4239    if (ArgType->getPointeeType().isConstQualified()) {
4240      Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4241      HadError = true;
4242    }
4243  }
4244
4245  if (OperType->getTypeQuals()) {
4246    Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4247    HadError = true;
4248  }
4249
4250  if (OperType->hasExceptionSpec()) {
4251    if (CheckEquivalentExceptionSpec(
4252          PDiag(diag::err_incorrect_defaulted_exception_spec)
4253            << CXXMoveAssignment,
4254          PDiag(),
4255          ExceptionType, SourceLocation(),
4256          OperType, MD->getLocation())) {
4257      HadError = true;
4258    }
4259  }
4260  if (First) {
4261    // We set the declaration to have the computed exception spec here.
4262    // We duplicate the one parameter type.
4263    EPI.RefQualifier = OperType->getRefQualifier();
4264    EPI.ExtInfo = OperType->getExtInfo();
4265    MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4266
4267    // Such a function is also trivial if the implicitly-declared function
4268    // would have been.
4269    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
4270  }
4271
4272  if (HadError) {
4273    MD->setInvalidDecl();
4274    return;
4275  }
4276
4277  if (ShouldDeleteSpecialMember(MD, CXXMoveAssignment)) {
4278    if (First) {
4279      MD->setDeletedAsWritten();
4280    } else {
4281      Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4282        << CXXMoveAssignment;
4283      MD->setInvalidDecl();
4284    }
4285  }
4286}
4287
4288void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4289  assert(DD->isExplicitlyDefaulted());
4290
4291  // Whether this was the first-declared instance of the destructor.
4292  bool First = DD == DD->getCanonicalDecl();
4293
4294  ImplicitExceptionSpecification Spec
4295    = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4296  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4297  const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4298                          *ExceptionType = Context.getFunctionType(
4299                         Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4300
4301  if (DtorType->hasExceptionSpec()) {
4302    if (CheckEquivalentExceptionSpec(
4303          PDiag(diag::err_incorrect_defaulted_exception_spec)
4304            << CXXDestructor,
4305          PDiag(),
4306          ExceptionType, SourceLocation(),
4307          DtorType, DD->getLocation())) {
4308      DD->setInvalidDecl();
4309      return;
4310    }
4311  }
4312  if (First) {
4313    // We set the declaration to have the computed exception spec here.
4314    // There are no parameters.
4315    EPI.ExtInfo = DtorType->getExtInfo();
4316    DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4317
4318    // Such a function is also trivial if the implicitly-declared function
4319    // would have been.
4320    DD->setTrivial(DD->getParent()->hasTrivialDestructor());
4321  }
4322
4323  if (ShouldDeleteSpecialMember(DD, CXXDestructor)) {
4324    if (First) {
4325      DD->setDeletedAsWritten();
4326    } else {
4327      Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
4328        << CXXDestructor;
4329      DD->setInvalidDecl();
4330    }
4331  }
4332}
4333
4334namespace {
4335struct SpecialMemberDeletionInfo {
4336  Sema &S;
4337  CXXMethodDecl *MD;
4338  Sema::CXXSpecialMember CSM;
4339  bool Diagnose;
4340
4341  // Properties of the special member, computed for convenience.
4342  bool IsConstructor, IsAssignment, IsMove, ConstArg, VolatileArg;
4343  SourceLocation Loc;
4344
4345  bool AllFieldsAreConst;
4346
4347  SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
4348                            Sema::CXXSpecialMember CSM, bool Diagnose)
4349    : S(S), MD(MD), CSM(CSM), Diagnose(Diagnose),
4350      IsConstructor(false), IsAssignment(false), IsMove(false),
4351      ConstArg(false), VolatileArg(false), Loc(MD->getLocation()),
4352      AllFieldsAreConst(true) {
4353    switch (CSM) {
4354      case Sema::CXXDefaultConstructor:
4355      case Sema::CXXCopyConstructor:
4356        IsConstructor = true;
4357        break;
4358      case Sema::CXXMoveConstructor:
4359        IsConstructor = true;
4360        IsMove = true;
4361        break;
4362      case Sema::CXXCopyAssignment:
4363        IsAssignment = true;
4364        break;
4365      case Sema::CXXMoveAssignment:
4366        IsAssignment = true;
4367        IsMove = true;
4368        break;
4369      case Sema::CXXDestructor:
4370        break;
4371      case Sema::CXXInvalid:
4372        llvm_unreachable("invalid special member kind");
4373    }
4374
4375    if (MD->getNumParams()) {
4376      ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4377      VolatileArg = MD->getParamDecl(0)->getType().isVolatileQualified();
4378    }
4379  }
4380
4381  bool inUnion() const { return MD->getParent()->isUnion(); }
4382
4383  /// Look up the corresponding special member in the given class.
4384  Sema::SpecialMemberOverloadResult *lookupIn(CXXRecordDecl *Class) {
4385    unsigned TQ = MD->getTypeQualifiers();
4386    return S.LookupSpecialMember(Class, CSM, ConstArg, VolatileArg,
4387                                 MD->getRefQualifier() == RQ_RValue,
4388                                 TQ & Qualifiers::Const,
4389                                 TQ & Qualifiers::Volatile);
4390  }
4391
4392  typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
4393
4394  bool shouldDeleteForBase(CXXBaseSpecifier *Base);
4395  bool shouldDeleteForField(FieldDecl *FD);
4396  bool shouldDeleteForAllConstMembers();
4397
4398  bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj);
4399  bool shouldDeleteForSubobjectCall(Subobject Subobj,
4400                                    Sema::SpecialMemberOverloadResult *SMOR,
4401                                    bool IsDtorCallInCtor);
4402
4403  bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
4404};
4405}
4406
4407/// Is the given special member inaccessible when used on the given
4408/// sub-object.
4409bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
4410                                             CXXMethodDecl *target) {
4411  /// If we're operating on a base class, the object type is the
4412  /// type of this special member.
4413  QualType objectTy;
4414  AccessSpecifier access = target->getAccess();;
4415  if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
4416    objectTy = S.Context.getTypeDeclType(MD->getParent());
4417    access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
4418
4419  // If we're operating on a field, the object type is the type of the field.
4420  } else {
4421    objectTy = S.Context.getTypeDeclType(target->getParent());
4422  }
4423
4424  return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
4425}
4426
4427/// Check whether we should delete a special member due to the implicit
4428/// definition containing a call to a special member of a subobject.
4429bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
4430    Subobject Subobj, Sema::SpecialMemberOverloadResult *SMOR,
4431    bool IsDtorCallInCtor) {
4432  CXXMethodDecl *Decl = SMOR->getMethod();
4433  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4434
4435  int DiagKind = -1;
4436
4437  if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
4438    DiagKind = !Decl ? 0 : 1;
4439  else if (SMOR->getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
4440    DiagKind = 2;
4441  else if (!isAccessible(Subobj, Decl))
4442    DiagKind = 3;
4443  else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
4444           !Decl->isTrivial()) {
4445    // A member of a union must have a trivial corresponding special member.
4446    // As a weird special case, a destructor call from a union's constructor
4447    // must be accessible and non-deleted, but need not be trivial. Such a
4448    // destructor is never actually called, but is semantically checked as
4449    // if it were.
4450    DiagKind = 4;
4451  }
4452
4453  if (DiagKind == -1)
4454    return false;
4455
4456  if (Diagnose) {
4457    if (Field) {
4458      S.Diag(Field->getLocation(),
4459             diag::note_deleted_special_member_class_subobject)
4460        << CSM << MD->getParent() << /*IsField*/true
4461        << Field << DiagKind << IsDtorCallInCtor;
4462    } else {
4463      CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
4464      S.Diag(Base->getLocStart(),
4465             diag::note_deleted_special_member_class_subobject)
4466        << CSM << MD->getParent() << /*IsField*/false
4467        << Base->getType() << DiagKind << IsDtorCallInCtor;
4468    }
4469
4470    if (DiagKind == 1)
4471      S.NoteDeletedFunction(Decl);
4472    // FIXME: Explain inaccessibility if DiagKind == 3.
4473  }
4474
4475  return true;
4476}
4477
4478/// Check whether we should delete a special member function due to having a
4479/// direct or virtual base class or static data member of class type M.
4480bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
4481    CXXRecordDecl *Class, Subobject Subobj) {
4482  FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
4483
4484  // C++11 [class.ctor]p5:
4485  // -- any direct or virtual base class, or non-static data member with no
4486  //    brace-or-equal-initializer, has class type M (or array thereof) and
4487  //    either M has no default constructor or overload resolution as applied
4488  //    to M's default constructor results in an ambiguity or in a function
4489  //    that is deleted or inaccessible
4490  // C++11 [class.copy]p11, C++11 [class.copy]p23:
4491  // -- a direct or virtual base class B that cannot be copied/moved because
4492  //    overload resolution, as applied to B's corresponding special member,
4493  //    results in an ambiguity or a function that is deleted or inaccessible
4494  //    from the defaulted special member
4495  // C++11 [class.dtor]p5:
4496  // -- any direct or virtual base class [...] has a type with a destructor
4497  //    that is deleted or inaccessible
4498  if (!(CSM == Sema::CXXDefaultConstructor &&
4499        Field && Field->hasInClassInitializer()) &&
4500      shouldDeleteForSubobjectCall(Subobj, lookupIn(Class), false))
4501    return true;
4502
4503  // C++11 [class.ctor]p5, C++11 [class.copy]p11:
4504  // -- any direct or virtual base class or non-static data member has a
4505  //    type with a destructor that is deleted or inaccessible
4506  if (IsConstructor) {
4507    Sema::SpecialMemberOverloadResult *SMOR =
4508        S.LookupSpecialMember(Class, Sema::CXXDestructor,
4509                              false, false, false, false, false);
4510    if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
4511      return true;
4512  }
4513
4514  return false;
4515}
4516
4517/// Check whether we should delete a special member function due to the class
4518/// having a particular direct or virtual base class.
4519bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
4520  CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
4521  return shouldDeleteForClassSubobject(BaseClass, Base);
4522}
4523
4524/// Check whether we should delete a special member function due to the class
4525/// having a particular non-static data member.
4526bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
4527  QualType FieldType = S.Context.getBaseElementType(FD->getType());
4528  CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4529
4530  if (CSM == Sema::CXXDefaultConstructor) {
4531    // For a default constructor, all references must be initialized in-class
4532    // and, if a union, it must have a non-const member.
4533    if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
4534      if (Diagnose)
4535        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4536          << MD->getParent() << FD << FieldType << /*Reference*/0;
4537      return true;
4538    }
4539    // C++11 [class.ctor]p5: any non-variant non-static data member of
4540    // const-qualified type (or array thereof) with no
4541    // brace-or-equal-initializer does not have a user-provided default
4542    // constructor.
4543    if (!inUnion() && FieldType.isConstQualified() &&
4544        !FD->hasInClassInitializer() &&
4545        (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
4546      if (Diagnose)
4547        S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
4548          << MD->getParent() << FD << FieldType << /*Const*/1;
4549      return true;
4550    }
4551
4552    if (inUnion() && !FieldType.isConstQualified())
4553      AllFieldsAreConst = false;
4554  } else if (CSM == Sema::CXXCopyConstructor) {
4555    // For a copy constructor, data members must not be of rvalue reference
4556    // type.
4557    if (FieldType->isRValueReferenceType()) {
4558      if (Diagnose)
4559        S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
4560          << MD->getParent() << FD << FieldType;
4561      return true;
4562    }
4563  } else if (IsAssignment) {
4564    // For an assignment operator, data members must not be of reference type.
4565    if (FieldType->isReferenceType()) {
4566      if (Diagnose)
4567        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4568          << IsMove << MD->getParent() << FD << FieldType << /*Reference*/0;
4569      return true;
4570    }
4571    if (!FieldRecord && FieldType.isConstQualified()) {
4572      // C++11 [class.copy]p23:
4573      // -- a non-static data member of const non-class type (or array thereof)
4574      if (Diagnose)
4575        S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
4576          << IsMove << MD->getParent() << FD << FieldType << /*Const*/1;
4577      return true;
4578    }
4579  }
4580
4581  if (FieldRecord) {
4582    // Some additional restrictions exist on the variant members.
4583    if (!inUnion() && FieldRecord->isUnion() &&
4584        FieldRecord->isAnonymousStructOrUnion()) {
4585      bool AllVariantFieldsAreConst = true;
4586
4587      // FIXME: Handle anonymous unions declared within anonymous unions.
4588      for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4589                                         UE = FieldRecord->field_end();
4590           UI != UE; ++UI) {
4591        QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
4592
4593        if (!UnionFieldType.isConstQualified())
4594          AllVariantFieldsAreConst = false;
4595
4596        CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
4597        if (UnionFieldRecord &&
4598            shouldDeleteForClassSubobject(UnionFieldRecord, *UI))
4599          return true;
4600      }
4601
4602      // At least one member in each anonymous union must be non-const
4603      if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
4604          FieldRecord->field_begin() != FieldRecord->field_end()) {
4605        if (Diagnose)
4606          S.Diag(FieldRecord->getLocation(),
4607                 diag::note_deleted_default_ctor_all_const)
4608            << MD->getParent() << /*anonymous union*/1;
4609        return true;
4610      }
4611
4612      // Don't check the implicit member of the anonymous union type.
4613      // This is technically non-conformant, but sanity demands it.
4614      return false;
4615    }
4616
4617    if (shouldDeleteForClassSubobject(FieldRecord, FD))
4618      return true;
4619  }
4620
4621  return false;
4622}
4623
4624/// C++11 [class.ctor] p5:
4625///   A defaulted default constructor for a class X is defined as deleted if
4626/// X is a union and all of its variant members are of const-qualified type.
4627bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
4628  // This is a silly definition, because it gives an empty union a deleted
4629  // default constructor. Don't do that.
4630  if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst &&
4631      (MD->getParent()->field_begin() != MD->getParent()->field_end())) {
4632    if (Diagnose)
4633      S.Diag(MD->getParent()->getLocation(),
4634             diag::note_deleted_default_ctor_all_const)
4635        << MD->getParent() << /*not anonymous union*/0;
4636    return true;
4637  }
4638  return false;
4639}
4640
4641/// Determine whether a defaulted special member function should be defined as
4642/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
4643/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
4644bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
4645                                     bool Diagnose) {
4646  assert(!MD->isInvalidDecl());
4647  CXXRecordDecl *RD = MD->getParent();
4648  assert(!RD->isDependentType() && "do deletion after instantiation");
4649  if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4650    return false;
4651
4652  // C++11 [expr.lambda.prim]p19:
4653  //   The closure type associated with a lambda-expression has a
4654  //   deleted (8.4.3) default constructor and a deleted copy
4655  //   assignment operator.
4656  if (RD->isLambda() &&
4657      (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
4658    if (Diagnose)
4659      Diag(RD->getLocation(), diag::note_lambda_decl);
4660    return true;
4661  }
4662
4663  // For an anonymous struct or union, the copy and assignment special members
4664  // will never be used, so skip the check. For an anonymous union declared at
4665  // namespace scope, the constructor and destructor are used.
4666  if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
4667      RD->isAnonymousStructOrUnion())
4668    return false;
4669
4670  // C++11 [class.copy]p7, p18:
4671  //   If the class definition declares a move constructor or move assignment
4672  //   operator, an implicitly declared copy constructor or copy assignment
4673  //   operator is defined as deleted.
4674  if (MD->isImplicit() &&
4675      (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
4676    CXXMethodDecl *UserDeclaredMove = 0;
4677
4678    // In Microsoft mode, a user-declared move only causes the deletion of the
4679    // corresponding copy operation, not both copy operations.
4680    if (RD->hasUserDeclaredMoveConstructor() &&
4681        (!getLangOpts().MicrosoftMode || CSM == CXXCopyConstructor)) {
4682      if (!Diagnose) return true;
4683      UserDeclaredMove = RD->getMoveConstructor();
4684      assert(UserDeclaredMove);
4685    } else if (RD->hasUserDeclaredMoveAssignment() &&
4686               (!getLangOpts().MicrosoftMode || CSM == CXXCopyAssignment)) {
4687      if (!Diagnose) return true;
4688      UserDeclaredMove = RD->getMoveAssignmentOperator();
4689      assert(UserDeclaredMove);
4690    }
4691
4692    if (UserDeclaredMove) {
4693      Diag(UserDeclaredMove->getLocation(),
4694           diag::note_deleted_copy_user_declared_move)
4695        << (CSM == CXXCopyAssignment) << RD
4696        << UserDeclaredMove->isMoveAssignmentOperator();
4697      return true;
4698    }
4699  }
4700
4701  // Do access control from the special member function
4702  ContextRAII MethodContext(*this, MD);
4703
4704  // C++11 [class.dtor]p5:
4705  // -- for a virtual destructor, lookup of the non-array deallocation function
4706  //    results in an ambiguity or in a function that is deleted or inaccessible
4707  if (CSM == CXXDestructor && MD->isVirtual()) {
4708    FunctionDecl *OperatorDelete = 0;
4709    DeclarationName Name =
4710      Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4711    if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
4712                                 OperatorDelete, false)) {
4713      if (Diagnose)
4714        Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
4715      return true;
4716    }
4717  }
4718
4719  SpecialMemberDeletionInfo SMI(*this, MD, CSM, Diagnose);
4720
4721  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4722                                          BE = RD->bases_end(); BI != BE; ++BI)
4723    if (!BI->isVirtual() &&
4724        SMI.shouldDeleteForBase(BI))
4725      return true;
4726
4727  for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4728                                          BE = RD->vbases_end(); BI != BE; ++BI)
4729    if (SMI.shouldDeleteForBase(BI))
4730      return true;
4731
4732  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4733                                     FE = RD->field_end(); FI != FE; ++FI)
4734    if (!FI->isInvalidDecl() && !FI->isUnnamedBitfield() &&
4735        SMI.shouldDeleteForField(*FI))
4736      return true;
4737
4738  if (SMI.shouldDeleteForAllConstMembers())
4739    return true;
4740
4741  return false;
4742}
4743
4744/// \brief Data used with FindHiddenVirtualMethod
4745namespace {
4746  struct FindHiddenVirtualMethodData {
4747    Sema *S;
4748    CXXMethodDecl *Method;
4749    llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4750    SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4751  };
4752}
4753
4754/// \brief Member lookup function that determines whether a given C++
4755/// method overloads virtual methods in a base class without overriding any,
4756/// to be used with CXXRecordDecl::lookupInBases().
4757static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4758                                    CXXBasePath &Path,
4759                                    void *UserData) {
4760  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4761
4762  FindHiddenVirtualMethodData &Data
4763    = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4764
4765  DeclarationName Name = Data.Method->getDeclName();
4766  assert(Name.getNameKind() == DeclarationName::Identifier);
4767
4768  bool foundSameNameMethod = false;
4769  SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4770  for (Path.Decls = BaseRecord->lookup(Name);
4771       Path.Decls.first != Path.Decls.second;
4772       ++Path.Decls.first) {
4773    NamedDecl *D = *Path.Decls.first;
4774    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4775      MD = MD->getCanonicalDecl();
4776      foundSameNameMethod = true;
4777      // Interested only in hidden virtual methods.
4778      if (!MD->isVirtual())
4779        continue;
4780      // If the method we are checking overrides a method from its base
4781      // don't warn about the other overloaded methods.
4782      if (!Data.S->IsOverload(Data.Method, MD, false))
4783        return true;
4784      // Collect the overload only if its hidden.
4785      if (!Data.OverridenAndUsingBaseMethods.count(MD))
4786        overloadedMethods.push_back(MD);
4787    }
4788  }
4789
4790  if (foundSameNameMethod)
4791    Data.OverloadedMethods.append(overloadedMethods.begin(),
4792                                   overloadedMethods.end());
4793  return foundSameNameMethod;
4794}
4795
4796/// \brief See if a method overloads virtual methods in a base class without
4797/// overriding any.
4798void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4799  if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4800                               MD->getLocation()) == DiagnosticsEngine::Ignored)
4801    return;
4802  if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4803    return;
4804
4805  CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4806                     /*bool RecordPaths=*/false,
4807                     /*bool DetectVirtual=*/false);
4808  FindHiddenVirtualMethodData Data;
4809  Data.Method = MD;
4810  Data.S = this;
4811
4812  // Keep the base methods that were overriden or introduced in the subclass
4813  // by 'using' in a set. A base method not in this set is hidden.
4814  for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4815       res.first != res.second; ++res.first) {
4816    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4817      for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4818                                          E = MD->end_overridden_methods();
4819           I != E; ++I)
4820        Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4821    if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4822      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4823        Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4824  }
4825
4826  if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4827      !Data.OverloadedMethods.empty()) {
4828    Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4829      << MD << (Data.OverloadedMethods.size() > 1);
4830
4831    for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4832      CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4833      Diag(overloadedMD->getLocation(),
4834           diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4835    }
4836  }
4837}
4838
4839void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4840                                             Decl *TagDecl,
4841                                             SourceLocation LBrac,
4842                                             SourceLocation RBrac,
4843                                             AttributeList *AttrList) {
4844  if (!TagDecl)
4845    return;
4846
4847  AdjustDeclIfTemplate(TagDecl);
4848
4849  ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4850              // strict aliasing violation!
4851              reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4852              FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4853
4854  CheckCompletedCXXClass(
4855                        dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4856}
4857
4858/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4859/// special functions, such as the default constructor, copy
4860/// constructor, or destructor, to the given C++ class (C++
4861/// [special]p1).  This routine can only be executed just before the
4862/// definition of the class is complete.
4863void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4864  if (!ClassDecl->hasUserDeclaredConstructor())
4865    ++ASTContext::NumImplicitDefaultConstructors;
4866
4867  if (!ClassDecl->hasUserDeclaredCopyConstructor())
4868    ++ASTContext::NumImplicitCopyConstructors;
4869
4870  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
4871    ++ASTContext::NumImplicitMoveConstructors;
4872
4873  if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4874    ++ASTContext::NumImplicitCopyAssignmentOperators;
4875
4876    // If we have a dynamic class, then the copy assignment operator may be
4877    // virtual, so we have to declare it immediately. This ensures that, e.g.,
4878    // it shows up in the right place in the vtable and that we diagnose
4879    // problems with the implicit exception specification.
4880    if (ClassDecl->isDynamicClass())
4881      DeclareImplicitCopyAssignment(ClassDecl);
4882  }
4883
4884  if (getLangOpts().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()) {
4885    ++ASTContext::NumImplicitMoveAssignmentOperators;
4886
4887    // Likewise for the move assignment operator.
4888    if (ClassDecl->isDynamicClass())
4889      DeclareImplicitMoveAssignment(ClassDecl);
4890  }
4891
4892  if (!ClassDecl->hasUserDeclaredDestructor()) {
4893    ++ASTContext::NumImplicitDestructors;
4894
4895    // If we have a dynamic class, then the destructor may be virtual, so we
4896    // have to declare the destructor immediately. This ensures that, e.g., it
4897    // shows up in the right place in the vtable and that we diagnose problems
4898    // with the implicit exception specification.
4899    if (ClassDecl->isDynamicClass())
4900      DeclareImplicitDestructor(ClassDecl);
4901  }
4902}
4903
4904void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4905  if (!D)
4906    return;
4907
4908  int NumParamList = D->getNumTemplateParameterLists();
4909  for (int i = 0; i < NumParamList; i++) {
4910    TemplateParameterList* Params = D->getTemplateParameterList(i);
4911    for (TemplateParameterList::iterator Param = Params->begin(),
4912                                      ParamEnd = Params->end();
4913          Param != ParamEnd; ++Param) {
4914      NamedDecl *Named = cast<NamedDecl>(*Param);
4915      if (Named->getDeclName()) {
4916        S->AddDecl(Named);
4917        IdResolver.AddDecl(Named);
4918      }
4919    }
4920  }
4921}
4922
4923void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4924  if (!D)
4925    return;
4926
4927  TemplateParameterList *Params = 0;
4928  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4929    Params = Template->getTemplateParameters();
4930  else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4931           = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4932    Params = PartialSpec->getTemplateParameters();
4933  else
4934    return;
4935
4936  for (TemplateParameterList::iterator Param = Params->begin(),
4937                                    ParamEnd = Params->end();
4938       Param != ParamEnd; ++Param) {
4939    NamedDecl *Named = cast<NamedDecl>(*Param);
4940    if (Named->getDeclName()) {
4941      S->AddDecl(Named);
4942      IdResolver.AddDecl(Named);
4943    }
4944  }
4945}
4946
4947void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4948  if (!RecordD) return;
4949  AdjustDeclIfTemplate(RecordD);
4950  CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4951  PushDeclContext(S, Record);
4952}
4953
4954void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4955  if (!RecordD) return;
4956  PopDeclContext();
4957}
4958
4959/// ActOnStartDelayedCXXMethodDeclaration - We have completed
4960/// parsing a top-level (non-nested) C++ class, and we are now
4961/// parsing those parts of the given Method declaration that could
4962/// not be parsed earlier (C++ [class.mem]p2), such as default
4963/// arguments. This action should enter the scope of the given
4964/// Method declaration as if we had just parsed the qualified method
4965/// name. However, it should not bring the parameters into scope;
4966/// that will be performed by ActOnDelayedCXXMethodParameter.
4967void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4968}
4969
4970/// ActOnDelayedCXXMethodParameter - We've already started a delayed
4971/// C++ method declaration. We're (re-)introducing the given
4972/// function parameter into scope for use in parsing later parts of
4973/// the method declaration. For example, we could see an
4974/// ActOnParamDefaultArgument event for this parameter.
4975void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4976  if (!ParamD)
4977    return;
4978
4979  ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4980
4981  // If this parameter has an unparsed default argument, clear it out
4982  // to make way for the parsed default argument.
4983  if (Param->hasUnparsedDefaultArg())
4984    Param->setDefaultArg(0);
4985
4986  S->AddDecl(Param);
4987  if (Param->getDeclName())
4988    IdResolver.AddDecl(Param);
4989}
4990
4991/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4992/// processing the delayed method declaration for Method. The method
4993/// declaration is now considered finished. There may be a separate
4994/// ActOnStartOfFunctionDef action later (not necessarily
4995/// immediately!) for this method, if it was also defined inside the
4996/// class body.
4997void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4998  if (!MethodD)
4999    return;
5000
5001  AdjustDeclIfTemplate(MethodD);
5002
5003  FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5004
5005  // Now that we have our default arguments, check the constructor
5006  // again. It could produce additional diagnostics or affect whether
5007  // the class has implicitly-declared destructors, among other
5008  // things.
5009  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5010    CheckConstructor(Constructor);
5011
5012  // Check the default arguments, which we may have added.
5013  if (!Method->isInvalidDecl())
5014    CheckCXXDefaultArguments(Method);
5015}
5016
5017/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5018/// the well-formedness of the constructor declarator @p D with type @p
5019/// R. If there are any errors in the declarator, this routine will
5020/// emit diagnostics and set the invalid bit to true.  In any case, the type
5021/// will be updated to reflect a well-formed type for the constructor and
5022/// returned.
5023QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5024                                          StorageClass &SC) {
5025  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5026
5027  // C++ [class.ctor]p3:
5028  //   A constructor shall not be virtual (10.3) or static (9.4). A
5029  //   constructor can be invoked for a const, volatile or const
5030  //   volatile object. A constructor shall not be declared const,
5031  //   volatile, or const volatile (9.3.2).
5032  if (isVirtual) {
5033    if (!D.isInvalidType())
5034      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5035        << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5036        << SourceRange(D.getIdentifierLoc());
5037    D.setInvalidType();
5038  }
5039  if (SC == SC_Static) {
5040    if (!D.isInvalidType())
5041      Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5042        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5043        << SourceRange(D.getIdentifierLoc());
5044    D.setInvalidType();
5045    SC = SC_None;
5046  }
5047
5048  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5049  if (FTI.TypeQuals != 0) {
5050    if (FTI.TypeQuals & Qualifiers::Const)
5051      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5052        << "const" << SourceRange(D.getIdentifierLoc());
5053    if (FTI.TypeQuals & Qualifiers::Volatile)
5054      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5055        << "volatile" << SourceRange(D.getIdentifierLoc());
5056    if (FTI.TypeQuals & Qualifiers::Restrict)
5057      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5058        << "restrict" << SourceRange(D.getIdentifierLoc());
5059    D.setInvalidType();
5060  }
5061
5062  // C++0x [class.ctor]p4:
5063  //   A constructor shall not be declared with a ref-qualifier.
5064  if (FTI.hasRefQualifier()) {
5065    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5066      << FTI.RefQualifierIsLValueRef
5067      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5068    D.setInvalidType();
5069  }
5070
5071  // Rebuild the function type "R" without any type qualifiers (in
5072  // case any of the errors above fired) and with "void" as the
5073  // return type, since constructors don't have return types.
5074  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5075  if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5076    return R;
5077
5078  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5079  EPI.TypeQuals = 0;
5080  EPI.RefQualifier = RQ_None;
5081
5082  return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5083                                 Proto->getNumArgs(), EPI);
5084}
5085
5086/// CheckConstructor - Checks a fully-formed constructor for
5087/// well-formedness, issuing any diagnostics required. Returns true if
5088/// the constructor declarator is invalid.
5089void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5090  CXXRecordDecl *ClassDecl
5091    = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5092  if (!ClassDecl)
5093    return Constructor->setInvalidDecl();
5094
5095  // C++ [class.copy]p3:
5096  //   A declaration of a constructor for a class X is ill-formed if
5097  //   its first parameter is of type (optionally cv-qualified) X and
5098  //   either there are no other parameters or else all other
5099  //   parameters have default arguments.
5100  if (!Constructor->isInvalidDecl() &&
5101      ((Constructor->getNumParams() == 1) ||
5102       (Constructor->getNumParams() > 1 &&
5103        Constructor->getParamDecl(1)->hasDefaultArg())) &&
5104      Constructor->getTemplateSpecializationKind()
5105                                              != TSK_ImplicitInstantiation) {
5106    QualType ParamType = Constructor->getParamDecl(0)->getType();
5107    QualType ClassTy = Context.getTagDeclType(ClassDecl);
5108    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5109      SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5110      const char *ConstRef
5111        = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5112                                                        : " const &";
5113      Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5114        << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5115
5116      // FIXME: Rather that making the constructor invalid, we should endeavor
5117      // to fix the type.
5118      Constructor->setInvalidDecl();
5119    }
5120  }
5121}
5122
5123/// CheckDestructor - Checks a fully-formed destructor definition for
5124/// well-formedness, issuing any diagnostics required.  Returns true
5125/// on error.
5126bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5127  CXXRecordDecl *RD = Destructor->getParent();
5128
5129  if (Destructor->isVirtual()) {
5130    SourceLocation Loc;
5131
5132    if (!Destructor->isImplicit())
5133      Loc = Destructor->getLocation();
5134    else
5135      Loc = RD->getLocation();
5136
5137    // If we have a virtual destructor, look up the deallocation function
5138    FunctionDecl *OperatorDelete = 0;
5139    DeclarationName Name =
5140    Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5141    if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5142      return true;
5143
5144    MarkFunctionReferenced(Loc, OperatorDelete);
5145
5146    Destructor->setOperatorDelete(OperatorDelete);
5147  }
5148
5149  return false;
5150}
5151
5152static inline bool
5153FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5154  return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5155          FTI.ArgInfo[0].Param &&
5156          cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5157}
5158
5159/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5160/// the well-formednes of the destructor declarator @p D with type @p
5161/// R. If there are any errors in the declarator, this routine will
5162/// emit diagnostics and set the declarator to invalid.  Even if this happens,
5163/// will be updated to reflect a well-formed type for the destructor and
5164/// returned.
5165QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5166                                         StorageClass& SC) {
5167  // C++ [class.dtor]p1:
5168  //   [...] A typedef-name that names a class is a class-name
5169  //   (7.1.3); however, a typedef-name that names a class shall not
5170  //   be used as the identifier in the declarator for a destructor
5171  //   declaration.
5172  QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5173  if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5174    Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5175      << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5176  else if (const TemplateSpecializationType *TST =
5177             DeclaratorType->getAs<TemplateSpecializationType>())
5178    if (TST->isTypeAlias())
5179      Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5180        << DeclaratorType << 1;
5181
5182  // C++ [class.dtor]p2:
5183  //   A destructor is used to destroy objects of its class type. A
5184  //   destructor takes no parameters, and no return type can be
5185  //   specified for it (not even void). The address of a destructor
5186  //   shall not be taken. A destructor shall not be static. A
5187  //   destructor can be invoked for a const, volatile or const
5188  //   volatile object. A destructor shall not be declared const,
5189  //   volatile or const volatile (9.3.2).
5190  if (SC == SC_Static) {
5191    if (!D.isInvalidType())
5192      Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5193        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5194        << SourceRange(D.getIdentifierLoc())
5195        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5196
5197    SC = SC_None;
5198  }
5199  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5200    // Destructors don't have return types, but the parser will
5201    // happily parse something like:
5202    //
5203    //   class X {
5204    //     float ~X();
5205    //   };
5206    //
5207    // The return type will be eliminated later.
5208    Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5209      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5210      << SourceRange(D.getIdentifierLoc());
5211  }
5212
5213  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5214  if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5215    if (FTI.TypeQuals & Qualifiers::Const)
5216      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5217        << "const" << SourceRange(D.getIdentifierLoc());
5218    if (FTI.TypeQuals & Qualifiers::Volatile)
5219      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5220        << "volatile" << SourceRange(D.getIdentifierLoc());
5221    if (FTI.TypeQuals & Qualifiers::Restrict)
5222      Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5223        << "restrict" << SourceRange(D.getIdentifierLoc());
5224    D.setInvalidType();
5225  }
5226
5227  // C++0x [class.dtor]p2:
5228  //   A destructor shall not be declared with a ref-qualifier.
5229  if (FTI.hasRefQualifier()) {
5230    Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5231      << FTI.RefQualifierIsLValueRef
5232      << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5233    D.setInvalidType();
5234  }
5235
5236  // Make sure we don't have any parameters.
5237  if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5238    Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5239
5240    // Delete the parameters.
5241    FTI.freeArgs();
5242    D.setInvalidType();
5243  }
5244
5245  // Make sure the destructor isn't variadic.
5246  if (FTI.isVariadic) {
5247    Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5248    D.setInvalidType();
5249  }
5250
5251  // Rebuild the function type "R" without any type qualifiers or
5252  // parameters (in case any of the errors above fired) and with
5253  // "void" as the return type, since destructors don't have return
5254  // types.
5255  if (!D.isInvalidType())
5256    return R;
5257
5258  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5259  FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5260  EPI.Variadic = false;
5261  EPI.TypeQuals = 0;
5262  EPI.RefQualifier = RQ_None;
5263  return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5264}
5265
5266/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5267/// well-formednes of the conversion function declarator @p D with
5268/// type @p R. If there are any errors in the declarator, this routine
5269/// will emit diagnostics and return true. Otherwise, it will return
5270/// false. Either way, the type @p R will be updated to reflect a
5271/// well-formed type for the conversion operator.
5272void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5273                                     StorageClass& SC) {
5274  // C++ [class.conv.fct]p1:
5275  //   Neither parameter types nor return type can be specified. The
5276  //   type of a conversion function (8.3.5) is "function taking no
5277  //   parameter returning conversion-type-id."
5278  if (SC == SC_Static) {
5279    if (!D.isInvalidType())
5280      Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5281        << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5282        << SourceRange(D.getIdentifierLoc());
5283    D.setInvalidType();
5284    SC = SC_None;
5285  }
5286
5287  QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5288
5289  if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5290    // Conversion functions don't have return types, but the parser will
5291    // happily parse something like:
5292    //
5293    //   class X {
5294    //     float operator bool();
5295    //   };
5296    //
5297    // The return type will be changed later anyway.
5298    Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5299      << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5300      << SourceRange(D.getIdentifierLoc());
5301    D.setInvalidType();
5302  }
5303
5304  const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5305
5306  // Make sure we don't have any parameters.
5307  if (Proto->getNumArgs() > 0) {
5308    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5309
5310    // Delete the parameters.
5311    D.getFunctionTypeInfo().freeArgs();
5312    D.setInvalidType();
5313  } else if (Proto->isVariadic()) {
5314    Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5315    D.setInvalidType();
5316  }
5317
5318  // Diagnose "&operator bool()" and other such nonsense.  This
5319  // is actually a gcc extension which we don't support.
5320  if (Proto->getResultType() != ConvType) {
5321    Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5322      << Proto->getResultType();
5323    D.setInvalidType();
5324    ConvType = Proto->getResultType();
5325  }
5326
5327  // C++ [class.conv.fct]p4:
5328  //   The conversion-type-id shall not represent a function type nor
5329  //   an array type.
5330  if (ConvType->isArrayType()) {
5331    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5332    ConvType = Context.getPointerType(ConvType);
5333    D.setInvalidType();
5334  } else if (ConvType->isFunctionType()) {
5335    Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5336    ConvType = Context.getPointerType(ConvType);
5337    D.setInvalidType();
5338  }
5339
5340  // Rebuild the function type "R" without any parameters (in case any
5341  // of the errors above fired) and with the conversion type as the
5342  // return type.
5343  if (D.isInvalidType())
5344    R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5345
5346  // C++0x explicit conversion operators.
5347  if (D.getDeclSpec().isExplicitSpecified())
5348    Diag(D.getDeclSpec().getExplicitSpecLoc(),
5349         getLangOpts().CPlusPlus0x ?
5350           diag::warn_cxx98_compat_explicit_conversion_functions :
5351           diag::ext_explicit_conversion_functions)
5352      << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5353}
5354
5355/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5356/// the declaration of the given C++ conversion function. This routine
5357/// is responsible for recording the conversion function in the C++
5358/// class, if possible.
5359Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5360  assert(Conversion && "Expected to receive a conversion function declaration");
5361
5362  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5363
5364  // Make sure we aren't redeclaring the conversion function.
5365  QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5366
5367  // C++ [class.conv.fct]p1:
5368  //   [...] A conversion function is never used to convert a
5369  //   (possibly cv-qualified) object to the (possibly cv-qualified)
5370  //   same object type (or a reference to it), to a (possibly
5371  //   cv-qualified) base class of that type (or a reference to it),
5372  //   or to (possibly cv-qualified) void.
5373  // FIXME: Suppress this warning if the conversion function ends up being a
5374  // virtual function that overrides a virtual function in a base class.
5375  QualType ClassType
5376    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5377  if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5378    ConvType = ConvTypeRef->getPointeeType();
5379  if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5380      Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5381    /* Suppress diagnostics for instantiations. */;
5382  else if (ConvType->isRecordType()) {
5383    ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5384    if (ConvType == ClassType)
5385      Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5386        << ClassType;
5387    else if (IsDerivedFrom(ClassType, ConvType))
5388      Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5389        <<  ClassType << ConvType;
5390  } else if (ConvType->isVoidType()) {
5391    Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5392      << ClassType << ConvType;
5393  }
5394
5395  if (FunctionTemplateDecl *ConversionTemplate
5396                                = Conversion->getDescribedFunctionTemplate())
5397    return ConversionTemplate;
5398
5399  return Conversion;
5400}
5401
5402//===----------------------------------------------------------------------===//
5403// Namespace Handling
5404//===----------------------------------------------------------------------===//
5405
5406
5407
5408/// ActOnStartNamespaceDef - This is called at the start of a namespace
5409/// definition.
5410Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5411                                   SourceLocation InlineLoc,
5412                                   SourceLocation NamespaceLoc,
5413                                   SourceLocation IdentLoc,
5414                                   IdentifierInfo *II,
5415                                   SourceLocation LBrace,
5416                                   AttributeList *AttrList) {
5417  SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5418  // For anonymous namespace, take the location of the left brace.
5419  SourceLocation Loc = II ? IdentLoc : LBrace;
5420  bool IsInline = InlineLoc.isValid();
5421  bool IsInvalid = false;
5422  bool IsStd = false;
5423  bool AddToKnown = false;
5424  Scope *DeclRegionScope = NamespcScope->getParent();
5425
5426  NamespaceDecl *PrevNS = 0;
5427  if (II) {
5428    // C++ [namespace.def]p2:
5429    //   The identifier in an original-namespace-definition shall not
5430    //   have been previously defined in the declarative region in
5431    //   which the original-namespace-definition appears. The
5432    //   identifier in an original-namespace-definition is the name of
5433    //   the namespace. Subsequently in that declarative region, it is
5434    //   treated as an original-namespace-name.
5435    //
5436    // Since namespace names are unique in their scope, and we don't
5437    // look through using directives, just look for any ordinary names.
5438
5439    const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5440    Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5441    Decl::IDNS_Namespace;
5442    NamedDecl *PrevDecl = 0;
5443    for (DeclContext::lookup_result R
5444         = CurContext->getRedeclContext()->lookup(II);
5445         R.first != R.second; ++R.first) {
5446      if ((*R.first)->getIdentifierNamespace() & IDNS) {
5447        PrevDecl = *R.first;
5448        break;
5449      }
5450    }
5451
5452    PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5453
5454    if (PrevNS) {
5455      // This is an extended namespace definition.
5456      if (IsInline != PrevNS->isInline()) {
5457        // inline-ness must match
5458        if (PrevNS->isInline()) {
5459          // The user probably just forgot the 'inline', so suggest that it
5460          // be added back.
5461          Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
5462            << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5463        } else {
5464          Diag(Loc, diag::err_inline_namespace_mismatch)
5465            << IsInline;
5466        }
5467        Diag(PrevNS->getLocation(), diag::note_previous_definition);
5468
5469        IsInline = PrevNS->isInline();
5470      }
5471    } else if (PrevDecl) {
5472      // This is an invalid name redefinition.
5473      Diag(Loc, diag::err_redefinition_different_kind)
5474        << II;
5475      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5476      IsInvalid = true;
5477      // Continue on to push Namespc as current DeclContext and return it.
5478    } else if (II->isStr("std") &&
5479               CurContext->getRedeclContext()->isTranslationUnit()) {
5480      // This is the first "real" definition of the namespace "std", so update
5481      // our cache of the "std" namespace to point at this definition.
5482      PrevNS = getStdNamespace();
5483      IsStd = true;
5484      AddToKnown = !IsInline;
5485    } else {
5486      // We've seen this namespace for the first time.
5487      AddToKnown = !IsInline;
5488    }
5489  } else {
5490    // Anonymous namespaces.
5491
5492    // Determine whether the parent already has an anonymous namespace.
5493    DeclContext *Parent = CurContext->getRedeclContext();
5494    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5495      PrevNS = TU->getAnonymousNamespace();
5496    } else {
5497      NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5498      PrevNS = ND->getAnonymousNamespace();
5499    }
5500
5501    if (PrevNS && IsInline != PrevNS->isInline()) {
5502      // inline-ness must match
5503      Diag(Loc, diag::err_inline_namespace_mismatch)
5504        << IsInline;
5505      Diag(PrevNS->getLocation(), diag::note_previous_definition);
5506
5507      // Recover by ignoring the new namespace's inline status.
5508      IsInline = PrevNS->isInline();
5509    }
5510  }
5511
5512  NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5513                                                 StartLoc, Loc, II, PrevNS);
5514  if (IsInvalid)
5515    Namespc->setInvalidDecl();
5516
5517  ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5518
5519  // FIXME: Should we be merging attributes?
5520  if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5521    PushNamespaceVisibilityAttr(Attr, Loc);
5522
5523  if (IsStd)
5524    StdNamespace = Namespc;
5525  if (AddToKnown)
5526    KnownNamespaces[Namespc] = false;
5527
5528  if (II) {
5529    PushOnScopeChains(Namespc, DeclRegionScope);
5530  } else {
5531    // Link the anonymous namespace into its parent.
5532    DeclContext *Parent = CurContext->getRedeclContext();
5533    if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5534      TU->setAnonymousNamespace(Namespc);
5535    } else {
5536      cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
5537    }
5538
5539    CurContext->addDecl(Namespc);
5540
5541    // C++ [namespace.unnamed]p1.  An unnamed-namespace-definition
5542    //   behaves as if it were replaced by
5543    //     namespace unique { /* empty body */ }
5544    //     using namespace unique;
5545    //     namespace unique { namespace-body }
5546    //   where all occurrences of 'unique' in a translation unit are
5547    //   replaced by the same identifier and this identifier differs
5548    //   from all other identifiers in the entire program.
5549
5550    // We just create the namespace with an empty name and then add an
5551    // implicit using declaration, just like the standard suggests.
5552    //
5553    // CodeGen enforces the "universally unique" aspect by giving all
5554    // declarations semantically contained within an anonymous
5555    // namespace internal linkage.
5556
5557    if (!PrevNS) {
5558      UsingDirectiveDecl* UD
5559        = UsingDirectiveDecl::Create(Context, CurContext,
5560                                     /* 'using' */ LBrace,
5561                                     /* 'namespace' */ SourceLocation(),
5562                                     /* qualifier */ NestedNameSpecifierLoc(),
5563                                     /* identifier */ SourceLocation(),
5564                                     Namespc,
5565                                     /* Ancestor */ CurContext);
5566      UD->setImplicit();
5567      CurContext->addDecl(UD);
5568    }
5569  }
5570
5571  // Although we could have an invalid decl (i.e. the namespace name is a
5572  // redefinition), push it as current DeclContext and try to continue parsing.
5573  // FIXME: We should be able to push Namespc here, so that the each DeclContext
5574  // for the namespace has the declarations that showed up in that particular
5575  // namespace definition.
5576  PushDeclContext(NamespcScope, Namespc);
5577  return Namespc;
5578}
5579
5580/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5581/// is a namespace alias, returns the namespace it points to.
5582static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5583  if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5584    return AD->getNamespace();
5585  return dyn_cast_or_null<NamespaceDecl>(D);
5586}
5587
5588/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5589/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5590void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5591  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5592  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5593  Namespc->setRBraceLoc(RBrace);
5594  PopDeclContext();
5595  if (Namespc->hasAttr<VisibilityAttr>())
5596    PopPragmaVisibility(true, RBrace);
5597}
5598
5599CXXRecordDecl *Sema::getStdBadAlloc() const {
5600  return cast_or_null<CXXRecordDecl>(
5601                                  StdBadAlloc.get(Context.getExternalSource()));
5602}
5603
5604NamespaceDecl *Sema::getStdNamespace() const {
5605  return cast_or_null<NamespaceDecl>(
5606                                 StdNamespace.get(Context.getExternalSource()));
5607}
5608
5609/// \brief Retrieve the special "std" namespace, which may require us to
5610/// implicitly define the namespace.
5611NamespaceDecl *Sema::getOrCreateStdNamespace() {
5612  if (!StdNamespace) {
5613    // The "std" namespace has not yet been defined, so build one implicitly.
5614    StdNamespace = NamespaceDecl::Create(Context,
5615                                         Context.getTranslationUnitDecl(),
5616                                         /*Inline=*/false,
5617                                         SourceLocation(), SourceLocation(),
5618                                         &PP.getIdentifierTable().get("std"),
5619                                         /*PrevDecl=*/0);
5620    getStdNamespace()->setImplicit(true);
5621  }
5622
5623  return getStdNamespace();
5624}
5625
5626bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5627  assert(getLangOpts().CPlusPlus &&
5628         "Looking for std::initializer_list outside of C++.");
5629
5630  // We're looking for implicit instantiations of
5631  // template <typename E> class std::initializer_list.
5632
5633  if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5634    return false;
5635
5636  ClassTemplateDecl *Template = 0;
5637  const TemplateArgument *Arguments = 0;
5638
5639  if (const RecordType *RT = Ty->getAs<RecordType>()) {
5640
5641    ClassTemplateSpecializationDecl *Specialization =
5642        dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5643    if (!Specialization)
5644      return false;
5645
5646    Template = Specialization->getSpecializedTemplate();
5647    Arguments = Specialization->getTemplateArgs().data();
5648  } else if (const TemplateSpecializationType *TST =
5649                 Ty->getAs<TemplateSpecializationType>()) {
5650    Template = dyn_cast_or_null<ClassTemplateDecl>(
5651        TST->getTemplateName().getAsTemplateDecl());
5652    Arguments = TST->getArgs();
5653  }
5654  if (!Template)
5655    return false;
5656
5657  if (!StdInitializerList) {
5658    // Haven't recognized std::initializer_list yet, maybe this is it.
5659    CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5660    if (TemplateClass->getIdentifier() !=
5661            &PP.getIdentifierTable().get("initializer_list") ||
5662        !getStdNamespace()->InEnclosingNamespaceSetOf(
5663            TemplateClass->getDeclContext()))
5664      return false;
5665    // This is a template called std::initializer_list, but is it the right
5666    // template?
5667    TemplateParameterList *Params = Template->getTemplateParameters();
5668    if (Params->getMinRequiredArguments() != 1)
5669      return false;
5670    if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5671      return false;
5672
5673    // It's the right template.
5674    StdInitializerList = Template;
5675  }
5676
5677  if (Template != StdInitializerList)
5678    return false;
5679
5680  // This is an instance of std::initializer_list. Find the argument type.
5681  if (Element)
5682    *Element = Arguments[0].getAsType();
5683  return true;
5684}
5685
5686static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5687  NamespaceDecl *Std = S.getStdNamespace();
5688  if (!Std) {
5689    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5690    return 0;
5691  }
5692
5693  LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5694                      Loc, Sema::LookupOrdinaryName);
5695  if (!S.LookupQualifiedName(Result, Std)) {
5696    S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5697    return 0;
5698  }
5699  ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5700  if (!Template) {
5701    Result.suppressDiagnostics();
5702    // We found something weird. Complain about the first thing we found.
5703    NamedDecl *Found = *Result.begin();
5704    S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5705    return 0;
5706  }
5707
5708  // We found some template called std::initializer_list. Now verify that it's
5709  // correct.
5710  TemplateParameterList *Params = Template->getTemplateParameters();
5711  if (Params->getMinRequiredArguments() != 1 ||
5712      !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5713    S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5714    return 0;
5715  }
5716
5717  return Template;
5718}
5719
5720QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5721  if (!StdInitializerList) {
5722    StdInitializerList = LookupStdInitializerList(*this, Loc);
5723    if (!StdInitializerList)
5724      return QualType();
5725  }
5726
5727  TemplateArgumentListInfo Args(Loc, Loc);
5728  Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5729                                       Context.getTrivialTypeSourceInfo(Element,
5730                                                                        Loc)));
5731  return Context.getCanonicalType(
5732      CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5733}
5734
5735bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5736  // C++ [dcl.init.list]p2:
5737  //   A constructor is an initializer-list constructor if its first parameter
5738  //   is of type std::initializer_list<E> or reference to possibly cv-qualified
5739  //   std::initializer_list<E> for some type E, and either there are no other
5740  //   parameters or else all other parameters have default arguments.
5741  if (Ctor->getNumParams() < 1 ||
5742      (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5743    return false;
5744
5745  QualType ArgType = Ctor->getParamDecl(0)->getType();
5746  if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5747    ArgType = RT->getPointeeType().getUnqualifiedType();
5748
5749  return isStdInitializerList(ArgType, 0);
5750}
5751
5752/// \brief Determine whether a using statement is in a context where it will be
5753/// apply in all contexts.
5754static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5755  switch (CurContext->getDeclKind()) {
5756    case Decl::TranslationUnit:
5757      return true;
5758    case Decl::LinkageSpec:
5759      return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5760    default:
5761      return false;
5762  }
5763}
5764
5765namespace {
5766
5767// Callback to only accept typo corrections that are namespaces.
5768class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5769 public:
5770  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5771    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5772      return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5773    }
5774    return false;
5775  }
5776};
5777
5778}
5779
5780static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5781                                       CXXScopeSpec &SS,
5782                                       SourceLocation IdentLoc,
5783                                       IdentifierInfo *Ident) {
5784  NamespaceValidatorCCC Validator;
5785  R.clear();
5786  if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5787                                               R.getLookupKind(), Sc, &SS,
5788                                               Validator)) {
5789    std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
5790    std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOpts()));
5791    if (DeclContext *DC = S.computeDeclContext(SS, false))
5792      S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5793        << Ident << DC << CorrectedQuotedStr << SS.getRange()
5794        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5795    else
5796      S.Diag(IdentLoc, diag::err_using_directive_suggest)
5797        << Ident << CorrectedQuotedStr
5798        << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5799
5800    S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5801         diag::note_namespace_defined_here) << CorrectedQuotedStr;
5802
5803    R.addDecl(Corrected.getCorrectionDecl());
5804    return true;
5805  }
5806  return false;
5807}
5808
5809Decl *Sema::ActOnUsingDirective(Scope *S,
5810                                          SourceLocation UsingLoc,
5811                                          SourceLocation NamespcLoc,
5812                                          CXXScopeSpec &SS,
5813                                          SourceLocation IdentLoc,
5814                                          IdentifierInfo *NamespcName,
5815                                          AttributeList *AttrList) {
5816  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5817  assert(NamespcName && "Invalid NamespcName.");
5818  assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5819
5820  // This can only happen along a recovery path.
5821  while (S->getFlags() & Scope::TemplateParamScope)
5822    S = S->getParent();
5823  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5824
5825  UsingDirectiveDecl *UDir = 0;
5826  NestedNameSpecifier *Qualifier = 0;
5827  if (SS.isSet())
5828    Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5829
5830  // Lookup namespace name.
5831  LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5832  LookupParsedName(R, S, &SS);
5833  if (R.isAmbiguous())
5834    return 0;
5835
5836  if (R.empty()) {
5837    R.clear();
5838    // Allow "using namespace std;" or "using namespace ::std;" even if
5839    // "std" hasn't been defined yet, for GCC compatibility.
5840    if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5841        NamespcName->isStr("std")) {
5842      Diag(IdentLoc, diag::ext_using_undefined_std);
5843      R.addDecl(getOrCreateStdNamespace());
5844      R.resolveKind();
5845    }
5846    // Otherwise, attempt typo correction.
5847    else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5848  }
5849
5850  if (!R.empty()) {
5851    NamedDecl *Named = R.getFoundDecl();
5852    assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5853        && "expected namespace decl");
5854    // C++ [namespace.udir]p1:
5855    //   A using-directive specifies that the names in the nominated
5856    //   namespace can be used in the scope in which the
5857    //   using-directive appears after the using-directive. During
5858    //   unqualified name lookup (3.4.1), the names appear as if they
5859    //   were declared in the nearest enclosing namespace which
5860    //   contains both the using-directive and the nominated
5861    //   namespace. [Note: in this context, "contains" means "contains
5862    //   directly or indirectly". ]
5863
5864    // Find enclosing context containing both using-directive and
5865    // nominated namespace.
5866    NamespaceDecl *NS = getNamespaceDecl(Named);
5867    DeclContext *CommonAncestor = cast<DeclContext>(NS);
5868    while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5869      CommonAncestor = CommonAncestor->getParent();
5870
5871    UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5872                                      SS.getWithLocInContext(Context),
5873                                      IdentLoc, Named, CommonAncestor);
5874
5875    if (IsUsingDirectiveInToplevelContext(CurContext) &&
5876        !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5877      Diag(IdentLoc, diag::warn_using_directive_in_header);
5878    }
5879
5880    PushUsingDirective(S, UDir);
5881  } else {
5882    Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5883  }
5884
5885  // FIXME: We ignore attributes for now.
5886  return UDir;
5887}
5888
5889void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5890  // If the scope has an associated entity and the using directive is at
5891  // namespace or translation unit scope, add the UsingDirectiveDecl into
5892  // its lookup structure so qualified name lookup can find it.
5893  DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity());
5894  if (Ctx && !Ctx->isFunctionOrMethod())
5895    Ctx->addDecl(UDir);
5896  else
5897    // Otherwise, it is at block sope. The using-directives will affect lookup
5898    // only to the end of the scope.
5899    S->PushUsingDirective(UDir);
5900}
5901
5902
5903Decl *Sema::ActOnUsingDeclaration(Scope *S,
5904                                  AccessSpecifier AS,
5905                                  bool HasUsingKeyword,
5906                                  SourceLocation UsingLoc,
5907                                  CXXScopeSpec &SS,
5908                                  UnqualifiedId &Name,
5909                                  AttributeList *AttrList,
5910                                  bool IsTypeName,
5911                                  SourceLocation TypenameLoc) {
5912  assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5913
5914  switch (Name.getKind()) {
5915  case UnqualifiedId::IK_ImplicitSelfParam:
5916  case UnqualifiedId::IK_Identifier:
5917  case UnqualifiedId::IK_OperatorFunctionId:
5918  case UnqualifiedId::IK_LiteralOperatorId:
5919  case UnqualifiedId::IK_ConversionFunctionId:
5920    break;
5921
5922  case UnqualifiedId::IK_ConstructorName:
5923  case UnqualifiedId::IK_ConstructorTemplateId:
5924    // C++0x inherited constructors.
5925    Diag(Name.getLocStart(),
5926         getLangOpts().CPlusPlus0x ?
5927           diag::warn_cxx98_compat_using_decl_constructor :
5928           diag::err_using_decl_constructor)
5929      << SS.getRange();
5930
5931    if (getLangOpts().CPlusPlus0x) break;
5932
5933    return 0;
5934
5935  case UnqualifiedId::IK_DestructorName:
5936    Diag(Name.getLocStart(), diag::err_using_decl_destructor)
5937      << SS.getRange();
5938    return 0;
5939
5940  case UnqualifiedId::IK_TemplateId:
5941    Diag(Name.getLocStart(), diag::err_using_decl_template_id)
5942      << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5943    return 0;
5944  }
5945
5946  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5947  DeclarationName TargetName = TargetNameInfo.getName();
5948  if (!TargetName)
5949    return 0;
5950
5951  // Warn about using declarations.
5952  // TODO: store that the declaration was written without 'using' and
5953  // talk about access decls instead of using decls in the
5954  // diagnostics.
5955  if (!HasUsingKeyword) {
5956    UsingLoc = Name.getLocStart();
5957
5958    Diag(UsingLoc, diag::warn_access_decl_deprecated)
5959      << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5960  }
5961
5962  if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5963      DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5964    return 0;
5965
5966  NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5967                                        TargetNameInfo, AttrList,
5968                                        /* IsInstantiation */ false,
5969                                        IsTypeName, TypenameLoc);
5970  if (UD)
5971    PushOnScopeChains(UD, S, /*AddToContext*/ false);
5972
5973  return UD;
5974}
5975
5976/// \brief Determine whether a using declaration considers the given
5977/// declarations as "equivalent", e.g., if they are redeclarations of
5978/// the same entity or are both typedefs of the same type.
5979static bool
5980IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5981                         bool &SuppressRedeclaration) {
5982  if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5983    SuppressRedeclaration = false;
5984    return true;
5985  }
5986
5987  if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5988    if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5989      SuppressRedeclaration = true;
5990      return Context.hasSameType(TD1->getUnderlyingType(),
5991                                 TD2->getUnderlyingType());
5992    }
5993
5994  return false;
5995}
5996
5997
5998/// Determines whether to create a using shadow decl for a particular
5999/// decl, given the set of decls existing prior to this using lookup.
6000bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6001                                const LookupResult &Previous) {
6002  // Diagnose finding a decl which is not from a base class of the
6003  // current class.  We do this now because there are cases where this
6004  // function will silently decide not to build a shadow decl, which
6005  // will pre-empt further diagnostics.
6006  //
6007  // We don't need to do this in C++0x because we do the check once on
6008  // the qualifier.
6009  //
6010  // FIXME: diagnose the following if we care enough:
6011  //   struct A { int foo; };
6012  //   struct B : A { using A::foo; };
6013  //   template <class T> struct C : A {};
6014  //   template <class T> struct D : C<T> { using B::foo; } // <---
6015  // This is invalid (during instantiation) in C++03 because B::foo
6016  // resolves to the using decl in B, which is not a base class of D<T>.
6017  // We can't diagnose it immediately because C<T> is an unknown
6018  // specialization.  The UsingShadowDecl in D<T> then points directly
6019  // to A::foo, which will look well-formed when we instantiate.
6020  // The right solution is to not collapse the shadow-decl chain.
6021  if (!getLangOpts().CPlusPlus0x && CurContext->isRecord()) {
6022    DeclContext *OrigDC = Orig->getDeclContext();
6023
6024    // Handle enums and anonymous structs.
6025    if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6026    CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6027    while (OrigRec->isAnonymousStructOrUnion())
6028      OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6029
6030    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6031      if (OrigDC == CurContext) {
6032        Diag(Using->getLocation(),
6033             diag::err_using_decl_nested_name_specifier_is_current_class)
6034          << Using->getQualifierLoc().getSourceRange();
6035        Diag(Orig->getLocation(), diag::note_using_decl_target);
6036        return true;
6037      }
6038
6039      Diag(Using->getQualifierLoc().getBeginLoc(),
6040           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6041        << Using->getQualifier()
6042        << cast<CXXRecordDecl>(CurContext)
6043        << Using->getQualifierLoc().getSourceRange();
6044      Diag(Orig->getLocation(), diag::note_using_decl_target);
6045      return true;
6046    }
6047  }
6048
6049  if (Previous.empty()) return false;
6050
6051  NamedDecl *Target = Orig;
6052  if (isa<UsingShadowDecl>(Target))
6053    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6054
6055  // If the target happens to be one of the previous declarations, we
6056  // don't have a conflict.
6057  //
6058  // FIXME: but we might be increasing its access, in which case we
6059  // should redeclare it.
6060  NamedDecl *NonTag = 0, *Tag = 0;
6061  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6062         I != E; ++I) {
6063    NamedDecl *D = (*I)->getUnderlyingDecl();
6064    bool Result;
6065    if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6066      return Result;
6067
6068    (isa<TagDecl>(D) ? Tag : NonTag) = D;
6069  }
6070
6071  if (Target->isFunctionOrFunctionTemplate()) {
6072    FunctionDecl *FD;
6073    if (isa<FunctionTemplateDecl>(Target))
6074      FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6075    else
6076      FD = cast<FunctionDecl>(Target);
6077
6078    NamedDecl *OldDecl = 0;
6079    switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
6080    case Ovl_Overload:
6081      return false;
6082
6083    case Ovl_NonFunction:
6084      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6085      break;
6086
6087    // We found a decl with the exact signature.
6088    case Ovl_Match:
6089      // If we're in a record, we want to hide the target, so we
6090      // return true (without a diagnostic) to tell the caller not to
6091      // build a shadow decl.
6092      if (CurContext->isRecord())
6093        return true;
6094
6095      // If we're not in a record, this is an error.
6096      Diag(Using->getLocation(), diag::err_using_decl_conflict);
6097      break;
6098    }
6099
6100    Diag(Target->getLocation(), diag::note_using_decl_target);
6101    Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6102    return true;
6103  }
6104
6105  // Target is not a function.
6106
6107  if (isa<TagDecl>(Target)) {
6108    // No conflict between a tag and a non-tag.
6109    if (!Tag) return false;
6110
6111    Diag(Using->getLocation(), diag::err_using_decl_conflict);
6112    Diag(Target->getLocation(), diag::note_using_decl_target);
6113    Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6114    return true;
6115  }
6116
6117  // No conflict between a tag and a non-tag.
6118  if (!NonTag) return false;
6119
6120  Diag(Using->getLocation(), diag::err_using_decl_conflict);
6121  Diag(Target->getLocation(), diag::note_using_decl_target);
6122  Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6123  return true;
6124}
6125
6126/// Builds a shadow declaration corresponding to a 'using' declaration.
6127UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
6128                                            UsingDecl *UD,
6129                                            NamedDecl *Orig) {
6130
6131  // If we resolved to another shadow declaration, just coalesce them.
6132  NamedDecl *Target = Orig;
6133  if (isa<UsingShadowDecl>(Target)) {
6134    Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6135    assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6136  }
6137
6138  UsingShadowDecl *Shadow
6139    = UsingShadowDecl::Create(Context, CurContext,
6140                              UD->getLocation(), UD, Target);
6141  UD->addShadowDecl(Shadow);
6142
6143  Shadow->setAccess(UD->getAccess());
6144  if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6145    Shadow->setInvalidDecl();
6146
6147  if (S)
6148    PushOnScopeChains(Shadow, S);
6149  else
6150    CurContext->addDecl(Shadow);
6151
6152
6153  return Shadow;
6154}
6155
6156/// Hides a using shadow declaration.  This is required by the current
6157/// using-decl implementation when a resolvable using declaration in a
6158/// class is followed by a declaration which would hide or override
6159/// one or more of the using decl's targets; for example:
6160///
6161///   struct Base { void foo(int); };
6162///   struct Derived : Base {
6163///     using Base::foo;
6164///     void foo(int);
6165///   };
6166///
6167/// The governing language is C++03 [namespace.udecl]p12:
6168///
6169///   When a using-declaration brings names from a base class into a
6170///   derived class scope, member functions in the derived class
6171///   override and/or hide member functions with the same name and
6172///   parameter types in a base class (rather than conflicting).
6173///
6174/// There are two ways to implement this:
6175///   (1) optimistically create shadow decls when they're not hidden
6176///       by existing declarations, or
6177///   (2) don't create any shadow decls (or at least don't make them
6178///       visible) until we've fully parsed/instantiated the class.
6179/// The problem with (1) is that we might have to retroactively remove
6180/// a shadow decl, which requires several O(n) operations because the
6181/// decl structures are (very reasonably) not designed for removal.
6182/// (2) avoids this but is very fiddly and phase-dependent.
6183void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6184  if (Shadow->getDeclName().getNameKind() ==
6185        DeclarationName::CXXConversionFunctionName)
6186    cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6187
6188  // Remove it from the DeclContext...
6189  Shadow->getDeclContext()->removeDecl(Shadow);
6190
6191  // ...and the scope, if applicable...
6192  if (S) {
6193    S->RemoveDecl(Shadow);
6194    IdResolver.RemoveDecl(Shadow);
6195  }
6196
6197  // ...and the using decl.
6198  Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6199
6200  // TODO: complain somehow if Shadow was used.  It shouldn't
6201  // be possible for this to happen, because...?
6202}
6203
6204/// Builds a using declaration.
6205///
6206/// \param IsInstantiation - Whether this call arises from an
6207///   instantiation of an unresolved using declaration.  We treat
6208///   the lookup differently for these declarations.
6209NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6210                                       SourceLocation UsingLoc,
6211                                       CXXScopeSpec &SS,
6212                                       const DeclarationNameInfo &NameInfo,
6213                                       AttributeList *AttrList,
6214                                       bool IsInstantiation,
6215                                       bool IsTypeName,
6216                                       SourceLocation TypenameLoc) {
6217  assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6218  SourceLocation IdentLoc = NameInfo.getLoc();
6219  assert(IdentLoc.isValid() && "Invalid TargetName location.");
6220
6221  // FIXME: We ignore attributes for now.
6222
6223  if (SS.isEmpty()) {
6224    Diag(IdentLoc, diag::err_using_requires_qualname);
6225    return 0;
6226  }
6227
6228  // Do the redeclaration lookup in the current scope.
6229  LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6230                        ForRedeclaration);
6231  Previous.setHideTags(false);
6232  if (S) {
6233    LookupName(Previous, S);
6234
6235    // It is really dumb that we have to do this.
6236    LookupResult::Filter F = Previous.makeFilter();
6237    while (F.hasNext()) {
6238      NamedDecl *D = F.next();
6239      if (!isDeclInScope(D, CurContext, S))
6240        F.erase();
6241    }
6242    F.done();
6243  } else {
6244    assert(IsInstantiation && "no scope in non-instantiation");
6245    assert(CurContext->isRecord() && "scope not record in instantiation");
6246    LookupQualifiedName(Previous, CurContext);
6247  }
6248
6249  // Check for invalid redeclarations.
6250  if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6251    return 0;
6252
6253  // Check for bad qualifiers.
6254  if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6255    return 0;
6256
6257  DeclContext *LookupContext = computeDeclContext(SS);
6258  NamedDecl *D;
6259  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6260  if (!LookupContext) {
6261    if (IsTypeName) {
6262      // FIXME: not all declaration name kinds are legal here
6263      D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6264                                              UsingLoc, TypenameLoc,
6265                                              QualifierLoc,
6266                                              IdentLoc, NameInfo.getName());
6267    } else {
6268      D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6269                                           QualifierLoc, NameInfo);
6270    }
6271  } else {
6272    D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6273                          NameInfo, IsTypeName);
6274  }
6275  D->setAccess(AS);
6276  CurContext->addDecl(D);
6277
6278  if (!LookupContext) return D;
6279  UsingDecl *UD = cast<UsingDecl>(D);
6280
6281  if (RequireCompleteDeclContext(SS, LookupContext)) {
6282    UD->setInvalidDecl();
6283    return UD;
6284  }
6285
6286  // The normal rules do not apply to inheriting constructor declarations.
6287  if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6288    if (CheckInheritingConstructorUsingDecl(UD))
6289      UD->setInvalidDecl();
6290    return UD;
6291  }
6292
6293  // Otherwise, look up the target name.
6294
6295  LookupResult R(*this, NameInfo, LookupOrdinaryName);
6296
6297  // Unlike most lookups, we don't always want to hide tag
6298  // declarations: tag names are visible through the using declaration
6299  // even if hidden by ordinary names, *except* in a dependent context
6300  // where it's important for the sanity of two-phase lookup.
6301  if (!IsInstantiation)
6302    R.setHideTags(false);
6303
6304  // For the purposes of this lookup, we have a base object type
6305  // equal to that of the current context.
6306  if (CurContext->isRecord()) {
6307    R.setBaseObjectType(
6308                   Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
6309  }
6310
6311  LookupQualifiedName(R, LookupContext);
6312
6313  if (R.empty()) {
6314    Diag(IdentLoc, diag::err_no_member)
6315      << NameInfo.getName() << LookupContext << SS.getRange();
6316    UD->setInvalidDecl();
6317    return UD;
6318  }
6319
6320  if (R.isAmbiguous()) {
6321    UD->setInvalidDecl();
6322    return UD;
6323  }
6324
6325  if (IsTypeName) {
6326    // If we asked for a typename and got a non-type decl, error out.
6327    if (!R.getAsSingle<TypeDecl>()) {
6328      Diag(IdentLoc, diag::err_using_typename_non_type);
6329      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6330        Diag((*I)->getUnderlyingDecl()->getLocation(),
6331             diag::note_using_decl_target);
6332      UD->setInvalidDecl();
6333      return UD;
6334    }
6335  } else {
6336    // If we asked for a non-typename and we got a type, error out,
6337    // but only if this is an instantiation of an unresolved using
6338    // decl.  Otherwise just silently find the type name.
6339    if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6340      Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6341      Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6342      UD->setInvalidDecl();
6343      return UD;
6344    }
6345  }
6346
6347  // C++0x N2914 [namespace.udecl]p6:
6348  // A using-declaration shall not name a namespace.
6349  if (R.getAsSingle<NamespaceDecl>()) {
6350    Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6351      << SS.getRange();
6352    UD->setInvalidDecl();
6353    return UD;
6354  }
6355
6356  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6357    if (!CheckUsingShadowDecl(UD, *I, Previous))
6358      BuildUsingShadowDecl(S, UD, *I);
6359  }
6360
6361  return UD;
6362}
6363
6364/// Additional checks for a using declaration referring to a constructor name.
6365bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
6366  assert(!UD->isTypeName() && "expecting a constructor name");
6367
6368  const Type *SourceType = UD->getQualifier()->getAsType();
6369  assert(SourceType &&
6370         "Using decl naming constructor doesn't have type in scope spec.");
6371  CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6372
6373  // Check whether the named type is a direct base class.
6374  CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6375  CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6376  for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6377       BaseIt != BaseE; ++BaseIt) {
6378    CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6379    if (CanonicalSourceType == BaseType)
6380      break;
6381    if (BaseIt->getType()->isDependentType())
6382      break;
6383  }
6384
6385  if (BaseIt == BaseE) {
6386    // Did not find SourceType in the bases.
6387    Diag(UD->getUsingLocation(),
6388         diag::err_using_decl_constructor_not_in_direct_base)
6389      << UD->getNameInfo().getSourceRange()
6390      << QualType(SourceType, 0) << TargetClass;
6391    return true;
6392  }
6393
6394  if (!CurContext->isDependentContext())
6395    BaseIt->setInheritConstructors();
6396
6397  return false;
6398}
6399
6400/// Checks that the given using declaration is not an invalid
6401/// redeclaration.  Note that this is checking only for the using decl
6402/// itself, not for any ill-formedness among the UsingShadowDecls.
6403bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6404                                       bool isTypeName,
6405                                       const CXXScopeSpec &SS,
6406                                       SourceLocation NameLoc,
6407                                       const LookupResult &Prev) {
6408  // C++03 [namespace.udecl]p8:
6409  // C++0x [namespace.udecl]p10:
6410  //   A using-declaration is a declaration and can therefore be used
6411  //   repeatedly where (and only where) multiple declarations are
6412  //   allowed.
6413  //
6414  // That's in non-member contexts.
6415  if (!CurContext->getRedeclContext()->isRecord())
6416    return false;
6417
6418  NestedNameSpecifier *Qual
6419    = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6420
6421  for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6422    NamedDecl *D = *I;
6423
6424    bool DTypename;
6425    NestedNameSpecifier *DQual;
6426    if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6427      DTypename = UD->isTypeName();
6428      DQual = UD->getQualifier();
6429    } else if (UnresolvedUsingValueDecl *UD
6430                 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6431      DTypename = false;
6432      DQual = UD->getQualifier();
6433    } else if (UnresolvedUsingTypenameDecl *UD
6434                 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6435      DTypename = true;
6436      DQual = UD->getQualifier();
6437    } else continue;
6438
6439    // using decls differ if one says 'typename' and the other doesn't.
6440    // FIXME: non-dependent using decls?
6441    if (isTypeName != DTypename) continue;
6442
6443    // using decls differ if they name different scopes (but note that
6444    // template instantiation can cause this check to trigger when it
6445    // didn't before instantiation).
6446    if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6447        Context.getCanonicalNestedNameSpecifier(DQual))
6448      continue;
6449
6450    Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6451    Diag(D->getLocation(), diag::note_using_decl) << 1;
6452    return true;
6453  }
6454
6455  return false;
6456}
6457
6458
6459/// Checks that the given nested-name qualifier used in a using decl
6460/// in the current context is appropriately related to the current
6461/// scope.  If an error is found, diagnoses it and returns true.
6462bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6463                                   const CXXScopeSpec &SS,
6464                                   SourceLocation NameLoc) {
6465  DeclContext *NamedContext = computeDeclContext(SS);
6466
6467  if (!CurContext->isRecord()) {
6468    // C++03 [namespace.udecl]p3:
6469    // C++0x [namespace.udecl]p8:
6470    //   A using-declaration for a class member shall be a member-declaration.
6471
6472    // If we weren't able to compute a valid scope, it must be a
6473    // dependent class scope.
6474    if (!NamedContext || NamedContext->isRecord()) {
6475      Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6476        << SS.getRange();
6477      return true;
6478    }
6479
6480    // Otherwise, everything is known to be fine.
6481    return false;
6482  }
6483
6484  // The current scope is a record.
6485
6486  // If the named context is dependent, we can't decide much.
6487  if (!NamedContext) {
6488    // FIXME: in C++0x, we can diagnose if we can prove that the
6489    // nested-name-specifier does not refer to a base class, which is
6490    // still possible in some cases.
6491
6492    // Otherwise we have to conservatively report that things might be
6493    // okay.
6494    return false;
6495  }
6496
6497  if (!NamedContext->isRecord()) {
6498    // Ideally this would point at the last name in the specifier,
6499    // but we don't have that level of source info.
6500    Diag(SS.getRange().getBegin(),
6501         diag::err_using_decl_nested_name_specifier_is_not_class)
6502      << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6503    return true;
6504  }
6505
6506  if (!NamedContext->isDependentContext() &&
6507      RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6508    return true;
6509
6510  if (getLangOpts().CPlusPlus0x) {
6511    // C++0x [namespace.udecl]p3:
6512    //   In a using-declaration used as a member-declaration, the
6513    //   nested-name-specifier shall name a base class of the class
6514    //   being defined.
6515
6516    if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6517                                 cast<CXXRecordDecl>(NamedContext))) {
6518      if (CurContext == NamedContext) {
6519        Diag(NameLoc,
6520             diag::err_using_decl_nested_name_specifier_is_current_class)
6521          << SS.getRange();
6522        return true;
6523      }
6524
6525      Diag(SS.getRange().getBegin(),
6526           diag::err_using_decl_nested_name_specifier_is_not_base_class)
6527        << (NestedNameSpecifier*) SS.getScopeRep()
6528        << cast<CXXRecordDecl>(CurContext)
6529        << SS.getRange();
6530      return true;
6531    }
6532
6533    return false;
6534  }
6535
6536  // C++03 [namespace.udecl]p4:
6537  //   A using-declaration used as a member-declaration shall refer
6538  //   to a member of a base class of the class being defined [etc.].
6539
6540  // Salient point: SS doesn't have to name a base class as long as
6541  // lookup only finds members from base classes.  Therefore we can
6542  // diagnose here only if we can prove that that can't happen,
6543  // i.e. if the class hierarchies provably don't intersect.
6544
6545  // TODO: it would be nice if "definitely valid" results were cached
6546  // in the UsingDecl and UsingShadowDecl so that these checks didn't
6547  // need to be repeated.
6548
6549  struct UserData {
6550    llvm::SmallPtrSet<const CXXRecordDecl*, 4> Bases;
6551
6552    static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6553      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6554      Data->Bases.insert(Base);
6555      return true;
6556    }
6557
6558    bool hasDependentBases(const CXXRecordDecl *Class) {
6559      return !Class->forallBases(collect, this);
6560    }
6561
6562    /// Returns true if the base is dependent or is one of the
6563    /// accumulated base classes.
6564    static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6565      UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6566      return !Data->Bases.count(Base);
6567    }
6568
6569    bool mightShareBases(const CXXRecordDecl *Class) {
6570      return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6571    }
6572  };
6573
6574  UserData Data;
6575
6576  // Returns false if we find a dependent base.
6577  if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6578    return false;
6579
6580  // Returns false if the class has a dependent base or if it or one
6581  // of its bases is present in the base set of the current context.
6582  if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6583    return false;
6584
6585  Diag(SS.getRange().getBegin(),
6586       diag::err_using_decl_nested_name_specifier_is_not_base_class)
6587    << (NestedNameSpecifier*) SS.getScopeRep()
6588    << cast<CXXRecordDecl>(CurContext)
6589    << SS.getRange();
6590
6591  return true;
6592}
6593
6594Decl *Sema::ActOnAliasDeclaration(Scope *S,
6595                                  AccessSpecifier AS,
6596                                  MultiTemplateParamsArg TemplateParamLists,
6597                                  SourceLocation UsingLoc,
6598                                  UnqualifiedId &Name,
6599                                  TypeResult Type) {
6600  // Skip up to the relevant declaration scope.
6601  while (S->getFlags() & Scope::TemplateParamScope)
6602    S = S->getParent();
6603  assert((S->getFlags() & Scope::DeclScope) &&
6604         "got alias-declaration outside of declaration scope");
6605
6606  if (Type.isInvalid())
6607    return 0;
6608
6609  bool Invalid = false;
6610  DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6611  TypeSourceInfo *TInfo = 0;
6612  GetTypeFromParser(Type.get(), &TInfo);
6613
6614  if (DiagnoseClassNameShadow(CurContext, NameInfo))
6615    return 0;
6616
6617  if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6618                                      UPPC_DeclarationType)) {
6619    Invalid = true;
6620    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6621                                             TInfo->getTypeLoc().getBeginLoc());
6622  }
6623
6624  LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6625  LookupName(Previous, S);
6626
6627  // Warn about shadowing the name of a template parameter.
6628  if (Previous.isSingleResult() &&
6629      Previous.getFoundDecl()->isTemplateParameter()) {
6630    DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
6631    Previous.clear();
6632  }
6633
6634  assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6635         "name in alias declaration must be an identifier");
6636  TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6637                                               Name.StartLocation,
6638                                               Name.Identifier, TInfo);
6639
6640  NewTD->setAccess(AS);
6641
6642  if (Invalid)
6643    NewTD->setInvalidDecl();
6644
6645  CheckTypedefForVariablyModifiedType(S, NewTD);
6646  Invalid |= NewTD->isInvalidDecl();
6647
6648  bool Redeclaration = false;
6649
6650  NamedDecl *NewND;
6651  if (TemplateParamLists.size()) {
6652    TypeAliasTemplateDecl *OldDecl = 0;
6653    TemplateParameterList *OldTemplateParams = 0;
6654
6655    if (TemplateParamLists.size() != 1) {
6656      Diag(UsingLoc, diag::err_alias_template_extra_headers)
6657        << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6658         TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6659    }
6660    TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6661
6662    // Only consider previous declarations in the same scope.
6663    FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6664                         /*ExplicitInstantiationOrSpecialization*/false);
6665    if (!Previous.empty()) {
6666      Redeclaration = true;
6667
6668      OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6669      if (!OldDecl && !Invalid) {
6670        Diag(UsingLoc, diag::err_redefinition_different_kind)
6671          << Name.Identifier;
6672
6673        NamedDecl *OldD = Previous.getRepresentativeDecl();
6674        if (OldD->getLocation().isValid())
6675          Diag(OldD->getLocation(), diag::note_previous_definition);
6676
6677        Invalid = true;
6678      }
6679
6680      if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6681        if (TemplateParameterListsAreEqual(TemplateParams,
6682                                           OldDecl->getTemplateParameters(),
6683                                           /*Complain=*/true,
6684                                           TPL_TemplateMatch))
6685          OldTemplateParams = OldDecl->getTemplateParameters();
6686        else
6687          Invalid = true;
6688
6689        TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6690        if (!Invalid &&
6691            !Context.hasSameType(OldTD->getUnderlyingType(),
6692                                 NewTD->getUnderlyingType())) {
6693          // FIXME: The C++0x standard does not clearly say this is ill-formed,
6694          // but we can't reasonably accept it.
6695          Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6696            << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6697          if (OldTD->getLocation().isValid())
6698            Diag(OldTD->getLocation(), diag::note_previous_definition);
6699          Invalid = true;
6700        }
6701      }
6702    }
6703
6704    // Merge any previous default template arguments into our parameters,
6705    // and check the parameter list.
6706    if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6707                                   TPC_TypeAliasTemplate))
6708      return 0;
6709
6710    TypeAliasTemplateDecl *NewDecl =
6711      TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6712                                    Name.Identifier, TemplateParams,
6713                                    NewTD);
6714
6715    NewDecl->setAccess(AS);
6716
6717    if (Invalid)
6718      NewDecl->setInvalidDecl();
6719    else if (OldDecl)
6720      NewDecl->setPreviousDeclaration(OldDecl);
6721
6722    NewND = NewDecl;
6723  } else {
6724    ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6725    NewND = NewTD;
6726  }
6727
6728  if (!Redeclaration)
6729    PushOnScopeChains(NewND, S);
6730
6731  return NewND;
6732}
6733
6734Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6735                                             SourceLocation NamespaceLoc,
6736                                             SourceLocation AliasLoc,
6737                                             IdentifierInfo *Alias,
6738                                             CXXScopeSpec &SS,
6739                                             SourceLocation IdentLoc,
6740                                             IdentifierInfo *Ident) {
6741
6742  // Lookup the namespace name.
6743  LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6744  LookupParsedName(R, S, &SS);
6745
6746  // Check if we have a previous declaration with the same name.
6747  NamedDecl *PrevDecl
6748    = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6749                       ForRedeclaration);
6750  if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6751    PrevDecl = 0;
6752
6753  if (PrevDecl) {
6754    if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6755      // We already have an alias with the same name that points to the same
6756      // namespace, so don't create a new one.
6757      // FIXME: At some point, we'll want to create the (redundant)
6758      // declaration to maintain better source information.
6759      if (!R.isAmbiguous() && !R.empty() &&
6760          AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6761        return 0;
6762    }
6763
6764    unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6765      diag::err_redefinition_different_kind;
6766    Diag(AliasLoc, DiagID) << Alias;
6767    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6768    return 0;
6769  }
6770
6771  if (R.isAmbiguous())
6772    return 0;
6773
6774  if (R.empty()) {
6775    if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6776      Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
6777      return 0;
6778    }
6779  }
6780
6781  NamespaceAliasDecl *AliasDecl =
6782    NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6783                               Alias, SS.getWithLocInContext(Context),
6784                               IdentLoc, R.getFoundDecl());
6785
6786  PushOnScopeChains(AliasDecl, S);
6787  return AliasDecl;
6788}
6789
6790namespace {
6791  /// \brief Scoped object used to handle the state changes required in Sema
6792  /// to implicitly define the body of a C++ member function;
6793  class ImplicitlyDefinedFunctionScope {
6794    Sema &S;
6795    Sema::ContextRAII SavedContext;
6796
6797  public:
6798    ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6799      : S(S), SavedContext(S, Method)
6800    {
6801      S.PushFunctionScope();
6802      S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6803    }
6804
6805    ~ImplicitlyDefinedFunctionScope() {
6806      S.PopExpressionEvaluationContext();
6807      S.PopFunctionScopeInfo();
6808    }
6809  };
6810}
6811
6812Sema::ImplicitExceptionSpecification
6813Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6814  // C++ [except.spec]p14:
6815  //   An implicitly declared special member function (Clause 12) shall have an
6816  //   exception-specification. [...]
6817  ImplicitExceptionSpecification ExceptSpec(Context);
6818  if (ClassDecl->isInvalidDecl())
6819    return ExceptSpec;
6820
6821  // Direct base-class constructors.
6822  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6823                                       BEnd = ClassDecl->bases_end();
6824       B != BEnd; ++B) {
6825    if (B->isVirtual()) // Handled below.
6826      continue;
6827
6828    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6829      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6830      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6831      // If this is a deleted function, add it anyway. This might be conformant
6832      // with the standard. This might not. I'm not sure. It might not matter.
6833      if (Constructor)
6834        ExceptSpec.CalledDecl(Constructor);
6835    }
6836  }
6837
6838  // Virtual base-class constructors.
6839  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6840                                       BEnd = ClassDecl->vbases_end();
6841       B != BEnd; ++B) {
6842    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6843      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6844      CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6845      // If this is a deleted function, add it anyway. This might be conformant
6846      // with the standard. This might not. I'm not sure. It might not matter.
6847      if (Constructor)
6848        ExceptSpec.CalledDecl(Constructor);
6849    }
6850  }
6851
6852  // Field constructors.
6853  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6854                               FEnd = ClassDecl->field_end();
6855       F != FEnd; ++F) {
6856    if (F->hasInClassInitializer()) {
6857      if (Expr *E = F->getInClassInitializer())
6858        ExceptSpec.CalledExpr(E);
6859      else if (!F->isInvalidDecl())
6860        ExceptSpec.SetDelayed();
6861    } else if (const RecordType *RecordTy
6862              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6863      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6864      CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6865      // If this is a deleted function, add it anyway. This might be conformant
6866      // with the standard. This might not. I'm not sure. It might not matter.
6867      // In particular, the problem is that this function never gets called. It
6868      // might just be ill-formed because this function attempts to refer to
6869      // a deleted function here.
6870      if (Constructor)
6871        ExceptSpec.CalledDecl(Constructor);
6872    }
6873  }
6874
6875  return ExceptSpec;
6876}
6877
6878CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6879                                                     CXXRecordDecl *ClassDecl) {
6880  // C++ [class.ctor]p5:
6881  //   A default constructor for a class X is a constructor of class X
6882  //   that can be called without an argument. If there is no
6883  //   user-declared constructor for class X, a default constructor is
6884  //   implicitly declared. An implicitly-declared default constructor
6885  //   is an inline public member of its class.
6886  assert(!ClassDecl->hasUserDeclaredConstructor() &&
6887         "Should not build implicit default constructor!");
6888
6889  ImplicitExceptionSpecification Spec =
6890    ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6891  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6892
6893  // Create the actual constructor declaration.
6894  CanQualType ClassType
6895    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6896  SourceLocation ClassLoc = ClassDecl->getLocation();
6897  DeclarationName Name
6898    = Context.DeclarationNames.getCXXConstructorName(ClassType);
6899  DeclarationNameInfo NameInfo(Name, ClassLoc);
6900  CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
6901      Context, ClassDecl, ClassLoc, NameInfo,
6902      Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
6903      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
6904      /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
6905        getLangOpts().CPlusPlus0x);
6906  DefaultCon->setAccess(AS_public);
6907  DefaultCon->setDefaulted();
6908  DefaultCon->setImplicit();
6909  DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6910
6911  // Note that we have declared this constructor.
6912  ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6913
6914  if (Scope *S = getScopeForContext(ClassDecl))
6915    PushOnScopeChains(DefaultCon, S, false);
6916  ClassDecl->addDecl(DefaultCon);
6917
6918  if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6919    DefaultCon->setDeletedAsWritten();
6920
6921  return DefaultCon;
6922}
6923
6924void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6925                                            CXXConstructorDecl *Constructor) {
6926  assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6927          !Constructor->doesThisDeclarationHaveABody() &&
6928          !Constructor->isDeleted()) &&
6929    "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6930
6931  CXXRecordDecl *ClassDecl = Constructor->getParent();
6932  assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6933
6934  ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6935  DiagnosticErrorTrap Trap(Diags);
6936  if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6937      Trap.hasErrorOccurred()) {
6938    Diag(CurrentLocation, diag::note_member_synthesized_at)
6939      << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6940    Constructor->setInvalidDecl();
6941    return;
6942  }
6943
6944  SourceLocation Loc = Constructor->getLocation();
6945  Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6946
6947  Constructor->setUsed();
6948  MarkVTableUsed(CurrentLocation, ClassDecl);
6949
6950  if (ASTMutationListener *L = getASTMutationListener()) {
6951    L->CompletedImplicitDefinition(Constructor);
6952  }
6953}
6954
6955/// Get any existing defaulted default constructor for the given class. Do not
6956/// implicitly define one if it does not exist.
6957static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6958                                                             CXXRecordDecl *D) {
6959  ASTContext &Context = Self.Context;
6960  QualType ClassType = Context.getTypeDeclType(D);
6961  DeclarationName ConstructorName
6962    = Context.DeclarationNames.getCXXConstructorName(
6963                      Context.getCanonicalType(ClassType.getUnqualifiedType()));
6964
6965  DeclContext::lookup_const_iterator Con, ConEnd;
6966  for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6967       Con != ConEnd; ++Con) {
6968    // A function template cannot be defaulted.
6969    if (isa<FunctionTemplateDecl>(*Con))
6970      continue;
6971
6972    CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6973    if (Constructor->isDefaultConstructor())
6974      return Constructor->isDefaulted() ? Constructor : 0;
6975  }
6976  return 0;
6977}
6978
6979void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6980  if (!D) return;
6981  AdjustDeclIfTemplate(D);
6982
6983  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6984  CXXConstructorDecl *CtorDecl
6985    = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6986
6987  if (!CtorDecl) return;
6988
6989  // Compute the exception specification for the default constructor.
6990  const FunctionProtoType *CtorTy =
6991    CtorDecl->getType()->castAs<FunctionProtoType>();
6992  if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6993    ImplicitExceptionSpecification Spec =
6994      ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6995    FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6996    assert(EPI.ExceptionSpecType != EST_Delayed);
6997
6998    CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6999  }
7000
7001  // If the default constructor is explicitly defaulted, checking the exception
7002  // specification is deferred until now.
7003  if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7004      !ClassDecl->isDependentType())
7005    CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7006}
7007
7008void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7009  // We start with an initial pass over the base classes to collect those that
7010  // inherit constructors from. If there are none, we can forgo all further
7011  // processing.
7012  typedef SmallVector<const RecordType *, 4> BasesVector;
7013  BasesVector BasesToInheritFrom;
7014  for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7015                                          BaseE = ClassDecl->bases_end();
7016         BaseIt != BaseE; ++BaseIt) {
7017    if (BaseIt->getInheritConstructors()) {
7018      QualType Base = BaseIt->getType();
7019      if (Base->isDependentType()) {
7020        // If we inherit constructors from anything that is dependent, just
7021        // abort processing altogether. We'll get another chance for the
7022        // instantiations.
7023        return;
7024      }
7025      BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7026    }
7027  }
7028  if (BasesToInheritFrom.empty())
7029    return;
7030
7031  // Now collect the constructors that we already have in the current class.
7032  // Those take precedence over inherited constructors.
7033  // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7034  //   unless there is a user-declared constructor with the same signature in
7035  //   the class where the using-declaration appears.
7036  llvm::SmallSet<const Type *, 8> ExistingConstructors;
7037  for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7038                                    CtorE = ClassDecl->ctor_end();
7039       CtorIt != CtorE; ++CtorIt) {
7040    ExistingConstructors.insert(
7041        Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7042  }
7043
7044  DeclarationName CreatedCtorName =
7045      Context.DeclarationNames.getCXXConstructorName(
7046          ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7047
7048  // Now comes the true work.
7049  // First, we keep a map from constructor types to the base that introduced
7050  // them. Needed for finding conflicting constructors. We also keep the
7051  // actually inserted declarations in there, for pretty diagnostics.
7052  typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7053  typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7054  ConstructorToSourceMap InheritedConstructors;
7055  for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7056                             BaseE = BasesToInheritFrom.end();
7057       BaseIt != BaseE; ++BaseIt) {
7058    const RecordType *Base = *BaseIt;
7059    CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7060    CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7061    for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7062                                      CtorE = BaseDecl->ctor_end();
7063         CtorIt != CtorE; ++CtorIt) {
7064      // Find the using declaration for inheriting this base's constructors.
7065      // FIXME: Don't perform name lookup just to obtain a source location!
7066      DeclarationName Name =
7067          Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7068      LookupResult Result(*this, Name, SourceLocation(), LookupUsingDeclName);
7069      LookupQualifiedName(Result, CurContext);
7070      UsingDecl *UD = Result.getAsSingle<UsingDecl>();
7071      SourceLocation UsingLoc = UD ? UD->getLocation() :
7072                                     ClassDecl->getLocation();
7073
7074      // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7075      //   from the class X named in the using-declaration consists of actual
7076      //   constructors and notional constructors that result from the
7077      //   transformation of defaulted parameters as follows:
7078      //   - all non-template default constructors of X, and
7079      //   - for each non-template constructor of X that has at least one
7080      //     parameter with a default argument, the set of constructors that
7081      //     results from omitting any ellipsis parameter specification and
7082      //     successively omitting parameters with a default argument from the
7083      //     end of the parameter-type-list.
7084      CXXConstructorDecl *BaseCtor = *CtorIt;
7085      bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7086      const FunctionProtoType *BaseCtorType =
7087          BaseCtor->getType()->getAs<FunctionProtoType>();
7088
7089      for (unsigned params = BaseCtor->getMinRequiredArguments(),
7090                    maxParams = BaseCtor->getNumParams();
7091           params <= maxParams; ++params) {
7092        // Skip default constructors. They're never inherited.
7093        if (params == 0)
7094          continue;
7095        // Skip copy and move constructors for the same reason.
7096        if (CanBeCopyOrMove && params == 1)
7097          continue;
7098
7099        // Build up a function type for this particular constructor.
7100        // FIXME: The working paper does not consider that the exception spec
7101        // for the inheriting constructor might be larger than that of the
7102        // source. This code doesn't yet, either. When it does, this code will
7103        // need to be delayed until after exception specifications and in-class
7104        // member initializers are attached.
7105        const Type *NewCtorType;
7106        if (params == maxParams)
7107          NewCtorType = BaseCtorType;
7108        else {
7109          SmallVector<QualType, 16> Args;
7110          for (unsigned i = 0; i < params; ++i) {
7111            Args.push_back(BaseCtorType->getArgType(i));
7112          }
7113          FunctionProtoType::ExtProtoInfo ExtInfo =
7114              BaseCtorType->getExtProtoInfo();
7115          ExtInfo.Variadic = false;
7116          NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7117                                                Args.data(), params, ExtInfo)
7118                       .getTypePtr();
7119        }
7120        const Type *CanonicalNewCtorType =
7121            Context.getCanonicalType(NewCtorType);
7122
7123        // Now that we have the type, first check if the class already has a
7124        // constructor with this signature.
7125        if (ExistingConstructors.count(CanonicalNewCtorType))
7126          continue;
7127
7128        // Then we check if we have already declared an inherited constructor
7129        // with this signature.
7130        std::pair<ConstructorToSourceMap::iterator, bool> result =
7131            InheritedConstructors.insert(std::make_pair(
7132                CanonicalNewCtorType,
7133                std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7134        if (!result.second) {
7135          // Already in the map. If it came from a different class, that's an
7136          // error. Not if it's from the same.
7137          CanQualType PreviousBase = result.first->second.first;
7138          if (CanonicalBase != PreviousBase) {
7139            const CXXConstructorDecl *PrevCtor = result.first->second.second;
7140            const CXXConstructorDecl *PrevBaseCtor =
7141                PrevCtor->getInheritedConstructor();
7142            assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7143
7144            Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7145            Diag(BaseCtor->getLocation(),
7146                 diag::note_using_decl_constructor_conflict_current_ctor);
7147            Diag(PrevBaseCtor->getLocation(),
7148                 diag::note_using_decl_constructor_conflict_previous_ctor);
7149            Diag(PrevCtor->getLocation(),
7150                 diag::note_using_decl_constructor_conflict_previous_using);
7151          }
7152          continue;
7153        }
7154
7155        // OK, we're there, now add the constructor.
7156        // C++0x [class.inhctor]p8: [...] that would be performed by a
7157        //   user-written inline constructor [...]
7158        DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7159        CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7160            Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7161            /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7162            /*ImplicitlyDeclared=*/true,
7163            // FIXME: Due to a defect in the standard, we treat inherited
7164            // constructors as constexpr even if that makes them ill-formed.
7165            /*Constexpr=*/BaseCtor->isConstexpr());
7166        NewCtor->setAccess(BaseCtor->getAccess());
7167
7168        // Build up the parameter decls and add them.
7169        SmallVector<ParmVarDecl *, 16> ParamDecls;
7170        for (unsigned i = 0; i < params; ++i) {
7171          ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7172                                                   UsingLoc, UsingLoc,
7173                                                   /*IdentifierInfo=*/0,
7174                                                   BaseCtorType->getArgType(i),
7175                                                   /*TInfo=*/0, SC_None,
7176                                                   SC_None, /*DefaultArg=*/0));
7177        }
7178        NewCtor->setParams(ParamDecls);
7179        NewCtor->setInheritedConstructor(BaseCtor);
7180
7181        ClassDecl->addDecl(NewCtor);
7182        result.first->second.second = NewCtor;
7183      }
7184    }
7185  }
7186}
7187
7188Sema::ImplicitExceptionSpecification
7189Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
7190  // C++ [except.spec]p14:
7191  //   An implicitly declared special member function (Clause 12) shall have
7192  //   an exception-specification.
7193  ImplicitExceptionSpecification ExceptSpec(Context);
7194  if (ClassDecl->isInvalidDecl())
7195    return ExceptSpec;
7196
7197  // Direct base-class destructors.
7198  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7199                                       BEnd = ClassDecl->bases_end();
7200       B != BEnd; ++B) {
7201    if (B->isVirtual()) // Handled below.
7202      continue;
7203
7204    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7205      ExceptSpec.CalledDecl(
7206                   LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7207  }
7208
7209  // Virtual base-class destructors.
7210  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7211                                       BEnd = ClassDecl->vbases_end();
7212       B != BEnd; ++B) {
7213    if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7214      ExceptSpec.CalledDecl(
7215                  LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7216  }
7217
7218  // Field destructors.
7219  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7220                               FEnd = ClassDecl->field_end();
7221       F != FEnd; ++F) {
7222    if (const RecordType *RecordTy
7223        = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7224      ExceptSpec.CalledDecl(
7225                  LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7226  }
7227
7228  return ExceptSpec;
7229}
7230
7231CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7232  // C++ [class.dtor]p2:
7233  //   If a class has no user-declared destructor, a destructor is
7234  //   declared implicitly. An implicitly-declared destructor is an
7235  //   inline public member of its class.
7236
7237  ImplicitExceptionSpecification Spec =
7238      ComputeDefaultedDtorExceptionSpec(ClassDecl);
7239  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7240
7241  // Create the actual destructor declaration.
7242  QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
7243
7244  CanQualType ClassType
7245    = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7246  SourceLocation ClassLoc = ClassDecl->getLocation();
7247  DeclarationName Name
7248    = Context.DeclarationNames.getCXXDestructorName(ClassType);
7249  DeclarationNameInfo NameInfo(Name, ClassLoc);
7250  CXXDestructorDecl *Destructor
7251      = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7252                                  /*isInline=*/true,
7253                                  /*isImplicitlyDeclared=*/true);
7254  Destructor->setAccess(AS_public);
7255  Destructor->setDefaulted();
7256  Destructor->setImplicit();
7257  Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7258
7259  // Note that we have declared this destructor.
7260  ++ASTContext::NumImplicitDestructorsDeclared;
7261
7262  // Introduce this destructor into its scope.
7263  if (Scope *S = getScopeForContext(ClassDecl))
7264    PushOnScopeChains(Destructor, S, false);
7265  ClassDecl->addDecl(Destructor);
7266
7267  // This could be uniqued if it ever proves significant.
7268  Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
7269
7270  AddOverriddenMethods(ClassDecl, Destructor);
7271
7272  if (ShouldDeleteSpecialMember(Destructor, CXXDestructor))
7273    Destructor->setDeletedAsWritten();
7274
7275  return Destructor;
7276}
7277
7278void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7279                                    CXXDestructorDecl *Destructor) {
7280  assert((Destructor->isDefaulted() &&
7281          !Destructor->doesThisDeclarationHaveABody() &&
7282          !Destructor->isDeleted()) &&
7283         "DefineImplicitDestructor - call it for implicit default dtor");
7284  CXXRecordDecl *ClassDecl = Destructor->getParent();
7285  assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7286
7287  if (Destructor->isInvalidDecl())
7288    return;
7289
7290  ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7291
7292  DiagnosticErrorTrap Trap(Diags);
7293  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7294                                         Destructor->getParent());
7295
7296  if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7297    Diag(CurrentLocation, diag::note_member_synthesized_at)
7298      << CXXDestructor << Context.getTagDeclType(ClassDecl);
7299
7300    Destructor->setInvalidDecl();
7301    return;
7302  }
7303
7304  SourceLocation Loc = Destructor->getLocation();
7305  Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7306  Destructor->setImplicitlyDefined(true);
7307  Destructor->setUsed();
7308  MarkVTableUsed(CurrentLocation, ClassDecl);
7309
7310  if (ASTMutationListener *L = getASTMutationListener()) {
7311    L->CompletedImplicitDefinition(Destructor);
7312  }
7313}
7314
7315void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7316                                         CXXDestructorDecl *destructor) {
7317  // C++11 [class.dtor]p3:
7318  //   A declaration of a destructor that does not have an exception-
7319  //   specification is implicitly considered to have the same exception-
7320  //   specification as an implicit declaration.
7321  const FunctionProtoType *dtorType = destructor->getType()->
7322                                        getAs<FunctionProtoType>();
7323  if (dtorType->hasExceptionSpec())
7324    return;
7325
7326  ImplicitExceptionSpecification exceptSpec =
7327      ComputeDefaultedDtorExceptionSpec(classDecl);
7328
7329  // Replace the destructor's type, building off the existing one. Fortunately,
7330  // the only thing of interest in the destructor type is its extended info.
7331  // The return and arguments are fixed.
7332  FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
7333  epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7334  epi.NumExceptions = exceptSpec.size();
7335  epi.Exceptions = exceptSpec.data();
7336  QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7337
7338  destructor->setType(ty);
7339
7340  // FIXME: If the destructor has a body that could throw, and the newly created
7341  // spec doesn't allow exceptions, we should emit a warning, because this
7342  // change in behavior can break conforming C++03 programs at runtime.
7343  // However, we don't have a body yet, so it needs to be done somewhere else.
7344}
7345
7346/// \brief Builds a statement that copies/moves the given entity from \p From to
7347/// \c To.
7348///
7349/// This routine is used to copy/move the members of a class with an
7350/// implicitly-declared copy/move assignment operator. When the entities being
7351/// copied are arrays, this routine builds for loops to copy them.
7352///
7353/// \param S The Sema object used for type-checking.
7354///
7355/// \param Loc The location where the implicit copy/move is being generated.
7356///
7357/// \param T The type of the expressions being copied/moved. Both expressions
7358/// must have this type.
7359///
7360/// \param To The expression we are copying/moving to.
7361///
7362/// \param From The expression we are copying/moving from.
7363///
7364/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7365/// Otherwise, it's a non-static member subobject.
7366///
7367/// \param Copying Whether we're copying or moving.
7368///
7369/// \param Depth Internal parameter recording the depth of the recursion.
7370///
7371/// \returns A statement or a loop that copies the expressions.
7372static StmtResult
7373BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7374                      Expr *To, Expr *From,
7375                      bool CopyingBaseSubobject, bool Copying,
7376                      unsigned Depth = 0) {
7377  // C++0x [class.copy]p28:
7378  //   Each subobject is assigned in the manner appropriate to its type:
7379  //
7380  //     - if the subobject is of class type, as if by a call to operator= with
7381  //       the subobject as the object expression and the corresponding
7382  //       subobject of x as a single function argument (as if by explicit
7383  //       qualification; that is, ignoring any possible virtual overriding
7384  //       functions in more derived classes);
7385  if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7386    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7387
7388    // Look for operator=.
7389    DeclarationName Name
7390      = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7391    LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7392    S.LookupQualifiedName(OpLookup, ClassDecl, false);
7393
7394    // Filter out any result that isn't a copy/move-assignment operator.
7395    LookupResult::Filter F = OpLookup.makeFilter();
7396    while (F.hasNext()) {
7397      NamedDecl *D = F.next();
7398      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7399        if (Method->isCopyAssignmentOperator() ||
7400            (!Copying && Method->isMoveAssignmentOperator()))
7401          continue;
7402
7403      F.erase();
7404    }
7405    F.done();
7406
7407    // Suppress the protected check (C++ [class.protected]) for each of the
7408    // assignment operators we found. This strange dance is required when
7409    // we're assigning via a base classes's copy-assignment operator. To
7410    // ensure that we're getting the right base class subobject (without
7411    // ambiguities), we need to cast "this" to that subobject type; to
7412    // ensure that we don't go through the virtual call mechanism, we need
7413    // to qualify the operator= name with the base class (see below). However,
7414    // this means that if the base class has a protected copy assignment
7415    // operator, the protected member access check will fail. So, we
7416    // rewrite "protected" access to "public" access in this case, since we
7417    // know by construction that we're calling from a derived class.
7418    if (CopyingBaseSubobject) {
7419      for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7420           L != LEnd; ++L) {
7421        if (L.getAccess() == AS_protected)
7422          L.setAccess(AS_public);
7423      }
7424    }
7425
7426    // Create the nested-name-specifier that will be used to qualify the
7427    // reference to operator=; this is required to suppress the virtual
7428    // call mechanism.
7429    CXXScopeSpec SS;
7430    const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
7431    SS.MakeTrivial(S.Context,
7432                   NestedNameSpecifier::Create(S.Context, 0, false,
7433                                               CanonicalT),
7434                   Loc);
7435
7436    // Create the reference to operator=.
7437    ExprResult OpEqualRef
7438      = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7439                                   /*TemplateKWLoc=*/SourceLocation(),
7440                                   /*FirstQualifierInScope=*/0,
7441                                   OpLookup,
7442                                   /*TemplateArgs=*/0,
7443                                   /*SuppressQualifierCheck=*/true);
7444    if (OpEqualRef.isInvalid())
7445      return StmtError();
7446
7447    // Build the call to the assignment operator.
7448
7449    ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7450                                                  OpEqualRef.takeAs<Expr>(),
7451                                                  Loc, &From, 1, Loc);
7452    if (Call.isInvalid())
7453      return StmtError();
7454
7455    return S.Owned(Call.takeAs<Stmt>());
7456  }
7457
7458  //     - if the subobject is of scalar type, the built-in assignment
7459  //       operator is used.
7460  const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7461  if (!ArrayTy) {
7462    ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7463    if (Assignment.isInvalid())
7464      return StmtError();
7465
7466    return S.Owned(Assignment.takeAs<Stmt>());
7467  }
7468
7469  //     - if the subobject is an array, each element is assigned, in the
7470  //       manner appropriate to the element type;
7471
7472  // Construct a loop over the array bounds, e.g.,
7473  //
7474  //   for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7475  //
7476  // that will copy each of the array elements.
7477  QualType SizeType = S.Context.getSizeType();
7478
7479  // Create the iteration variable.
7480  IdentifierInfo *IterationVarName = 0;
7481  {
7482    SmallString<8> Str;
7483    llvm::raw_svector_ostream OS(Str);
7484    OS << "__i" << Depth;
7485    IterationVarName = &S.Context.Idents.get(OS.str());
7486  }
7487  VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7488                                          IterationVarName, SizeType,
7489                            S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7490                                          SC_None, SC_None);
7491
7492  // Initialize the iteration variable to zero.
7493  llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7494  IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7495
7496  // Create a reference to the iteration variable; we'll use this several
7497  // times throughout.
7498  Expr *IterationVarRef
7499    = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
7500  assert(IterationVarRef && "Reference to invented variable cannot fail!");
7501  Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7502  assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7503
7504  // Create the DeclStmt that holds the iteration variable.
7505  Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7506
7507  // Create the comparison against the array bound.
7508  llvm::APInt Upper
7509    = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7510  Expr *Comparison
7511    = new (S.Context) BinaryOperator(IterationVarRefRVal,
7512                     IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7513                                     BO_NE, S.Context.BoolTy,
7514                                     VK_RValue, OK_Ordinary, Loc);
7515
7516  // Create the pre-increment of the iteration variable.
7517  Expr *Increment
7518    = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7519                                    VK_LValue, OK_Ordinary, Loc);
7520
7521  // Subscript the "from" and "to" expressions with the iteration variable.
7522  From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7523                                                         IterationVarRefRVal,
7524                                                         Loc));
7525  To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7526                                                       IterationVarRefRVal,
7527                                                       Loc));
7528  if (!Copying) // Cast to rvalue
7529    From = CastForMoving(S, From);
7530
7531  // Build the copy/move for an individual element of the array.
7532  StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7533                                          To, From, CopyingBaseSubobject,
7534                                          Copying, Depth + 1);
7535  if (Copy.isInvalid())
7536    return StmtError();
7537
7538  // Construct the loop that copies all elements of this array.
7539  return S.ActOnForStmt(Loc, Loc, InitStmt,
7540                        S.MakeFullExpr(Comparison),
7541                        0, S.MakeFullExpr(Increment),
7542                        Loc, Copy.take());
7543}
7544
7545std::pair<Sema::ImplicitExceptionSpecification, bool>
7546Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7547                                                   CXXRecordDecl *ClassDecl) {
7548  if (ClassDecl->isInvalidDecl())
7549    return std::make_pair(ImplicitExceptionSpecification(Context), false);
7550
7551  // C++ [class.copy]p10:
7552  //   If the class definition does not explicitly declare a copy
7553  //   assignment operator, one is declared implicitly.
7554  //   The implicitly-defined copy assignment operator for a class X
7555  //   will have the form
7556  //
7557  //       X& X::operator=(const X&)
7558  //
7559  //   if
7560  bool HasConstCopyAssignment = true;
7561
7562  //       -- each direct base class B of X has a copy assignment operator
7563  //          whose parameter is of type const B&, const volatile B& or B,
7564  //          and
7565  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7566                                       BaseEnd = ClassDecl->bases_end();
7567       HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7568    // We'll handle this below
7569    if (LangOpts.CPlusPlus0x && Base->isVirtual())
7570      continue;
7571
7572    assert(!Base->getType()->isDependentType() &&
7573           "Cannot generate implicit members for class with dependent bases.");
7574    CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7575    LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7576                            &HasConstCopyAssignment);
7577  }
7578
7579  // In C++11, the above citation has "or virtual" added
7580  if (LangOpts.CPlusPlus0x) {
7581    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7582                                         BaseEnd = ClassDecl->vbases_end();
7583         HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7584      assert(!Base->getType()->isDependentType() &&
7585             "Cannot generate implicit members for class with dependent bases.");
7586      CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7587      LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7588                              &HasConstCopyAssignment);
7589    }
7590  }
7591
7592  //       -- for all the nonstatic data members of X that are of a class
7593  //          type M (or array thereof), each such class type has a copy
7594  //          assignment operator whose parameter is of type const M&,
7595  //          const volatile M& or M.
7596  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7597                                  FieldEnd = ClassDecl->field_end();
7598       HasConstCopyAssignment && Field != FieldEnd;
7599       ++Field) {
7600    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7601    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7602      LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7603                              &HasConstCopyAssignment);
7604    }
7605  }
7606
7607  //   Otherwise, the implicitly declared copy assignment operator will
7608  //   have the form
7609  //
7610  //       X& X::operator=(X&)
7611
7612  // C++ [except.spec]p14:
7613  //   An implicitly declared special member function (Clause 12) shall have an
7614  //   exception-specification. [...]
7615
7616  // It is unspecified whether or not an implicit copy assignment operator
7617  // attempts to deduplicate calls to assignment operators of virtual bases are
7618  // made. As such, this exception specification is effectively unspecified.
7619  // Based on a similar decision made for constness in C++0x, we're erring on
7620  // the side of assuming such calls to be made regardless of whether they
7621  // actually happen.
7622  ImplicitExceptionSpecification ExceptSpec(Context);
7623  unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
7624  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7625                                       BaseEnd = ClassDecl->bases_end();
7626       Base != BaseEnd; ++Base) {
7627    if (Base->isVirtual())
7628      continue;
7629
7630    CXXRecordDecl *BaseClassDecl
7631      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7632    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7633                                                            ArgQuals, false, 0))
7634      ExceptSpec.CalledDecl(CopyAssign);
7635  }
7636
7637  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7638                                       BaseEnd = ClassDecl->vbases_end();
7639       Base != BaseEnd; ++Base) {
7640    CXXRecordDecl *BaseClassDecl
7641      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7642    if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7643                                                            ArgQuals, false, 0))
7644      ExceptSpec.CalledDecl(CopyAssign);
7645  }
7646
7647  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7648                                  FieldEnd = ClassDecl->field_end();
7649       Field != FieldEnd;
7650       ++Field) {
7651    QualType FieldType = Context.getBaseElementType((*Field)->getType());
7652    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7653      if (CXXMethodDecl *CopyAssign =
7654          LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7655        ExceptSpec.CalledDecl(CopyAssign);
7656    }
7657  }
7658
7659  return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7660}
7661
7662CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7663  // Note: The following rules are largely analoguous to the copy
7664  // constructor rules. Note that virtual bases are not taken into account
7665  // for determining the argument type of the operator. Note also that
7666  // operators taking an object instead of a reference are allowed.
7667
7668  ImplicitExceptionSpecification Spec(Context);
7669  bool Const;
7670  llvm::tie(Spec, Const) =
7671    ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7672
7673  QualType ArgType = Context.getTypeDeclType(ClassDecl);
7674  QualType RetType = Context.getLValueReferenceType(ArgType);
7675  if (Const)
7676    ArgType = ArgType.withConst();
7677  ArgType = Context.getLValueReferenceType(ArgType);
7678
7679  //   An implicitly-declared copy assignment operator is an inline public
7680  //   member of its class.
7681  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7682  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7683  SourceLocation ClassLoc = ClassDecl->getLocation();
7684  DeclarationNameInfo NameInfo(Name, ClassLoc);
7685  CXXMethodDecl *CopyAssignment
7686    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7687                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
7688                            /*TInfo=*/0, /*isStatic=*/false,
7689                            /*StorageClassAsWritten=*/SC_None,
7690                            /*isInline=*/true, /*isConstexpr=*/false,
7691                            SourceLocation());
7692  CopyAssignment->setAccess(AS_public);
7693  CopyAssignment->setDefaulted();
7694  CopyAssignment->setImplicit();
7695  CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7696
7697  // Add the parameter to the operator.
7698  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7699                                               ClassLoc, ClassLoc, /*Id=*/0,
7700                                               ArgType, /*TInfo=*/0,
7701                                               SC_None,
7702                                               SC_None, 0);
7703  CopyAssignment->setParams(FromParam);
7704
7705  // Note that we have added this copy-assignment operator.
7706  ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7707
7708  if (Scope *S = getScopeForContext(ClassDecl))
7709    PushOnScopeChains(CopyAssignment, S, false);
7710  ClassDecl->addDecl(CopyAssignment);
7711
7712  // C++0x [class.copy]p19:
7713  //   ....  If the class definition does not explicitly declare a copy
7714  //   assignment operator, there is no user-declared move constructor, and
7715  //   there is no user-declared move assignment operator, a copy assignment
7716  //   operator is implicitly declared as defaulted.
7717  if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
7718    CopyAssignment->setDeletedAsWritten();
7719
7720  AddOverriddenMethods(ClassDecl, CopyAssignment);
7721  return CopyAssignment;
7722}
7723
7724void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7725                                        CXXMethodDecl *CopyAssignOperator) {
7726  assert((CopyAssignOperator->isDefaulted() &&
7727          CopyAssignOperator->isOverloadedOperator() &&
7728          CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7729          !CopyAssignOperator->doesThisDeclarationHaveABody() &&
7730          !CopyAssignOperator->isDeleted()) &&
7731         "DefineImplicitCopyAssignment called for wrong function");
7732
7733  CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7734
7735  if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7736    CopyAssignOperator->setInvalidDecl();
7737    return;
7738  }
7739
7740  CopyAssignOperator->setUsed();
7741
7742  ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7743  DiagnosticErrorTrap Trap(Diags);
7744
7745  // C++0x [class.copy]p30:
7746  //   The implicitly-defined or explicitly-defaulted copy assignment operator
7747  //   for a non-union class X performs memberwise copy assignment of its
7748  //   subobjects. The direct base classes of X are assigned first, in the
7749  //   order of their declaration in the base-specifier-list, and then the
7750  //   immediate non-static data members of X are assigned, in the order in
7751  //   which they were declared in the class definition.
7752
7753  // The statements that form the synthesized function body.
7754  ASTOwningVector<Stmt*> Statements(*this);
7755
7756  // The parameter for the "other" object, which we are copying from.
7757  ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7758  Qualifiers OtherQuals = Other->getType().getQualifiers();
7759  QualType OtherRefType = Other->getType();
7760  if (const LValueReferenceType *OtherRef
7761                                = OtherRefType->getAs<LValueReferenceType>()) {
7762    OtherRefType = OtherRef->getPointeeType();
7763    OtherQuals = OtherRefType.getQualifiers();
7764  }
7765
7766  // Our location for everything implicitly-generated.
7767  SourceLocation Loc = CopyAssignOperator->getLocation();
7768
7769  // Construct a reference to the "other" object. We'll be using this
7770  // throughout the generated ASTs.
7771  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7772  assert(OtherRef && "Reference to parameter cannot fail!");
7773
7774  // Construct the "this" pointer. We'll be using this throughout the generated
7775  // ASTs.
7776  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7777  assert(This && "Reference to this cannot fail!");
7778
7779  // Assign base classes.
7780  bool Invalid = false;
7781  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7782       E = ClassDecl->bases_end(); Base != E; ++Base) {
7783    // Form the assignment:
7784    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7785    QualType BaseType = Base->getType().getUnqualifiedType();
7786    if (!BaseType->isRecordType()) {
7787      Invalid = true;
7788      continue;
7789    }
7790
7791    CXXCastPath BasePath;
7792    BasePath.push_back(Base);
7793
7794    // Construct the "from" expression, which is an implicit cast to the
7795    // appropriately-qualified base type.
7796    Expr *From = OtherRef;
7797    From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7798                             CK_UncheckedDerivedToBase,
7799                             VK_LValue, &BasePath).take();
7800
7801    // Dereference "this".
7802    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7803
7804    // Implicitly cast "this" to the appropriately-qualified base type.
7805    To = ImpCastExprToType(To.take(),
7806                           Context.getCVRQualifiedType(BaseType,
7807                                     CopyAssignOperator->getTypeQualifiers()),
7808                           CK_UncheckedDerivedToBase,
7809                           VK_LValue, &BasePath);
7810
7811    // Build the copy.
7812    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7813                                            To.get(), From,
7814                                            /*CopyingBaseSubobject=*/true,
7815                                            /*Copying=*/true);
7816    if (Copy.isInvalid()) {
7817      Diag(CurrentLocation, diag::note_member_synthesized_at)
7818        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7819      CopyAssignOperator->setInvalidDecl();
7820      return;
7821    }
7822
7823    // Success! Record the copy.
7824    Statements.push_back(Copy.takeAs<Expr>());
7825  }
7826
7827  // \brief Reference to the __builtin_memcpy function.
7828  Expr *BuiltinMemCpyRef = 0;
7829  // \brief Reference to the __builtin_objc_memmove_collectable function.
7830  Expr *CollectableMemCpyRef = 0;
7831
7832  // Assign non-static members.
7833  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7834                                  FieldEnd = ClassDecl->field_end();
7835       Field != FieldEnd; ++Field) {
7836    if (Field->isUnnamedBitfield())
7837      continue;
7838
7839    // Check for members of reference type; we can't copy those.
7840    if (Field->getType()->isReferenceType()) {
7841      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7842        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7843      Diag(Field->getLocation(), diag::note_declared_at);
7844      Diag(CurrentLocation, diag::note_member_synthesized_at)
7845        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7846      Invalid = true;
7847      continue;
7848    }
7849
7850    // Check for members of const-qualified, non-class type.
7851    QualType BaseType = Context.getBaseElementType(Field->getType());
7852    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7853      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7854        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7855      Diag(Field->getLocation(), diag::note_declared_at);
7856      Diag(CurrentLocation, diag::note_member_synthesized_at)
7857        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7858      Invalid = true;
7859      continue;
7860    }
7861
7862    // Suppress assigning zero-width bitfields.
7863    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7864      continue;
7865
7866    QualType FieldType = Field->getType().getNonReferenceType();
7867    if (FieldType->isIncompleteArrayType()) {
7868      assert(ClassDecl->hasFlexibleArrayMember() &&
7869             "Incomplete array type is not valid");
7870      continue;
7871    }
7872
7873    // Build references to the field in the object we're copying from and to.
7874    CXXScopeSpec SS; // Intentionally empty
7875    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7876                              LookupMemberName);
7877    MemberLookup.addDecl(*Field);
7878    MemberLookup.resolveKind();
7879    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7880                                               Loc, /*IsArrow=*/false,
7881                                               SS, SourceLocation(), 0,
7882                                               MemberLookup, 0);
7883    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7884                                             Loc, /*IsArrow=*/true,
7885                                             SS, SourceLocation(), 0,
7886                                             MemberLookup, 0);
7887    assert(!From.isInvalid() && "Implicit field reference cannot fail");
7888    assert(!To.isInvalid() && "Implicit field reference cannot fail");
7889
7890    // If the field should be copied with __builtin_memcpy rather than via
7891    // explicit assignments, do so. This optimization only applies for arrays
7892    // of scalars and arrays of class type with trivial copy-assignment
7893    // operators.
7894    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7895        && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7896      // Compute the size of the memory buffer to be copied.
7897      QualType SizeType = Context.getSizeType();
7898      llvm::APInt Size(Context.getTypeSize(SizeType),
7899                       Context.getTypeSizeInChars(BaseType).getQuantity());
7900      for (const ConstantArrayType *Array
7901              = Context.getAsConstantArrayType(FieldType);
7902           Array;
7903           Array = Context.getAsConstantArrayType(Array->getElementType())) {
7904        llvm::APInt ArraySize
7905          = Array->getSize().zextOrTrunc(Size.getBitWidth());
7906        Size *= ArraySize;
7907      }
7908
7909      // Take the address of the field references for "from" and "to".
7910      From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7911      To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7912
7913      bool NeedsCollectableMemCpy =
7914          (BaseType->isRecordType() &&
7915           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7916
7917      if (NeedsCollectableMemCpy) {
7918        if (!CollectableMemCpyRef) {
7919          // Create a reference to the __builtin_objc_memmove_collectable function.
7920          LookupResult R(*this,
7921                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
7922                         Loc, LookupOrdinaryName);
7923          LookupName(R, TUScope, true);
7924
7925          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7926          if (!CollectableMemCpy) {
7927            // Something went horribly wrong earlier, and we will have
7928            // complained about it.
7929            Invalid = true;
7930            continue;
7931          }
7932
7933          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7934                                                  CollectableMemCpy->getType(),
7935                                                  VK_LValue, Loc, 0).take();
7936          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7937        }
7938      }
7939      // Create a reference to the __builtin_memcpy builtin function.
7940      else if (!BuiltinMemCpyRef) {
7941        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7942                       LookupOrdinaryName);
7943        LookupName(R, TUScope, true);
7944
7945        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7946        if (!BuiltinMemCpy) {
7947          // Something went horribly wrong earlier, and we will have complained
7948          // about it.
7949          Invalid = true;
7950          continue;
7951        }
7952
7953        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7954                                            BuiltinMemCpy->getType(),
7955                                            VK_LValue, Loc, 0).take();
7956        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7957      }
7958
7959      ASTOwningVector<Expr*> CallArgs(*this);
7960      CallArgs.push_back(To.takeAs<Expr>());
7961      CallArgs.push_back(From.takeAs<Expr>());
7962      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7963      ExprResult Call = ExprError();
7964      if (NeedsCollectableMemCpy)
7965        Call = ActOnCallExpr(/*Scope=*/0,
7966                             CollectableMemCpyRef,
7967                             Loc, move_arg(CallArgs),
7968                             Loc);
7969      else
7970        Call = ActOnCallExpr(/*Scope=*/0,
7971                             BuiltinMemCpyRef,
7972                             Loc, move_arg(CallArgs),
7973                             Loc);
7974
7975      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7976      Statements.push_back(Call.takeAs<Expr>());
7977      continue;
7978    }
7979
7980    // Build the copy of this field.
7981    StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7982                                            To.get(), From.get(),
7983                                            /*CopyingBaseSubobject=*/false,
7984                                            /*Copying=*/true);
7985    if (Copy.isInvalid()) {
7986      Diag(CurrentLocation, diag::note_member_synthesized_at)
7987        << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7988      CopyAssignOperator->setInvalidDecl();
7989      return;
7990    }
7991
7992    // Success! Record the copy.
7993    Statements.push_back(Copy.takeAs<Stmt>());
7994  }
7995
7996  if (!Invalid) {
7997    // Add a "return *this;"
7998    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7999
8000    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8001    if (Return.isInvalid())
8002      Invalid = true;
8003    else {
8004      Statements.push_back(Return.takeAs<Stmt>());
8005
8006      if (Trap.hasErrorOccurred()) {
8007        Diag(CurrentLocation, diag::note_member_synthesized_at)
8008          << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8009        Invalid = true;
8010      }
8011    }
8012  }
8013
8014  if (Invalid) {
8015    CopyAssignOperator->setInvalidDecl();
8016    return;
8017  }
8018
8019  StmtResult Body;
8020  {
8021    CompoundScopeRAII CompoundScope(*this);
8022    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8023                             /*isStmtExpr=*/false);
8024    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8025  }
8026  CopyAssignOperator->setBody(Body.takeAs<Stmt>());
8027
8028  if (ASTMutationListener *L = getASTMutationListener()) {
8029    L->CompletedImplicitDefinition(CopyAssignOperator);
8030  }
8031}
8032
8033Sema::ImplicitExceptionSpecification
8034Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8035  ImplicitExceptionSpecification ExceptSpec(Context);
8036
8037  if (ClassDecl->isInvalidDecl())
8038    return ExceptSpec;
8039
8040  // C++0x [except.spec]p14:
8041  //   An implicitly declared special member function (Clause 12) shall have an
8042  //   exception-specification. [...]
8043
8044  // It is unspecified whether or not an implicit move assignment operator
8045  // attempts to deduplicate calls to assignment operators of virtual bases are
8046  // made. As such, this exception specification is effectively unspecified.
8047  // Based on a similar decision made for constness in C++0x, we're erring on
8048  // the side of assuming such calls to be made regardless of whether they
8049  // actually happen.
8050  // Note that a move constructor is not implicitly declared when there are
8051  // virtual bases, but it can still be user-declared and explicitly defaulted.
8052  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8053                                       BaseEnd = ClassDecl->bases_end();
8054       Base != BaseEnd; ++Base) {
8055    if (Base->isVirtual())
8056      continue;
8057
8058    CXXRecordDecl *BaseClassDecl
8059      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8060    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8061                                                           false, 0))
8062      ExceptSpec.CalledDecl(MoveAssign);
8063  }
8064
8065  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8066                                       BaseEnd = ClassDecl->vbases_end();
8067       Base != BaseEnd; ++Base) {
8068    CXXRecordDecl *BaseClassDecl
8069      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8070    if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8071                                                           false, 0))
8072      ExceptSpec.CalledDecl(MoveAssign);
8073  }
8074
8075  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8076                                  FieldEnd = ClassDecl->field_end();
8077       Field != FieldEnd;
8078       ++Field) {
8079    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8080    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8081      if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8082                                                             false, 0))
8083        ExceptSpec.CalledDecl(MoveAssign);
8084    }
8085  }
8086
8087  return ExceptSpec;
8088}
8089
8090/// Determine whether the class type has any direct or indirect virtual base
8091/// classes which have a non-trivial move assignment operator.
8092static bool
8093hasVirtualBaseWithNonTrivialMoveAssignment(Sema &S, CXXRecordDecl *ClassDecl) {
8094  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8095                                          BaseEnd = ClassDecl->vbases_end();
8096       Base != BaseEnd; ++Base) {
8097    CXXRecordDecl *BaseClass =
8098        cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8099
8100    // Try to declare the move assignment. If it would be deleted, then the
8101    // class does not have a non-trivial move assignment.
8102    if (BaseClass->needsImplicitMoveAssignment())
8103      S.DeclareImplicitMoveAssignment(BaseClass);
8104
8105    // If the class has both a trivial move assignment and a non-trivial move
8106    // assignment, hasTrivialMoveAssignment() is false.
8107    if (BaseClass->hasDeclaredMoveAssignment() &&
8108        !BaseClass->hasTrivialMoveAssignment())
8109      return true;
8110  }
8111
8112  return false;
8113}
8114
8115/// Determine whether the given type either has a move constructor or is
8116/// trivially copyable.
8117static bool
8118hasMoveOrIsTriviallyCopyable(Sema &S, QualType Type, bool IsConstructor) {
8119  Type = S.Context.getBaseElementType(Type);
8120
8121  // FIXME: Technically, non-trivially-copyable non-class types, such as
8122  // reference types, are supposed to return false here, but that appears
8123  // to be a standard defect.
8124  CXXRecordDecl *ClassDecl = Type->getAsCXXRecordDecl();
8125  if (!ClassDecl)
8126    return true;
8127
8128  if (Type.isTriviallyCopyableType(S.Context))
8129    return true;
8130
8131  if (IsConstructor) {
8132    if (ClassDecl->needsImplicitMoveConstructor())
8133      S.DeclareImplicitMoveConstructor(ClassDecl);
8134    return ClassDecl->hasDeclaredMoveConstructor();
8135  }
8136
8137  if (ClassDecl->needsImplicitMoveAssignment())
8138    S.DeclareImplicitMoveAssignment(ClassDecl);
8139  return ClassDecl->hasDeclaredMoveAssignment();
8140}
8141
8142/// Determine whether all non-static data members and direct or virtual bases
8143/// of class \p ClassDecl have either a move operation, or are trivially
8144/// copyable.
8145static bool subobjectsHaveMoveOrTrivialCopy(Sema &S, CXXRecordDecl *ClassDecl,
8146                                            bool IsConstructor) {
8147  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8148                                          BaseEnd = ClassDecl->bases_end();
8149       Base != BaseEnd; ++Base) {
8150    if (Base->isVirtual())
8151      continue;
8152
8153    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8154      return false;
8155  }
8156
8157  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8158                                          BaseEnd = ClassDecl->vbases_end();
8159       Base != BaseEnd; ++Base) {
8160    if (!hasMoveOrIsTriviallyCopyable(S, Base->getType(), IsConstructor))
8161      return false;
8162  }
8163
8164  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8165                                     FieldEnd = ClassDecl->field_end();
8166       Field != FieldEnd; ++Field) {
8167    if (!hasMoveOrIsTriviallyCopyable(S, (*Field)->getType(), IsConstructor))
8168      return false;
8169  }
8170
8171  return true;
8172}
8173
8174CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8175  // C++11 [class.copy]p20:
8176  //   If the definition of a class X does not explicitly declare a move
8177  //   assignment operator, one will be implicitly declared as defaulted
8178  //   if and only if:
8179  //
8180  //   - [first 4 bullets]
8181  assert(ClassDecl->needsImplicitMoveAssignment());
8182
8183  // [Checked after we build the declaration]
8184  //   - the move assignment operator would not be implicitly defined as
8185  //     deleted,
8186
8187  // [DR1402]:
8188  //   - X has no direct or indirect virtual base class with a non-trivial
8189  //     move assignment operator, and
8190  //   - each of X's non-static data members and direct or virtual base classes
8191  //     has a type that either has a move assignment operator or is trivially
8192  //     copyable.
8193  if (hasVirtualBaseWithNonTrivialMoveAssignment(*this, ClassDecl) ||
8194      !subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl,/*Constructor*/false)) {
8195    ClassDecl->setFailedImplicitMoveAssignment();
8196    return 0;
8197  }
8198
8199  // Note: The following rules are largely analoguous to the move
8200  // constructor rules.
8201
8202  ImplicitExceptionSpecification Spec(
8203      ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8204
8205  QualType ArgType = Context.getTypeDeclType(ClassDecl);
8206  QualType RetType = Context.getLValueReferenceType(ArgType);
8207  ArgType = Context.getRValueReferenceType(ArgType);
8208
8209  //   An implicitly-declared move assignment operator is an inline public
8210  //   member of its class.
8211  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8212  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8213  SourceLocation ClassLoc = ClassDecl->getLocation();
8214  DeclarationNameInfo NameInfo(Name, ClassLoc);
8215  CXXMethodDecl *MoveAssignment
8216    = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8217                            Context.getFunctionType(RetType, &ArgType, 1, EPI),
8218                            /*TInfo=*/0, /*isStatic=*/false,
8219                            /*StorageClassAsWritten=*/SC_None,
8220                            /*isInline=*/true,
8221                            /*isConstexpr=*/false,
8222                            SourceLocation());
8223  MoveAssignment->setAccess(AS_public);
8224  MoveAssignment->setDefaulted();
8225  MoveAssignment->setImplicit();
8226  MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8227
8228  // Add the parameter to the operator.
8229  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8230                                               ClassLoc, ClassLoc, /*Id=*/0,
8231                                               ArgType, /*TInfo=*/0,
8232                                               SC_None,
8233                                               SC_None, 0);
8234  MoveAssignment->setParams(FromParam);
8235
8236  // Note that we have added this copy-assignment operator.
8237  ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8238
8239  // C++0x [class.copy]p9:
8240  //   If the definition of a class X does not explicitly declare a move
8241  //   assignment operator, one will be implicitly declared as defaulted if and
8242  //   only if:
8243  //   [...]
8244  //   - the move assignment operator would not be implicitly defined as
8245  //     deleted.
8246  if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
8247    // Cache this result so that we don't try to generate this over and over
8248    // on every lookup, leaking memory and wasting time.
8249    ClassDecl->setFailedImplicitMoveAssignment();
8250    return 0;
8251  }
8252
8253  if (Scope *S = getScopeForContext(ClassDecl))
8254    PushOnScopeChains(MoveAssignment, S, false);
8255  ClassDecl->addDecl(MoveAssignment);
8256
8257  AddOverriddenMethods(ClassDecl, MoveAssignment);
8258  return MoveAssignment;
8259}
8260
8261void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8262                                        CXXMethodDecl *MoveAssignOperator) {
8263  assert((MoveAssignOperator->isDefaulted() &&
8264          MoveAssignOperator->isOverloadedOperator() &&
8265          MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8266          !MoveAssignOperator->doesThisDeclarationHaveABody() &&
8267          !MoveAssignOperator->isDeleted()) &&
8268         "DefineImplicitMoveAssignment called for wrong function");
8269
8270  CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8271
8272  if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8273    MoveAssignOperator->setInvalidDecl();
8274    return;
8275  }
8276
8277  MoveAssignOperator->setUsed();
8278
8279  ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8280  DiagnosticErrorTrap Trap(Diags);
8281
8282  // C++0x [class.copy]p28:
8283  //   The implicitly-defined or move assignment operator for a non-union class
8284  //   X performs memberwise move assignment of its subobjects. The direct base
8285  //   classes of X are assigned first, in the order of their declaration in the
8286  //   base-specifier-list, and then the immediate non-static data members of X
8287  //   are assigned, in the order in which they were declared in the class
8288  //   definition.
8289
8290  // The statements that form the synthesized function body.
8291  ASTOwningVector<Stmt*> Statements(*this);
8292
8293  // The parameter for the "other" object, which we are move from.
8294  ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8295  QualType OtherRefType = Other->getType()->
8296      getAs<RValueReferenceType>()->getPointeeType();
8297  assert(OtherRefType.getQualifiers() == 0 &&
8298         "Bad argument type of defaulted move assignment");
8299
8300  // Our location for everything implicitly-generated.
8301  SourceLocation Loc = MoveAssignOperator->getLocation();
8302
8303  // Construct a reference to the "other" object. We'll be using this
8304  // throughout the generated ASTs.
8305  Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8306  assert(OtherRef && "Reference to parameter cannot fail!");
8307  // Cast to rvalue.
8308  OtherRef = CastForMoving(*this, OtherRef);
8309
8310  // Construct the "this" pointer. We'll be using this throughout the generated
8311  // ASTs.
8312  Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8313  assert(This && "Reference to this cannot fail!");
8314
8315  // Assign base classes.
8316  bool Invalid = false;
8317  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8318       E = ClassDecl->bases_end(); Base != E; ++Base) {
8319    // Form the assignment:
8320    //   static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8321    QualType BaseType = Base->getType().getUnqualifiedType();
8322    if (!BaseType->isRecordType()) {
8323      Invalid = true;
8324      continue;
8325    }
8326
8327    CXXCastPath BasePath;
8328    BasePath.push_back(Base);
8329
8330    // Construct the "from" expression, which is an implicit cast to the
8331    // appropriately-qualified base type.
8332    Expr *From = OtherRef;
8333    From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8334                             VK_XValue, &BasePath).take();
8335
8336    // Dereference "this".
8337    ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8338
8339    // Implicitly cast "this" to the appropriately-qualified base type.
8340    To = ImpCastExprToType(To.take(),
8341                           Context.getCVRQualifiedType(BaseType,
8342                                     MoveAssignOperator->getTypeQualifiers()),
8343                           CK_UncheckedDerivedToBase,
8344                           VK_LValue, &BasePath);
8345
8346    // Build the move.
8347    StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8348                                            To.get(), From,
8349                                            /*CopyingBaseSubobject=*/true,
8350                                            /*Copying=*/false);
8351    if (Move.isInvalid()) {
8352      Diag(CurrentLocation, diag::note_member_synthesized_at)
8353        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8354      MoveAssignOperator->setInvalidDecl();
8355      return;
8356    }
8357
8358    // Success! Record the move.
8359    Statements.push_back(Move.takeAs<Expr>());
8360  }
8361
8362  // \brief Reference to the __builtin_memcpy function.
8363  Expr *BuiltinMemCpyRef = 0;
8364  // \brief Reference to the __builtin_objc_memmove_collectable function.
8365  Expr *CollectableMemCpyRef = 0;
8366
8367  // Assign non-static members.
8368  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8369                                  FieldEnd = ClassDecl->field_end();
8370       Field != FieldEnd; ++Field) {
8371    if (Field->isUnnamedBitfield())
8372      continue;
8373
8374    // Check for members of reference type; we can't move those.
8375    if (Field->getType()->isReferenceType()) {
8376      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8377        << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8378      Diag(Field->getLocation(), diag::note_declared_at);
8379      Diag(CurrentLocation, diag::note_member_synthesized_at)
8380        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8381      Invalid = true;
8382      continue;
8383    }
8384
8385    // Check for members of const-qualified, non-class type.
8386    QualType BaseType = Context.getBaseElementType(Field->getType());
8387    if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8388      Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8389        << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8390      Diag(Field->getLocation(), diag::note_declared_at);
8391      Diag(CurrentLocation, diag::note_member_synthesized_at)
8392        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8393      Invalid = true;
8394      continue;
8395    }
8396
8397    // Suppress assigning zero-width bitfields.
8398    if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8399      continue;
8400
8401    QualType FieldType = Field->getType().getNonReferenceType();
8402    if (FieldType->isIncompleteArrayType()) {
8403      assert(ClassDecl->hasFlexibleArrayMember() &&
8404             "Incomplete array type is not valid");
8405      continue;
8406    }
8407
8408    // Build references to the field in the object we're copying from and to.
8409    CXXScopeSpec SS; // Intentionally empty
8410    LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8411                              LookupMemberName);
8412    MemberLookup.addDecl(*Field);
8413    MemberLookup.resolveKind();
8414    ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8415                                               Loc, /*IsArrow=*/false,
8416                                               SS, SourceLocation(), 0,
8417                                               MemberLookup, 0);
8418    ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8419                                             Loc, /*IsArrow=*/true,
8420                                             SS, SourceLocation(), 0,
8421                                             MemberLookup, 0);
8422    assert(!From.isInvalid() && "Implicit field reference cannot fail");
8423    assert(!To.isInvalid() && "Implicit field reference cannot fail");
8424
8425    assert(!From.get()->isLValue() && // could be xvalue or prvalue
8426        "Member reference with rvalue base must be rvalue except for reference "
8427        "members, which aren't allowed for move assignment.");
8428
8429    // If the field should be copied with __builtin_memcpy rather than via
8430    // explicit assignments, do so. This optimization only applies for arrays
8431    // of scalars and arrays of class type with trivial move-assignment
8432    // operators.
8433    if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8434        && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8435      // Compute the size of the memory buffer to be copied.
8436      QualType SizeType = Context.getSizeType();
8437      llvm::APInt Size(Context.getTypeSize(SizeType),
8438                       Context.getTypeSizeInChars(BaseType).getQuantity());
8439      for (const ConstantArrayType *Array
8440              = Context.getAsConstantArrayType(FieldType);
8441           Array;
8442           Array = Context.getAsConstantArrayType(Array->getElementType())) {
8443        llvm::APInt ArraySize
8444          = Array->getSize().zextOrTrunc(Size.getBitWidth());
8445        Size *= ArraySize;
8446      }
8447
8448      // Take the address of the field references for "from" and "to". We
8449      // directly construct UnaryOperators here because semantic analysis
8450      // does not permit us to take the address of an xvalue.
8451      From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8452                             Context.getPointerType(From.get()->getType()),
8453                             VK_RValue, OK_Ordinary, Loc);
8454      To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8455                           Context.getPointerType(To.get()->getType()),
8456                           VK_RValue, OK_Ordinary, Loc);
8457
8458      bool NeedsCollectableMemCpy =
8459          (BaseType->isRecordType() &&
8460           BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8461
8462      if (NeedsCollectableMemCpy) {
8463        if (!CollectableMemCpyRef) {
8464          // Create a reference to the __builtin_objc_memmove_collectable function.
8465          LookupResult R(*this,
8466                         &Context.Idents.get("__builtin_objc_memmove_collectable"),
8467                         Loc, LookupOrdinaryName);
8468          LookupName(R, TUScope, true);
8469
8470          FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8471          if (!CollectableMemCpy) {
8472            // Something went horribly wrong earlier, and we will have
8473            // complained about it.
8474            Invalid = true;
8475            continue;
8476          }
8477
8478          CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8479                                                  CollectableMemCpy->getType(),
8480                                                  VK_LValue, Loc, 0).take();
8481          assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8482        }
8483      }
8484      // Create a reference to the __builtin_memcpy builtin function.
8485      else if (!BuiltinMemCpyRef) {
8486        LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8487                       LookupOrdinaryName);
8488        LookupName(R, TUScope, true);
8489
8490        FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8491        if (!BuiltinMemCpy) {
8492          // Something went horribly wrong earlier, and we will have complained
8493          // about it.
8494          Invalid = true;
8495          continue;
8496        }
8497
8498        BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8499                                            BuiltinMemCpy->getType(),
8500                                            VK_LValue, Loc, 0).take();
8501        assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8502      }
8503
8504      ASTOwningVector<Expr*> CallArgs(*this);
8505      CallArgs.push_back(To.takeAs<Expr>());
8506      CallArgs.push_back(From.takeAs<Expr>());
8507      CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8508      ExprResult Call = ExprError();
8509      if (NeedsCollectableMemCpy)
8510        Call = ActOnCallExpr(/*Scope=*/0,
8511                             CollectableMemCpyRef,
8512                             Loc, move_arg(CallArgs),
8513                             Loc);
8514      else
8515        Call = ActOnCallExpr(/*Scope=*/0,
8516                             BuiltinMemCpyRef,
8517                             Loc, move_arg(CallArgs),
8518                             Loc);
8519
8520      assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8521      Statements.push_back(Call.takeAs<Expr>());
8522      continue;
8523    }
8524
8525    // Build the move of this field.
8526    StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8527                                            To.get(), From.get(),
8528                                            /*CopyingBaseSubobject=*/false,
8529                                            /*Copying=*/false);
8530    if (Move.isInvalid()) {
8531      Diag(CurrentLocation, diag::note_member_synthesized_at)
8532        << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8533      MoveAssignOperator->setInvalidDecl();
8534      return;
8535    }
8536
8537    // Success! Record the copy.
8538    Statements.push_back(Move.takeAs<Stmt>());
8539  }
8540
8541  if (!Invalid) {
8542    // Add a "return *this;"
8543    ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8544
8545    StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8546    if (Return.isInvalid())
8547      Invalid = true;
8548    else {
8549      Statements.push_back(Return.takeAs<Stmt>());
8550
8551      if (Trap.hasErrorOccurred()) {
8552        Diag(CurrentLocation, diag::note_member_synthesized_at)
8553          << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8554        Invalid = true;
8555      }
8556    }
8557  }
8558
8559  if (Invalid) {
8560    MoveAssignOperator->setInvalidDecl();
8561    return;
8562  }
8563
8564  StmtResult Body;
8565  {
8566    CompoundScopeRAII CompoundScope(*this);
8567    Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8568                             /*isStmtExpr=*/false);
8569    assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8570  }
8571  MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8572
8573  if (ASTMutationListener *L = getASTMutationListener()) {
8574    L->CompletedImplicitDefinition(MoveAssignOperator);
8575  }
8576}
8577
8578std::pair<Sema::ImplicitExceptionSpecification, bool>
8579Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
8580  if (ClassDecl->isInvalidDecl())
8581    return std::make_pair(ImplicitExceptionSpecification(Context), false);
8582
8583  // C++ [class.copy]p5:
8584  //   The implicitly-declared copy constructor for a class X will
8585  //   have the form
8586  //
8587  //       X::X(const X&)
8588  //
8589  //   if
8590  // FIXME: It ought to be possible to store this on the record.
8591  bool HasConstCopyConstructor = true;
8592
8593  //     -- each direct or virtual base class B of X has a copy
8594  //        constructor whose first parameter is of type const B& or
8595  //        const volatile B&, and
8596  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8597                                       BaseEnd = ClassDecl->bases_end();
8598       HasConstCopyConstructor && Base != BaseEnd;
8599       ++Base) {
8600    // Virtual bases are handled below.
8601    if (Base->isVirtual())
8602      continue;
8603
8604    CXXRecordDecl *BaseClassDecl
8605      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8606    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8607                             &HasConstCopyConstructor);
8608  }
8609
8610  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8611                                       BaseEnd = ClassDecl->vbases_end();
8612       HasConstCopyConstructor && Base != BaseEnd;
8613       ++Base) {
8614    CXXRecordDecl *BaseClassDecl
8615      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8616    LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8617                             &HasConstCopyConstructor);
8618  }
8619
8620  //     -- for all the nonstatic data members of X that are of a
8621  //        class type M (or array thereof), each such class type
8622  //        has a copy constructor whose first parameter is of type
8623  //        const M& or const volatile M&.
8624  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8625                                  FieldEnd = ClassDecl->field_end();
8626       HasConstCopyConstructor && Field != FieldEnd;
8627       ++Field) {
8628    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8629    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8630      LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8631                               &HasConstCopyConstructor);
8632    }
8633  }
8634  //   Otherwise, the implicitly declared copy constructor will have
8635  //   the form
8636  //
8637  //       X::X(X&)
8638
8639  // C++ [except.spec]p14:
8640  //   An implicitly declared special member function (Clause 12) shall have an
8641  //   exception-specification. [...]
8642  ImplicitExceptionSpecification ExceptSpec(Context);
8643  unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8644  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8645                                       BaseEnd = ClassDecl->bases_end();
8646       Base != BaseEnd;
8647       ++Base) {
8648    // Virtual bases are handled below.
8649    if (Base->isVirtual())
8650      continue;
8651
8652    CXXRecordDecl *BaseClassDecl
8653      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8654    if (CXXConstructorDecl *CopyConstructor =
8655          LookupCopyingConstructor(BaseClassDecl, Quals))
8656      ExceptSpec.CalledDecl(CopyConstructor);
8657  }
8658  for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8659                                       BaseEnd = ClassDecl->vbases_end();
8660       Base != BaseEnd;
8661       ++Base) {
8662    CXXRecordDecl *BaseClassDecl
8663      = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8664    if (CXXConstructorDecl *CopyConstructor =
8665          LookupCopyingConstructor(BaseClassDecl, Quals))
8666      ExceptSpec.CalledDecl(CopyConstructor);
8667  }
8668  for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8669                                  FieldEnd = ClassDecl->field_end();
8670       Field != FieldEnd;
8671       ++Field) {
8672    QualType FieldType = Context.getBaseElementType((*Field)->getType());
8673    if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8674      if (CXXConstructorDecl *CopyConstructor =
8675        LookupCopyingConstructor(FieldClassDecl, Quals))
8676      ExceptSpec.CalledDecl(CopyConstructor);
8677    }
8678  }
8679
8680  return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8681}
8682
8683CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8684                                                    CXXRecordDecl *ClassDecl) {
8685  // C++ [class.copy]p4:
8686  //   If the class definition does not explicitly declare a copy
8687  //   constructor, one is declared implicitly.
8688
8689  ImplicitExceptionSpecification Spec(Context);
8690  bool Const;
8691  llvm::tie(Spec, Const) =
8692    ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8693
8694  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8695  QualType ArgType = ClassType;
8696  if (Const)
8697    ArgType = ArgType.withConst();
8698  ArgType = Context.getLValueReferenceType(ArgType);
8699
8700  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8701
8702  DeclarationName Name
8703    = Context.DeclarationNames.getCXXConstructorName(
8704                                           Context.getCanonicalType(ClassType));
8705  SourceLocation ClassLoc = ClassDecl->getLocation();
8706  DeclarationNameInfo NameInfo(Name, ClassLoc);
8707
8708  //   An implicitly-declared copy constructor is an inline public
8709  //   member of its class.
8710  CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8711      Context, ClassDecl, ClassLoc, NameInfo,
8712      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8713      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8714      /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8715        getLangOpts().CPlusPlus0x);
8716  CopyConstructor->setAccess(AS_public);
8717  CopyConstructor->setDefaulted();
8718  CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8719
8720  // Note that we have declared this constructor.
8721  ++ASTContext::NumImplicitCopyConstructorsDeclared;
8722
8723  // Add the parameter to the constructor.
8724  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8725                                               ClassLoc, ClassLoc,
8726                                               /*IdentifierInfo=*/0,
8727                                               ArgType, /*TInfo=*/0,
8728                                               SC_None,
8729                                               SC_None, 0);
8730  CopyConstructor->setParams(FromParam);
8731
8732  if (Scope *S = getScopeForContext(ClassDecl))
8733    PushOnScopeChains(CopyConstructor, S, false);
8734  ClassDecl->addDecl(CopyConstructor);
8735
8736  // C++11 [class.copy]p8:
8737  //   ... If the class definition does not explicitly declare a copy
8738  //   constructor, there is no user-declared move constructor, and there is no
8739  //   user-declared move assignment operator, a copy constructor is implicitly
8740  //   declared as defaulted.
8741  if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8742    CopyConstructor->setDeletedAsWritten();
8743
8744  return CopyConstructor;
8745}
8746
8747void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8748                                   CXXConstructorDecl *CopyConstructor) {
8749  assert((CopyConstructor->isDefaulted() &&
8750          CopyConstructor->isCopyConstructor() &&
8751          !CopyConstructor->doesThisDeclarationHaveABody() &&
8752          !CopyConstructor->isDeleted()) &&
8753         "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8754
8755  CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8756  assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8757
8758  ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8759  DiagnosticErrorTrap Trap(Diags);
8760
8761  if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8762      Trap.hasErrorOccurred()) {
8763    Diag(CurrentLocation, diag::note_member_synthesized_at)
8764      << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8765    CopyConstructor->setInvalidDecl();
8766  }  else {
8767    Sema::CompoundScopeRAII CompoundScope(*this);
8768    CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8769                                               CopyConstructor->getLocation(),
8770                                               MultiStmtArg(*this, 0, 0),
8771                                               /*isStmtExpr=*/false)
8772                                                              .takeAs<Stmt>());
8773    CopyConstructor->setImplicitlyDefined(true);
8774  }
8775
8776  CopyConstructor->setUsed();
8777  if (ASTMutationListener *L = getASTMutationListener()) {
8778    L->CompletedImplicitDefinition(CopyConstructor);
8779  }
8780}
8781
8782Sema::ImplicitExceptionSpecification
8783Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8784  // C++ [except.spec]p14:
8785  //   An implicitly declared special member function (Clause 12) shall have an
8786  //   exception-specification. [...]
8787  ImplicitExceptionSpecification ExceptSpec(Context);
8788  if (ClassDecl->isInvalidDecl())
8789    return ExceptSpec;
8790
8791  // Direct base-class constructors.
8792  for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8793                                       BEnd = ClassDecl->bases_end();
8794       B != BEnd; ++B) {
8795    if (B->isVirtual()) // Handled below.
8796      continue;
8797
8798    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8799      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8800      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8801      // If this is a deleted function, add it anyway. This might be conformant
8802      // with the standard. This might not. I'm not sure. It might not matter.
8803      if (Constructor)
8804        ExceptSpec.CalledDecl(Constructor);
8805    }
8806  }
8807
8808  // Virtual base-class constructors.
8809  for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8810                                       BEnd = ClassDecl->vbases_end();
8811       B != BEnd; ++B) {
8812    if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8813      CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8814      CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8815      // If this is a deleted function, add it anyway. This might be conformant
8816      // with the standard. This might not. I'm not sure. It might not matter.
8817      if (Constructor)
8818        ExceptSpec.CalledDecl(Constructor);
8819    }
8820  }
8821
8822  // Field constructors.
8823  for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8824                               FEnd = ClassDecl->field_end();
8825       F != FEnd; ++F) {
8826    if (const RecordType *RecordTy
8827              = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8828      CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8829      CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8830      // If this is a deleted function, add it anyway. This might be conformant
8831      // with the standard. This might not. I'm not sure. It might not matter.
8832      // In particular, the problem is that this function never gets called. It
8833      // might just be ill-formed because this function attempts to refer to
8834      // a deleted function here.
8835      if (Constructor)
8836        ExceptSpec.CalledDecl(Constructor);
8837    }
8838  }
8839
8840  return ExceptSpec;
8841}
8842
8843CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8844                                                    CXXRecordDecl *ClassDecl) {
8845  // C++11 [class.copy]p9:
8846  //   If the definition of a class X does not explicitly declare a move
8847  //   constructor, one will be implicitly declared as defaulted if and only if:
8848  //
8849  //   - [first 4 bullets]
8850  assert(ClassDecl->needsImplicitMoveConstructor());
8851
8852  // [Checked after we build the declaration]
8853  //   - the move assignment operator would not be implicitly defined as
8854  //     deleted,
8855
8856  // [DR1402]:
8857  //   - each of X's non-static data members and direct or virtual base classes
8858  //     has a type that either has a move constructor or is trivially copyable.
8859  if (!subobjectsHaveMoveOrTrivialCopy(*this, ClassDecl, /*Constructor*/true)) {
8860    ClassDecl->setFailedImplicitMoveConstructor();
8861    return 0;
8862  }
8863
8864  ImplicitExceptionSpecification Spec(
8865      ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8866
8867  QualType ClassType = Context.getTypeDeclType(ClassDecl);
8868  QualType ArgType = Context.getRValueReferenceType(ClassType);
8869
8870  FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8871
8872  DeclarationName Name
8873    = Context.DeclarationNames.getCXXConstructorName(
8874                                           Context.getCanonicalType(ClassType));
8875  SourceLocation ClassLoc = ClassDecl->getLocation();
8876  DeclarationNameInfo NameInfo(Name, ClassLoc);
8877
8878  // C++0x [class.copy]p11:
8879  //   An implicitly-declared copy/move constructor is an inline public
8880  //   member of its class.
8881  CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8882      Context, ClassDecl, ClassLoc, NameInfo,
8883      Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8884      /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8885      /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8886        getLangOpts().CPlusPlus0x);
8887  MoveConstructor->setAccess(AS_public);
8888  MoveConstructor->setDefaulted();
8889  MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8890
8891  // Add the parameter to the constructor.
8892  ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8893                                               ClassLoc, ClassLoc,
8894                                               /*IdentifierInfo=*/0,
8895                                               ArgType, /*TInfo=*/0,
8896                                               SC_None,
8897                                               SC_None, 0);
8898  MoveConstructor->setParams(FromParam);
8899
8900  // C++0x [class.copy]p9:
8901  //   If the definition of a class X does not explicitly declare a move
8902  //   constructor, one will be implicitly declared as defaulted if and only if:
8903  //   [...]
8904  //   - the move constructor would not be implicitly defined as deleted.
8905  if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8906    // Cache this result so that we don't try to generate this over and over
8907    // on every lookup, leaking memory and wasting time.
8908    ClassDecl->setFailedImplicitMoveConstructor();
8909    return 0;
8910  }
8911
8912  // Note that we have declared this constructor.
8913  ++ASTContext::NumImplicitMoveConstructorsDeclared;
8914
8915  if (Scope *S = getScopeForContext(ClassDecl))
8916    PushOnScopeChains(MoveConstructor, S, false);
8917  ClassDecl->addDecl(MoveConstructor);
8918
8919  return MoveConstructor;
8920}
8921
8922void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8923                                   CXXConstructorDecl *MoveConstructor) {
8924  assert((MoveConstructor->isDefaulted() &&
8925          MoveConstructor->isMoveConstructor() &&
8926          !MoveConstructor->doesThisDeclarationHaveABody() &&
8927          !MoveConstructor->isDeleted()) &&
8928         "DefineImplicitMoveConstructor - call it for implicit move ctor");
8929
8930  CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8931  assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8932
8933  ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8934  DiagnosticErrorTrap Trap(Diags);
8935
8936  if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8937      Trap.hasErrorOccurred()) {
8938    Diag(CurrentLocation, diag::note_member_synthesized_at)
8939      << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8940    MoveConstructor->setInvalidDecl();
8941  }  else {
8942    Sema::CompoundScopeRAII CompoundScope(*this);
8943    MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8944                                               MoveConstructor->getLocation(),
8945                                               MultiStmtArg(*this, 0, 0),
8946                                               /*isStmtExpr=*/false)
8947                                                              .takeAs<Stmt>());
8948    MoveConstructor->setImplicitlyDefined(true);
8949  }
8950
8951  MoveConstructor->setUsed();
8952
8953  if (ASTMutationListener *L = getASTMutationListener()) {
8954    L->CompletedImplicitDefinition(MoveConstructor);
8955  }
8956}
8957
8958bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
8959  return FD->isDeleted() &&
8960         (FD->isDefaulted() || FD->isImplicit()) &&
8961         isa<CXXMethodDecl>(FD);
8962}
8963
8964/// \brief Mark the call operator of the given lambda closure type as "used".
8965static void markLambdaCallOperatorUsed(Sema &S, CXXRecordDecl *Lambda) {
8966  CXXMethodDecl *CallOperator
8967    = cast<CXXMethodDecl>(
8968        *Lambda->lookup(
8969          S.Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
8970  CallOperator->setReferenced();
8971  CallOperator->setUsed();
8972}
8973
8974void Sema::DefineImplicitLambdaToFunctionPointerConversion(
8975       SourceLocation CurrentLocation,
8976       CXXConversionDecl *Conv)
8977{
8978  CXXRecordDecl *Lambda = Conv->getParent();
8979
8980  // Make sure that the lambda call operator is marked used.
8981  markLambdaCallOperatorUsed(*this, Lambda);
8982
8983  Conv->setUsed();
8984
8985  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
8986  DiagnosticErrorTrap Trap(Diags);
8987
8988  // Return the address of the __invoke function.
8989  DeclarationName InvokeName = &Context.Idents.get("__invoke");
8990  CXXMethodDecl *Invoke
8991    = cast<CXXMethodDecl>(*Lambda->lookup(InvokeName).first);
8992  Expr *FunctionRef = BuildDeclRefExpr(Invoke, Invoke->getType(),
8993                                       VK_LValue, Conv->getLocation()).take();
8994  assert(FunctionRef && "Can't refer to __invoke function?");
8995  Stmt *Return = ActOnReturnStmt(Conv->getLocation(), FunctionRef).take();
8996  Conv->setBody(new (Context) CompoundStmt(Context, &Return, 1,
8997                                           Conv->getLocation(),
8998                                           Conv->getLocation()));
8999
9000  // Fill in the __invoke function with a dummy implementation. IR generation
9001  // will fill in the actual details.
9002  Invoke->setUsed();
9003  Invoke->setReferenced();
9004  Invoke->setBody(new (Context) CompoundStmt(Context, 0, 0, Conv->getLocation(),
9005                                             Conv->getLocation()));
9006
9007  if (ASTMutationListener *L = getASTMutationListener()) {
9008    L->CompletedImplicitDefinition(Conv);
9009    L->CompletedImplicitDefinition(Invoke);
9010  }
9011}
9012
9013void Sema::DefineImplicitLambdaToBlockPointerConversion(
9014       SourceLocation CurrentLocation,
9015       CXXConversionDecl *Conv)
9016{
9017  Conv->setUsed();
9018
9019  ImplicitlyDefinedFunctionScope Scope(*this, Conv);
9020  DiagnosticErrorTrap Trap(Diags);
9021
9022  // Copy-initialize the lambda object as needed to capture it.
9023  Expr *This = ActOnCXXThis(CurrentLocation).take();
9024  Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).take();
9025
9026  ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
9027                                                        Conv->getLocation(),
9028                                                        Conv, DerefThis);
9029
9030  // If we're not under ARC, make sure we still get the _Block_copy/autorelease
9031  // behavior.  Note that only the general conversion function does this
9032  // (since it's unusable otherwise); in the case where we inline the
9033  // block literal, it has block literal lifetime semantics.
9034  if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
9035    BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
9036                                          CK_CopyAndAutoreleaseBlockObject,
9037                                          BuildBlock.get(), 0, VK_RValue);
9038
9039  if (BuildBlock.isInvalid()) {
9040    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9041    Conv->setInvalidDecl();
9042    return;
9043  }
9044
9045  // Create the return statement that returns the block from the conversion
9046  // function.
9047  StmtResult Return = ActOnReturnStmt(Conv->getLocation(), BuildBlock.get());
9048  if (Return.isInvalid()) {
9049    Diag(CurrentLocation, diag::note_lambda_to_block_conv);
9050    Conv->setInvalidDecl();
9051    return;
9052  }
9053
9054  // Set the body of the conversion function.
9055  Stmt *ReturnS = Return.take();
9056  Conv->setBody(new (Context) CompoundStmt(Context, &ReturnS, 1,
9057                                           Conv->getLocation(),
9058                                           Conv->getLocation()));
9059
9060  // We're done; notify the mutation listener, if any.
9061  if (ASTMutationListener *L = getASTMutationListener()) {
9062    L->CompletedImplicitDefinition(Conv);
9063  }
9064}
9065
9066/// \brief Determine whether the given list arguments contains exactly one
9067/// "real" (non-default) argument.
9068static bool hasOneRealArgument(MultiExprArg Args) {
9069  switch (Args.size()) {
9070  case 0:
9071    return false;
9072
9073  default:
9074    if (!Args.get()[1]->isDefaultArgument())
9075      return false;
9076
9077    // fall through
9078  case 1:
9079    return !Args.get()[0]->isDefaultArgument();
9080  }
9081
9082  return false;
9083}
9084
9085ExprResult
9086Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9087                            CXXConstructorDecl *Constructor,
9088                            MultiExprArg ExprArgs,
9089                            bool HadMultipleCandidates,
9090                            bool RequiresZeroInit,
9091                            unsigned ConstructKind,
9092                            SourceRange ParenRange) {
9093  bool Elidable = false;
9094
9095  // C++0x [class.copy]p34:
9096  //   When certain criteria are met, an implementation is allowed to
9097  //   omit the copy/move construction of a class object, even if the
9098  //   copy/move constructor and/or destructor for the object have
9099  //   side effects. [...]
9100  //     - when a temporary class object that has not been bound to a
9101  //       reference (12.2) would be copied/moved to a class object
9102  //       with the same cv-unqualified type, the copy/move operation
9103  //       can be omitted by constructing the temporary object
9104  //       directly into the target of the omitted copy/move
9105  if (ConstructKind == CXXConstructExpr::CK_Complete &&
9106      Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
9107    Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
9108    Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
9109  }
9110
9111  return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
9112                               Elidable, move(ExprArgs), HadMultipleCandidates,
9113                               RequiresZeroInit, ConstructKind, ParenRange);
9114}
9115
9116/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9117/// including handling of its default argument expressions.
9118ExprResult
9119Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9120                            CXXConstructorDecl *Constructor, bool Elidable,
9121                            MultiExprArg ExprArgs,
9122                            bool HadMultipleCandidates,
9123                            bool RequiresZeroInit,
9124                            unsigned ConstructKind,
9125                            SourceRange ParenRange) {
9126  unsigned NumExprs = ExprArgs.size();
9127  Expr **Exprs = (Expr **)ExprArgs.release();
9128
9129  for (specific_attr_iterator<NonNullAttr>
9130           i = Constructor->specific_attr_begin<NonNullAttr>(),
9131           e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9132    const NonNullAttr *NonNull = *i;
9133    CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9134  }
9135
9136  MarkFunctionReferenced(ConstructLoc, Constructor);
9137  return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
9138                                        Constructor, Elidable, Exprs, NumExprs,
9139                                        HadMultipleCandidates, /*FIXME*/false,
9140                                        RequiresZeroInit,
9141              static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9142                                        ParenRange));
9143}
9144
9145bool Sema::InitializeVarWithConstructor(VarDecl *VD,
9146                                        CXXConstructorDecl *Constructor,
9147                                        MultiExprArg Exprs,
9148                                        bool HadMultipleCandidates) {
9149  // FIXME: Provide the correct paren SourceRange when available.
9150  ExprResult TempResult =
9151    BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
9152                          move(Exprs), HadMultipleCandidates, false,
9153                          CXXConstructExpr::CK_Complete, SourceRange());
9154  if (TempResult.isInvalid())
9155    return true;
9156
9157  Expr *Temp = TempResult.takeAs<Expr>();
9158  CheckImplicitConversions(Temp, VD->getLocation());
9159  MarkFunctionReferenced(VD->getLocation(), Constructor);
9160  Temp = MaybeCreateExprWithCleanups(Temp);
9161  VD->setInit(Temp);
9162
9163  return false;
9164}
9165
9166void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
9167  if (VD->isInvalidDecl()) return;
9168
9169  CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
9170  if (ClassDecl->isInvalidDecl()) return;
9171  if (ClassDecl->hasIrrelevantDestructor()) return;
9172  if (ClassDecl->isDependentContext()) return;
9173
9174  CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
9175  MarkFunctionReferenced(VD->getLocation(), Destructor);
9176  CheckDestructorAccess(VD->getLocation(), Destructor,
9177                        PDiag(diag::err_access_dtor_var)
9178                        << VD->getDeclName()
9179                        << VD->getType());
9180  DiagnoseUseOfDecl(Destructor, VD->getLocation());
9181
9182  if (!VD->hasGlobalStorage()) return;
9183
9184  // Emit warning for non-trivial dtor in global scope (a real global,
9185  // class-static, function-static).
9186  Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9187
9188  // TODO: this should be re-enabled for static locals by !CXAAtExit
9189  if (!VD->isStaticLocal())
9190    Diag(VD->getLocation(), diag::warn_global_destructor);
9191}
9192
9193/// \brief Given a constructor and the set of arguments provided for the
9194/// constructor, convert the arguments and add any required default arguments
9195/// to form a proper call to this constructor.
9196///
9197/// \returns true if an error occurred, false otherwise.
9198bool
9199Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9200                              MultiExprArg ArgsPtr,
9201                              SourceLocation Loc,
9202                              ASTOwningVector<Expr*> &ConvertedArgs,
9203                              bool AllowExplicit) {
9204  // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9205  unsigned NumArgs = ArgsPtr.size();
9206  Expr **Args = (Expr **)ArgsPtr.get();
9207
9208  const FunctionProtoType *Proto
9209    = Constructor->getType()->getAs<FunctionProtoType>();
9210  assert(Proto && "Constructor without a prototype?");
9211  unsigned NumArgsInProto = Proto->getNumArgs();
9212
9213  // If too few arguments are available, we'll fill in the rest with defaults.
9214  if (NumArgs < NumArgsInProto)
9215    ConvertedArgs.reserve(NumArgsInProto);
9216  else
9217    ConvertedArgs.reserve(NumArgs);
9218
9219  VariadicCallType CallType =
9220    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
9221  SmallVector<Expr *, 8> AllArgs;
9222  bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9223                                        Proto, 0, Args, NumArgs, AllArgs,
9224                                        CallType, AllowExplicit);
9225  ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
9226
9227  DiagnoseSentinelCalls(Constructor, Loc, AllArgs.data(), AllArgs.size());
9228
9229  // FIXME: Missing call to CheckFunctionCall or equivalent
9230
9231  return Invalid;
9232}
9233
9234static inline bool
9235CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9236                                       const FunctionDecl *FnDecl) {
9237  const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9238  if (isa<NamespaceDecl>(DC)) {
9239    return SemaRef.Diag(FnDecl->getLocation(),
9240                        diag::err_operator_new_delete_declared_in_namespace)
9241      << FnDecl->getDeclName();
9242  }
9243
9244  if (isa<TranslationUnitDecl>(DC) &&
9245      FnDecl->getStorageClass() == SC_Static) {
9246    return SemaRef.Diag(FnDecl->getLocation(),
9247                        diag::err_operator_new_delete_declared_static)
9248      << FnDecl->getDeclName();
9249  }
9250
9251  return false;
9252}
9253
9254static inline bool
9255CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9256                            CanQualType ExpectedResultType,
9257                            CanQualType ExpectedFirstParamType,
9258                            unsigned DependentParamTypeDiag,
9259                            unsigned InvalidParamTypeDiag) {
9260  QualType ResultType =
9261    FnDecl->getType()->getAs<FunctionType>()->getResultType();
9262
9263  // Check that the result type is not dependent.
9264  if (ResultType->isDependentType())
9265    return SemaRef.Diag(FnDecl->getLocation(),
9266                        diag::err_operator_new_delete_dependent_result_type)
9267    << FnDecl->getDeclName() << ExpectedResultType;
9268
9269  // Check that the result type is what we expect.
9270  if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9271    return SemaRef.Diag(FnDecl->getLocation(),
9272                        diag::err_operator_new_delete_invalid_result_type)
9273    << FnDecl->getDeclName() << ExpectedResultType;
9274
9275  // A function template must have at least 2 parameters.
9276  if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9277    return SemaRef.Diag(FnDecl->getLocation(),
9278                      diag::err_operator_new_delete_template_too_few_parameters)
9279        << FnDecl->getDeclName();
9280
9281  // The function decl must have at least 1 parameter.
9282  if (FnDecl->getNumParams() == 0)
9283    return SemaRef.Diag(FnDecl->getLocation(),
9284                        diag::err_operator_new_delete_too_few_parameters)
9285      << FnDecl->getDeclName();
9286
9287  // Check the the first parameter type is not dependent.
9288  QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9289  if (FirstParamType->isDependentType())
9290    return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9291      << FnDecl->getDeclName() << ExpectedFirstParamType;
9292
9293  // Check that the first parameter type is what we expect.
9294  if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9295      ExpectedFirstParamType)
9296    return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9297    << FnDecl->getDeclName() << ExpectedFirstParamType;
9298
9299  return false;
9300}
9301
9302static bool
9303CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9304  // C++ [basic.stc.dynamic.allocation]p1:
9305  //   A program is ill-formed if an allocation function is declared in a
9306  //   namespace scope other than global scope or declared static in global
9307  //   scope.
9308  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9309    return true;
9310
9311  CanQualType SizeTy =
9312    SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9313
9314  // C++ [basic.stc.dynamic.allocation]p1:
9315  //  The return type shall be void*. The first parameter shall have type
9316  //  std::size_t.
9317  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9318                                  SizeTy,
9319                                  diag::err_operator_new_dependent_param_type,
9320                                  diag::err_operator_new_param_type))
9321    return true;
9322
9323  // C++ [basic.stc.dynamic.allocation]p1:
9324  //  The first parameter shall not have an associated default argument.
9325  if (FnDecl->getParamDecl(0)->hasDefaultArg())
9326    return SemaRef.Diag(FnDecl->getLocation(),
9327                        diag::err_operator_new_default_arg)
9328      << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9329
9330  return false;
9331}
9332
9333static bool
9334CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9335  // C++ [basic.stc.dynamic.deallocation]p1:
9336  //   A program is ill-formed if deallocation functions are declared in a
9337  //   namespace scope other than global scope or declared static in global
9338  //   scope.
9339  if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9340    return true;
9341
9342  // C++ [basic.stc.dynamic.deallocation]p2:
9343  //   Each deallocation function shall return void and its first parameter
9344  //   shall be void*.
9345  if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9346                                  SemaRef.Context.VoidPtrTy,
9347                                 diag::err_operator_delete_dependent_param_type,
9348                                 diag::err_operator_delete_param_type))
9349    return true;
9350
9351  return false;
9352}
9353
9354/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9355/// of this overloaded operator is well-formed. If so, returns false;
9356/// otherwise, emits appropriate diagnostics and returns true.
9357bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9358  assert(FnDecl && FnDecl->isOverloadedOperator() &&
9359         "Expected an overloaded operator declaration");
9360
9361  OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9362
9363  // C++ [over.oper]p5:
9364  //   The allocation and deallocation functions, operator new,
9365  //   operator new[], operator delete and operator delete[], are
9366  //   described completely in 3.7.3. The attributes and restrictions
9367  //   found in the rest of this subclause do not apply to them unless
9368  //   explicitly stated in 3.7.3.
9369  if (Op == OO_Delete || Op == OO_Array_Delete)
9370    return CheckOperatorDeleteDeclaration(*this, FnDecl);
9371
9372  if (Op == OO_New || Op == OO_Array_New)
9373    return CheckOperatorNewDeclaration(*this, FnDecl);
9374
9375  // C++ [over.oper]p6:
9376  //   An operator function shall either be a non-static member
9377  //   function or be a non-member function and have at least one
9378  //   parameter whose type is a class, a reference to a class, an
9379  //   enumeration, or a reference to an enumeration.
9380  if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9381    if (MethodDecl->isStatic())
9382      return Diag(FnDecl->getLocation(),
9383                  diag::err_operator_overload_static) << FnDecl->getDeclName();
9384  } else {
9385    bool ClassOrEnumParam = false;
9386    for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9387                                   ParamEnd = FnDecl->param_end();
9388         Param != ParamEnd; ++Param) {
9389      QualType ParamType = (*Param)->getType().getNonReferenceType();
9390      if (ParamType->isDependentType() || ParamType->isRecordType() ||
9391          ParamType->isEnumeralType()) {
9392        ClassOrEnumParam = true;
9393        break;
9394      }
9395    }
9396
9397    if (!ClassOrEnumParam)
9398      return Diag(FnDecl->getLocation(),
9399                  diag::err_operator_overload_needs_class_or_enum)
9400        << FnDecl->getDeclName();
9401  }
9402
9403  // C++ [over.oper]p8:
9404  //   An operator function cannot have default arguments (8.3.6),
9405  //   except where explicitly stated below.
9406  //
9407  // Only the function-call operator allows default arguments
9408  // (C++ [over.call]p1).
9409  if (Op != OO_Call) {
9410    for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9411         Param != FnDecl->param_end(); ++Param) {
9412      if ((*Param)->hasDefaultArg())
9413        return Diag((*Param)->getLocation(),
9414                    diag::err_operator_overload_default_arg)
9415          << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9416    }
9417  }
9418
9419  static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9420    { false, false, false }
9421#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9422    , { Unary, Binary, MemberOnly }
9423#include "clang/Basic/OperatorKinds.def"
9424  };
9425
9426  bool CanBeUnaryOperator = OperatorUses[Op][0];
9427  bool CanBeBinaryOperator = OperatorUses[Op][1];
9428  bool MustBeMemberOperator = OperatorUses[Op][2];
9429
9430  // C++ [over.oper]p8:
9431  //   [...] Operator functions cannot have more or fewer parameters
9432  //   than the number required for the corresponding operator, as
9433  //   described in the rest of this subclause.
9434  unsigned NumParams = FnDecl->getNumParams()
9435                     + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9436  if (Op != OO_Call &&
9437      ((NumParams == 1 && !CanBeUnaryOperator) ||
9438       (NumParams == 2 && !CanBeBinaryOperator) ||
9439       (NumParams < 1) || (NumParams > 2))) {
9440    // We have the wrong number of parameters.
9441    unsigned ErrorKind;
9442    if (CanBeUnaryOperator && CanBeBinaryOperator) {
9443      ErrorKind = 2;  // 2 -> unary or binary.
9444    } else if (CanBeUnaryOperator) {
9445      ErrorKind = 0;  // 0 -> unary
9446    } else {
9447      assert(CanBeBinaryOperator &&
9448             "All non-call overloaded operators are unary or binary!");
9449      ErrorKind = 1;  // 1 -> binary
9450    }
9451
9452    return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9453      << FnDecl->getDeclName() << NumParams << ErrorKind;
9454  }
9455
9456  // Overloaded operators other than operator() cannot be variadic.
9457  if (Op != OO_Call &&
9458      FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9459    return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9460      << FnDecl->getDeclName();
9461  }
9462
9463  // Some operators must be non-static member functions.
9464  if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9465    return Diag(FnDecl->getLocation(),
9466                diag::err_operator_overload_must_be_member)
9467      << FnDecl->getDeclName();
9468  }
9469
9470  // C++ [over.inc]p1:
9471  //   The user-defined function called operator++ implements the
9472  //   prefix and postfix ++ operator. If this function is a member
9473  //   function with no parameters, or a non-member function with one
9474  //   parameter of class or enumeration type, it defines the prefix
9475  //   increment operator ++ for objects of that type. If the function
9476  //   is a member function with one parameter (which shall be of type
9477  //   int) or a non-member function with two parameters (the second
9478  //   of which shall be of type int), it defines the postfix
9479  //   increment operator ++ for objects of that type.
9480  if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9481    ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9482    bool ParamIsInt = false;
9483    if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9484      ParamIsInt = BT->getKind() == BuiltinType::Int;
9485
9486    if (!ParamIsInt)
9487      return Diag(LastParam->getLocation(),
9488                  diag::err_operator_overload_post_incdec_must_be_int)
9489        << LastParam->getType() << (Op == OO_MinusMinus);
9490  }
9491
9492  return false;
9493}
9494
9495/// CheckLiteralOperatorDeclaration - Check whether the declaration
9496/// of this literal operator function is well-formed. If so, returns
9497/// false; otherwise, emits appropriate diagnostics and returns true.
9498bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9499  if (isa<CXXMethodDecl>(FnDecl)) {
9500    Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9501      << FnDecl->getDeclName();
9502    return true;
9503  }
9504
9505  if (FnDecl->isExternC()) {
9506    Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
9507    return true;
9508  }
9509
9510  bool Valid = false;
9511
9512  // This might be the definition of a literal operator template.
9513  FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
9514  // This might be a specialization of a literal operator template.
9515  if (!TpDecl)
9516    TpDecl = FnDecl->getPrimaryTemplate();
9517
9518  // template <char...> type operator "" name() is the only valid template
9519  // signature, and the only valid signature with no parameters.
9520  if (TpDecl) {
9521    if (FnDecl->param_size() == 0) {
9522      // Must have only one template parameter
9523      TemplateParameterList *Params = TpDecl->getTemplateParameters();
9524      if (Params->size() == 1) {
9525        NonTypeTemplateParmDecl *PmDecl =
9526          cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9527
9528        // The template parameter must be a char parameter pack.
9529        if (PmDecl && PmDecl->isTemplateParameterPack() &&
9530            Context.hasSameType(PmDecl->getType(), Context.CharTy))
9531          Valid = true;
9532      }
9533    }
9534  } else if (FnDecl->param_size()) {
9535    // Check the first parameter
9536    FunctionDecl::param_iterator Param = FnDecl->param_begin();
9537
9538    QualType T = (*Param)->getType().getUnqualifiedType();
9539
9540    // unsigned long long int, long double, and any character type are allowed
9541    // as the only parameters.
9542    if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9543        Context.hasSameType(T, Context.LongDoubleTy) ||
9544        Context.hasSameType(T, Context.CharTy) ||
9545        Context.hasSameType(T, Context.WCharTy) ||
9546        Context.hasSameType(T, Context.Char16Ty) ||
9547        Context.hasSameType(T, Context.Char32Ty)) {
9548      if (++Param == FnDecl->param_end())
9549        Valid = true;
9550      goto FinishedParams;
9551    }
9552
9553    // Otherwise it must be a pointer to const; let's strip those qualifiers.
9554    const PointerType *PT = T->getAs<PointerType>();
9555    if (!PT)
9556      goto FinishedParams;
9557    T = PT->getPointeeType();
9558    if (!T.isConstQualified() || T.isVolatileQualified())
9559      goto FinishedParams;
9560    T = T.getUnqualifiedType();
9561
9562    // Move on to the second parameter;
9563    ++Param;
9564
9565    // If there is no second parameter, the first must be a const char *
9566    if (Param == FnDecl->param_end()) {
9567      if (Context.hasSameType(T, Context.CharTy))
9568        Valid = true;
9569      goto FinishedParams;
9570    }
9571
9572    // const char *, const wchar_t*, const char16_t*, and const char32_t*
9573    // are allowed as the first parameter to a two-parameter function
9574    if (!(Context.hasSameType(T, Context.CharTy) ||
9575          Context.hasSameType(T, Context.WCharTy) ||
9576          Context.hasSameType(T, Context.Char16Ty) ||
9577          Context.hasSameType(T, Context.Char32Ty)))
9578      goto FinishedParams;
9579
9580    // The second and final parameter must be an std::size_t
9581    T = (*Param)->getType().getUnqualifiedType();
9582    if (Context.hasSameType(T, Context.getSizeType()) &&
9583        ++Param == FnDecl->param_end())
9584      Valid = true;
9585  }
9586
9587  // FIXME: This diagnostic is absolutely terrible.
9588FinishedParams:
9589  if (!Valid) {
9590    Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9591      << FnDecl->getDeclName();
9592    return true;
9593  }
9594
9595  // A parameter-declaration-clause containing a default argument is not
9596  // equivalent to any of the permitted forms.
9597  for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9598                                    ParamEnd = FnDecl->param_end();
9599       Param != ParamEnd; ++Param) {
9600    if ((*Param)->hasDefaultArg()) {
9601      Diag((*Param)->getDefaultArgRange().getBegin(),
9602           diag::err_literal_operator_default_argument)
9603        << (*Param)->getDefaultArgRange();
9604      break;
9605    }
9606  }
9607
9608  StringRef LiteralName
9609    = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9610  if (LiteralName[0] != '_') {
9611    // C++11 [usrlit.suffix]p1:
9612    //   Literal suffix identifiers that do not start with an underscore
9613    //   are reserved for future standardization.
9614    Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9615  }
9616
9617  return false;
9618}
9619
9620/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9621/// linkage specification, including the language and (if present)
9622/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9623/// the location of the language string literal, which is provided
9624/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9625/// the '{' brace. Otherwise, this linkage specification does not
9626/// have any braces.
9627Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9628                                           SourceLocation LangLoc,
9629                                           StringRef Lang,
9630                                           SourceLocation LBraceLoc) {
9631  LinkageSpecDecl::LanguageIDs Language;
9632  if (Lang == "\"C\"")
9633    Language = LinkageSpecDecl::lang_c;
9634  else if (Lang == "\"C++\"")
9635    Language = LinkageSpecDecl::lang_cxx;
9636  else {
9637    Diag(LangLoc, diag::err_bad_language);
9638    return 0;
9639  }
9640
9641  // FIXME: Add all the various semantics of linkage specifications
9642
9643  LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9644                                               ExternLoc, LangLoc, Language);
9645  CurContext->addDecl(D);
9646  PushDeclContext(S, D);
9647  return D;
9648}
9649
9650/// ActOnFinishLinkageSpecification - Complete the definition of
9651/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9652/// valid, it's the position of the closing '}' brace in a linkage
9653/// specification that uses braces.
9654Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9655                                            Decl *LinkageSpec,
9656                                            SourceLocation RBraceLoc) {
9657  if (LinkageSpec) {
9658    if (RBraceLoc.isValid()) {
9659      LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9660      LSDecl->setRBraceLoc(RBraceLoc);
9661    }
9662    PopDeclContext();
9663  }
9664  return LinkageSpec;
9665}
9666
9667/// \brief Perform semantic analysis for the variable declaration that
9668/// occurs within a C++ catch clause, returning the newly-created
9669/// variable.
9670VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9671                                         TypeSourceInfo *TInfo,
9672                                         SourceLocation StartLoc,
9673                                         SourceLocation Loc,
9674                                         IdentifierInfo *Name) {
9675  bool Invalid = false;
9676  QualType ExDeclType = TInfo->getType();
9677
9678  // Arrays and functions decay.
9679  if (ExDeclType->isArrayType())
9680    ExDeclType = Context.getArrayDecayedType(ExDeclType);
9681  else if (ExDeclType->isFunctionType())
9682    ExDeclType = Context.getPointerType(ExDeclType);
9683
9684  // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9685  // The exception-declaration shall not denote a pointer or reference to an
9686  // incomplete type, other than [cv] void*.
9687  // N2844 forbids rvalue references.
9688  if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9689    Diag(Loc, diag::err_catch_rvalue_ref);
9690    Invalid = true;
9691  }
9692
9693  QualType BaseType = ExDeclType;
9694  int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9695  unsigned DK = diag::err_catch_incomplete;
9696  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9697    BaseType = Ptr->getPointeeType();
9698    Mode = 1;
9699    DK = diag::err_catch_incomplete_ptr;
9700  } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9701    // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9702    BaseType = Ref->getPointeeType();
9703    Mode = 2;
9704    DK = diag::err_catch_incomplete_ref;
9705  }
9706  if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9707      !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
9708    Invalid = true;
9709
9710  if (!Invalid && !ExDeclType->isDependentType() &&
9711      RequireNonAbstractType(Loc, ExDeclType,
9712                             diag::err_abstract_type_in_decl,
9713                             AbstractVariableType))
9714    Invalid = true;
9715
9716  // Only the non-fragile NeXT runtime currently supports C++ catches
9717  // of ObjC types, and no runtime supports catching ObjC types by value.
9718  if (!Invalid && getLangOpts().ObjC1) {
9719    QualType T = ExDeclType;
9720    if (const ReferenceType *RT = T->getAs<ReferenceType>())
9721      T = RT->getPointeeType();
9722
9723    if (T->isObjCObjectType()) {
9724      Diag(Loc, diag::err_objc_object_catch);
9725      Invalid = true;
9726    } else if (T->isObjCObjectPointerType()) {
9727      if (!getLangOpts().ObjCNonFragileABI)
9728        Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9729    }
9730  }
9731
9732  VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9733                                    ExDeclType, TInfo, SC_None, SC_None);
9734  ExDecl->setExceptionVariable(true);
9735
9736  // In ARC, infer 'retaining' for variables of retainable type.
9737  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9738    Invalid = true;
9739
9740  if (!Invalid && !ExDeclType->isDependentType()) {
9741    if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9742      // C++ [except.handle]p16:
9743      //   The object declared in an exception-declaration or, if the
9744      //   exception-declaration does not specify a name, a temporary (12.2) is
9745      //   copy-initialized (8.5) from the exception object. [...]
9746      //   The object is destroyed when the handler exits, after the destruction
9747      //   of any automatic objects initialized within the handler.
9748      //
9749      // We just pretend to initialize the object with itself, then make sure
9750      // it can be destroyed later.
9751      QualType initType = ExDeclType;
9752
9753      InitializedEntity entity =
9754        InitializedEntity::InitializeVariable(ExDecl);
9755      InitializationKind initKind =
9756        InitializationKind::CreateCopy(Loc, SourceLocation());
9757
9758      Expr *opaqueValue =
9759        new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9760      InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9761      ExprResult result = sequence.Perform(*this, entity, initKind,
9762                                           MultiExprArg(&opaqueValue, 1));
9763      if (result.isInvalid())
9764        Invalid = true;
9765      else {
9766        // If the constructor used was non-trivial, set this as the
9767        // "initializer".
9768        CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9769        if (!construct->getConstructor()->isTrivial()) {
9770          Expr *init = MaybeCreateExprWithCleanups(construct);
9771          ExDecl->setInit(init);
9772        }
9773
9774        // And make sure it's destructable.
9775        FinalizeVarWithDestructor(ExDecl, recordType);
9776      }
9777    }
9778  }
9779
9780  if (Invalid)
9781    ExDecl->setInvalidDecl();
9782
9783  return ExDecl;
9784}
9785
9786/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9787/// handler.
9788Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9789  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9790  bool Invalid = D.isInvalidType();
9791
9792  // Check for unexpanded parameter packs.
9793  if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9794                                               UPPC_ExceptionType)) {
9795    TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9796                                             D.getIdentifierLoc());
9797    Invalid = true;
9798  }
9799
9800  IdentifierInfo *II = D.getIdentifier();
9801  if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9802                                             LookupOrdinaryName,
9803                                             ForRedeclaration)) {
9804    // The scope should be freshly made just for us. There is just no way
9805    // it contains any previous declaration.
9806    assert(!S->isDeclScope(PrevDecl));
9807    if (PrevDecl->isTemplateParameter()) {
9808      // Maybe we will complain about the shadowed template parameter.
9809      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9810      PrevDecl = 0;
9811    }
9812  }
9813
9814  if (D.getCXXScopeSpec().isSet() && !Invalid) {
9815    Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9816      << D.getCXXScopeSpec().getRange();
9817    Invalid = true;
9818  }
9819
9820  VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9821                                              D.getLocStart(),
9822                                              D.getIdentifierLoc(),
9823                                              D.getIdentifier());
9824  if (Invalid)
9825    ExDecl->setInvalidDecl();
9826
9827  // Add the exception declaration into this scope.
9828  if (II)
9829    PushOnScopeChains(ExDecl, S);
9830  else
9831    CurContext->addDecl(ExDecl);
9832
9833  ProcessDeclAttributes(S, ExDecl, D);
9834  return ExDecl;
9835}
9836
9837Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9838                                         Expr *AssertExpr,
9839                                         Expr *AssertMessageExpr_,
9840                                         SourceLocation RParenLoc) {
9841  StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
9842
9843  if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9844    // In a static_assert-declaration, the constant-expression shall be a
9845    // constant expression that can be contextually converted to bool.
9846    ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9847    if (Converted.isInvalid())
9848      return 0;
9849
9850    llvm::APSInt Cond;
9851    if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9852          PDiag(diag::err_static_assert_expression_is_not_constant),
9853          /*AllowFold=*/false).isInvalid())
9854      return 0;
9855
9856    if (!Cond) {
9857      llvm::SmallString<256> MsgBuffer;
9858      llvm::raw_svector_ostream Msg(MsgBuffer);
9859      AssertMessage->printPretty(Msg, Context, 0, getPrintingPolicy());
9860      Diag(StaticAssertLoc, diag::err_static_assert_failed)
9861        << Msg.str() << AssertExpr->getSourceRange();
9862    }
9863  }
9864
9865  if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9866    return 0;
9867
9868  Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9869                                        AssertExpr, AssertMessage, RParenLoc);
9870
9871  CurContext->addDecl(Decl);
9872  return Decl;
9873}
9874
9875/// \brief Perform semantic analysis of the given friend type declaration.
9876///
9877/// \returns A friend declaration that.
9878FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9879                                      SourceLocation FriendLoc,
9880                                      TypeSourceInfo *TSInfo) {
9881  assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9882
9883  QualType T = TSInfo->getType();
9884  SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9885
9886  // C++03 [class.friend]p2:
9887  //   An elaborated-type-specifier shall be used in a friend declaration
9888  //   for a class.*
9889  //
9890  //   * The class-key of the elaborated-type-specifier is required.
9891  if (!ActiveTemplateInstantiations.empty()) {
9892    // Do not complain about the form of friend template types during
9893    // template instantiation; we will already have complained when the
9894    // template was declared.
9895  } else if (!T->isElaboratedTypeSpecifier()) {
9896    // If we evaluated the type to a record type, suggest putting
9897    // a tag in front.
9898    if (const RecordType *RT = T->getAs<RecordType>()) {
9899      RecordDecl *RD = RT->getDecl();
9900
9901      std::string InsertionText = std::string(" ") + RD->getKindName();
9902
9903      Diag(TypeRange.getBegin(),
9904           getLangOpts().CPlusPlus0x ?
9905             diag::warn_cxx98_compat_unelaborated_friend_type :
9906             diag::ext_unelaborated_friend_type)
9907        << (unsigned) RD->getTagKind()
9908        << T
9909        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9910                                      InsertionText);
9911    } else {
9912      Diag(FriendLoc,
9913           getLangOpts().CPlusPlus0x ?
9914             diag::warn_cxx98_compat_nonclass_type_friend :
9915             diag::ext_nonclass_type_friend)
9916        << T
9917        << SourceRange(FriendLoc, TypeRange.getEnd());
9918    }
9919  } else if (T->getAs<EnumType>()) {
9920    Diag(FriendLoc,
9921         getLangOpts().CPlusPlus0x ?
9922           diag::warn_cxx98_compat_enum_friend :
9923           diag::ext_enum_friend)
9924      << T
9925      << SourceRange(FriendLoc, TypeRange.getEnd());
9926  }
9927
9928  // C++0x [class.friend]p3:
9929  //   If the type specifier in a friend declaration designates a (possibly
9930  //   cv-qualified) class type, that class is declared as a friend; otherwise,
9931  //   the friend declaration is ignored.
9932
9933  // FIXME: C++0x has some syntactic restrictions on friend type declarations
9934  // in [class.friend]p3 that we do not implement.
9935
9936  return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
9937}
9938
9939/// Handle a friend tag declaration where the scope specifier was
9940/// templated.
9941Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9942                                    unsigned TagSpec, SourceLocation TagLoc,
9943                                    CXXScopeSpec &SS,
9944                                    IdentifierInfo *Name, SourceLocation NameLoc,
9945                                    AttributeList *Attr,
9946                                    MultiTemplateParamsArg TempParamLists) {
9947  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9948
9949  bool isExplicitSpecialization = false;
9950  bool Invalid = false;
9951
9952  if (TemplateParameterList *TemplateParams
9953        = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9954                                                  TempParamLists.get(),
9955                                                  TempParamLists.size(),
9956                                                  /*friend*/ true,
9957                                                  isExplicitSpecialization,
9958                                                  Invalid)) {
9959    if (TemplateParams->size() > 0) {
9960      // This is a declaration of a class template.
9961      if (Invalid)
9962        return 0;
9963
9964      return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9965                                SS, Name, NameLoc, Attr,
9966                                TemplateParams, AS_public,
9967                                /*ModulePrivateLoc=*/SourceLocation(),
9968                                TempParamLists.size() - 1,
9969                   (TemplateParameterList**) TempParamLists.release()).take();
9970    } else {
9971      // The "template<>" header is extraneous.
9972      Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9973        << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9974      isExplicitSpecialization = true;
9975    }
9976  }
9977
9978  if (Invalid) return 0;
9979
9980  bool isAllExplicitSpecializations = true;
9981  for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9982    if (TempParamLists.get()[I]->size()) {
9983      isAllExplicitSpecializations = false;
9984      break;
9985    }
9986  }
9987
9988  // FIXME: don't ignore attributes.
9989
9990  // If it's explicit specializations all the way down, just forget
9991  // about the template header and build an appropriate non-templated
9992  // friend.  TODO: for source fidelity, remember the headers.
9993  if (isAllExplicitSpecializations) {
9994    if (SS.isEmpty()) {
9995      bool Owned = false;
9996      bool IsDependent = false;
9997      return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
9998                      Attr, AS_public,
9999                      /*ModulePrivateLoc=*/SourceLocation(),
10000                      MultiTemplateParamsArg(), Owned, IsDependent,
10001                      /*ScopedEnumKWLoc=*/SourceLocation(),
10002                      /*ScopedEnumUsesClassTag=*/false,
10003                      /*UnderlyingType=*/TypeResult());
10004    }
10005
10006    NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10007    ElaboratedTypeKeyword Keyword
10008      = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10009    QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
10010                                   *Name, NameLoc);
10011    if (T.isNull())
10012      return 0;
10013
10014    TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10015    if (isa<DependentNameType>(T)) {
10016      DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10017      TL.setElaboratedKeywordLoc(TagLoc);
10018      TL.setQualifierLoc(QualifierLoc);
10019      TL.setNameLoc(NameLoc);
10020    } else {
10021      ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
10022      TL.setElaboratedKeywordLoc(TagLoc);
10023      TL.setQualifierLoc(QualifierLoc);
10024      cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10025    }
10026
10027    FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10028                                            TSI, FriendLoc);
10029    Friend->setAccess(AS_public);
10030    CurContext->addDecl(Friend);
10031    return Friend;
10032  }
10033
10034  assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10035
10036
10037
10038  // Handle the case of a templated-scope friend class.  e.g.
10039  //   template <class T> class A<T>::B;
10040  // FIXME: we don't support these right now.
10041  ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10042  QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10043  TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10044  DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
10045  TL.setElaboratedKeywordLoc(TagLoc);
10046  TL.setQualifierLoc(SS.getWithLocInContext(Context));
10047  TL.setNameLoc(NameLoc);
10048
10049  FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10050                                          TSI, FriendLoc);
10051  Friend->setAccess(AS_public);
10052  Friend->setUnsupportedFriend(true);
10053  CurContext->addDecl(Friend);
10054  return Friend;
10055}
10056
10057
10058/// Handle a friend type declaration.  This works in tandem with
10059/// ActOnTag.
10060///
10061/// Notes on friend class templates:
10062///
10063/// We generally treat friend class declarations as if they were
10064/// declaring a class.  So, for example, the elaborated type specifier
10065/// in a friend declaration is required to obey the restrictions of a
10066/// class-head (i.e. no typedefs in the scope chain), template
10067/// parameters are required to match up with simple template-ids, &c.
10068/// However, unlike when declaring a template specialization, it's
10069/// okay to refer to a template specialization without an empty
10070/// template parameter declaration, e.g.
10071///   friend class A<T>::B<unsigned>;
10072/// We permit this as a special case; if there are any template
10073/// parameters present at all, require proper matching, i.e.
10074///   template <> template <class T> friend class A<int>::B;
10075Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
10076                                MultiTemplateParamsArg TempParams) {
10077  SourceLocation Loc = DS.getLocStart();
10078
10079  assert(DS.isFriendSpecified());
10080  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10081
10082  // Try to convert the decl specifier to a type.  This works for
10083  // friend templates because ActOnTag never produces a ClassTemplateDecl
10084  // for a TUK_Friend.
10085  Declarator TheDeclarator(DS, Declarator::MemberContext);
10086  TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10087  QualType T = TSI->getType();
10088  if (TheDeclarator.isInvalidType())
10089    return 0;
10090
10091  if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10092    return 0;
10093
10094  // This is definitely an error in C++98.  It's probably meant to
10095  // be forbidden in C++0x, too, but the specification is just
10096  // poorly written.
10097  //
10098  // The problem is with declarations like the following:
10099  //   template <T> friend A<T>::foo;
10100  // where deciding whether a class C is a friend or not now hinges
10101  // on whether there exists an instantiation of A that causes
10102  // 'foo' to equal C.  There are restrictions on class-heads
10103  // (which we declare (by fiat) elaborated friend declarations to
10104  // be) that makes this tractable.
10105  //
10106  // FIXME: handle "template <> friend class A<T>;", which
10107  // is possibly well-formed?  Who even knows?
10108  if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
10109    Diag(Loc, diag::err_tagless_friend_type_template)
10110      << DS.getSourceRange();
10111    return 0;
10112  }
10113
10114  // C++98 [class.friend]p1: A friend of a class is a function
10115  //   or class that is not a member of the class . . .
10116  // This is fixed in DR77, which just barely didn't make the C++03
10117  // deadline.  It's also a very silly restriction that seriously
10118  // affects inner classes and which nobody else seems to implement;
10119  // thus we never diagnose it, not even in -pedantic.
10120  //
10121  // But note that we could warn about it: it's always useless to
10122  // friend one of your own members (it's not, however, worthless to
10123  // friend a member of an arbitrary specialization of your template).
10124
10125  Decl *D;
10126  if (unsigned NumTempParamLists = TempParams.size())
10127    D = FriendTemplateDecl::Create(Context, CurContext, Loc,
10128                                   NumTempParamLists,
10129                                   TempParams.release(),
10130                                   TSI,
10131                                   DS.getFriendSpecLoc());
10132  else
10133    D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
10134
10135  if (!D)
10136    return 0;
10137
10138  D->setAccess(AS_public);
10139  CurContext->addDecl(D);
10140
10141  return D;
10142}
10143
10144Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
10145                                    MultiTemplateParamsArg TemplateParams) {
10146  const DeclSpec &DS = D.getDeclSpec();
10147
10148  assert(DS.isFriendSpecified());
10149  assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10150
10151  SourceLocation Loc = D.getIdentifierLoc();
10152  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10153
10154  // C++ [class.friend]p1
10155  //   A friend of a class is a function or class....
10156  // Note that this sees through typedefs, which is intended.
10157  // It *doesn't* see through dependent types, which is correct
10158  // according to [temp.arg.type]p3:
10159  //   If a declaration acquires a function type through a
10160  //   type dependent on a template-parameter and this causes
10161  //   a declaration that does not use the syntactic form of a
10162  //   function declarator to have a function type, the program
10163  //   is ill-formed.
10164  if (!TInfo->getType()->isFunctionType()) {
10165    Diag(Loc, diag::err_unexpected_friend);
10166
10167    // It might be worthwhile to try to recover by creating an
10168    // appropriate declaration.
10169    return 0;
10170  }
10171
10172  // C++ [namespace.memdef]p3
10173  //  - If a friend declaration in a non-local class first declares a
10174  //    class or function, the friend class or function is a member
10175  //    of the innermost enclosing namespace.
10176  //  - The name of the friend is not found by simple name lookup
10177  //    until a matching declaration is provided in that namespace
10178  //    scope (either before or after the class declaration granting
10179  //    friendship).
10180  //  - If a friend function is called, its name may be found by the
10181  //    name lookup that considers functions from namespaces and
10182  //    classes associated with the types of the function arguments.
10183  //  - When looking for a prior declaration of a class or a function
10184  //    declared as a friend, scopes outside the innermost enclosing
10185  //    namespace scope are not considered.
10186
10187  CXXScopeSpec &SS = D.getCXXScopeSpec();
10188  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10189  DeclarationName Name = NameInfo.getName();
10190  assert(Name);
10191
10192  // Check for unexpanded parameter packs.
10193  if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10194      DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10195      DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10196    return 0;
10197
10198  // The context we found the declaration in, or in which we should
10199  // create the declaration.
10200  DeclContext *DC;
10201  Scope *DCScope = S;
10202  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10203                        ForRedeclaration);
10204
10205  // FIXME: there are different rules in local classes
10206
10207  // There are four cases here.
10208  //   - There's no scope specifier, in which case we just go to the
10209  //     appropriate scope and look for a function or function template
10210  //     there as appropriate.
10211  // Recover from invalid scope qualifiers as if they just weren't there.
10212  if (SS.isInvalid() || !SS.isSet()) {
10213    // C++0x [namespace.memdef]p3:
10214    //   If the name in a friend declaration is neither qualified nor
10215    //   a template-id and the declaration is a function or an
10216    //   elaborated-type-specifier, the lookup to determine whether
10217    //   the entity has been previously declared shall not consider
10218    //   any scopes outside the innermost enclosing namespace.
10219    // C++0x [class.friend]p11:
10220    //   If a friend declaration appears in a local class and the name
10221    //   specified is an unqualified name, a prior declaration is
10222    //   looked up without considering scopes that are outside the
10223    //   innermost enclosing non-class scope. For a friend function
10224    //   declaration, if there is no prior declaration, the program is
10225    //   ill-formed.
10226    bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
10227    bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
10228
10229    // Find the appropriate context according to the above.
10230    DC = CurContext;
10231    while (true) {
10232      // Skip class contexts.  If someone can cite chapter and verse
10233      // for this behavior, that would be nice --- it's what GCC and
10234      // EDG do, and it seems like a reasonable intent, but the spec
10235      // really only says that checks for unqualified existing
10236      // declarations should stop at the nearest enclosing namespace,
10237      // not that they should only consider the nearest enclosing
10238      // namespace.
10239      while (DC->isRecord() || DC->isTransparentContext())
10240        DC = DC->getParent();
10241
10242      LookupQualifiedName(Previous, DC);
10243
10244      // TODO: decide what we think about using declarations.
10245      if (isLocal || !Previous.empty())
10246        break;
10247
10248      if (isTemplateId) {
10249        if (isa<TranslationUnitDecl>(DC)) break;
10250      } else {
10251        if (DC->isFileContext()) break;
10252      }
10253      DC = DC->getParent();
10254    }
10255
10256    // C++ [class.friend]p1: A friend of a class is a function or
10257    //   class that is not a member of the class . . .
10258    // C++11 changes this for both friend types and functions.
10259    // Most C++ 98 compilers do seem to give an error here, so
10260    // we do, too.
10261    if (!Previous.empty() && DC->Equals(CurContext))
10262      Diag(DS.getFriendSpecLoc(),
10263           getLangOpts().CPlusPlus0x ?
10264             diag::warn_cxx98_compat_friend_is_member :
10265             diag::err_friend_is_member);
10266
10267    DCScope = getScopeForDeclContext(S, DC);
10268
10269    // C++ [class.friend]p6:
10270    //   A function can be defined in a friend declaration of a class if and
10271    //   only if the class is a non-local class (9.8), the function name is
10272    //   unqualified, and the function has namespace scope.
10273    if (isLocal && D.isFunctionDefinition()) {
10274      Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10275    }
10276
10277  //   - There's a non-dependent scope specifier, in which case we
10278  //     compute it and do a previous lookup there for a function
10279  //     or function template.
10280  } else if (!SS.getScopeRep()->isDependent()) {
10281    DC = computeDeclContext(SS);
10282    if (!DC) return 0;
10283
10284    if (RequireCompleteDeclContext(SS, DC)) return 0;
10285
10286    LookupQualifiedName(Previous, DC);
10287
10288    // Ignore things found implicitly in the wrong scope.
10289    // TODO: better diagnostics for this case.  Suggesting the right
10290    // qualified scope would be nice...
10291    LookupResult::Filter F = Previous.makeFilter();
10292    while (F.hasNext()) {
10293      NamedDecl *D = F.next();
10294      if (!DC->InEnclosingNamespaceSetOf(
10295              D->getDeclContext()->getRedeclContext()))
10296        F.erase();
10297    }
10298    F.done();
10299
10300    if (Previous.empty()) {
10301      D.setInvalidType();
10302      Diag(Loc, diag::err_qualified_friend_not_found)
10303          << Name << TInfo->getType();
10304      return 0;
10305    }
10306
10307    // C++ [class.friend]p1: A friend of a class is a function or
10308    //   class that is not a member of the class . . .
10309    if (DC->Equals(CurContext))
10310      Diag(DS.getFriendSpecLoc(),
10311           getLangOpts().CPlusPlus0x ?
10312             diag::warn_cxx98_compat_friend_is_member :
10313             diag::err_friend_is_member);
10314
10315    if (D.isFunctionDefinition()) {
10316      // C++ [class.friend]p6:
10317      //   A function can be defined in a friend declaration of a class if and
10318      //   only if the class is a non-local class (9.8), the function name is
10319      //   unqualified, and the function has namespace scope.
10320      SemaDiagnosticBuilder DB
10321        = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10322
10323      DB << SS.getScopeRep();
10324      if (DC->isFileContext())
10325        DB << FixItHint::CreateRemoval(SS.getRange());
10326      SS.clear();
10327    }
10328
10329  //   - There's a scope specifier that does not match any template
10330  //     parameter lists, in which case we use some arbitrary context,
10331  //     create a method or method template, and wait for instantiation.
10332  //   - There's a scope specifier that does match some template
10333  //     parameter lists, which we don't handle right now.
10334  } else {
10335    if (D.isFunctionDefinition()) {
10336      // C++ [class.friend]p6:
10337      //   A function can be defined in a friend declaration of a class if and
10338      //   only if the class is a non-local class (9.8), the function name is
10339      //   unqualified, and the function has namespace scope.
10340      Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10341        << SS.getScopeRep();
10342    }
10343
10344    DC = CurContext;
10345    assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10346  }
10347
10348  if (!DC->isRecord()) {
10349    // This implies that it has to be an operator or function.
10350    if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10351        D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10352        D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10353      Diag(Loc, diag::err_introducing_special_friend) <<
10354        (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10355         D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10356      return 0;
10357    }
10358  }
10359
10360  // FIXME: This is an egregious hack to cope with cases where the scope stack
10361  // does not contain the declaration context, i.e., in an out-of-line
10362  // definition of a class.
10363  Scope FakeDCScope(S, Scope::DeclScope, Diags);
10364  if (!DCScope) {
10365    FakeDCScope.setEntity(DC);
10366    DCScope = &FakeDCScope;
10367  }
10368
10369  bool AddToScope = true;
10370  NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10371                                          move(TemplateParams), AddToScope);
10372  if (!ND) return 0;
10373
10374  assert(ND->getDeclContext() == DC);
10375  assert(ND->getLexicalDeclContext() == CurContext);
10376
10377  // Add the function declaration to the appropriate lookup tables,
10378  // adjusting the redeclarations list as necessary.  We don't
10379  // want to do this yet if the friending class is dependent.
10380  //
10381  // Also update the scope-based lookup if the target context's
10382  // lookup context is in lexical scope.
10383  if (!CurContext->isDependentContext()) {
10384    DC = DC->getRedeclContext();
10385    DC->makeDeclVisibleInContext(ND);
10386    if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10387      PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10388  }
10389
10390  FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10391                                       D.getIdentifierLoc(), ND,
10392                                       DS.getFriendSpecLoc());
10393  FrD->setAccess(AS_public);
10394  CurContext->addDecl(FrD);
10395
10396  if (ND->isInvalidDecl())
10397    FrD->setInvalidDecl();
10398  else {
10399    FunctionDecl *FD;
10400    if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10401      FD = FTD->getTemplatedDecl();
10402    else
10403      FD = cast<FunctionDecl>(ND);
10404
10405    // Mark templated-scope function declarations as unsupported.
10406    if (FD->getNumTemplateParameterLists())
10407      FrD->setUnsupportedFriend(true);
10408  }
10409
10410  return ND;
10411}
10412
10413void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10414  AdjustDeclIfTemplate(Dcl);
10415
10416  FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10417  if (!Fn) {
10418    Diag(DelLoc, diag::err_deleted_non_function);
10419    return;
10420  }
10421  if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
10422    Diag(DelLoc, diag::err_deleted_decl_not_first);
10423    Diag(Prev->getLocation(), diag::note_previous_declaration);
10424    // If the declaration wasn't the first, we delete the function anyway for
10425    // recovery.
10426  }
10427  Fn->setDeletedAsWritten();
10428
10429  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10430  if (!MD)
10431    return;
10432
10433  // A deleted special member function is trivial if the corresponding
10434  // implicitly-declared function would have been.
10435  switch (getSpecialMember(MD)) {
10436  case CXXInvalid:
10437    break;
10438  case CXXDefaultConstructor:
10439    MD->setTrivial(MD->getParent()->hasTrivialDefaultConstructor());
10440    break;
10441  case CXXCopyConstructor:
10442    MD->setTrivial(MD->getParent()->hasTrivialCopyConstructor());
10443    break;
10444  case CXXMoveConstructor:
10445    MD->setTrivial(MD->getParent()->hasTrivialMoveConstructor());
10446    break;
10447  case CXXCopyAssignment:
10448    MD->setTrivial(MD->getParent()->hasTrivialCopyAssignment());
10449    break;
10450  case CXXMoveAssignment:
10451    MD->setTrivial(MD->getParent()->hasTrivialMoveAssignment());
10452    break;
10453  case CXXDestructor:
10454    MD->setTrivial(MD->getParent()->hasTrivialDestructor());
10455    break;
10456  }
10457}
10458
10459void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10460  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10461
10462  if (MD) {
10463    if (MD->getParent()->isDependentType()) {
10464      MD->setDefaulted();
10465      MD->setExplicitlyDefaulted();
10466      return;
10467    }
10468
10469    CXXSpecialMember Member = getSpecialMember(MD);
10470    if (Member == CXXInvalid) {
10471      Diag(DefaultLoc, diag::err_default_special_members);
10472      return;
10473    }
10474
10475    MD->setDefaulted();
10476    MD->setExplicitlyDefaulted();
10477
10478    // If this definition appears within the record, do the checking when
10479    // the record is complete.
10480    const FunctionDecl *Primary = MD;
10481    if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10482      // Find the uninstantiated declaration that actually had the '= default'
10483      // on it.
10484      MD->getTemplateInstantiationPattern()->isDefined(Primary);
10485
10486    if (Primary == Primary->getCanonicalDecl())
10487      return;
10488
10489    switch (Member) {
10490    case CXXDefaultConstructor: {
10491      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10492      CheckExplicitlyDefaultedDefaultConstructor(CD);
10493      if (!CD->isInvalidDecl())
10494        DefineImplicitDefaultConstructor(DefaultLoc, CD);
10495      break;
10496    }
10497
10498    case CXXCopyConstructor: {
10499      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10500      CheckExplicitlyDefaultedCopyConstructor(CD);
10501      if (!CD->isInvalidDecl())
10502        DefineImplicitCopyConstructor(DefaultLoc, CD);
10503      break;
10504    }
10505
10506    case CXXCopyAssignment: {
10507      CheckExplicitlyDefaultedCopyAssignment(MD);
10508      if (!MD->isInvalidDecl())
10509        DefineImplicitCopyAssignment(DefaultLoc, MD);
10510      break;
10511    }
10512
10513    case CXXDestructor: {
10514      CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10515      CheckExplicitlyDefaultedDestructor(DD);
10516      if (!DD->isInvalidDecl())
10517        DefineImplicitDestructor(DefaultLoc, DD);
10518      break;
10519    }
10520
10521    case CXXMoveConstructor: {
10522      CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10523      CheckExplicitlyDefaultedMoveConstructor(CD);
10524      if (!CD->isInvalidDecl())
10525        DefineImplicitMoveConstructor(DefaultLoc, CD);
10526      break;
10527    }
10528
10529    case CXXMoveAssignment: {
10530      CheckExplicitlyDefaultedMoveAssignment(MD);
10531      if (!MD->isInvalidDecl())
10532        DefineImplicitMoveAssignment(DefaultLoc, MD);
10533      break;
10534    }
10535
10536    case CXXInvalid:
10537      llvm_unreachable("Invalid special member.");
10538    }
10539  } else {
10540    Diag(DefaultLoc, diag::err_default_special_members);
10541  }
10542}
10543
10544static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10545  for (Stmt::child_range CI = S->children(); CI; ++CI) {
10546    Stmt *SubStmt = *CI;
10547    if (!SubStmt)
10548      continue;
10549    if (isa<ReturnStmt>(SubStmt))
10550      Self.Diag(SubStmt->getLocStart(),
10551           diag::err_return_in_constructor_handler);
10552    if (!isa<Expr>(SubStmt))
10553      SearchForReturnInStmt(Self, SubStmt);
10554  }
10555}
10556
10557void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10558  for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10559    CXXCatchStmt *Handler = TryBlock->getHandler(I);
10560    SearchForReturnInStmt(*this, Handler);
10561  }
10562}
10563
10564bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10565                                             const CXXMethodDecl *Old) {
10566  QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10567  QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10568
10569  if (Context.hasSameType(NewTy, OldTy) ||
10570      NewTy->isDependentType() || OldTy->isDependentType())
10571    return false;
10572
10573  // Check if the return types are covariant
10574  QualType NewClassTy, OldClassTy;
10575
10576  /// Both types must be pointers or references to classes.
10577  if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10578    if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10579      NewClassTy = NewPT->getPointeeType();
10580      OldClassTy = OldPT->getPointeeType();
10581    }
10582  } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10583    if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10584      if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10585        NewClassTy = NewRT->getPointeeType();
10586        OldClassTy = OldRT->getPointeeType();
10587      }
10588    }
10589  }
10590
10591  // The return types aren't either both pointers or references to a class type.
10592  if (NewClassTy.isNull()) {
10593    Diag(New->getLocation(),
10594         diag::err_different_return_type_for_overriding_virtual_function)
10595      << New->getDeclName() << NewTy << OldTy;
10596    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10597
10598    return true;
10599  }
10600
10601  // C++ [class.virtual]p6:
10602  //   If the return type of D::f differs from the return type of B::f, the
10603  //   class type in the return type of D::f shall be complete at the point of
10604  //   declaration of D::f or shall be the class type D.
10605  if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10606    if (!RT->isBeingDefined() &&
10607        RequireCompleteType(New->getLocation(), NewClassTy,
10608                            PDiag(diag::err_covariant_return_incomplete)
10609                              << New->getDeclName()))
10610    return true;
10611  }
10612
10613  if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10614    // Check if the new class derives from the old class.
10615    if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10616      Diag(New->getLocation(),
10617           diag::err_covariant_return_not_derived)
10618      << New->getDeclName() << NewTy << OldTy;
10619      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10620      return true;
10621    }
10622
10623    // Check if we the conversion from derived to base is valid.
10624    if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10625                    diag::err_covariant_return_inaccessible_base,
10626                    diag::err_covariant_return_ambiguous_derived_to_base_conv,
10627                    // FIXME: Should this point to the return type?
10628                    New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10629      // FIXME: this note won't trigger for delayed access control
10630      // diagnostics, and it's impossible to get an undelayed error
10631      // here from access control during the original parse because
10632      // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10633      Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10634      return true;
10635    }
10636  }
10637
10638  // The qualifiers of the return types must be the same.
10639  if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10640    Diag(New->getLocation(),
10641         diag::err_covariant_return_type_different_qualifications)
10642    << New->getDeclName() << NewTy << OldTy;
10643    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10644    return true;
10645  };
10646
10647
10648  // The new class type must have the same or less qualifiers as the old type.
10649  if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10650    Diag(New->getLocation(),
10651         diag::err_covariant_return_type_class_type_more_qualified)
10652    << New->getDeclName() << NewTy << OldTy;
10653    Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10654    return true;
10655  };
10656
10657  return false;
10658}
10659
10660/// \brief Mark the given method pure.
10661///
10662/// \param Method the method to be marked pure.
10663///
10664/// \param InitRange the source range that covers the "0" initializer.
10665bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10666  SourceLocation EndLoc = InitRange.getEnd();
10667  if (EndLoc.isValid())
10668    Method->setRangeEnd(EndLoc);
10669
10670  if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10671    Method->setPure();
10672    return false;
10673  }
10674
10675  if (!Method->isInvalidDecl())
10676    Diag(Method->getLocation(), diag::err_non_virtual_pure)
10677      << Method->getDeclName() << InitRange;
10678  return true;
10679}
10680
10681/// \brief Determine whether the given declaration is a static data member.
10682static bool isStaticDataMember(Decl *D) {
10683  VarDecl *Var = dyn_cast_or_null<VarDecl>(D);
10684  if (!Var)
10685    return false;
10686
10687  return Var->isStaticDataMember();
10688}
10689/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10690/// an initializer for the out-of-line declaration 'Dcl'.  The scope
10691/// is a fresh scope pushed for just this purpose.
10692///
10693/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10694/// static data member of class X, names should be looked up in the scope of
10695/// class X.
10696void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10697  // If there is no declaration, there was an error parsing it.
10698  if (D == 0 || D->isInvalidDecl()) return;
10699
10700  // We should only get called for declarations with scope specifiers, like:
10701  //   int foo::bar;
10702  assert(D->isOutOfLine());
10703  EnterDeclaratorContext(S, D->getDeclContext());
10704
10705  // If we are parsing the initializer for a static data member, push a
10706  // new expression evaluation context that is associated with this static
10707  // data member.
10708  if (isStaticDataMember(D))
10709    PushExpressionEvaluationContext(PotentiallyEvaluated, D);
10710}
10711
10712/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10713/// initializer for the out-of-line declaration 'D'.
10714void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10715  // If there is no declaration, there was an error parsing it.
10716  if (D == 0 || D->isInvalidDecl()) return;
10717
10718  if (isStaticDataMember(D))
10719    PopExpressionEvaluationContext();
10720
10721  assert(D->isOutOfLine());
10722  ExitDeclaratorContext(S);
10723}
10724
10725/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10726/// C++ if/switch/while/for statement.
10727/// e.g: "if (int x = f()) {...}"
10728DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10729  // C++ 6.4p2:
10730  // The declarator shall not specify a function or an array.
10731  // The type-specifier-seq shall not contain typedef and shall not declare a
10732  // new class or enumeration.
10733  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10734         "Parser allowed 'typedef' as storage class of condition decl.");
10735
10736  Decl *Dcl = ActOnDeclarator(S, D);
10737  if (!Dcl)
10738    return true;
10739
10740  if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10741    Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10742      << D.getSourceRange();
10743    return true;
10744  }
10745
10746  return Dcl;
10747}
10748
10749void Sema::LoadExternalVTableUses() {
10750  if (!ExternalSource)
10751    return;
10752
10753  SmallVector<ExternalVTableUse, 4> VTables;
10754  ExternalSource->ReadUsedVTables(VTables);
10755  SmallVector<VTableUse, 4> NewUses;
10756  for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10757    llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10758      = VTablesUsed.find(VTables[I].Record);
10759    // Even if a definition wasn't required before, it may be required now.
10760    if (Pos != VTablesUsed.end()) {
10761      if (!Pos->second && VTables[I].DefinitionRequired)
10762        Pos->second = true;
10763      continue;
10764    }
10765
10766    VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10767    NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10768  }
10769
10770  VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10771}
10772
10773void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10774                          bool DefinitionRequired) {
10775  // Ignore any vtable uses in unevaluated operands or for classes that do
10776  // not have a vtable.
10777  if (!Class->isDynamicClass() || Class->isDependentContext() ||
10778      CurContext->isDependentContext() ||
10779      ExprEvalContexts.back().Context == Unevaluated)
10780    return;
10781
10782  // Try to insert this class into the map.
10783  LoadExternalVTableUses();
10784  Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10785  std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10786    Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10787  if (!Pos.second) {
10788    // If we already had an entry, check to see if we are promoting this vtable
10789    // to required a definition. If so, we need to reappend to the VTableUses
10790    // list, since we may have already processed the first entry.
10791    if (DefinitionRequired && !Pos.first->second) {
10792      Pos.first->second = true;
10793    } else {
10794      // Otherwise, we can early exit.
10795      return;
10796    }
10797  }
10798
10799  // Local classes need to have their virtual members marked
10800  // immediately. For all other classes, we mark their virtual members
10801  // at the end of the translation unit.
10802  if (Class->isLocalClass())
10803    MarkVirtualMembersReferenced(Loc, Class);
10804  else
10805    VTableUses.push_back(std::make_pair(Class, Loc));
10806}
10807
10808bool Sema::DefineUsedVTables() {
10809  LoadExternalVTableUses();
10810  if (VTableUses.empty())
10811    return false;
10812
10813  // Note: The VTableUses vector could grow as a result of marking
10814  // the members of a class as "used", so we check the size each
10815  // time through the loop and prefer indices (with are stable) to
10816  // iterators (which are not).
10817  bool DefinedAnything = false;
10818  for (unsigned I = 0; I != VTableUses.size(); ++I) {
10819    CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10820    if (!Class)
10821      continue;
10822
10823    SourceLocation Loc = VTableUses[I].second;
10824
10825    // If this class has a key function, but that key function is
10826    // defined in another translation unit, we don't need to emit the
10827    // vtable even though we're using it.
10828    const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10829    if (KeyFunction && !KeyFunction->hasBody()) {
10830      switch (KeyFunction->getTemplateSpecializationKind()) {
10831      case TSK_Undeclared:
10832      case TSK_ExplicitSpecialization:
10833      case TSK_ExplicitInstantiationDeclaration:
10834        // The key function is in another translation unit.
10835        continue;
10836
10837      case TSK_ExplicitInstantiationDefinition:
10838      case TSK_ImplicitInstantiation:
10839        // We will be instantiating the key function.
10840        break;
10841      }
10842    } else if (!KeyFunction) {
10843      // If we have a class with no key function that is the subject
10844      // of an explicit instantiation declaration, suppress the
10845      // vtable; it will live with the explicit instantiation
10846      // definition.
10847      bool IsExplicitInstantiationDeclaration
10848        = Class->getTemplateSpecializationKind()
10849                                      == TSK_ExplicitInstantiationDeclaration;
10850      for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10851                                 REnd = Class->redecls_end();
10852           R != REnd; ++R) {
10853        TemplateSpecializationKind TSK
10854          = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10855        if (TSK == TSK_ExplicitInstantiationDeclaration)
10856          IsExplicitInstantiationDeclaration = true;
10857        else if (TSK == TSK_ExplicitInstantiationDefinition) {
10858          IsExplicitInstantiationDeclaration = false;
10859          break;
10860        }
10861      }
10862
10863      if (IsExplicitInstantiationDeclaration)
10864        continue;
10865    }
10866
10867    // Mark all of the virtual members of this class as referenced, so
10868    // that we can build a vtable. Then, tell the AST consumer that a
10869    // vtable for this class is required.
10870    DefinedAnything = true;
10871    MarkVirtualMembersReferenced(Loc, Class);
10872    CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10873    Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10874
10875    // Optionally warn if we're emitting a weak vtable.
10876    if (Class->getLinkage() == ExternalLinkage &&
10877        Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10878      const FunctionDecl *KeyFunctionDef = 0;
10879      if (!KeyFunction ||
10880          (KeyFunction->hasBody(KeyFunctionDef) &&
10881           KeyFunctionDef->isInlined()))
10882        Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10883             TSK_ExplicitInstantiationDefinition
10884             ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10885          << Class;
10886    }
10887  }
10888  VTableUses.clear();
10889
10890  return DefinedAnything;
10891}
10892
10893void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10894                                        const CXXRecordDecl *RD) {
10895  for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10896       e = RD->method_end(); i != e; ++i) {
10897    CXXMethodDecl *MD = *i;
10898
10899    // C++ [basic.def.odr]p2:
10900    //   [...] A virtual member function is used if it is not pure. [...]
10901    if (MD->isVirtual() && !MD->isPure())
10902      MarkFunctionReferenced(Loc, MD);
10903  }
10904
10905  // Only classes that have virtual bases need a VTT.
10906  if (RD->getNumVBases() == 0)
10907    return;
10908
10909  for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10910           e = RD->bases_end(); i != e; ++i) {
10911    const CXXRecordDecl *Base =
10912        cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10913    if (Base->getNumVBases() == 0)
10914      continue;
10915    MarkVirtualMembersReferenced(Loc, Base);
10916  }
10917}
10918
10919/// SetIvarInitializers - This routine builds initialization ASTs for the
10920/// Objective-C implementation whose ivars need be initialized.
10921void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10922  if (!getLangOpts().CPlusPlus)
10923    return;
10924  if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10925    SmallVector<ObjCIvarDecl*, 8> ivars;
10926    CollectIvarsToConstructOrDestruct(OID, ivars);
10927    if (ivars.empty())
10928      return;
10929    SmallVector<CXXCtorInitializer*, 32> AllToInit;
10930    for (unsigned i = 0; i < ivars.size(); i++) {
10931      FieldDecl *Field = ivars[i];
10932      if (Field->isInvalidDecl())
10933        continue;
10934
10935      CXXCtorInitializer *Member;
10936      InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10937      InitializationKind InitKind =
10938        InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10939
10940      InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10941      ExprResult MemberInit =
10942        InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10943      MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10944      // Note, MemberInit could actually come back empty if no initialization
10945      // is required (e.g., because it would call a trivial default constructor)
10946      if (!MemberInit.get() || MemberInit.isInvalid())
10947        continue;
10948
10949      Member =
10950        new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10951                                         SourceLocation(),
10952                                         MemberInit.takeAs<Expr>(),
10953                                         SourceLocation());
10954      AllToInit.push_back(Member);
10955
10956      // Be sure that the destructor is accessible and is marked as referenced.
10957      if (const RecordType *RecordTy
10958                  = Context.getBaseElementType(Field->getType())
10959                                                        ->getAs<RecordType>()) {
10960                    CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10961        if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10962          MarkFunctionReferenced(Field->getLocation(), Destructor);
10963          CheckDestructorAccess(Field->getLocation(), Destructor,
10964                            PDiag(diag::err_access_dtor_ivar)
10965                              << Context.getBaseElementType(Field->getType()));
10966        }
10967      }
10968    }
10969    ObjCImplementation->setIvarInitializers(Context,
10970                                            AllToInit.data(), AllToInit.size());
10971  }
10972}
10973
10974static
10975void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10976                           llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10977                           llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10978                           llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10979                           Sema &S) {
10980  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10981                                                   CE = Current.end();
10982  if (Ctor->isInvalidDecl())
10983    return;
10984
10985  const FunctionDecl *FNTarget = 0;
10986  CXXConstructorDecl *Target;
10987
10988  // We ignore the result here since if we don't have a body, Target will be
10989  // null below.
10990  (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10991  Target
10992= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10993
10994  CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10995                     // Avoid dereferencing a null pointer here.
10996                     *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10997
10998  if (!Current.insert(Canonical))
10999    return;
11000
11001  // We know that beyond here, we aren't chaining into a cycle.
11002  if (!Target || !Target->isDelegatingConstructor() ||
11003      Target->isInvalidDecl() || Valid.count(TCanonical)) {
11004    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11005      Valid.insert(*CI);
11006    Current.clear();
11007  // We've hit a cycle.
11008  } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11009             Current.count(TCanonical)) {
11010    // If we haven't diagnosed this cycle yet, do so now.
11011    if (!Invalid.count(TCanonical)) {
11012      S.Diag((*Ctor->init_begin())->getSourceLocation(),
11013             diag::warn_delegating_ctor_cycle)
11014        << Ctor;
11015
11016      // Don't add a note for a function delegating directo to itself.
11017      if (TCanonical != Canonical)
11018        S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11019
11020      CXXConstructorDecl *C = Target;
11021      while (C->getCanonicalDecl() != Canonical) {
11022        (void)C->getTargetConstructor()->hasBody(FNTarget);
11023        assert(FNTarget && "Ctor cycle through bodiless function");
11024
11025        C
11026       = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11027        S.Diag(C->getLocation(), diag::note_which_delegates_to);
11028      }
11029    }
11030
11031    for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11032      Invalid.insert(*CI);
11033    Current.clear();
11034  } else {
11035    DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11036  }
11037}
11038
11039
11040void Sema::CheckDelegatingCtorCycles() {
11041  llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11042
11043  llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11044                                                   CE = Current.end();
11045
11046  for (DelegatingCtorDeclsType::iterator
11047         I = DelegatingCtorDecls.begin(ExternalSource),
11048         E = DelegatingCtorDecls.end();
11049       I != E; ++I) {
11050   DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
11051  }
11052
11053  for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11054    (*CI)->setInvalidDecl();
11055}
11056
11057namespace {
11058  /// \brief AST visitor that finds references to the 'this' expression.
11059  class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
11060    Sema &S;
11061
11062  public:
11063    explicit FindCXXThisExpr(Sema &S) : S(S) { }
11064
11065    bool VisitCXXThisExpr(CXXThisExpr *E) {
11066      S.Diag(E->getLocation(), diag::err_this_static_member_func)
11067        << E->isImplicit();
11068      return false;
11069    }
11070  };
11071}
11072
11073bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
11074  TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
11075  if (!TSInfo)
11076    return false;
11077
11078  TypeLoc TL = TSInfo->getTypeLoc();
11079  FunctionProtoTypeLoc *ProtoTL = dyn_cast<FunctionProtoTypeLoc>(&TL);
11080  if (!ProtoTL)
11081    return false;
11082
11083  // C++11 [expr.prim.general]p3:
11084  //   [The expression this] shall not appear before the optional
11085  //   cv-qualifier-seq and it shall not appear within the declaration of a
11086  //   static member function (although its type and value category are defined
11087  //   within a static member function as they are within a non-static member
11088  //   function). [ Note: this is because declaration matching does not occur
11089  //  until the complete declarator is known. — end note ]
11090  const FunctionProtoType *Proto = ProtoTL->getTypePtr();
11091  FindCXXThisExpr Finder(*this);
11092
11093  // If the return type came after the cv-qualifier-seq, check it now.
11094  if (Proto->hasTrailingReturn() &&
11095      !Finder.TraverseTypeLoc(ProtoTL->getResultLoc()))
11096    return true;
11097
11098  // Check the exception specification.
11099  switch (Proto->getExceptionSpecType()) {
11100  case EST_BasicNoexcept:
11101  case EST_Delayed:
11102  case EST_DynamicNone:
11103  case EST_MSAny:
11104  case EST_None:
11105    break;
11106
11107  case EST_ComputedNoexcept:
11108    if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
11109      return true;
11110
11111  case EST_Dynamic:
11112    for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
11113                                            EEnd = Proto->exception_end();
11114         E != EEnd; ++E) {
11115      if (!Finder.TraverseType(*E))
11116        return true;
11117    }
11118    break;
11119  }
11120
11121  return checkThisInStaticMemberFunctionAttributes(Method);
11122}
11123
11124bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
11125  FindCXXThisExpr Finder(*this);
11126
11127  // Check attributes.
11128  for (Decl::attr_iterator A = Method->attr_begin(), AEnd = Method->attr_end();
11129       A != AEnd; ++A) {
11130    // FIXME: This should be emitted by tblgen.
11131    Expr *Arg = 0;
11132    ArrayRef<Expr *> Args;
11133    if (GuardedByAttr *G = dyn_cast<GuardedByAttr>(*A))
11134      Arg = G->getArg();
11135    else if (PtGuardedByAttr *G = dyn_cast<PtGuardedByAttr>(*A))
11136      Arg = G->getArg();
11137    else if (AcquiredAfterAttr *AA = dyn_cast<AcquiredAfterAttr>(*A))
11138      Args = ArrayRef<Expr *>(AA->args_begin(), AA->args_size());
11139    else if (AcquiredBeforeAttr *AB = dyn_cast<AcquiredBeforeAttr>(*A))
11140      Args = ArrayRef<Expr *>(AB->args_begin(), AB->args_size());
11141    else if (ExclusiveLockFunctionAttr *ELF
11142               = dyn_cast<ExclusiveLockFunctionAttr>(*A))
11143      Args = ArrayRef<Expr *>(ELF->args_begin(), ELF->args_size());
11144    else if (SharedLockFunctionAttr *SLF
11145               = dyn_cast<SharedLockFunctionAttr>(*A))
11146      Args = ArrayRef<Expr *>(SLF->args_begin(), SLF->args_size());
11147    else if (ExclusiveTrylockFunctionAttr *ETLF
11148               = dyn_cast<ExclusiveTrylockFunctionAttr>(*A)) {
11149      Arg = ETLF->getSuccessValue();
11150      Args = ArrayRef<Expr *>(ETLF->args_begin(), ETLF->args_size());
11151    } else if (SharedTrylockFunctionAttr *STLF
11152                 = dyn_cast<SharedTrylockFunctionAttr>(*A)) {
11153      Arg = STLF->getSuccessValue();
11154      Args = ArrayRef<Expr *>(STLF->args_begin(), STLF->args_size());
11155    } else if (UnlockFunctionAttr *UF = dyn_cast<UnlockFunctionAttr>(*A))
11156      Args = ArrayRef<Expr *>(UF->args_begin(), UF->args_size());
11157    else if (LockReturnedAttr *LR = dyn_cast<LockReturnedAttr>(*A))
11158      Arg = LR->getArg();
11159    else if (LocksExcludedAttr *LE = dyn_cast<LocksExcludedAttr>(*A))
11160      Args = ArrayRef<Expr *>(LE->args_begin(), LE->args_size());
11161    else if (ExclusiveLocksRequiredAttr *ELR
11162               = dyn_cast<ExclusiveLocksRequiredAttr>(*A))
11163      Args = ArrayRef<Expr *>(ELR->args_begin(), ELR->args_size());
11164    else if (SharedLocksRequiredAttr *SLR
11165               = dyn_cast<SharedLocksRequiredAttr>(*A))
11166      Args = ArrayRef<Expr *>(SLR->args_begin(), SLR->args_size());
11167
11168    if (Arg && !Finder.TraverseStmt(Arg))
11169      return true;
11170
11171    for (unsigned I = 0, N = Args.size(); I != N; ++I) {
11172      if (!Finder.TraverseStmt(Args[I]))
11173        return true;
11174    }
11175  }
11176
11177  return false;
11178}
11179
11180/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11181Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11182  // Implicitly declared functions (e.g. copy constructors) are
11183  // __host__ __device__
11184  if (D->isImplicit())
11185    return CFT_HostDevice;
11186
11187  if (D->hasAttr<CUDAGlobalAttr>())
11188    return CFT_Global;
11189
11190  if (D->hasAttr<CUDADeviceAttr>()) {
11191    if (D->hasAttr<CUDAHostAttr>())
11192      return CFT_HostDevice;
11193    else
11194      return CFT_Device;
11195  }
11196
11197  return CFT_Host;
11198}
11199
11200bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11201                           CUDAFunctionTarget CalleeTarget) {
11202  // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11203  // Callable from the device only."
11204  if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11205    return true;
11206
11207  // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11208  // Callable from the host only."
11209  // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11210  // Callable from the host only."
11211  if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11212      (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11213    return true;
11214
11215  if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11216    return true;
11217
11218  return false;
11219}
11220