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