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