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