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