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