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