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