1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ declarations.
12 //===----------------------------------------------------------------------===//
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"
39 using namespace clang;
41 //===----------------------------------------------------------------------===//
42 // CheckDefaultArgumentVisitor
43 //===----------------------------------------------------------------------===//
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> {
57 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58 : DefaultArg(defarg), S(s) {}
60 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
62 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
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);
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
94 if (VDecl->isLocalVarDecl())
95 return S->Diag(DRE->getSourceRange().getBegin(),
96 diag::err_param_default_argument_references_local)
97 << VDecl->getDeclName() << DefaultArg->getSourceRange();
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
108 return S->Diag(ThisE->getSourceRange().getBegin(),
109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
114 void 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)
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
125 // If this function can throw any exceptions, make a note of that.
126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
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.
135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
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;
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.");
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
163 ComputedEST = EST_None;
165 // noexcept(true) won't change anything either.
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();
177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
178 Exceptions.push_back(*E);
181 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
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.
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).
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.
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.
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
211 Sema::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();
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,
227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
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())
234 Arg = Result.takeAs<Expr>();
236 CheckImplicitConversions(Arg, EqualLoc);
237 Arg = MaybeCreateExprWithCleanups(Arg);
239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
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);
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
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.
261 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
263 if (!param || !DefaultArg)
266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
267 UnparsedDefaultArgLocs.erase(Param);
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();
277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
283 // Check that the default argument is well-formed
284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
286 Param->setInvalidDecl();
290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
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.
297 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
305 Param->setUnparsedDefaultArg();
307 UnparsedDefaultArgLocs[Param] = ArgLoc;
310 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311 /// the default argument for the parameter param failed.
312 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
318 Param->setInvalidDecl();
320 UnparsedDefaultArgLocs.erase(Param);
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.
328 void 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) {
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());
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);
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.
362 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
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).
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);
387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
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());
404 NewParam->setDefaultArg(OldParam->getInit());
405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
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:
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
418 Diag(NewParam->getLocation(), DiagDefaultParamID)
419 << NewParam->getDefaultArgRange();
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())
428 OldParam = Older->getParamDecl(p);
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());
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)
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
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.
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
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
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)
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]
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);
519 if (CheckEquivalentExceptionSpec(Old, New))
525 /// \brief Merge the exception specifications of two variable declarations.
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.
530 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
531 // Shortcut if exceptions are disabled.
532 if (!getLangOptions().CXXExceptions)
535 assert(Context.hasSameType(New->getType(), Old->getType()) &&
536 "Should only be called if types are otherwise the same.");
538 QualType NewType = New->getType();
539 QualType OldType = Old->getType();
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();
554 if (!NewType->isFunctionProtoType())
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
560 if (CheckEquivalentExceptionSpec(
561 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
562 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
563 New->setInvalidDecl();
567 /// CheckCXXDefaultArguments - Verify that the default arguments for a
568 /// function declaration are well-formed according to C++
569 /// [dcl.fct.default].
570 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
571 unsigned NumParams = FD->getNumParams();
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())
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();
598 Diag(Param->getLocation(),
599 diag::err_param_default_argument_missing);
601 LastMissingDefaultArg = p;
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);
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.
622 static 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) :
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;
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.
651 // This implements C++0x [dcl.constexpr]p3,4, as amended by N3308.
653 // \param CCK Specifies whether to produce diagnostics if the function does not
654 // satisfy the requirements.
655 bool 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");
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))
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();
691 // C++0x [dcl.constexpr]p3:
692 // The definition of a constexpr function shall satisfy the following
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);
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);
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) :
720 /*AllowIncompleteType*/ true)) {
721 if (CCK == CCK_NoteNonConstexprInstantiation)
722 Diag(NewFD->getLocation(),
723 diag::note_constexpr_tmpl_non_literal_return) << RT;
727 // - each of its parameter types shall be a literal type;
728 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
735 /// Check the given declaration statement is legal within a constexpr function
736 /// body. C++0x [dcl.constexpr]p3,p4.
738 /// \return true if the body is OK, false if we have diagnosed a problem.
739 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
741 // C++0x [dcl.constexpr]p3 and p4:
742 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
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:
749 case Decl::UsingShadow:
750 case Decl::UsingDirective:
751 case Decl::UnresolvedUsingTypename:
752 // - static_assert-declarations
753 // - using-declarations,
754 // - using-directives,
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);
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);
786 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
787 << isa<CXXConstructorDecl>(Dcl);
791 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
792 << isa<CXXConstructorDecl>(Dcl);
800 /// Check that the given field is initialized within a constexpr constructor.
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.
808 static void CheckConstexprCtorInitializer(Sema &SemaRef,
809 const FunctionDecl *Dcl,
811 llvm::SmallSet<Decl*, 16> &Inits,
813 if (Field->isUnnamedBitfield())
816 if (!Inits.count(Field)) {
818 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
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();
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);
833 /// Check the body for the given constexpr function declaration only contains
834 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
836 /// \return true if the body is OK, false if we have diagnosed a problem.
837 bool 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
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);
853 // - its function-body shall be [...] a compound-statement that contains only
854 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
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,
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)))
874 case Stmt::ReturnStmtClass:
875 // - and exactly one return statement;
876 if (isa<CXXConstructorDecl>(Dcl))
879 ReturnStmts.push_back((*BodyIt)->getLocStart());
881 // - every constructor call and implicit conversion used in initializing
882 // the return value shall be one of those allowed in a constant
884 // Deal with this as part of a general check that the function can produce
885 // a constant expression (for [dcl.constexpr]p5).
892 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
893 << isa<CXXConstructorDecl>(Dcl);
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
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);
908 } else if (!Constructor->isDependentContext() &&
909 !Constructor->isDelegatingConstructor()) {
910 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
912 // Skip detailed checking if we have enough initializers, and we would
913 // allow at most one initializer per member.
914 bool AnyAnonStructUnionMembers = false;
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;
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();
932 if (FieldDecl *FD = (*I)->getMember())
934 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
935 Inits.insert(ID->chain_begin(), ID->chain_end());
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);
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).
961 if (ReturnStmts.empty()) {
962 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
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);
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.
980 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
981 const CXXScopeSpec *SS) {
982 assert(getLangOptions().CPlusPlus && "No class names in C!");
984 CXXRecordDecl *CurDecl;
985 if (SS && SS->isSet() && !SS->isInvalid()) {
986 DeclContext *DC = computeDeclContext(*SS, true);
987 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
989 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
991 if (CurDecl && CurDecl->getIdentifier())
992 return &II == CurDecl->getIdentifier();
997 /// \brief Check the validity of a C++ base class specifier.
999 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1000 /// and returns NULL otherwise.
1002 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1003 SourceRange SpecifierRange,
1004 bool Virtual, AccessSpecifier Access,
1005 TypeSourceInfo *TInfo,
1006 SourceLocation EllipsisLoc) {
1007 QualType BaseType = TInfo->getType();
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)
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();
1024 if (BaseType->isDependentType())
1025 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1026 Class->getTagKind() == TTK_Class,
1027 Access, TInfo, EllipsisLoc);
1029 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
1031 // Base specifiers must be record types.
1032 if (!BaseType->isRecordType()) {
1033 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
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;
1044 // C++ [class.derived]p2:
1045 // The class-name in a base-specifier shall not be an incompletely
1047 if (RequireCompleteType(BaseLoc, BaseType,
1048 PDiag(diag::err_incomplete_base_class)
1049 << SpecifierRange)) {
1050 Class->setInvalidDecl();
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");
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();
1073 if (BaseDecl->isInvalidDecl())
1074 Class->setInvalidDecl();
1076 // Create the base specifier.
1077 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
1078 Class->getTagKind() == TTK_Class,
1079 Access, TInfo, EllipsisLoc);
1082 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1083 /// one entry in the base class list of a class specifier, for
1085 /// class foo : public bar, virtual private baz {
1086 /// 'public bar' and 'virtual private baz' are each base-specifiers.
1088 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
1089 bool Virtual, AccessSpecifier Access,
1090 ParsedType basetype, SourceLocation BaseLoc,
1091 SourceLocation EllipsisLoc) {
1095 AdjustDeclIfTemplate(classdecl);
1096 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
1100 TypeSourceInfo *TInfo = 0;
1101 GetTypeFromParser(basetype, &TInfo);
1103 if (EllipsisLoc.isInvalid() &&
1104 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
1108 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
1109 Virtual, Access, TInfo,
1116 /// \brief Performs the actual work of attaching the given base class
1117 /// specifiers to a C++ class.
1118 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1119 unsigned NumBases) {
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
1127 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
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();
1145 // Delete the duplicate base class specifier; we're going to
1146 // overwrite its pointer later.
1147 Context.Deallocate(Bases[idx]);
1151 // Okay, add this new base class.
1152 KnownBaseTypes[NewBaseType] = Bases[idx];
1153 Bases[NumGoodBases++] = Bases[idx];
1157 // Attach the remaining base class specifiers to the derived class.
1158 Class->setBases(Bases, NumGoodBases);
1160 // Delete the remaining (good) base class specifiers, since their
1161 // data has been copied into the CXXRecordDecl.
1162 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
1163 Context.Deallocate(Bases[idx]);
1168 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
1169 /// class, after checking whether there are any duplicate base
1171 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
1172 unsigned NumBases) {
1173 if (!ClassDecl || !Bases || !NumBases)
1176 AdjustDeclIfTemplate(ClassDecl);
1177 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
1178 (CXXBaseSpecifier**)(Bases), NumBases);
1181 static CXXRecordDecl *GetClassForType(QualType T) {
1182 if (const RecordType *RT = T->getAs<RecordType>())
1183 return cast<CXXRecordDecl>(RT->getDecl());
1184 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1185 return ICT->getDecl();
1190 /// \brief Determine whether the type \p Derived is a C++ class that is
1191 /// derived from the type \p Base.
1192 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1193 if (!getLangOptions().CPlusPlus)
1196 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1200 CXXRecordDecl *BaseRD = GetClassForType(Base);
1204 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1205 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
1208 /// \brief Determine whether the type \p Derived is a C++ class that is
1209 /// derived from the type \p Base.
1210 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1211 if (!getLangOptions().CPlusPlus)
1214 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1218 CXXRecordDecl *BaseRD = GetClassForType(Base);
1222 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1225 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
1226 CXXCastPath &BasePathArray) {
1227 assert(BasePathArray.empty() && "Base path array must be empty!");
1228 assert(Paths.isRecordingPaths() && "Must record paths!");
1230 const CXXBasePath &Path = Paths.front();
1232 // We first go backward and check if we have a virtual base.
1233 // FIXME: It would be better if CXXBasePath had the base specifier for
1234 // the nearest virtual base.
1236 for (unsigned I = Path.size(); I != 0; --I) {
1237 if (Path[I - 1].Base->isVirtual()) {
1243 // Now add all bases.
1244 for (unsigned I = Start, E = Path.size(); I != E; ++I)
1245 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
1248 /// \brief Determine whether the given base path includes a virtual
1250 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1251 for (CXXCastPath::const_iterator B = BasePath.begin(),
1252 BEnd = BasePath.end();
1254 if ((*B)->isVirtual())
1260 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1261 /// conversion (where Derived and Base are class types) is
1262 /// well-formed, meaning that the conversion is unambiguous (and
1263 /// that all of the base classes are accessible). Returns true
1264 /// and emits a diagnostic if the code is ill-formed, returns false
1265 /// otherwise. Loc is the location where this routine should point to
1266 /// if there is an error, and Range is the source range to highlight
1267 /// if there is an error.
1269 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1270 unsigned InaccessibleBaseID,
1271 unsigned AmbigiousBaseConvID,
1272 SourceLocation Loc, SourceRange Range,
1273 DeclarationName Name,
1274 CXXCastPath *BasePath) {
1275 // First, determine whether the path from Derived to Base is
1276 // ambiguous. This is slightly more expensive than checking whether
1277 // the Derived to Base conversion exists, because here we need to
1278 // explore multiple paths to determine if there is an ambiguity.
1279 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1280 /*DetectVirtual=*/false);
1281 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1282 assert(DerivationOkay &&
1283 "Can only be used with a derived-to-base conversion");
1284 (void)DerivationOkay;
1286 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
1287 if (InaccessibleBaseID) {
1288 // Check that the base class can be accessed.
1289 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1290 InaccessibleBaseID)) {
1291 case AR_inaccessible:
1300 // Build a base path if necessary.
1302 BuildBasePathArray(Paths, *BasePath);
1306 // We know that the derived-to-base conversion is ambiguous, and
1307 // we're going to produce a diagnostic. Perform the derived-to-base
1308 // search just one more time to compute all of the possible paths so
1309 // that we can print them out. This is more expensive than any of
1310 // the previous derived-to-base checks we've done, but at this point
1311 // performance isn't as much of an issue.
1313 Paths.setRecordingPaths(true);
1314 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1315 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1318 // Build up a textual representation of the ambiguous paths, e.g.,
1319 // D -> B -> A, that will be used to illustrate the ambiguous
1320 // conversions in the diagnostic. We only print one of the paths
1321 // to each base class subobject.
1322 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1324 Diag(Loc, AmbigiousBaseConvID)
1325 << Derived << Base << PathDisplayStr << Range << Name;
1330 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
1331 SourceLocation Loc, SourceRange Range,
1332 CXXCastPath *BasePath,
1333 bool IgnoreAccess) {
1334 return CheckDerivedToBaseConversion(Derived, Base,
1336 : diag::err_upcast_to_inaccessible_base,
1337 diag::err_ambiguous_derived_to_base_conv,
1338 Loc, Range, DeclarationName(),
1343 /// @brief Builds a string representing ambiguous paths from a
1344 /// specific derived class to different subobjects of the same base
1347 /// This function builds a string that can be used in error messages
1348 /// to show the different paths that one can take through the
1349 /// inheritance hierarchy to go from the derived class to different
1350 /// subobjects of a base class. The result looks something like this:
1352 /// struct D -> struct B -> struct A
1353 /// struct D -> struct C -> struct A
1355 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1356 std::string PathDisplayStr;
1357 std::set<unsigned> DisplayedPaths;
1358 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1359 Path != Paths.end(); ++Path) {
1360 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1361 // We haven't displayed a path to this particular base
1362 // class subobject yet.
1363 PathDisplayStr += "\n ";
1364 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1365 for (CXXBasePath::const_iterator Element = Path->begin();
1366 Element != Path->end(); ++Element)
1367 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1371 return PathDisplayStr;
1374 //===----------------------------------------------------------------------===//
1375 // C++ class member Handling
1376 //===----------------------------------------------------------------------===//
1378 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1379 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1380 SourceLocation ASLoc,
1381 SourceLocation ColonLoc,
1382 AttributeList *Attrs) {
1383 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1384 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1386 CurContext->addHiddenDecl(ASDecl);
1387 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
1390 /// CheckOverrideControl - Check C++0x override control semantics.
1391 void Sema::CheckOverrideControl(const Decl *D) {
1392 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
1393 if (!MD || !MD->isVirtual())
1396 if (MD->isDependentContext())
1399 // C++0x [class.virtual]p3:
1400 // If a virtual function is marked with the virt-specifier override and does
1401 // not override a member function of a base class,
1402 // the program is ill-formed.
1403 bool HasOverriddenMethods =
1404 MD->begin_overridden_methods() != MD->end_overridden_methods();
1405 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1406 Diag(MD->getLocation(),
1407 diag::err_function_marked_override_not_overriding)
1408 << MD->getDeclName();
1413 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1414 /// function overrides a virtual member function marked 'final', according to
1415 /// C++0x [class.virtual]p3.
1416 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1417 const CXXMethodDecl *Old) {
1418 if (!Old->hasAttr<FinalAttr>())
1421 Diag(New->getLocation(), diag::err_final_function_overridden)
1422 << New->getDeclName();
1423 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1427 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1428 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1429 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1430 /// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1431 /// present but parsing it has been deferred.
1433 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1434 MultiTemplateParamsArg TemplateParameterLists,
1435 Expr *BW, const VirtSpecifiers &VS,
1436 bool HasDeferredInit) {
1437 const DeclSpec &DS = D.getDeclSpec();
1438 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1439 DeclarationName Name = NameInfo.getName();
1440 SourceLocation Loc = NameInfo.getLoc();
1442 // For anonymous bitfields, the location should point to the type.
1443 if (Loc.isInvalid())
1444 Loc = D.getSourceRange().getBegin();
1446 Expr *BitWidth = static_cast<Expr*>(BW);
1448 assert(isa<CXXRecordDecl>(CurContext));
1449 assert(!DS.isFriendSpecified());
1451 bool isFunc = D.isDeclarationOfFunction();
1453 // C++ 9.2p6: A member shall not be declared to have automatic storage
1454 // duration (auto, register) or with the extern storage-class-specifier.
1455 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1456 // data members and cannot be applied to names declared const or static,
1457 // and cannot be applied to reference members.
1458 switch (DS.getStorageClassSpec()) {
1459 case DeclSpec::SCS_unspecified:
1460 case DeclSpec::SCS_typedef:
1461 case DeclSpec::SCS_static:
1464 case DeclSpec::SCS_mutable:
1466 if (DS.getStorageClassSpecLoc().isValid())
1467 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1469 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1471 // FIXME: It would be nicer if the keyword was ignored only for this
1472 // declarator. Otherwise we could get follow-up errors.
1473 D.getMutableDeclSpec().ClearStorageClassSpecs();
1477 if (DS.getStorageClassSpecLoc().isValid())
1478 Diag(DS.getStorageClassSpecLoc(),
1479 diag::err_storageclass_invalid_for_member);
1481 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1482 D.getMutableDeclSpec().ClearStorageClassSpecs();
1485 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1486 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1491 CXXScopeSpec &SS = D.getCXXScopeSpec();
1493 // Data members must have identifiers for names.
1494 if (Name.getNameKind() != DeclarationName::Identifier) {
1495 Diag(Loc, diag::err_bad_variable_name)
1500 IdentifierInfo *II = Name.getAsIdentifierInfo();
1502 // Member field could not be with "template" keyword.
1503 // So TemplateParameterLists should be empty in this case.
1504 if (TemplateParameterLists.size()) {
1505 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1506 if (TemplateParams->size()) {
1507 // There is no such thing as a member field template.
1508 Diag(D.getIdentifierLoc(), diag::err_template_member)
1510 << SourceRange(TemplateParams->getTemplateLoc(),
1511 TemplateParams->getRAngleLoc());
1513 // There is an extraneous 'template<>' for this member.
1514 Diag(TemplateParams->getTemplateLoc(),
1515 diag::err_template_member_noparams)
1517 << SourceRange(TemplateParams->getTemplateLoc(),
1518 TemplateParams->getRAngleLoc());
1523 if (SS.isSet() && !SS.isInvalid()) {
1524 // The user provided a superfluous scope specifier inside a class
1530 DeclContext *DC = 0;
1531 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1532 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1533 << Name << FixItHint::CreateRemoval(SS.getRange());
1535 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1536 << Name << SS.getRange();
1541 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1542 HasDeferredInit, AS);
1543 assert(Member && "HandleField never returns null");
1545 assert(!HasDeferredInit);
1547 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
1552 // Non-instance-fields can't have a bitfield.
1554 if (Member->isInvalidDecl()) {
1555 // don't emit another diagnostic.
1556 } else if (isa<VarDecl>(Member)) {
1557 // C++ 9.6p3: A bit-field shall not be a static member.
1558 // "static member 'A' cannot be a bit-field"
1559 Diag(Loc, diag::err_static_not_bitfield)
1560 << Name << BitWidth->getSourceRange();
1561 } else if (isa<TypedefDecl>(Member)) {
1562 // "typedef member 'x' cannot be a bit-field"
1563 Diag(Loc, diag::err_typedef_not_bitfield)
1564 << Name << BitWidth->getSourceRange();
1566 // A function typedef ("typedef int f(); f a;").
1567 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1568 Diag(Loc, diag::err_not_integral_type_bitfield)
1569 << Name << cast<ValueDecl>(Member)->getType()
1570 << BitWidth->getSourceRange();
1574 Member->setInvalidDecl();
1577 Member->setAccess(AS);
1579 // If we have declared a member function template, set the access of the
1580 // templated declaration as well.
1581 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1582 FunTmpl->getTemplatedDecl()->setAccess(AS);
1585 if (VS.isOverrideSpecified()) {
1586 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1587 if (!MD || !MD->isVirtual()) {
1588 Diag(Member->getLocStart(),
1589 diag::override_keyword_only_allowed_on_virtual_member_functions)
1590 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1592 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1594 if (VS.isFinalSpecified()) {
1595 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1596 if (!MD || !MD->isVirtual()) {
1597 Diag(Member->getLocStart(),
1598 diag::override_keyword_only_allowed_on_virtual_member_functions)
1599 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1601 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1604 if (VS.getLastLocation().isValid()) {
1605 // Update the end location of a method that has a virt-specifiers.
1606 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1607 MD->setRangeEnd(VS.getLastLocation());
1610 CheckOverrideControl(Member);
1612 assert((Name || isInstField) && "No identifier for non-field ?");
1615 FieldCollector->Add(cast<FieldDecl>(Member));
1619 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1620 /// in-class initializer for a non-static C++ class member, and after
1621 /// instantiating an in-class initializer in a class template. Such actions
1622 /// are deferred until the class is complete.
1624 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1626 FieldDecl *FD = cast<FieldDecl>(D);
1629 FD->setInvalidDecl();
1630 FD->removeInClassInitializer();
1634 ExprResult Init = InitExpr;
1635 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1636 // FIXME: if there is no EqualLoc, this is list-initialization.
1637 Init = PerformCopyInitialization(
1638 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1639 if (Init.isInvalid()) {
1640 FD->setInvalidDecl();
1644 CheckImplicitConversions(Init.get(), EqualLoc);
1647 // C++0x [class.base.init]p7:
1648 // The initialization of each base and member constitutes a
1650 Init = MaybeCreateExprWithCleanups(Init);
1651 if (Init.isInvalid()) {
1652 FD->setInvalidDecl();
1656 InitExpr = Init.release();
1658 FD->setInClassInitializer(InitExpr);
1661 /// \brief Find the direct and/or virtual base specifiers that
1662 /// correspond to the given base type, for use in base initialization
1663 /// within a constructor.
1664 static bool FindBaseInitializer(Sema &SemaRef,
1665 CXXRecordDecl *ClassDecl,
1667 const CXXBaseSpecifier *&DirectBaseSpec,
1668 const CXXBaseSpecifier *&VirtualBaseSpec) {
1669 // First, check for a direct base class.
1671 for (CXXRecordDecl::base_class_const_iterator Base
1672 = ClassDecl->bases_begin();
1673 Base != ClassDecl->bases_end(); ++Base) {
1674 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1675 // We found a direct base of this type. That's what we're
1677 DirectBaseSpec = &*Base;
1682 // Check for a virtual base class.
1683 // FIXME: We might be able to short-circuit this if we know in advance that
1684 // there are no virtual bases.
1685 VirtualBaseSpec = 0;
1686 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1687 // We haven't found a base yet; search the class hierarchy for a
1688 // virtual base class.
1689 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1690 /*DetectVirtual=*/false);
1691 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1693 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1694 Path != Paths.end(); ++Path) {
1695 if (Path->back().Base->isVirtual()) {
1696 VirtualBaseSpec = Path->back().Base;
1703 return DirectBaseSpec || VirtualBaseSpec;
1706 /// \brief Handle a C++ member initializer using braced-init-list syntax.
1708 Sema::ActOnMemInitializer(Decl *ConstructorD,
1711 IdentifierInfo *MemberOrBase,
1712 ParsedType TemplateTypeTy,
1713 SourceLocation IdLoc,
1715 SourceLocation EllipsisLoc) {
1716 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1717 IdLoc, MultiInitializer(InitList), EllipsisLoc);
1720 /// \brief Handle a C++ member initializer using parentheses syntax.
1722 Sema::ActOnMemInitializer(Decl *ConstructorD,
1725 IdentifierInfo *MemberOrBase,
1726 ParsedType TemplateTypeTy,
1727 SourceLocation IdLoc,
1728 SourceLocation LParenLoc,
1729 Expr **Args, unsigned NumArgs,
1730 SourceLocation RParenLoc,
1731 SourceLocation EllipsisLoc) {
1732 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1733 IdLoc, MultiInitializer(LParenLoc, Args, NumArgs,
1738 /// \brief Handle a C++ member initializer.
1740 Sema::BuildMemInitializer(Decl *ConstructorD,
1743 IdentifierInfo *MemberOrBase,
1744 ParsedType TemplateTypeTy,
1745 SourceLocation IdLoc,
1746 const MultiInitializer &Args,
1747 SourceLocation EllipsisLoc) {
1751 AdjustDeclIfTemplate(ConstructorD);
1753 CXXConstructorDecl *Constructor
1754 = dyn_cast<CXXConstructorDecl>(ConstructorD);
1756 // The user wrote a constructor initializer on a function that is
1757 // not a C++ constructor. Ignore the error for now, because we may
1758 // have more member initializers coming; we'll diagnose it just
1759 // once in ActOnMemInitializers.
1763 CXXRecordDecl *ClassDecl = Constructor->getParent();
1765 // C++ [class.base.init]p2:
1766 // Names in a mem-initializer-id are looked up in the scope of the
1767 // constructor's class and, if not found in that scope, are looked
1768 // up in the scope containing the constructor's definition.
1769 // [Note: if the constructor's class contains a member with the
1770 // same name as a direct or virtual base class of the class, a
1771 // mem-initializer-id naming the member or base class and composed
1772 // of a single identifier refers to the class member. A
1773 // mem-initializer-id for the hidden base class may be specified
1774 // using a qualified name. ]
1775 if (!SS.getScopeRep() && !TemplateTypeTy) {
1776 // Look for a member, first.
1777 FieldDecl *Member = 0;
1778 DeclContext::lookup_result Result
1779 = ClassDecl->lookup(MemberOrBase);
1780 if (Result.first != Result.second) {
1781 Member = dyn_cast<FieldDecl>(*Result.first);
1784 if (EllipsisLoc.isValid())
1785 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1786 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1788 return BuildMemberInitializer(Member, Args, IdLoc);
1791 // Handle anonymous union case.
1792 if (IndirectFieldDecl* IndirectField
1793 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1794 if (EllipsisLoc.isValid())
1795 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1796 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1798 return BuildMemberInitializer(IndirectField, Args, IdLoc);
1802 // It didn't name a member, so see if it names a class.
1804 TypeSourceInfo *TInfo = 0;
1806 if (TemplateTypeTy) {
1807 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1809 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1810 LookupParsedName(R, S, &SS);
1812 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1814 if (R.isAmbiguous()) return true;
1816 // We don't want access-control diagnostics here.
1817 R.suppressDiagnostics();
1819 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1820 bool NotUnknownSpecialization = false;
1821 DeclContext *DC = computeDeclContext(SS, false);
1822 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1823 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1825 if (!NotUnknownSpecialization) {
1826 // When the scope specifier can refer to a member of an unknown
1827 // specialization, we take it as a type name.
1828 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1829 SS.getWithLocInContext(Context),
1830 *MemberOrBase, IdLoc);
1831 if (BaseType.isNull())
1835 R.setLookupName(MemberOrBase);
1839 // If no results were found, try to correct typos.
1840 TypoCorrection Corr;
1841 if (R.empty() && BaseType.isNull() &&
1842 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
1843 ClassDecl, false, CTC_NoKeywords))) {
1844 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1845 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1846 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
1847 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1848 // We have found a non-static data member with a similar
1849 // name to what was typed; complain and initialize that
1851 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1852 << MemberOrBase << true << CorrectedQuotedStr
1853 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1854 Diag(Member->getLocation(), diag::note_previous_decl)
1855 << CorrectedQuotedStr;
1857 return BuildMemberInitializer(Member, Args, IdLoc);
1859 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
1860 const CXXBaseSpecifier *DirectBaseSpec;
1861 const CXXBaseSpecifier *VirtualBaseSpec;
1862 if (FindBaseInitializer(*this, ClassDecl,
1863 Context.getTypeDeclType(Type),
1864 DirectBaseSpec, VirtualBaseSpec)) {
1865 // We have found a direct or virtual base class with a
1866 // similar name to what was typed; complain and initialize
1868 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1869 << MemberOrBase << false << CorrectedQuotedStr
1870 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1872 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1874 Diag(BaseSpec->getSourceRange().getBegin(),
1875 diag::note_base_class_specified_here)
1876 << BaseSpec->getType()
1877 << BaseSpec->getSourceRange();
1884 if (!TyD && BaseType.isNull()) {
1885 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1886 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1891 if (BaseType.isNull()) {
1892 BaseType = Context.getTypeDeclType(TyD);
1894 NestedNameSpecifier *Qualifier =
1895 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1897 // FIXME: preserve source range information
1898 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1904 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1906 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
1909 /// Checks a member initializer expression for cases where reference (or
1910 /// pointer) members are bound to by-value parameters (or their addresses).
1911 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1913 SourceLocation IdLoc) {
1914 QualType MemberTy = Member->getType();
1916 // We only handle pointers and references currently.
1917 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1918 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1921 const bool IsPointer = MemberTy->isPointerType();
1923 if (const UnaryOperator *Op
1924 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1925 // The only case we're worried about with pointers requires taking the
1927 if (Op->getOpcode() != UO_AddrOf)
1930 Init = Op->getSubExpr();
1932 // We only handle address-of expression initializers for pointers.
1937 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1938 // Taking the address of a temporary will be diagnosed as a hard error.
1942 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1943 << Member << Init->getSourceRange();
1944 } else if (const DeclRefExpr *DRE
1945 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1946 // We only warn when referring to a non-reference parameter declaration.
1947 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
1948 if (!Parameter || Parameter->getType()->isReferenceType())
1951 S.Diag(Init->getExprLoc(),
1952 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
1953 : diag::warn_bind_ref_member_to_parameter)
1954 << Member << Parameter << Init->getSourceRange();
1956 // Other initializers are fine.
1960 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
1961 << (unsigned)IsPointer;
1964 /// Checks an initializer expression for use of uninitialized fields, such as
1965 /// containing the field that is being initialized. Returns true if there is an
1966 /// uninitialized field was used an updates the SourceLocation parameter; false
1968 static bool InitExprContainsUninitializedFields(const Stmt *S,
1969 const ValueDecl *LhsField,
1970 SourceLocation *L) {
1971 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1973 if (isa<CallExpr>(S)) {
1974 // Do not descend into function calls or constructors, as the use
1975 // of an uninitialized field may be valid. One would have to inspect
1976 // the contents of the function/ctor to determine if it is safe or not.
1977 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1978 // may be safe, depending on what the function/ctor does.
1981 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1982 const NamedDecl *RhsField = ME->getMemberDecl();
1984 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1985 // The member expression points to a static data member.
1986 assert(VD->isStaticDataMember() &&
1987 "Member points to non-static data member!");
1992 if (isa<EnumConstantDecl>(RhsField)) {
1993 // The member expression points to an enum.
1997 if (RhsField == LhsField) {
1998 // Initializing a field with itself. Throw a warning.
1999 // But wait; there are exceptions!
2000 // Exception #1: The field may not belong to this record.
2001 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
2002 const Expr *base = ME->getBase();
2003 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2004 // Even though the field matches, it does not belong to this record.
2007 // None of the exceptions triggered; return true to indicate an
2008 // uninitialized field was used.
2009 *L = ME->getMemberLoc();
2012 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
2013 // sizeof/alignof doesn't reference contents, do not warn.
2015 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2016 // address-of doesn't reference contents (the pointer may be dereferenced
2017 // in the same expression but it would be rare; and weird).
2018 if (UOE->getOpcode() == UO_AddrOf)
2021 for (Stmt::const_child_range it = S->children(); it; ++it) {
2023 // An expression such as 'member(arg ?: "")' may trigger this.
2026 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2033 Sema::BuildMemberInitializer(ValueDecl *Member,
2034 const MultiInitializer &Args,
2035 SourceLocation IdLoc) {
2036 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2037 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2038 assert((DirectMember || IndirectMember) &&
2039 "Member must be a FieldDecl or IndirectFieldDecl");
2041 if (Member->isInvalidDecl())
2044 // Diagnose value-uses of fields to initialize themselves, e.g.
2046 // where foo is not also a parameter to the constructor.
2047 // TODO: implement -Wuninitialized and fold this into that framework.
2048 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2052 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2053 Arg = DIE->getInit();
2054 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
2055 // FIXME: Return true in the case when other fields are used before being
2056 // uninitialized. For example, let this field be the i'th field. When
2057 // initializing the i'th field, throw a warning if any of the >= i'th
2058 // fields are used, as they are not yet initialized.
2059 // Right now we are only handling the case where the i'th field uses
2060 // itself in its initializer.
2061 Diag(L, diag::warn_field_is_uninit);
2065 bool HasDependentArg = Args.isTypeDependent();
2068 if (Member->getType()->isDependentType() || HasDependentArg) {
2069 // Can't check initialization for a member of dependent type or when
2070 // any of the arguments are type-dependent expressions.
2071 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
2073 DiscardCleanupsInEvaluationContext();
2075 // Initialize the member.
2076 InitializedEntity MemberEntity =
2077 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2078 : InitializedEntity::InitializeMember(IndirectMember, 0);
2079 InitializationKind Kind =
2080 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2083 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
2084 if (MemberInit.isInvalid())
2087 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
2089 // C++0x [class.base.init]p7:
2090 // The initialization of each base and member constitutes a
2092 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
2093 if (MemberInit.isInvalid())
2096 // If we are in a dependent context, template instantiation will
2097 // perform this type-checking again. Just save the arguments that we
2098 // received in a ParenListExpr.
2099 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2100 // of the information that we have about the member
2101 // initializer. However, deconstructing the ASTs is a dicey process,
2102 // and this approach is far more likely to get the corner cases right.
2103 if (CurContext->isDependentContext()) {
2104 Init = Args.CreateInitExpr(Context,
2105 Member->getType().getNonReferenceType());
2107 Init = MemberInit.get();
2108 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2113 return new (Context) CXXCtorInitializer(Context, DirectMember,
2114 IdLoc, Args.getStartLoc(),
2115 Init, Args.getEndLoc());
2117 return new (Context) CXXCtorInitializer(Context, IndirectMember,
2118 IdLoc, Args.getStartLoc(),
2119 Init, Args.getEndLoc());
2124 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
2125 const MultiInitializer &Args,
2126 SourceLocation NameLoc,
2127 CXXRecordDecl *ClassDecl) {
2128 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
2129 if (!LangOpts.CPlusPlus0x)
2130 return Diag(Loc, diag::err_delegation_0x_only)
2131 << TInfo->getTypeLoc().getLocalSourceRange();
2133 // Initialize the object.
2134 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2135 QualType(ClassDecl->getTypeForDecl(), 0));
2136 InitializationKind Kind =
2137 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2140 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
2141 if (DelegationInit.isInvalid())
2144 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
2145 CXXConstructorDecl *Constructor
2146 = ConExpr->getConstructor();
2147 assert(Constructor && "Delegating constructor with no target?");
2149 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
2151 // C++0x [class.base.init]p7:
2152 // The initialization of each base and member constitutes a
2154 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2155 if (DelegationInit.isInvalid())
2158 assert(!CurContext->isDependentContext());
2159 return new (Context) CXXCtorInitializer(Context, Loc, Args.getStartLoc(),
2161 DelegationInit.takeAs<Expr>(),
2166 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
2167 const MultiInitializer &Args,
2168 CXXRecordDecl *ClassDecl,
2169 SourceLocation EllipsisLoc) {
2170 bool HasDependentArg = Args.isTypeDependent();
2172 SourceLocation BaseLoc
2173 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
2175 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2176 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2177 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2179 // C++ [class.base.init]p2:
2180 // [...] Unless the mem-initializer-id names a nonstatic data
2181 // member of the constructor's class or a direct or virtual base
2182 // of that class, the mem-initializer is ill-formed. A
2183 // mem-initializer-list can initialize a base class using any
2184 // name that denotes that base class type.
2185 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2187 if (EllipsisLoc.isValid()) {
2188 // This is a pack expansion.
2189 if (!BaseType->containsUnexpandedParameterPack()) {
2190 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2191 << SourceRange(BaseLoc, Args.getEndLoc());
2193 EllipsisLoc = SourceLocation();
2196 // Check for any unexpanded parameter packs.
2197 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2200 if (Args.DiagnoseUnexpandedParameterPack(*this))
2204 // Check for direct and virtual base classes.
2205 const CXXBaseSpecifier *DirectBaseSpec = 0;
2206 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2208 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2210 return BuildDelegatingInitializer(BaseTInfo, Args, BaseLoc, ClassDecl);
2212 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2215 // C++ [base.class.init]p2:
2216 // Unless the mem-initializer-id names a nonstatic data member of the
2217 // constructor's class or a direct or virtual base of that class, the
2218 // mem-initializer is ill-formed.
2219 if (!DirectBaseSpec && !VirtualBaseSpec) {
2220 // If the class has any dependent bases, then it's possible that
2221 // one of those types will resolve to the same type as
2222 // BaseType. Therefore, just treat this as a dependent base
2223 // class initialization. FIXME: Should we try to check the
2224 // initialization anyway? It seems odd.
2225 if (ClassDecl->hasAnyDependentBases())
2228 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2229 << BaseType << Context.getTypeDeclType(ClassDecl)
2230 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2235 // Can't check initialization for a base of dependent type or when
2236 // any of the arguments are type-dependent expressions.
2237 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
2239 DiscardCleanupsInEvaluationContext();
2241 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2242 /*IsVirtual=*/false,
2243 Args.getStartLoc(), BaseInit,
2244 Args.getEndLoc(), EllipsisLoc);
2247 // C++ [base.class.init]p2:
2248 // If a mem-initializer-id is ambiguous because it designates both
2249 // a direct non-virtual base class and an inherited virtual base
2250 // class, the mem-initializer is ill-formed.
2251 if (DirectBaseSpec && VirtualBaseSpec)
2252 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
2253 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2255 CXXBaseSpecifier *BaseSpec
2256 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2258 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2260 // Initialize the base.
2261 InitializedEntity BaseEntity =
2262 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
2263 InitializationKind Kind =
2264 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2267 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
2268 if (BaseInit.isInvalid())
2271 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2273 // C++0x [class.base.init]p7:
2274 // The initialization of each base and member constitutes a
2276 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
2277 if (BaseInit.isInvalid())
2280 // If we are in a dependent context, template instantiation will
2281 // perform this type-checking again. Just save the arguments that we
2282 // received in a ParenListExpr.
2283 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2284 // of the information that we have about the base
2285 // initializer. However, deconstructing the ASTs is a dicey process,
2286 // and this approach is far more likely to get the corner cases right.
2287 if (CurContext->isDependentContext())
2288 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
2290 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2291 BaseSpec->isVirtual(),
2293 BaseInit.takeAs<Expr>(),
2294 Args.getEndLoc(), EllipsisLoc);
2297 // Create a static_cast\<T&&>(expr).
2298 static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2299 QualType ExprType = E->getType();
2300 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2301 SourceLocation ExprLoc = E->getLocStart();
2302 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2303 TargetType, ExprLoc);
2305 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2306 SourceRange(ExprLoc, ExprLoc),
2307 E->getSourceRange()).take();
2310 /// ImplicitInitializerKind - How an implicit base or member initializer should
2311 /// initialize its base or member.
2312 enum ImplicitInitializerKind {
2319 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2320 ImplicitInitializerKind ImplicitInitKind,
2321 CXXBaseSpecifier *BaseSpec,
2322 bool IsInheritedVirtualBase,
2323 CXXCtorInitializer *&CXXBaseInit) {
2324 InitializedEntity InitEntity
2325 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2326 IsInheritedVirtualBase);
2328 ExprResult BaseInit;
2330 switch (ImplicitInitKind) {
2332 InitializationKind InitKind
2333 = InitializationKind::CreateDefault(Constructor->getLocation());
2334 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2335 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2336 MultiExprArg(SemaRef, 0, 0));
2342 bool Moving = ImplicitInitKind == IIK_Move;
2343 ParmVarDecl *Param = Constructor->getParamDecl(0);
2344 QualType ParamType = Param->getType().getNonReferenceType();
2347 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
2348 Constructor->getLocation(), ParamType,
2351 // Cast to the base class to avoid ambiguities.
2353 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2354 ParamType.getQualifiers());
2357 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2360 CXXCastPath BasePath;
2361 BasePath.push_back(BaseSpec);
2362 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2363 CK_UncheckedDerivedToBase,
2364 Moving ? VK_XValue : VK_LValue,
2367 InitializationKind InitKind
2368 = InitializationKind::CreateDirect(Constructor->getLocation(),
2369 SourceLocation(), SourceLocation());
2370 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2372 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
2373 MultiExprArg(&CopyCtorArg, 1));
2378 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
2379 if (BaseInit.isInvalid())
2383 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2384 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2386 BaseSpec->isVirtual(),
2388 BaseInit.takeAs<Expr>(),
2395 static bool RefersToRValueRef(Expr *MemRef) {
2396 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2397 return Referenced->getType()->isRValueReferenceType();
2401 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
2402 ImplicitInitializerKind ImplicitInitKind,
2403 FieldDecl *Field, IndirectFieldDecl *Indirect,
2404 CXXCtorInitializer *&CXXMemberInit) {
2405 if (Field->isInvalidDecl())
2408 SourceLocation Loc = Constructor->getLocation();
2410 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2411 bool Moving = ImplicitInitKind == IIK_Move;
2412 ParmVarDecl *Param = Constructor->getParamDecl(0);
2413 QualType ParamType = Param->getType().getNonReferenceType();
2415 // Suppress copying zero-width bitfields.
2416 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2419 Expr *MemberExprBase =
2420 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
2421 Loc, ParamType, VK_LValue, 0);
2424 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2427 // Build a reference to this field within the parameter.
2429 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2430 Sema::LookupMemberName);
2431 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2432 : cast<ValueDecl>(Field), AS_public);
2433 MemberLookup.resolveKind();
2435 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2439 /*FirstQualifierInScope=*/0,
2441 /*TemplateArgs=*/0);
2442 if (CtorArg.isInvalid())
2445 // C++11 [class.copy]p15:
2446 // - if a member m has rvalue reference type T&&, it is direct-initialized
2447 // with static_cast<T&&>(x.m);
2448 if (RefersToRValueRef(CtorArg.get())) {
2449 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2452 // When the field we are copying is an array, create index variables for
2453 // each dimension of the array. We use these index variables to subscript
2454 // the source array, and other clients (e.g., CodeGen) will perform the
2455 // necessary iteration with these index variables.
2456 SmallVector<VarDecl *, 4> IndexVariables;
2457 QualType BaseType = Field->getType();
2458 QualType SizeType = SemaRef.Context.getSizeType();
2459 bool InitializingArray = false;
2460 while (const ConstantArrayType *Array
2461 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2462 InitializingArray = true;
2463 // Create the iteration variable for this array index.
2464 IdentifierInfo *IterationVarName = 0;
2466 llvm::SmallString<8> Str;
2467 llvm::raw_svector_ostream OS(Str);
2468 OS << "__i" << IndexVariables.size();
2469 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2471 VarDecl *IterationVar
2472 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2473 IterationVarName, SizeType,
2474 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2476 IndexVariables.push_back(IterationVar);
2478 // Create a reference to the iteration variable.
2479 ExprResult IterationVarRef
2480 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2481 assert(!IterationVarRef.isInvalid() &&
2482 "Reference to invented variable cannot fail!");
2484 // Subscript the array with this iteration variable.
2485 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
2486 IterationVarRef.take(),
2488 if (CtorArg.isInvalid())
2491 BaseType = Array->getElementType();
2494 // The array subscript expression is an lvalue, which is wrong for moving.
2495 if (Moving && InitializingArray)
2496 CtorArg = CastForMoving(SemaRef, CtorArg.take());
2498 // Construct the entity that we will be initializing. For an array, this
2499 // will be first element in the array, which may require several levels
2500 // of array-subscript entities.
2501 SmallVector<InitializedEntity, 4> Entities;
2502 Entities.reserve(1 + IndexVariables.size());
2504 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2506 Entities.push_back(InitializedEntity::InitializeMember(Field));
2507 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2508 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2512 // Direct-initialize to use the copy constructor.
2513 InitializationKind InitKind =
2514 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2516 Expr *CtorArgE = CtorArg.takeAs<Expr>();
2517 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2520 ExprResult MemberInit
2521 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2522 MultiExprArg(&CtorArgE, 1));
2523 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2524 if (MemberInit.isInvalid())
2528 assert(IndexVariables.size() == 0 &&
2529 "Indirect field improperly initialized");
2531 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2533 MemberInit.takeAs<Expr>(),
2536 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2537 Loc, MemberInit.takeAs<Expr>(),
2539 IndexVariables.data(),
2540 IndexVariables.size());
2544 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2546 QualType FieldBaseElementType =
2547 SemaRef.Context.getBaseElementType(Field->getType());
2549 if (FieldBaseElementType->isRecordType()) {
2550 InitializedEntity InitEntity
2551 = Indirect? InitializedEntity::InitializeMember(Indirect)
2552 : InitializedEntity::InitializeMember(Field);
2553 InitializationKind InitKind =
2554 InitializationKind::CreateDefault(Loc);
2556 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2557 ExprResult MemberInit =
2558 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2560 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2561 if (MemberInit.isInvalid())
2565 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2571 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2578 if (!Field->getParent()->isUnion()) {
2579 if (FieldBaseElementType->isReferenceType()) {
2580 SemaRef.Diag(Constructor->getLocation(),
2581 diag::err_uninitialized_member_in_ctor)
2582 << (int)Constructor->isImplicit()
2583 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2584 << 0 << Field->getDeclName();
2585 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2589 if (FieldBaseElementType.isConstQualified()) {
2590 SemaRef.Diag(Constructor->getLocation(),
2591 diag::err_uninitialized_member_in_ctor)
2592 << (int)Constructor->isImplicit()
2593 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2594 << 1 << Field->getDeclName();
2595 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2600 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2601 FieldBaseElementType->isObjCRetainableType() &&
2602 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2603 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2605 // Default-initialize Objective-C pointers to NULL.
2607 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2609 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2614 // Nothing to initialize.
2620 struct BaseAndFieldInfo {
2622 CXXConstructorDecl *Ctor;
2623 bool AnyErrorsInInits;
2624 ImplicitInitializerKind IIK;
2625 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2626 SmallVector<CXXCtorInitializer*, 8> AllToInit;
2628 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2629 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2630 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2631 if (Generated && Ctor->isCopyConstructor())
2633 else if (Generated && Ctor->isMoveConstructor())
2641 /// \brief Determine whether the given indirect field declaration is somewhere
2642 /// within an anonymous union.
2643 static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2644 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2645 CEnd = F->chain_end();
2647 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2648 if (Record->isUnion())
2654 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2656 IndirectFieldDecl *Indirect = 0) {
2658 // Overwhelmingly common case: we have a direct initializer for this field.
2659 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2660 Info.AllToInit.push_back(Init);
2664 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2665 // has a brace-or-equal-initializer, the entity is initialized as specified
2667 if (Field->hasInClassInitializer()) {
2668 CXXCtorInitializer *Init;
2670 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2672 SourceLocation(), 0,
2675 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2677 SourceLocation(), 0,
2679 Info.AllToInit.push_back(Init);
2683 // Don't build an implicit initializer for union members if none was
2684 // explicitly specified.
2685 if (Field->getParent()->isUnion() ||
2686 (Indirect && isWithinAnonymousUnion(Indirect)))
2689 // Don't try to build an implicit initializer if there were semantic
2690 // errors in any of the initializers (and therefore we might be
2691 // missing some that the user actually wrote).
2692 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2695 CXXCtorInitializer *Init = 0;
2696 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2701 Info.AllToInit.push_back(Init);
2707 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2708 CXXCtorInitializer *Initializer) {
2709 assert(Initializer->isDelegatingInitializer());
2710 Constructor->setNumCtorInitializers(1);
2711 CXXCtorInitializer **initializer =
2712 new (Context) CXXCtorInitializer*[1];
2713 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2714 Constructor->setCtorInitializers(initializer);
2716 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2717 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2718 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2721 DelegatingCtorDecls.push_back(Constructor);
2726 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2727 CXXCtorInitializer **Initializers,
2728 unsigned NumInitializers,
2730 if (Constructor->isDependentContext()) {
2731 // Just store the initializers as written, they will be checked during
2733 if (NumInitializers > 0) {
2734 Constructor->setNumCtorInitializers(NumInitializers);
2735 CXXCtorInitializer **baseOrMemberInitializers =
2736 new (Context) CXXCtorInitializer*[NumInitializers];
2737 memcpy(baseOrMemberInitializers, Initializers,
2738 NumInitializers * sizeof(CXXCtorInitializer*));
2739 Constructor->setCtorInitializers(baseOrMemberInitializers);
2745 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2747 // We need to build the initializer AST according to order of construction
2748 // and not what user specified in the Initializers list.
2749 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2753 bool HadError = false;
2755 for (unsigned i = 0; i < NumInitializers; i++) {
2756 CXXCtorInitializer *Member = Initializers[i];
2758 if (Member->isBaseInitializer())
2759 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2761 Info.AllBaseFields[Member->getAnyMember()] = Member;
2764 // Keep track of the direct virtual bases.
2765 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2766 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2767 E = ClassDecl->bases_end(); I != E; ++I) {
2769 DirectVBases.insert(I);
2772 // Push virtual bases before others.
2773 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2774 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2776 if (CXXCtorInitializer *Value
2777 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2778 Info.AllToInit.push_back(Value);
2779 } else if (!AnyErrors) {
2780 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2781 CXXCtorInitializer *CXXBaseInit;
2782 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2783 VBase, IsInheritedVirtualBase,
2789 Info.AllToInit.push_back(CXXBaseInit);
2793 // Non-virtual bases.
2794 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2795 E = ClassDecl->bases_end(); Base != E; ++Base) {
2796 // Virtuals are in the virtual base list and already constructed.
2797 if (Base->isVirtual())
2800 if (CXXCtorInitializer *Value
2801 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2802 Info.AllToInit.push_back(Value);
2803 } else if (!AnyErrors) {
2804 CXXCtorInitializer *CXXBaseInit;
2805 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2806 Base, /*IsInheritedVirtualBase=*/false,
2812 Info.AllToInit.push_back(CXXBaseInit);
2817 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2818 MemEnd = ClassDecl->decls_end();
2819 Mem != MemEnd; ++Mem) {
2820 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
2821 // C++ [class.bit]p2:
2822 // A declaration for a bit-field that omits the identifier declares an
2823 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2825 if (F->isUnnamedBitfield())
2828 if (F->getType()->isIncompleteArrayType()) {
2829 assert(ClassDecl->hasFlexibleArrayMember() &&
2830 "Incomplete array type is not valid");
2834 // If we're not generating the implicit copy/move constructor, then we'll
2835 // handle anonymous struct/union fields based on their individual
2837 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2840 if (CollectFieldInitializer(*this, Info, F))
2845 // Beyond this point, we only consider default initialization.
2846 if (Info.IIK != IIK_Default)
2849 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2850 if (F->getType()->isIncompleteArrayType()) {
2851 assert(ClassDecl->hasFlexibleArrayMember() &&
2852 "Incomplete array type is not valid");
2856 // Initialize each field of an anonymous struct individually.
2857 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2864 NumInitializers = Info.AllToInit.size();
2865 if (NumInitializers > 0) {
2866 Constructor->setNumCtorInitializers(NumInitializers);
2867 CXXCtorInitializer **baseOrMemberInitializers =
2868 new (Context) CXXCtorInitializer*[NumInitializers];
2869 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2870 NumInitializers * sizeof(CXXCtorInitializer*));
2871 Constructor->setCtorInitializers(baseOrMemberInitializers);
2873 // Constructors implicitly reference the base and member
2875 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2876 Constructor->getParent());
2882 static void *GetKeyForTopLevelField(FieldDecl *Field) {
2883 // For anonymous unions, use the class declaration as the key.
2884 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2885 if (RT->getDecl()->isAnonymousStructOrUnion())
2886 return static_cast<void *>(RT->getDecl());
2888 return static_cast<void *>(Field);
2891 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2892 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2895 static void *GetKeyForMember(ASTContext &Context,
2896 CXXCtorInitializer *Member) {
2897 if (!Member->isAnyMemberInitializer())
2898 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2900 // For fields injected into the class via declaration of an anonymous union,
2901 // use its anonymous union class declaration as the unique key.
2902 FieldDecl *Field = Member->getAnyMember();
2904 // If the field is a member of an anonymous struct or union, our key
2905 // is the anonymous record decl that's a direct child of the class.
2906 RecordDecl *RD = Field->getParent();
2907 if (RD->isAnonymousStructOrUnion()) {
2909 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2910 if (Parent->isAnonymousStructOrUnion())
2916 return static_cast<void *>(RD);
2919 return static_cast<void *>(Field);
2923 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2924 const CXXConstructorDecl *Constructor,
2925 CXXCtorInitializer **Inits,
2926 unsigned NumInits) {
2927 if (Constructor->getDeclContext()->isDependentContext())
2930 // Don't check initializers order unless the warning is enabled at the
2931 // location of at least one initializer.
2932 bool ShouldCheckOrder = false;
2933 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2934 CXXCtorInitializer *Init = Inits[InitIndex];
2935 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2936 Init->getSourceLocation())
2937 != DiagnosticsEngine::Ignored) {
2938 ShouldCheckOrder = true;
2942 if (!ShouldCheckOrder)
2945 // Build the list of bases and members in the order that they'll
2946 // actually be initialized. The explicit initializers should be in
2947 // this same order but may be missing things.
2948 SmallVector<const void*, 32> IdealInitKeys;
2950 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2952 // 1. Virtual bases.
2953 for (CXXRecordDecl::base_class_const_iterator VBase =
2954 ClassDecl->vbases_begin(),
2955 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2956 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2958 // 2. Non-virtual bases.
2959 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2960 E = ClassDecl->bases_end(); Base != E; ++Base) {
2961 if (Base->isVirtual())
2963 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2966 // 3. Direct fields.
2967 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2968 E = ClassDecl->field_end(); Field != E; ++Field) {
2969 if (Field->isUnnamedBitfield())
2972 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2975 unsigned NumIdealInits = IdealInitKeys.size();
2976 unsigned IdealIndex = 0;
2978 CXXCtorInitializer *PrevInit = 0;
2979 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2980 CXXCtorInitializer *Init = Inits[InitIndex];
2981 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2983 // Scan forward to try to find this initializer in the idealized
2984 // initializers list.
2985 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2986 if (InitKey == IdealInitKeys[IdealIndex])
2989 // If we didn't find this initializer, it must be because we
2990 // scanned past it on a previous iteration. That can only
2991 // happen if we're out of order; emit a warning.
2992 if (IdealIndex == NumIdealInits && PrevInit) {
2993 Sema::SemaDiagnosticBuilder D =
2994 SemaRef.Diag(PrevInit->getSourceLocation(),
2995 diag::warn_initializer_out_of_order);
2997 if (PrevInit->isAnyMemberInitializer())
2998 D << 0 << PrevInit->getAnyMember()->getDeclName();
3000 D << 1 << PrevInit->getBaseClassInfo()->getType();
3002 if (Init->isAnyMemberInitializer())
3003 D << 0 << Init->getAnyMember()->getDeclName();
3005 D << 1 << Init->getBaseClassInfo()->getType();
3007 // Move back to the initializer's location in the ideal list.
3008 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3009 if (InitKey == IdealInitKeys[IdealIndex])
3012 assert(IdealIndex != NumIdealInits &&
3013 "initializer not found in initializer list");
3021 bool CheckRedundantInit(Sema &S,
3022 CXXCtorInitializer *Init,
3023 CXXCtorInitializer *&PrevInit) {
3029 if (FieldDecl *Field = Init->getMember())
3030 S.Diag(Init->getSourceLocation(),
3031 diag::err_multiple_mem_initialization)
3032 << Field->getDeclName()
3033 << Init->getSourceRange();
3035 const Type *BaseClass = Init->getBaseClass();
3036 assert(BaseClass && "neither field nor base");
3037 S.Diag(Init->getSourceLocation(),
3038 diag::err_multiple_base_initialization)
3039 << QualType(BaseClass, 0)
3040 << Init->getSourceRange();
3042 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3043 << 0 << PrevInit->getSourceRange();
3048 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
3049 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3051 bool CheckRedundantUnionInit(Sema &S,
3052 CXXCtorInitializer *Init,
3053 RedundantUnionMap &Unions) {
3054 FieldDecl *Field = Init->getAnyMember();
3055 RecordDecl *Parent = Field->getParent();
3056 if (!Parent->isAnonymousStructOrUnion())
3059 NamedDecl *Child = Field;
3061 if (Parent->isUnion()) {
3062 UnionEntry &En = Unions[Parent];
3063 if (En.first && En.first != Child) {
3064 S.Diag(Init->getSourceLocation(),
3065 diag::err_multiple_mem_union_initialization)
3066 << Field->getDeclName()
3067 << Init->getSourceRange();
3068 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3069 << 0 << En.second->getSourceRange();
3071 } else if (!En.first) {
3078 Parent = cast<RecordDecl>(Parent->getDeclContext());
3079 } while (Parent->isAnonymousStructOrUnion());
3085 /// ActOnMemInitializers - Handle the member initializers for a constructor.
3086 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
3087 SourceLocation ColonLoc,
3088 CXXCtorInitializer **meminits,
3089 unsigned NumMemInits,
3091 if (!ConstructorDecl)
3094 AdjustDeclIfTemplate(ConstructorDecl);
3096 CXXConstructorDecl *Constructor
3097 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
3100 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3104 CXXCtorInitializer **MemInits =
3105 reinterpret_cast<CXXCtorInitializer **>(meminits);
3107 // Mapping for the duplicate initializers check.
3108 // For member initializers, this is keyed with a FieldDecl*.
3109 // For base initializers, this is keyed with a Type*.
3110 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
3112 // Mapping for the inconsistent anonymous-union initializers check.
3113 RedundantUnionMap MemberUnions;
3115 bool HadError = false;
3116 for (unsigned i = 0; i < NumMemInits; i++) {
3117 CXXCtorInitializer *Init = MemInits[i];
3119 // Set the source order index.
3120 Init->setSourceOrder(i);
3122 if (Init->isAnyMemberInitializer()) {
3123 FieldDecl *Field = Init->getAnyMember();
3124 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3125 CheckRedundantUnionInit(*this, Init, MemberUnions))
3127 } else if (Init->isBaseInitializer()) {
3128 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3129 if (CheckRedundantInit(*this, Init, Members[Key]))
3132 assert(Init->isDelegatingInitializer());
3133 // This must be the only initializer
3134 if (i != 0 || NumMemInits > 1) {
3135 Diag(MemInits[0]->getSourceLocation(),
3136 diag::err_delegating_initializer_alone)
3137 << MemInits[0]->getSourceRange();
3139 // We will treat this as being the only initializer.
3141 SetDelegatingInitializer(Constructor, MemInits[i]);
3142 // Return immediately as the initializer is set.
3150 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
3152 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
3156 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3157 CXXRecordDecl *ClassDecl) {
3158 // Ignore dependent contexts. Also ignore unions, since their members never
3159 // have destructors implicitly called.
3160 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
3163 // FIXME: all the access-control diagnostics are positioned on the
3164 // field/base declaration. That's probably good; that said, the
3165 // user might reasonably want to know why the destructor is being
3166 // emitted, and we currently don't say.
3168 // Non-static data members.
3169 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3170 E = ClassDecl->field_end(); I != E; ++I) {
3171 FieldDecl *Field = *I;
3172 if (Field->isInvalidDecl())
3174 QualType FieldType = Context.getBaseElementType(Field->getType());
3176 const RecordType* RT = FieldType->getAs<RecordType>();
3180 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3181 if (FieldClassDecl->isInvalidDecl())
3183 if (FieldClassDecl->hasTrivialDestructor())
3186 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
3187 assert(Dtor && "No dtor found for FieldClassDecl!");
3188 CheckDestructorAccess(Field->getLocation(), Dtor,
3189 PDiag(diag::err_access_dtor_field)
3190 << Field->getDeclName()
3193 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3196 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3199 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3200 E = ClassDecl->bases_end(); Base != E; ++Base) {
3201 // Bases are always records in a well-formed non-dependent class.
3202 const RecordType *RT = Base->getType()->getAs<RecordType>();
3204 // Remember direct virtual bases.
3205 if (Base->isVirtual())
3206 DirectVirtualBases.insert(RT);
3208 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3209 // If our base class is invalid, we probably can't get its dtor anyway.
3210 if (BaseClassDecl->isInvalidDecl())
3212 // Ignore trivial destructors.
3213 if (BaseClassDecl->hasTrivialDestructor())
3216 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3217 assert(Dtor && "No dtor found for BaseClassDecl!");
3219 // FIXME: caret should be on the start of the class name
3220 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
3221 PDiag(diag::err_access_dtor_base)
3223 << Base->getSourceRange());
3225 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3229 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3230 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
3232 // Bases are always records in a well-formed non-dependent class.
3233 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3235 // Ignore direct virtual bases.
3236 if (DirectVirtualBases.count(RT))
3239 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
3240 // If our base class is invalid, we probably can't get its dtor anyway.
3241 if (BaseClassDecl->isInvalidDecl())
3243 // Ignore trivial destructors.
3244 if (BaseClassDecl->hasTrivialDestructor())
3247 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
3248 assert(Dtor && "No dtor found for BaseClassDecl!");
3249 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
3250 PDiag(diag::err_access_dtor_vbase)
3251 << VBase->getType());
3253 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
3257 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
3261 if (CXXConstructorDecl *Constructor
3262 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
3263 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
3266 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3267 unsigned DiagID, AbstractDiagSelID SelID) {
3269 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
3271 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
3274 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
3275 const PartialDiagnostic &PD) {
3276 if (!getLangOptions().CPlusPlus)
3279 if (const ArrayType *AT = Context.getAsArrayType(T))
3280 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3282 if (const PointerType *PT = T->getAs<PointerType>()) {
3283 // Find the innermost pointer type.
3284 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
3287 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
3288 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
3291 const RecordType *RT = T->getAs<RecordType>();
3295 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3297 // We can't answer whether something is abstract until it has a
3298 // definition. If it's currently being defined, we'll walk back
3299 // over all the declarations when we have a full definition.
3300 const CXXRecordDecl *Def = RD->getDefinition();
3301 if (!Def || Def->isBeingDefined())
3304 if (!RD->isAbstract())
3307 Diag(Loc, PD) << RD->getDeclName();
3308 DiagnoseAbstractType(RD);
3313 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3314 // Check if we've already emitted the list of pure virtual functions
3316 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
3319 CXXFinalOverriderMap FinalOverriders;
3320 RD->getFinalOverriders(FinalOverriders);
3322 // Keep a set of seen pure methods so we won't diagnose the same method
3324 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3326 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3327 MEnd = FinalOverriders.end();
3330 for (OverridingMethods::iterator SO = M->second.begin(),
3331 SOEnd = M->second.end();
3332 SO != SOEnd; ++SO) {
3333 // C++ [class.abstract]p4:
3334 // A class is abstract if it contains or inherits at least one
3335 // pure virtual function for which the final overrider is pure
3339 if (SO->second.size() != 1)
3342 if (!SO->second.front().Method->isPure())
3345 if (!SeenPureMethods.insert(SO->second.front().Method))
3348 Diag(SO->second.front().Method->getLocation(),
3349 diag::note_pure_virtual_function)
3350 << SO->second.front().Method->getDeclName() << RD->getDeclName();
3354 if (!PureVirtualClassDiagSet)
3355 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3356 PureVirtualClassDiagSet->insert(RD);
3360 struct AbstractUsageInfo {
3362 CXXRecordDecl *Record;
3363 CanQualType AbstractType;
3366 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3367 : S(S), Record(Record),
3368 AbstractType(S.Context.getCanonicalType(
3369 S.Context.getTypeDeclType(Record))),
3372 void DiagnoseAbstractType() {
3373 if (Invalid) return;
3374 S.DiagnoseAbstractType(Record);
3378 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3381 struct CheckAbstractUsage {
3382 AbstractUsageInfo &Info;
3383 const NamedDecl *Ctx;
3385 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3386 : Info(Info), Ctx(Ctx) {}
3388 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3389 switch (TL.getTypeLocClass()) {
3390 #define ABSTRACT_TYPELOC(CLASS, PARENT)
3391 #define TYPELOC(CLASS, PARENT) \
3392 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3393 #include "clang/AST/TypeLocNodes.def"
3397 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3398 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3399 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3403 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3404 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
3408 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3409 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3412 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3413 // Visit the type parameters from a permissive context.
3414 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3415 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3416 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3417 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3418 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3419 // TODO: other template argument types?
3423 // Visit pointee types from a permissive context.
3424 #define CheckPolymorphic(Type) \
3425 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3426 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3428 CheckPolymorphic(PointerTypeLoc)
3429 CheckPolymorphic(ReferenceTypeLoc)
3430 CheckPolymorphic(MemberPointerTypeLoc)
3431 CheckPolymorphic(BlockPointerTypeLoc)
3432 CheckPolymorphic(AtomicTypeLoc)
3434 /// Handle all the types we haven't given a more specific
3435 /// implementation for above.
3436 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3437 // Every other kind of type that we haven't called out already
3438 // that has an inner type is either (1) sugar or (2) contains that
3439 // inner type in some way as a subobject.
3440 if (TypeLoc Next = TL.getNextTypeLoc())
3441 return Visit(Next, Sel);
3443 // If there's no inner type and we're in a permissive context,
3445 if (Sel == Sema::AbstractNone) return;
3447 // Check whether the type matches the abstract type.
3448 QualType T = TL.getType();
3449 if (T->isArrayType()) {
3450 Sel = Sema::AbstractArrayType;
3451 T = Info.S.Context.getBaseElementType(T);
3453 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3454 if (CT != Info.AbstractType) return;
3456 // It matched; do some magic.
3457 if (Sel == Sema::AbstractArrayType) {
3458 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3459 << T << TL.getSourceRange();
3461 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3462 << Sel << T << TL.getSourceRange();
3464 Info.DiagnoseAbstractType();
3468 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3469 Sema::AbstractDiagSelID Sel) {
3470 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3475 /// Check for invalid uses of an abstract type in a method declaration.
3476 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3477 CXXMethodDecl *MD) {
3478 // No need to do the check on definitions, which require that
3479 // the return/param types be complete.
3480 if (MD->doesThisDeclarationHaveABody())
3483 // For safety's sake, just ignore it if we don't have type source
3484 // information. This should never happen for non-implicit methods,
3486 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3487 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3490 /// Check for invalid uses of an abstract type within a class definition.
3491 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3492 CXXRecordDecl *RD) {
3493 for (CXXRecordDecl::decl_iterator
3494 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3496 if (D->isImplicit()) continue;
3498 // Methods and method templates.
3499 if (isa<CXXMethodDecl>(D)) {
3500 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3501 } else if (isa<FunctionTemplateDecl>(D)) {
3502 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3503 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3505 // Fields and static variables.
3506 } else if (isa<FieldDecl>(D)) {
3507 FieldDecl *FD = cast<FieldDecl>(D);
3508 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3509 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3510 } else if (isa<VarDecl>(D)) {
3511 VarDecl *VD = cast<VarDecl>(D);
3512 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3513 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3515 // Nested classes and class templates.
3516 } else if (isa<CXXRecordDecl>(D)) {
3517 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3518 } else if (isa<ClassTemplateDecl>(D)) {
3519 CheckAbstractClassUsage(Info,
3520 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3525 /// \brief Perform semantic checks on a class definition that has been
3526 /// completing, introducing implicitly-declared members, checking for
3527 /// abstract types, etc.
3528 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3532 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3533 AbstractUsageInfo Info(*this, Record);
3534 CheckAbstractClassUsage(Info, Record);
3537 // If this is not an aggregate type and has no user-declared constructor,
3538 // complain about any non-static data members of reference or const scalar
3539 // type, since they will never get initializers.
3540 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3541 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3542 bool Complained = false;
3543 for (RecordDecl::field_iterator F = Record->field_begin(),
3544 FEnd = Record->field_end();
3546 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
3549 if (F->getType()->isReferenceType() ||
3550 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3552 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3553 << Record->getTagKind() << Record;
3557 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3558 << F->getType()->isReferenceType()
3559 << F->getDeclName();
3564 if (Record->isDynamicClass() && !Record->isDependentType())
3565 DynamicClasses.push_back(Record);
3567 if (Record->getIdentifier()) {
3568 // C++ [class.mem]p13:
3569 // If T is the name of a class, then each of the following shall have a
3570 // name different from T:
3571 // - every member of every anonymous union that is a member of class T.
3573 // C++ [class.mem]p14:
3574 // In addition, if class T has a user-declared constructor (12.1), every
3575 // non-static data member of class T shall have a name different from T.
3576 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3577 R.first != R.second; ++R.first) {
3578 NamedDecl *D = *R.first;
3579 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3580 isa<IndirectFieldDecl>(D)) {
3581 Diag(D->getLocation(), diag::err_member_name_of_class)
3582 << D->getDeclName();
3588 // Warn if the class has virtual methods but non-virtual public destructor.
3589 if (Record->isPolymorphic() && !Record->isDependentType()) {
3590 CXXDestructorDecl *dtor = Record->getDestructor();
3591 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3592 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3593 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3596 // See if a method overloads virtual methods in a base
3597 /// class without overriding any.
3598 if (!Record->isDependentType()) {
3599 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3600 MEnd = Record->method_end();
3602 if (!(*M)->isStatic())
3603 DiagnoseHiddenVirtualMethods(Record, *M);
3607 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3608 // function that is not a constructor declares that member function to be
3609 // const. [...] The class of which that function is a member shall be
3612 // It's fine to diagnose constructors here too: such constructors cannot
3613 // produce a constant expression, so are ill-formed (no diagnostic required).
3615 // If the class has virtual bases, any constexpr members will already have
3616 // been diagnosed by the checks performed on the member declaration, so
3617 // suppress this (less useful) diagnostic.
3618 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3619 !Record->isLiteral() && !Record->getNumVBases()) {
3620 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3621 MEnd = Record->method_end();
3623 if ((*M)->isConstexpr()) {
3624 switch (Record->getTemplateSpecializationKind()) {
3625 case TSK_ImplicitInstantiation:
3626 case TSK_ExplicitInstantiationDeclaration:
3627 case TSK_ExplicitInstantiationDefinition:
3628 // If a template instantiates to a non-literal type, but its members
3629 // instantiate to constexpr functions, the template is technically
3630 // ill-formed, but we allow it for sanity. Such members are treated as
3632 (*M)->setConstexpr(false);
3635 case TSK_Undeclared:
3636 case TSK_ExplicitSpecialization:
3637 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3638 PDiag(diag::err_constexpr_method_non_literal));
3642 // Only produce one error per class.
3648 // Declare inherited constructors. We do this eagerly here because:
3649 // - The standard requires an eager diagnostic for conflicting inherited
3650 // constructors from different classes.
3651 // - The lazy declaration of the other implicit constructors is so as to not
3652 // waste space and performance on classes that are not meant to be
3653 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3654 // have inherited constructors.
3655 DeclareInheritedConstructors(Record);
3657 if (!Record->isDependentType())
3658 CheckExplicitlyDefaultedMethods(Record);
3661 void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3662 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3663 ME = Record->method_end();
3665 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3666 switch (getSpecialMember(*MI)) {
3667 case CXXDefaultConstructor:
3668 CheckExplicitlyDefaultedDefaultConstructor(
3669 cast<CXXConstructorDecl>(*MI));
3673 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3676 case CXXCopyConstructor:
3677 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3680 case CXXCopyAssignment:
3681 CheckExplicitlyDefaultedCopyAssignment(*MI);
3684 case CXXMoveConstructor:
3685 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
3688 case CXXMoveAssignment:
3689 CheckExplicitlyDefaultedMoveAssignment(*MI);
3693 llvm_unreachable("non-special member explicitly defaulted!");
3700 void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3701 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3703 // Whether this was the first-declared instance of the constructor.
3704 // This affects whether we implicitly add an exception spec (and, eventually,
3705 // constexpr). It is also ill-formed to explicitly default a constructor such
3706 // that it would be deleted. (C++0x [decl.fct.def.default])
3707 bool First = CD == CD->getCanonicalDecl();
3709 bool HadError = false;
3710 if (CD->getNumParams() != 0) {
3711 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3712 << CD->getSourceRange();
3716 ImplicitExceptionSpecification Spec
3717 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3718 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3719 if (EPI.ExceptionSpecType == EST_Delayed) {
3720 // Exception specification depends on some deferred part of the class. We'll
3721 // try again when the class's definition has been fully processed.
3724 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3725 *ExceptionType = Context.getFunctionType(
3726 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3728 if (CtorType->hasExceptionSpec()) {
3729 if (CheckEquivalentExceptionSpec(
3730 PDiag(diag::err_incorrect_defaulted_exception_spec)
3731 << CXXDefaultConstructor,
3733 ExceptionType, SourceLocation(),
3734 CtorType, CD->getLocation())) {
3738 // We set the declaration to have the computed exception spec here.
3739 // We know there are no parameters.
3740 EPI.ExtInfo = CtorType->getExtInfo();
3741 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3745 CD->setInvalidDecl();
3749 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
3751 CD->setDeletedAsWritten();
3753 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3754 << CXXDefaultConstructor;
3755 CD->setInvalidDecl();
3760 void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3761 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3763 // Whether this was the first-declared instance of the constructor.
3764 bool First = CD == CD->getCanonicalDecl();
3766 bool HadError = false;
3767 if (CD->getNumParams() != 1) {
3768 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3769 << CD->getSourceRange();
3773 ImplicitExceptionSpecification Spec(Context);
3775 llvm::tie(Spec, Const) =
3776 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3778 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3779 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3780 *ExceptionType = Context.getFunctionType(
3781 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3783 // Check for parameter type matching.
3784 // This is a copy ctor so we know it's a cv-qualified reference to T.
3785 QualType ArgType = CtorType->getArgType(0);
3786 if (ArgType->getPointeeType().isVolatileQualified()) {
3787 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3790 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3791 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3795 if (CtorType->hasExceptionSpec()) {
3796 if (CheckEquivalentExceptionSpec(
3797 PDiag(diag::err_incorrect_defaulted_exception_spec)
3798 << CXXCopyConstructor,
3800 ExceptionType, SourceLocation(),
3801 CtorType, CD->getLocation())) {
3805 // We set the declaration to have the computed exception spec here.
3806 // We duplicate the one parameter type.
3807 EPI.ExtInfo = CtorType->getExtInfo();
3808 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3812 CD->setInvalidDecl();
3816 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
3818 CD->setDeletedAsWritten();
3820 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3821 << CXXCopyConstructor;
3822 CD->setInvalidDecl();
3827 void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3828 assert(MD->isExplicitlyDefaulted());
3830 // Whether this was the first-declared instance of the operator
3831 bool First = MD == MD->getCanonicalDecl();
3833 bool HadError = false;
3834 if (MD->getNumParams() != 1) {
3835 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3836 << MD->getSourceRange();
3840 QualType ReturnType =
3841 MD->getType()->getAs<FunctionType>()->getResultType();
3842 if (!ReturnType->isLValueReferenceType() ||
3843 !Context.hasSameType(
3844 Context.getCanonicalType(ReturnType->getPointeeType()),
3845 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3846 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3850 ImplicitExceptionSpecification Spec(Context);
3852 llvm::tie(Spec, Const) =
3853 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3855 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3856 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3857 *ExceptionType = Context.getFunctionType(
3858 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3860 QualType ArgType = OperType->getArgType(0);
3861 if (!ArgType->isLValueReferenceType()) {
3862 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3865 if (ArgType->getPointeeType().isVolatileQualified()) {
3866 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3869 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3870 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3875 if (OperType->getTypeQuals()) {
3876 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3880 if (OperType->hasExceptionSpec()) {
3881 if (CheckEquivalentExceptionSpec(
3882 PDiag(diag::err_incorrect_defaulted_exception_spec)
3883 << CXXCopyAssignment,
3885 ExceptionType, SourceLocation(),
3886 OperType, MD->getLocation())) {
3890 // We set the declaration to have the computed exception spec here.
3891 // We duplicate the one parameter type.
3892 EPI.RefQualifier = OperType->getRefQualifier();
3893 EPI.ExtInfo = OperType->getExtInfo();
3894 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3898 MD->setInvalidDecl();
3902 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3904 MD->setDeletedAsWritten();
3906 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3907 << CXXCopyAssignment;
3908 MD->setInvalidDecl();
3913 void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
3914 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
3916 // Whether this was the first-declared instance of the constructor.
3917 bool First = CD == CD->getCanonicalDecl();
3919 bool HadError = false;
3920 if (CD->getNumParams() != 1) {
3921 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
3922 << CD->getSourceRange();
3926 ImplicitExceptionSpecification Spec(
3927 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
3929 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3930 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3931 *ExceptionType = Context.getFunctionType(
3932 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3934 // Check for parameter type matching.
3935 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
3936 QualType ArgType = CtorType->getArgType(0);
3937 if (ArgType->getPointeeType().isVolatileQualified()) {
3938 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
3941 if (ArgType->getPointeeType().isConstQualified()) {
3942 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
3946 if (CtorType->hasExceptionSpec()) {
3947 if (CheckEquivalentExceptionSpec(
3948 PDiag(diag::err_incorrect_defaulted_exception_spec)
3949 << CXXMoveConstructor,
3951 ExceptionType, SourceLocation(),
3952 CtorType, CD->getLocation())) {
3956 // We set the declaration to have the computed exception spec here.
3957 // We duplicate the one parameter type.
3958 EPI.ExtInfo = CtorType->getExtInfo();
3959 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3963 CD->setInvalidDecl();
3967 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
3969 CD->setDeletedAsWritten();
3971 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3972 << CXXMoveConstructor;
3973 CD->setInvalidDecl();
3978 void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
3979 assert(MD->isExplicitlyDefaulted());
3981 // Whether this was the first-declared instance of the operator
3982 bool First = MD == MD->getCanonicalDecl();
3984 bool HadError = false;
3985 if (MD->getNumParams() != 1) {
3986 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
3987 << MD->getSourceRange();
3991 QualType ReturnType =
3992 MD->getType()->getAs<FunctionType>()->getResultType();
3993 if (!ReturnType->isLValueReferenceType() ||
3994 !Context.hasSameType(
3995 Context.getCanonicalType(ReturnType->getPointeeType()),
3996 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3997 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4001 ImplicitExceptionSpecification Spec(
4002 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4004 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4005 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4006 *ExceptionType = Context.getFunctionType(
4007 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4009 QualType ArgType = OperType->getArgType(0);
4010 if (!ArgType->isRValueReferenceType()) {
4011 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4014 if (ArgType->getPointeeType().isVolatileQualified()) {
4015 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4018 if (ArgType->getPointeeType().isConstQualified()) {
4019 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4024 if (OperType->getTypeQuals()) {
4025 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4029 if (OperType->hasExceptionSpec()) {
4030 if (CheckEquivalentExceptionSpec(
4031 PDiag(diag::err_incorrect_defaulted_exception_spec)
4032 << CXXMoveAssignment,
4034 ExceptionType, SourceLocation(),
4035 OperType, MD->getLocation())) {
4039 // We set the declaration to have the computed exception spec here.
4040 // We duplicate the one parameter type.
4041 EPI.RefQualifier = OperType->getRefQualifier();
4042 EPI.ExtInfo = OperType->getExtInfo();
4043 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4047 MD->setInvalidDecl();
4051 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4053 MD->setDeletedAsWritten();
4055 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4056 << CXXMoveAssignment;
4057 MD->setInvalidDecl();
4062 void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4063 assert(DD->isExplicitlyDefaulted());
4065 // Whether this was the first-declared instance of the destructor.
4066 bool First = DD == DD->getCanonicalDecl();
4068 ImplicitExceptionSpecification Spec
4069 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4070 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4071 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4072 *ExceptionType = Context.getFunctionType(
4073 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4075 if (DtorType->hasExceptionSpec()) {
4076 if (CheckEquivalentExceptionSpec(
4077 PDiag(diag::err_incorrect_defaulted_exception_spec)
4080 ExceptionType, SourceLocation(),
4081 DtorType, DD->getLocation())) {
4082 DD->setInvalidDecl();
4086 // We set the declaration to have the computed exception spec here.
4087 // There are no parameters.
4088 EPI.ExtInfo = DtorType->getExtInfo();
4089 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4092 if (ShouldDeleteDestructor(DD)) {
4094 DD->setDeletedAsWritten();
4096 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
4098 DD->setInvalidDecl();
4103 /// This function implements the following C++0x paragraphs:
4104 /// - [class.ctor]/5
4105 /// - [class.copy]/11
4106 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4107 assert(!MD->isInvalidDecl());
4108 CXXRecordDecl *RD = MD->getParent();
4109 assert(!RD->isDependentType() && "do deletion after instantiation");
4110 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4113 bool IsUnion = RD->isUnion();
4114 bool IsConstructor = false;
4115 bool IsAssignment = false;
4116 bool IsMove = false;
4118 bool ConstArg = false;
4121 case CXXDefaultConstructor:
4122 IsConstructor = true;
4124 case CXXCopyConstructor:
4125 IsConstructor = true;
4126 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4128 case CXXMoveConstructor:
4129 IsConstructor = true;
4133 llvm_unreachable("function only currently implemented for default ctors");
4136 SourceLocation Loc = MD->getLocation();
4138 // Do access control from the special member function
4139 ContextRAII MethodContext(*this, MD);
4141 bool AllConst = true;
4143 // We do this because we should never actually use an anonymous
4144 // union's constructor.
4145 if (IsUnion && RD->isAnonymousStructOrUnion())
4148 // FIXME: We should put some diagnostic logic right into this function.
4150 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4151 BE = RD->bases_end();
4153 // We'll handle this one later
4154 if (BI->isVirtual())
4157 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4158 assert(BaseDecl && "base isn't a CXXRecordDecl");
4160 // Unless we have an assignment operator, the base's destructor must
4161 // be accessible and not deleted.
4162 if (!IsAssignment) {
4163 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4164 if (BaseDtor->isDeleted())
4166 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4171 // Finding the corresponding member in the base should lead to a
4172 // unique, accessible, non-deleted function. If we are doing
4173 // a destructor, we have already checked this case.
4174 if (CSM != CXXDestructor) {
4175 SpecialMemberOverloadResult *SMOR =
4176 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
4178 if (!SMOR->hasSuccess())
4180 CXXMethodDecl *BaseMember = SMOR->getMethod();
4181 if (IsConstructor) {
4182 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4183 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4184 PDiag()) != AR_accessible)
4187 // For a move operation, the corresponding operation must actually
4188 // be a move operation (and not a copy selected by overload
4189 // resolution) unless we are working on a trivially copyable class.
4190 if (IsMove && !BaseCtor->isMoveConstructor() &&
4191 !BaseDecl->isTriviallyCopyable())
4197 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4198 BE = RD->vbases_end();
4200 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4201 assert(BaseDecl && "base isn't a CXXRecordDecl");
4203 // Unless we have an assignment operator, the base's destructor must
4204 // be accessible and not deleted.
4205 if (!IsAssignment) {
4206 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4207 if (BaseDtor->isDeleted())
4209 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4214 // Finding the corresponding member in the base should lead to a
4215 // unique, accessible, non-deleted function.
4216 if (CSM != CXXDestructor) {
4217 SpecialMemberOverloadResult *SMOR =
4218 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
4220 if (!SMOR->hasSuccess())
4222 CXXMethodDecl *BaseMember = SMOR->getMethod();
4223 if (IsConstructor) {
4224 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4225 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4226 PDiag()) != AR_accessible)
4229 // For a move operation, the corresponding operation must actually
4230 // be a move operation (and not a copy selected by overload
4231 // resolution) unless we are working on a trivially copyable class.
4232 if (IsMove && !BaseCtor->isMoveConstructor() &&
4233 !BaseDecl->isTriviallyCopyable())
4239 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4240 FE = RD->field_end();
4242 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
4245 QualType FieldType = Context.getBaseElementType(FI->getType());
4246 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4248 // For a default constructor, all references must be initialized in-class
4249 // and, if a union, it must have a non-const member.
4250 if (CSM == CXXDefaultConstructor) {
4251 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4254 if (IsUnion && !FieldType.isConstQualified())
4256 // For a copy constructor, data members must not be of rvalue reference
4258 } else if (CSM == CXXCopyConstructor) {
4259 if (FieldType->isRValueReferenceType())
4264 // For a default constructor, a const member must have a user-provided
4265 // default constructor or else be explicitly initialized.
4266 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
4267 !FI->hasInClassInitializer() &&
4268 !FieldRecord->hasUserProvidedDefaultConstructor())
4271 // Some additional restrictions exist on the variant members.
4272 if (!IsUnion && FieldRecord->isUnion() &&
4273 FieldRecord->isAnonymousStructOrUnion()) {
4274 // We're okay to reuse AllConst here since we only care about the
4275 // value otherwise if we're in a union.
4278 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4279 UE = FieldRecord->field_end();
4281 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4282 CXXRecordDecl *UnionFieldRecord =
4283 UnionFieldType->getAsCXXRecordDecl();
4285 if (!UnionFieldType.isConstQualified())
4288 if (UnionFieldRecord) {
4289 // FIXME: Checking for accessibility and validity of this
4290 // destructor is technically going beyond the
4291 // standard, but this is believed to be a defect.
4292 if (!IsAssignment) {
4293 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4294 if (FieldDtor->isDeleted())
4296 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4299 if (!FieldDtor->isTrivial())
4303 if (CSM != CXXDestructor) {
4304 SpecialMemberOverloadResult *SMOR =
4305 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
4306 false, false, false);
4307 // FIXME: Checking for accessibility and validity of this
4308 // corresponding member is technically going beyond the
4309 // standard, but this is believed to be a defect.
4310 if (!SMOR->hasSuccess())
4313 CXXMethodDecl *FieldMember = SMOR->getMethod();
4314 // A member of a union must have a trivial corresponding
4316 if (!FieldMember->isTrivial())
4319 if (IsConstructor) {
4320 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4321 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4322 PDiag()) != AR_accessible)
4329 // At least one member in each anonymous union must be non-const
4330 if (CSM == CXXDefaultConstructor && AllConst)
4333 // Don't try to initialize the anonymous union
4334 // This is technically non-conformant, but sanity demands it.
4338 // Unless we're doing assignment, the field's destructor must be
4339 // accessible and not deleted.
4340 if (!IsAssignment) {
4341 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4342 if (FieldDtor->isDeleted())
4344 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4349 // Check that the corresponding member of the field is accessible,
4350 // unique, and non-deleted. We don't do this if it has an explicit
4351 // initialization when default-constructing.
4352 if (CSM != CXXDestructor &&
4353 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4354 SpecialMemberOverloadResult *SMOR =
4355 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
4357 if (!SMOR->hasSuccess())
4360 CXXMethodDecl *FieldMember = SMOR->getMethod();
4361 if (IsConstructor) {
4362 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4363 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4364 PDiag()) != AR_accessible)
4367 // For a move operation, the corresponding operation must actually
4368 // be a move operation (and not a copy selected by overload
4369 // resolution) unless we are working on a trivially copyable class.
4370 if (IsMove && !FieldCtor->isMoveConstructor() &&
4371 !FieldRecord->isTriviallyCopyable())
4375 // We need the corresponding member of a union to be trivial so that
4376 // we can safely copy them all simultaneously.
4377 // FIXME: Note that performing the check here (where we rely on the lack
4378 // of an in-class initializer) is technically ill-formed. However, this
4379 // seems most obviously to be a bug in the standard.
4380 if (IsUnion && !FieldMember->isTrivial())
4383 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4384 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4385 // We can't initialize a const member of non-class type to any value.
4390 // We can't have all const members in a union when default-constructing,
4391 // or else they're all nonsensical garbage values that can't be changed.
4392 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
4398 bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4399 CXXRecordDecl *RD = MD->getParent();
4400 assert(!RD->isDependentType() && "do deletion after instantiation");
4401 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4404 SourceLocation Loc = MD->getLocation();
4406 // Do access control from the constructor
4407 ContextRAII MethodContext(*this, MD);
4409 bool Union = RD->isUnion();
4412 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4413 Qualifiers::Const : 0;
4415 // We do this because we should never actually use an anonymous
4416 // union's constructor.
4417 if (Union && RD->isAnonymousStructOrUnion())
4420 // FIXME: We should put some diagnostic logic right into this function.
4422 // C++0x [class.copy]/20
4423 // A defaulted [copy] assignment operator for class X is defined as deleted
4426 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4427 BE = RD->bases_end();
4429 // We'll handle this one later
4430 if (BI->isVirtual())
4433 QualType BaseType = BI->getType();
4434 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4435 assert(BaseDecl && "base isn't a CXXRecordDecl");
4437 // -- a [direct base class] B that cannot be [copied] because overload
4438 // resolution, as applied to B's [copy] assignment operator, results in
4439 // an ambiguity or a function that is deleted or inaccessible from the
4440 // assignment operator
4441 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4443 if (!CopyOper || CopyOper->isDeleted())
4445 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4449 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4450 BE = RD->vbases_end();
4452 QualType BaseType = BI->getType();
4453 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4454 assert(BaseDecl && "base isn't a CXXRecordDecl");
4456 // -- a [virtual base class] B that cannot be [copied] because overload
4457 // resolution, as applied to B's [copy] assignment operator, results in
4458 // an ambiguity or a function that is deleted or inaccessible from the
4459 // assignment operator
4460 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4462 if (!CopyOper || CopyOper->isDeleted())
4464 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4468 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4469 FE = RD->field_end();
4471 if (FI->isUnnamedBitfield())
4474 QualType FieldType = Context.getBaseElementType(FI->getType());
4476 // -- a non-static data member of reference type
4477 if (FieldType->isReferenceType())
4480 // -- a non-static data member of const non-class type (or array thereof)
4481 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4484 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4487 // This is an anonymous union
4488 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4489 // Anonymous unions inside unions do not variant members create
4491 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4492 UE = FieldRecord->field_end();
4494 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4495 CXXRecordDecl *UnionFieldRecord =
4496 UnionFieldType->getAsCXXRecordDecl();
4498 // -- a variant member with a non-trivial [copy] assignment operator
4499 // and X is a union-like class
4500 if (UnionFieldRecord &&
4501 !UnionFieldRecord->hasTrivialCopyAssignment())
4506 // Don't try to initalize an anonymous union
4508 // -- a variant member with a non-trivial [copy] assignment operator
4509 // and X is a union-like class
4510 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4514 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4516 if (!CopyOper || CopyOper->isDeleted())
4518 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
4526 bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4527 CXXRecordDecl *RD = MD->getParent();
4528 assert(!RD->isDependentType() && "do deletion after instantiation");
4529 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4532 SourceLocation Loc = MD->getLocation();
4534 // Do access control from the constructor
4535 ContextRAII MethodContext(*this, MD);
4537 bool Union = RD->isUnion();
4539 // We do this because we should never actually use an anonymous
4540 // union's constructor.
4541 if (Union && RD->isAnonymousStructOrUnion())
4544 // C++0x [class.copy]/20
4545 // A defaulted [move] assignment operator for class X is defined as deleted
4548 // -- for the move constructor, [...] any direct or indirect virtual base
4550 if (RD->getNumVBases() != 0)
4553 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4554 BE = RD->bases_end();
4557 QualType BaseType = BI->getType();
4558 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4559 assert(BaseDecl && "base isn't a CXXRecordDecl");
4561 // -- a [direct base class] B that cannot be [moved] because overload
4562 // resolution, as applied to B's [move] assignment operator, results in
4563 // an ambiguity or a function that is deleted or inaccessible from the
4564 // assignment operator
4565 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4566 if (!MoveOper || MoveOper->isDeleted())
4568 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4571 // -- for the move assignment operator, a [direct base class] with a type
4572 // that does not have a move assignment operator and is not trivially
4574 if (!MoveOper->isMoveAssignmentOperator() &&
4575 !BaseDecl->isTriviallyCopyable())
4579 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4580 FE = RD->field_end();
4582 if (FI->isUnnamedBitfield())
4585 QualType FieldType = Context.getBaseElementType(FI->getType());
4587 // -- a non-static data member of reference type
4588 if (FieldType->isReferenceType())
4591 // -- a non-static data member of const non-class type (or array thereof)
4592 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4595 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4598 // This is an anonymous union
4599 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4600 // Anonymous unions inside unions do not variant members create
4602 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4603 UE = FieldRecord->field_end();
4605 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4606 CXXRecordDecl *UnionFieldRecord =
4607 UnionFieldType->getAsCXXRecordDecl();
4609 // -- a variant member with a non-trivial [move] assignment operator
4610 // and X is a union-like class
4611 if (UnionFieldRecord &&
4612 !UnionFieldRecord->hasTrivialMoveAssignment())
4617 // Don't try to initalize an anonymous union
4619 // -- a variant member with a non-trivial [move] assignment operator
4620 // and X is a union-like class
4621 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4625 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4626 if (!MoveOper || MoveOper->isDeleted())
4628 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4631 // -- for the move assignment operator, a [non-static data member] with a
4632 // type that does not have a move assignment operator and is not
4633 // trivially copyable.
4634 if (!MoveOper->isMoveAssignmentOperator() &&
4635 !FieldRecord->isTriviallyCopyable())
4643 bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4644 CXXRecordDecl *RD = DD->getParent();
4645 assert(!RD->isDependentType() && "do deletion after instantiation");
4646 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4649 SourceLocation Loc = DD->getLocation();
4651 // Do access control from the destructor
4652 ContextRAII CtorContext(*this, DD);
4654 bool Union = RD->isUnion();
4656 // We do this because we should never actually use an anonymous
4657 // union's destructor.
4658 if (Union && RD->isAnonymousStructOrUnion())
4661 // C++0x [class.dtor]p5
4662 // A defaulted destructor for a class X is defined as deleted if:
4663 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4664 BE = RD->bases_end();
4666 // We'll handle this one later
4667 if (BI->isVirtual())
4670 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4671 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4672 assert(BaseDtor && "base has no destructor");
4674 // -- any direct or virtual base class has a deleted destructor or
4675 // a destructor that is inaccessible from the defaulted destructor
4676 if (BaseDtor->isDeleted())
4678 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4683 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4684 BE = RD->vbases_end();
4686 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4687 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4688 assert(BaseDtor && "base has no destructor");
4690 // -- any direct or virtual base class has a deleted destructor or
4691 // a destructor that is inaccessible from the defaulted destructor
4692 if (BaseDtor->isDeleted())
4694 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4699 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4700 FE = RD->field_end();
4702 QualType FieldType = Context.getBaseElementType(FI->getType());
4703 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4705 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4706 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4707 UE = FieldRecord->field_end();
4709 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4710 CXXRecordDecl *UnionFieldRecord =
4711 UnionFieldType->getAsCXXRecordDecl();
4713 // -- X is a union-like class that has a variant member with a non-
4714 // trivial destructor.
4715 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4718 // Technically we are supposed to do this next check unconditionally.
4719 // But that makes absolutely no sense.
4721 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4723 // -- any of the non-static data members has class type M (or array
4724 // thereof) and M has a deleted destructor or a destructor that is
4725 // inaccessible from the defaulted destructor
4726 if (FieldDtor->isDeleted())
4728 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4732 // -- X is a union-like class that has a variant member with a non-
4733 // trivial destructor.
4734 if (Union && !FieldDtor->isTrivial())
4740 if (DD->isVirtual()) {
4741 FunctionDecl *OperatorDelete = 0;
4742 DeclarationName Name =
4743 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4744 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
4753 /// \brief Data used with FindHiddenVirtualMethod
4755 struct FindHiddenVirtualMethodData {
4757 CXXMethodDecl *Method;
4758 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4759 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4763 /// \brief Member lookup function that determines whether a given C++
4764 /// method overloads virtual methods in a base class without overriding any,
4765 /// to be used with CXXRecordDecl::lookupInBases().
4766 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4769 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4771 FindHiddenVirtualMethodData &Data
4772 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4774 DeclarationName Name = Data.Method->getDeclName();
4775 assert(Name.getNameKind() == DeclarationName::Identifier);
4777 bool foundSameNameMethod = false;
4778 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4779 for (Path.Decls = BaseRecord->lookup(Name);
4780 Path.Decls.first != Path.Decls.second;
4781 ++Path.Decls.first) {
4782 NamedDecl *D = *Path.Decls.first;
4783 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4784 MD = MD->getCanonicalDecl();
4785 foundSameNameMethod = true;
4786 // Interested only in hidden virtual methods.
4787 if (!MD->isVirtual())
4789 // If the method we are checking overrides a method from its base
4790 // don't warn about the other overloaded methods.
4791 if (!Data.S->IsOverload(Data.Method, MD, false))
4793 // Collect the overload only if its hidden.
4794 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4795 overloadedMethods.push_back(MD);
4799 if (foundSameNameMethod)
4800 Data.OverloadedMethods.append(overloadedMethods.begin(),
4801 overloadedMethods.end());
4802 return foundSameNameMethod;
4805 /// \brief See if a method overloads virtual methods in a base class without
4807 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4808 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4809 MD->getLocation()) == DiagnosticsEngine::Ignored)
4811 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4814 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4815 /*bool RecordPaths=*/false,
4816 /*bool DetectVirtual=*/false);
4817 FindHiddenVirtualMethodData Data;
4821 // Keep the base methods that were overriden or introduced in the subclass
4822 // by 'using' in a set. A base method not in this set is hidden.
4823 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4824 res.first != res.second; ++res.first) {
4825 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4826 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4827 E = MD->end_overridden_methods();
4829 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4830 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4831 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4832 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4835 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4836 !Data.OverloadedMethods.empty()) {
4837 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4838 << MD << (Data.OverloadedMethods.size() > 1);
4840 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4841 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4842 Diag(overloadedMD->getLocation(),
4843 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4848 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4850 SourceLocation LBrac,
4851 SourceLocation RBrac,
4852 AttributeList *AttrList) {
4856 AdjustDeclIfTemplate(TagDecl);
4858 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
4859 // strict aliasing violation!
4860 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4861 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
4863 CheckCompletedCXXClass(
4864 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4867 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4868 /// special functions, such as the default constructor, copy
4869 /// constructor, or destructor, to the given C++ class (C++
4870 /// [special]p1). This routine can only be executed just before the
4871 /// definition of the class is complete.
4872 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4873 if (!ClassDecl->hasUserDeclaredConstructor())
4874 ++ASTContext::NumImplicitDefaultConstructors;
4876 if (!ClassDecl->hasUserDeclaredCopyConstructor())
4877 ++ASTContext::NumImplicitCopyConstructors;
4879 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4880 ++ASTContext::NumImplicitCopyAssignmentOperators;
4882 // If we have a dynamic class, then the copy assignment operator may be
4883 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4884 // it shows up in the right place in the vtable and that we diagnose
4885 // problems with the implicit exception specification.
4886 if (ClassDecl->isDynamicClass())
4887 DeclareImplicitCopyAssignment(ClassDecl);
4890 if (!ClassDecl->hasUserDeclaredDestructor()) {
4891 ++ASTContext::NumImplicitDestructors;
4893 // If we have a dynamic class, then the destructor may be virtual, so we
4894 // have to declare the destructor immediately. This ensures that, e.g., it
4895 // shows up in the right place in the vtable and that we diagnose problems
4896 // with the implicit exception specification.
4897 if (ClassDecl->isDynamicClass())
4898 DeclareImplicitDestructor(ClassDecl);
4902 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4906 int NumParamList = D->getNumTemplateParameterLists();
4907 for (int i = 0; i < NumParamList; i++) {
4908 TemplateParameterList* Params = D->getTemplateParameterList(i);
4909 for (TemplateParameterList::iterator Param = Params->begin(),
4910 ParamEnd = Params->end();
4911 Param != ParamEnd; ++Param) {
4912 NamedDecl *Named = cast<NamedDecl>(*Param);
4913 if (Named->getDeclName()) {
4915 IdResolver.AddDecl(Named);
4921 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4925 TemplateParameterList *Params = 0;
4926 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4927 Params = Template->getTemplateParameters();
4928 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4929 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4930 Params = PartialSpec->getTemplateParameters();
4934 for (TemplateParameterList::iterator Param = Params->begin(),
4935 ParamEnd = Params->end();
4936 Param != ParamEnd; ++Param) {
4937 NamedDecl *Named = cast<NamedDecl>(*Param);
4938 if (Named->getDeclName()) {
4940 IdResolver.AddDecl(Named);
4945 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4946 if (!RecordD) return;
4947 AdjustDeclIfTemplate(RecordD);
4948 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4949 PushDeclContext(S, Record);
4952 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4953 if (!RecordD) return;
4957 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
4958 /// parsing a top-level (non-nested) C++ class, and we are now
4959 /// parsing those parts of the given Method declaration that could
4960 /// not be parsed earlier (C++ [class.mem]p2), such as default
4961 /// arguments. This action should enter the scope of the given
4962 /// Method declaration as if we had just parsed the qualified method
4963 /// name. However, it should not bring the parameters into scope;
4964 /// that will be performed by ActOnDelayedCXXMethodParameter.
4965 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4968 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
4969 /// C++ method declaration. We're (re-)introducing the given
4970 /// function parameter into scope for use in parsing later parts of
4971 /// the method declaration. For example, we could see an
4972 /// ActOnParamDefaultArgument event for this parameter.
4973 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4977 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4979 // If this parameter has an unparsed default argument, clear it out
4980 // to make way for the parsed default argument.
4981 if (Param->hasUnparsedDefaultArg())
4982 Param->setDefaultArg(0);
4985 if (Param->getDeclName())
4986 IdResolver.AddDecl(Param);
4989 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4990 /// processing the delayed method declaration for Method. The method
4991 /// declaration is now considered finished. There may be a separate
4992 /// ActOnStartOfFunctionDef action later (not necessarily
4993 /// immediately!) for this method, if it was also defined inside the
4995 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4999 AdjustDeclIfTemplate(MethodD);
5001 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
5003 // Now that we have our default arguments, check the constructor
5004 // again. It could produce additional diagnostics or affect whether
5005 // the class has implicitly-declared destructors, among other
5007 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5008 CheckConstructor(Constructor);
5010 // Check the default arguments, which we may have added.
5011 if (!Method->isInvalidDecl())
5012 CheckCXXDefaultArguments(Method);
5015 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
5016 /// the well-formedness of the constructor declarator @p D with type @p
5017 /// R. If there are any errors in the declarator, this routine will
5018 /// emit diagnostics and set the invalid bit to true. In any case, the type
5019 /// will be updated to reflect a well-formed type for the constructor and
5021 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
5023 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
5025 // C++ [class.ctor]p3:
5026 // A constructor shall not be virtual (10.3) or static (9.4). A
5027 // constructor can be invoked for a const, volatile or const
5028 // volatile object. A constructor shall not be declared const,
5029 // volatile, or const volatile (9.3.2).
5031 if (!D.isInvalidType())
5032 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5033 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5034 << SourceRange(D.getIdentifierLoc());
5037 if (SC == SC_Static) {
5038 if (!D.isInvalidType())
5039 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5040 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5041 << SourceRange(D.getIdentifierLoc());
5046 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5047 if (FTI.TypeQuals != 0) {
5048 if (FTI.TypeQuals & Qualifiers::Const)
5049 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5050 << "const" << SourceRange(D.getIdentifierLoc());
5051 if (FTI.TypeQuals & Qualifiers::Volatile)
5052 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5053 << "volatile" << SourceRange(D.getIdentifierLoc());
5054 if (FTI.TypeQuals & Qualifiers::Restrict)
5055 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5056 << "restrict" << SourceRange(D.getIdentifierLoc());
5060 // C++0x [class.ctor]p4:
5061 // A constructor shall not be declared with a ref-qualifier.
5062 if (FTI.hasRefQualifier()) {
5063 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5064 << FTI.RefQualifierIsLValueRef
5065 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5069 // Rebuild the function type "R" without any type qualifiers (in
5070 // case any of the errors above fired) and with "void" as the
5071 // return type, since constructors don't have return types.
5072 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5073 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5076 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5078 EPI.RefQualifier = RQ_None;
5080 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
5081 Proto->getNumArgs(), EPI);
5084 /// CheckConstructor - Checks a fully-formed constructor for
5085 /// well-formedness, issuing any diagnostics required. Returns true if
5086 /// the constructor declarator is invalid.
5087 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
5088 CXXRecordDecl *ClassDecl
5089 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5091 return Constructor->setInvalidDecl();
5093 // C++ [class.copy]p3:
5094 // A declaration of a constructor for a class X is ill-formed if
5095 // its first parameter is of type (optionally cv-qualified) X and
5096 // either there are no other parameters or else all other
5097 // parameters have default arguments.
5098 if (!Constructor->isInvalidDecl() &&
5099 ((Constructor->getNumParams() == 1) ||
5100 (Constructor->getNumParams() > 1 &&
5101 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5102 Constructor->getTemplateSpecializationKind()
5103 != TSK_ImplicitInstantiation) {
5104 QualType ParamType = Constructor->getParamDecl(0)->getType();
5105 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5106 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
5107 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
5108 const char *ConstRef
5109 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5111 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
5112 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
5114 // FIXME: Rather that making the constructor invalid, we should endeavor
5116 Constructor->setInvalidDecl();
5121 /// CheckDestructor - Checks a fully-formed destructor definition for
5122 /// well-formedness, issuing any diagnostics required. Returns true
5124 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
5125 CXXRecordDecl *RD = Destructor->getParent();
5127 if (Destructor->isVirtual()) {
5130 if (!Destructor->isImplicit())
5131 Loc = Destructor->getLocation();
5133 Loc = RD->getLocation();
5135 // If we have a virtual destructor, look up the deallocation function
5136 FunctionDecl *OperatorDelete = 0;
5137 DeclarationName Name =
5138 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
5139 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
5142 MarkDeclarationReferenced(Loc, OperatorDelete);
5144 Destructor->setOperatorDelete(OperatorDelete);
5151 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5152 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5153 FTI.ArgInfo[0].Param &&
5154 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
5157 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5158 /// the well-formednes of the destructor declarator @p D with type @p
5159 /// R. If there are any errors in the declarator, this routine will
5160 /// emit diagnostics and set the declarator to invalid. Even if this happens,
5161 /// will be updated to reflect a well-formed type for the destructor and
5163 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
5165 // C++ [class.dtor]p1:
5166 // [...] A typedef-name that names a class is a class-name
5167 // (7.1.3); however, a typedef-name that names a class shall not
5168 // be used as the identifier in the declarator for a destructor
5170 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
5171 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
5172 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5173 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
5174 else if (const TemplateSpecializationType *TST =
5175 DeclaratorType->getAs<TemplateSpecializationType>())
5176 if (TST->isTypeAlias())
5177 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5178 << DeclaratorType << 1;
5180 // C++ [class.dtor]p2:
5181 // A destructor is used to destroy objects of its class type. A
5182 // destructor takes no parameters, and no return type can be
5183 // specified for it (not even void). The address of a destructor
5184 // shall not be taken. A destructor shall not be static. A
5185 // destructor can be invoked for a const, volatile or const
5186 // volatile object. A destructor shall not be declared const,
5187 // volatile or const volatile (9.3.2).
5188 if (SC == SC_Static) {
5189 if (!D.isInvalidType())
5190 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5191 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5192 << SourceRange(D.getIdentifierLoc())
5193 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5197 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5198 // Destructors don't have return types, but the parser will
5199 // happily parse something like:
5205 // The return type will be eliminated later.
5206 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5207 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5208 << SourceRange(D.getIdentifierLoc());
5211 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5212 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
5213 if (FTI.TypeQuals & Qualifiers::Const)
5214 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5215 << "const" << SourceRange(D.getIdentifierLoc());
5216 if (FTI.TypeQuals & Qualifiers::Volatile)
5217 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5218 << "volatile" << SourceRange(D.getIdentifierLoc());
5219 if (FTI.TypeQuals & Qualifiers::Restrict)
5220 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5221 << "restrict" << SourceRange(D.getIdentifierLoc());
5225 // C++0x [class.dtor]p2:
5226 // A destructor shall not be declared with a ref-qualifier.
5227 if (FTI.hasRefQualifier()) {
5228 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5229 << FTI.RefQualifierIsLValueRef
5230 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5234 // Make sure we don't have any parameters.
5235 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
5236 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5238 // Delete the parameters.
5243 // Make sure the destructor isn't variadic.
5244 if (FTI.isVariadic) {
5245 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
5249 // Rebuild the function type "R" without any type qualifiers or
5250 // parameters (in case any of the errors above fired) and with
5251 // "void" as the return type, since destructors don't have return
5253 if (!D.isInvalidType())
5256 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5257 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5258 EPI.Variadic = false;
5260 EPI.RefQualifier = RQ_None;
5261 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
5264 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5265 /// well-formednes of the conversion function declarator @p D with
5266 /// type @p R. If there are any errors in the declarator, this routine
5267 /// will emit diagnostics and return true. Otherwise, it will return
5268 /// false. Either way, the type @p R will be updated to reflect a
5269 /// well-formed type for the conversion operator.
5270 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
5272 // C++ [class.conv.fct]p1:
5273 // Neither parameter types nor return type can be specified. The
5274 // type of a conversion function (8.3.5) is "function taking no
5275 // parameter returning conversion-type-id."
5276 if (SC == SC_Static) {
5277 if (!D.isInvalidType())
5278 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5279 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5280 << SourceRange(D.getIdentifierLoc());
5285 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5287 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
5288 // Conversion functions don't have return types, but the parser will
5289 // happily parse something like:
5292 // float operator bool();
5295 // The return type will be changed later anyway.
5296 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5297 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5298 << SourceRange(D.getIdentifierLoc());
5302 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5304 // Make sure we don't have any parameters.
5305 if (Proto->getNumArgs() > 0) {
5306 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5308 // Delete the parameters.
5309 D.getFunctionTypeInfo().freeArgs();
5311 } else if (Proto->isVariadic()) {
5312 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
5316 // Diagnose "&operator bool()" and other such nonsense. This
5317 // is actually a gcc extension which we don't support.
5318 if (Proto->getResultType() != ConvType) {
5319 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5320 << Proto->getResultType();
5322 ConvType = Proto->getResultType();
5325 // C++ [class.conv.fct]p4:
5326 // The conversion-type-id shall not represent a function type nor
5328 if (ConvType->isArrayType()) {
5329 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5330 ConvType = Context.getPointerType(ConvType);
5332 } else if (ConvType->isFunctionType()) {
5333 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5334 ConvType = Context.getPointerType(ConvType);
5338 // Rebuild the function type "R" without any parameters (in case any
5339 // of the errors above fired) and with the conversion type as the
5341 if (D.isInvalidType())
5342 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
5344 // C++0x explicit conversion operators.
5345 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
5346 Diag(D.getDeclSpec().getExplicitSpecLoc(),
5347 diag::warn_explicit_conversion_functions)
5348 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
5351 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5352 /// the declaration of the given C++ conversion function. This routine
5353 /// is responsible for recording the conversion function in the C++
5354 /// class, if possible.
5355 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
5356 assert(Conversion && "Expected to receive a conversion function declaration");
5358 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
5360 // Make sure we aren't redeclaring the conversion function.
5361 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
5363 // C++ [class.conv.fct]p1:
5364 // [...] A conversion function is never used to convert a
5365 // (possibly cv-qualified) object to the (possibly cv-qualified)
5366 // same object type (or a reference to it), to a (possibly
5367 // cv-qualified) base class of that type (or a reference to it),
5368 // or to (possibly cv-qualified) void.
5369 // FIXME: Suppress this warning if the conversion function ends up being a
5370 // virtual function that overrides a virtual function in a base class.
5372 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
5373 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
5374 ConvType = ConvTypeRef->getPointeeType();
5375 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5376 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5377 /* Suppress diagnostics for instantiations. */;
5378 else if (ConvType->isRecordType()) {
5379 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5380 if (ConvType == ClassType)
5381 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
5383 else if (IsDerivedFrom(ClassType, ConvType))
5384 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
5385 << ClassType << ConvType;
5386 } else if (ConvType->isVoidType()) {
5387 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
5388 << ClassType << ConvType;
5391 if (FunctionTemplateDecl *ConversionTemplate
5392 = Conversion->getDescribedFunctionTemplate())
5393 return ConversionTemplate;
5398 //===----------------------------------------------------------------------===//
5399 // Namespace Handling
5400 //===----------------------------------------------------------------------===//
5404 /// ActOnStartNamespaceDef - This is called at the start of a namespace
5406 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
5407 SourceLocation InlineLoc,
5408 SourceLocation NamespaceLoc,
5409 SourceLocation IdentLoc,
5411 SourceLocation LBrace,
5412 AttributeList *AttrList) {
5413 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5414 // For anonymous namespace, take the location of the left brace.
5415 SourceLocation Loc = II ? IdentLoc : LBrace;
5416 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
5418 Namespc->setInline(InlineLoc.isValid());
5420 Scope *DeclRegionScope = NamespcScope->getParent();
5422 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
5424 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
5425 PushNamespaceVisibilityAttr(Attr);
5428 // C++ [namespace.def]p2:
5429 // The identifier in an original-namespace-definition shall not
5430 // have been previously defined in the declarative region in
5431 // which the original-namespace-definition appears. The
5432 // identifier in an original-namespace-definition is the name of
5433 // the namespace. Subsequently in that declarative region, it is
5434 // treated as an original-namespace-name.
5436 // Since namespace names are unique in their scope, and we don't
5437 // look through using directives, just look for any ordinary names.
5439 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
5440 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5441 Decl::IDNS_Namespace;
5442 NamedDecl *PrevDecl = 0;
5443 for (DeclContext::lookup_result R
5444 = CurContext->getRedeclContext()->lookup(II);
5445 R.first != R.second; ++R.first) {
5446 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5447 PrevDecl = *R.first;
5452 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
5453 // This is an extended namespace definition.
5454 if (Namespc->isInline() != OrigNS->isInline()) {
5455 // inline-ness must match
5456 if (OrigNS->isInline()) {
5457 // The user probably just forgot the 'inline', so suggest that it
5459 Diag(Namespc->getLocation(),
5460 diag::warn_inline_namespace_reopened_noninline)
5461 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5463 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5464 << Namespc->isInline();
5466 Diag(OrigNS->getLocation(), diag::note_previous_definition);
5468 // Recover by ignoring the new namespace's inline status.
5469 Namespc->setInline(OrigNS->isInline());
5472 // Attach this namespace decl to the chain of extended namespace
5474 OrigNS->setNextNamespace(Namespc);
5475 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
5477 // Remove the previous declaration from the scope.
5478 if (DeclRegionScope->isDeclScope(OrigNS)) {
5479 IdResolver.RemoveDecl(OrigNS);
5480 DeclRegionScope->RemoveDecl(OrigNS);
5482 } else if (PrevDecl) {
5483 // This is an invalid name redefinition.
5484 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
5485 << Namespc->getDeclName();
5486 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5487 Namespc->setInvalidDecl();
5488 // Continue on to push Namespc as current DeclContext and return it.
5489 } else if (II->isStr("std") &&
5490 CurContext->getRedeclContext()->isTranslationUnit()) {
5491 // This is the first "real" definition of the namespace "std", so update
5492 // our cache of the "std" namespace to point at this definition.
5493 if (NamespaceDecl *StdNS = getStdNamespace()) {
5494 // We had already defined a dummy namespace "std". Link this new
5495 // namespace definition to the dummy namespace "std".
5496 StdNS->setNextNamespace(Namespc);
5497 StdNS->setLocation(IdentLoc);
5498 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
5501 // Make our StdNamespace cache point at the first real definition of the
5503 StdNamespace = Namespc;
5505 // Add this instance of "std" to the set of known namespaces
5506 KnownNamespaces[Namespc] = false;
5507 } else if (!Namespc->isInline()) {
5508 // Since this is an "original" namespace, add it to the known set of
5509 // namespaces if it is not an inline namespace.
5510 KnownNamespaces[Namespc] = false;
5513 PushOnScopeChains(Namespc, DeclRegionScope);
5515 // Anonymous namespaces.
5516 assert(Namespc->isAnonymousNamespace());
5518 // Link the anonymous namespace into its parent.
5519 NamespaceDecl *PrevDecl;
5520 DeclContext *Parent = CurContext->getRedeclContext();
5521 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5522 PrevDecl = TU->getAnonymousNamespace();
5523 TU->setAnonymousNamespace(Namespc);
5525 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
5526 PrevDecl = ND->getAnonymousNamespace();
5527 ND->setAnonymousNamespace(Namespc);
5530 // Link the anonymous namespace with its previous declaration.
5532 assert(PrevDecl->isAnonymousNamespace());
5533 assert(!PrevDecl->getNextNamespace());
5534 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
5535 PrevDecl->setNextNamespace(Namespc);
5537 if (Namespc->isInline() != PrevDecl->isInline()) {
5538 // inline-ness must match
5539 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
5540 << Namespc->isInline();
5541 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5542 Namespc->setInvalidDecl();
5543 // Recover by ignoring the new namespace's inline status.
5544 Namespc->setInline(PrevDecl->isInline());
5548 CurContext->addDecl(Namespc);
5550 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5551 // behaves as if it were replaced by
5552 // namespace unique { /* empty body */ }
5553 // using namespace unique;
5554 // namespace unique { namespace-body }
5555 // where all occurrences of 'unique' in a translation unit are
5556 // replaced by the same identifier and this identifier differs
5557 // from all other identifiers in the entire program.
5559 // We just create the namespace with an empty name and then add an
5560 // implicit using declaration, just like the standard suggests.
5562 // CodeGen enforces the "universally unique" aspect by giving all
5563 // declarations semantically contained within an anonymous
5564 // namespace internal linkage.
5567 UsingDirectiveDecl* UD
5568 = UsingDirectiveDecl::Create(Context, CurContext,
5569 /* 'using' */ LBrace,
5570 /* 'namespace' */ SourceLocation(),
5571 /* qualifier */ NestedNameSpecifierLoc(),
5572 /* identifier */ SourceLocation(),
5574 /* Ancestor */ CurContext);
5576 CurContext->addDecl(UD);
5580 // Although we could have an invalid decl (i.e. the namespace name is a
5581 // redefinition), push it as current DeclContext and try to continue parsing.
5582 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5583 // for the namespace has the declarations that showed up in that particular
5584 // namespace definition.
5585 PushDeclContext(NamespcScope, Namespc);
5589 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5590 /// is a namespace alias, returns the namespace it points to.
5591 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5592 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5593 return AD->getNamespace();
5594 return dyn_cast_or_null<NamespaceDecl>(D);
5597 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
5598 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
5599 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
5600 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5601 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
5602 Namespc->setRBraceLoc(RBrace);
5604 if (Namespc->hasAttr<VisibilityAttr>())
5605 PopPragmaVisibility();
5608 CXXRecordDecl *Sema::getStdBadAlloc() const {
5609 return cast_or_null<CXXRecordDecl>(
5610 StdBadAlloc.get(Context.getExternalSource()));
5613 NamespaceDecl *Sema::getStdNamespace() const {
5614 return cast_or_null<NamespaceDecl>(
5615 StdNamespace.get(Context.getExternalSource()));
5618 /// \brief Retrieve the special "std" namespace, which may require us to
5619 /// implicitly define the namespace.
5620 NamespaceDecl *Sema::getOrCreateStdNamespace() {
5621 if (!StdNamespace) {
5622 // The "std" namespace has not yet been defined, so build one implicitly.
5623 StdNamespace = NamespaceDecl::Create(Context,
5624 Context.getTranslationUnitDecl(),
5625 SourceLocation(), SourceLocation(),
5626 &PP.getIdentifierTable().get("std"));
5627 getStdNamespace()->setImplicit(true);
5630 return getStdNamespace();
5633 /// \brief Determine whether a using statement is in a context where it will be
5634 /// apply in all contexts.
5635 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5636 switch (CurContext->getDeclKind()) {
5637 case Decl::TranslationUnit:
5639 case Decl::LinkageSpec:
5640 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5646 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5648 SourceLocation IdentLoc,
5649 IdentifierInfo *Ident) {
5651 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
5652 R.getLookupKind(), Sc, &SS, NULL,
5653 false, S.CTC_NoKeywords, NULL)) {
5654 if (Corrected.getCorrectionDeclAs<NamespaceDecl>() ||
5655 Corrected.getCorrectionDeclAs<NamespaceAliasDecl>()) {
5656 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5657 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5658 if (DeclContext *DC = S.computeDeclContext(SS, false))
5659 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5660 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5661 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5663 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5664 << Ident << CorrectedQuotedStr
5665 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5667 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5668 diag::note_namespace_defined_here) << CorrectedQuotedStr;
5670 Ident = Corrected.getCorrectionAsIdentifierInfo();
5671 R.addDecl(Corrected.getCorrectionDecl());
5674 R.setLookupName(Ident);
5679 Decl *Sema::ActOnUsingDirective(Scope *S,
5680 SourceLocation UsingLoc,
5681 SourceLocation NamespcLoc,
5683 SourceLocation IdentLoc,
5684 IdentifierInfo *NamespcName,
5685 AttributeList *AttrList) {
5686 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5687 assert(NamespcName && "Invalid NamespcName.");
5688 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
5690 // This can only happen along a recovery path.
5691 while (S->getFlags() & Scope::TemplateParamScope)
5693 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5695 UsingDirectiveDecl *UDir = 0;
5696 NestedNameSpecifier *Qualifier = 0;
5698 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5700 // Lookup namespace name.
5701 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
5702 LookupParsedName(R, S, &SS);
5703 if (R.isAmbiguous())
5708 // Allow "using namespace std;" or "using namespace ::std;" even if
5709 // "std" hasn't been defined yet, for GCC compatibility.
5710 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
5711 NamespcName->isStr("std")) {
5712 Diag(IdentLoc, diag::ext_using_undefined_std);
5713 R.addDecl(getOrCreateStdNamespace());
5716 // Otherwise, attempt typo correction.
5717 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
5721 NamedDecl *Named = R.getFoundDecl();
5722 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5723 && "expected namespace decl");
5724 // C++ [namespace.udir]p1:
5725 // A using-directive specifies that the names in the nominated
5726 // namespace can be used in the scope in which the
5727 // using-directive appears after the using-directive. During
5728 // unqualified name lookup (3.4.1), the names appear as if they
5729 // were declared in the nearest enclosing namespace which
5730 // contains both the using-directive and the nominated
5731 // namespace. [Note: in this context, "contains" means "contains
5732 // directly or indirectly". ]
5734 // Find enclosing context containing both using-directive and
5735 // nominated namespace.
5736 NamespaceDecl *NS = getNamespaceDecl(Named);
5737 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5738 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5739 CommonAncestor = CommonAncestor->getParent();
5741 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5742 SS.getWithLocInContext(Context),
5743 IdentLoc, Named, CommonAncestor);
5745 if (IsUsingDirectiveInToplevelContext(CurContext) &&
5746 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
5747 Diag(IdentLoc, diag::warn_using_directive_in_header);
5750 PushUsingDirective(S, UDir);
5752 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5755 // FIXME: We ignore attributes for now.
5759 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5760 // If scope has associated entity, then using directive is at namespace
5761 // or translation unit scope. We add UsingDirectiveDecls, into
5762 // it's lookup structure.
5763 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
5766 // Otherwise it is block-sope. using-directives will affect lookup
5767 // only to the end of scope.
5768 S->PushUsingDirective(UDir);
5772 Decl *Sema::ActOnUsingDeclaration(Scope *S,
5774 bool HasUsingKeyword,
5775 SourceLocation UsingLoc,
5777 UnqualifiedId &Name,
5778 AttributeList *AttrList,
5780 SourceLocation TypenameLoc) {
5781 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5783 switch (Name.getKind()) {
5784 case UnqualifiedId::IK_ImplicitSelfParam:
5785 case UnqualifiedId::IK_Identifier:
5786 case UnqualifiedId::IK_OperatorFunctionId:
5787 case UnqualifiedId::IK_LiteralOperatorId:
5788 case UnqualifiedId::IK_ConversionFunctionId:
5791 case UnqualifiedId::IK_ConstructorName:
5792 case UnqualifiedId::IK_ConstructorTemplateId:
5793 // C++0x inherited constructors.
5794 if (getLangOptions().CPlusPlus0x) break;
5796 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5800 case UnqualifiedId::IK_DestructorName:
5801 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5805 case UnqualifiedId::IK_TemplateId:
5806 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5807 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5811 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5812 DeclarationName TargetName = TargetNameInfo.getName();
5816 // Warn about using declarations.
5817 // TODO: store that the declaration was written without 'using' and
5818 // talk about access decls instead of using decls in the
5820 if (!HasUsingKeyword) {
5821 UsingLoc = Name.getSourceRange().getBegin();
5823 Diag(UsingLoc, diag::warn_access_decl_deprecated)
5824 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5827 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5828 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5831 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5832 TargetNameInfo, AttrList,
5833 /* IsInstantiation */ false,
5834 IsTypeName, TypenameLoc);
5836 PushOnScopeChains(UD, S, /*AddToContext*/ false);
5841 /// \brief Determine whether a using declaration considers the given
5842 /// declarations as "equivalent", e.g., if they are redeclarations of
5843 /// the same entity or are both typedefs of the same type.
5845 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5846 bool &SuppressRedeclaration) {
5847 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5848 SuppressRedeclaration = false;
5852 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5853 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5854 SuppressRedeclaration = true;
5855 return Context.hasSameType(TD1->getUnderlyingType(),
5856 TD2->getUnderlyingType());
5863 /// Determines whether to create a using shadow decl for a particular
5864 /// decl, given the set of decls existing prior to this using lookup.
5865 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5866 const LookupResult &Previous) {
5867 // Diagnose finding a decl which is not from a base class of the
5868 // current class. We do this now because there are cases where this
5869 // function will silently decide not to build a shadow decl, which
5870 // will pre-empt further diagnostics.
5872 // We don't need to do this in C++0x because we do the check once on
5875 // FIXME: diagnose the following if we care enough:
5876 // struct A { int foo; };
5877 // struct B : A { using A::foo; };
5878 // template <class T> struct C : A {};
5879 // template <class T> struct D : C<T> { using B::foo; } // <---
5880 // This is invalid (during instantiation) in C++03 because B::foo
5881 // resolves to the using decl in B, which is not a base class of D<T>.
5882 // We can't diagnose it immediately because C<T> is an unknown
5883 // specialization. The UsingShadowDecl in D<T> then points directly
5884 // to A::foo, which will look well-formed when we instantiate.
5885 // The right solution is to not collapse the shadow-decl chain.
5886 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5887 DeclContext *OrigDC = Orig->getDeclContext();
5889 // Handle enums and anonymous structs.
5890 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5891 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5892 while (OrigRec->isAnonymousStructOrUnion())
5893 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5895 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5896 if (OrigDC == CurContext) {
5897 Diag(Using->getLocation(),
5898 diag::err_using_decl_nested_name_specifier_is_current_class)
5899 << Using->getQualifierLoc().getSourceRange();
5900 Diag(Orig->getLocation(), diag::note_using_decl_target);
5904 Diag(Using->getQualifierLoc().getBeginLoc(),
5905 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5906 << Using->getQualifier()
5907 << cast<CXXRecordDecl>(CurContext)
5908 << Using->getQualifierLoc().getSourceRange();
5909 Diag(Orig->getLocation(), diag::note_using_decl_target);
5914 if (Previous.empty()) return false;
5916 NamedDecl *Target = Orig;
5917 if (isa<UsingShadowDecl>(Target))
5918 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5920 // If the target happens to be one of the previous declarations, we
5921 // don't have a conflict.
5923 // FIXME: but we might be increasing its access, in which case we
5924 // should redeclare it.
5925 NamedDecl *NonTag = 0, *Tag = 0;
5926 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5928 NamedDecl *D = (*I)->getUnderlyingDecl();
5930 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5933 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5936 if (Target->isFunctionOrFunctionTemplate()) {
5938 if (isa<FunctionTemplateDecl>(Target))
5939 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5941 FD = cast<FunctionDecl>(Target);
5943 NamedDecl *OldDecl = 0;
5944 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5948 case Ovl_NonFunction:
5949 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5952 // We found a decl with the exact signature.
5954 // If we're in a record, we want to hide the target, so we
5955 // return true (without a diagnostic) to tell the caller not to
5956 // build a shadow decl.
5957 if (CurContext->isRecord())
5960 // If we're not in a record, this is an error.
5961 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5965 Diag(Target->getLocation(), diag::note_using_decl_target);
5966 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5970 // Target is not a function.
5972 if (isa<TagDecl>(Target)) {
5973 // No conflict between a tag and a non-tag.
5974 if (!Tag) return false;
5976 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5977 Diag(Target->getLocation(), diag::note_using_decl_target);
5978 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5982 // No conflict between a tag and a non-tag.
5983 if (!NonTag) return false;
5985 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5986 Diag(Target->getLocation(), diag::note_using_decl_target);
5987 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5991 /// Builds a shadow declaration corresponding to a 'using' declaration.
5992 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5996 // If we resolved to another shadow declaration, just coalesce them.
5997 NamedDecl *Target = Orig;
5998 if (isa<UsingShadowDecl>(Target)) {
5999 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6000 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
6003 UsingShadowDecl *Shadow
6004 = UsingShadowDecl::Create(Context, CurContext,
6005 UD->getLocation(), UD, Target);
6006 UD->addShadowDecl(Shadow);
6008 Shadow->setAccess(UD->getAccess());
6009 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6010 Shadow->setInvalidDecl();
6013 PushOnScopeChains(Shadow, S);
6015 CurContext->addDecl(Shadow);
6021 /// Hides a using shadow declaration. This is required by the current
6022 /// using-decl implementation when a resolvable using declaration in a
6023 /// class is followed by a declaration which would hide or override
6024 /// one or more of the using decl's targets; for example:
6026 /// struct Base { void foo(int); };
6027 /// struct Derived : Base {
6028 /// using Base::foo;
6032 /// The governing language is C++03 [namespace.udecl]p12:
6034 /// When a using-declaration brings names from a base class into a
6035 /// derived class scope, member functions in the derived class
6036 /// override and/or hide member functions with the same name and
6037 /// parameter types in a base class (rather than conflicting).
6039 /// There are two ways to implement this:
6040 /// (1) optimistically create shadow decls when they're not hidden
6041 /// by existing declarations, or
6042 /// (2) don't create any shadow decls (or at least don't make them
6043 /// visible) until we've fully parsed/instantiated the class.
6044 /// The problem with (1) is that we might have to retroactively remove
6045 /// a shadow decl, which requires several O(n) operations because the
6046 /// decl structures are (very reasonably) not designed for removal.
6047 /// (2) avoids this but is very fiddly and phase-dependent.
6048 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
6049 if (Shadow->getDeclName().getNameKind() ==
6050 DeclarationName::CXXConversionFunctionName)
6051 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6053 // Remove it from the DeclContext...
6054 Shadow->getDeclContext()->removeDecl(Shadow);
6056 // ...and the scope, if applicable...
6058 S->RemoveDecl(Shadow);
6059 IdResolver.RemoveDecl(Shadow);
6062 // ...and the using decl.
6063 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6065 // TODO: complain somehow if Shadow was used. It shouldn't
6066 // be possible for this to happen, because...?
6069 /// Builds a using declaration.
6071 /// \param IsInstantiation - Whether this call arises from an
6072 /// instantiation of an unresolved using declaration. We treat
6073 /// the lookup differently for these declarations.
6074 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6075 SourceLocation UsingLoc,
6077 const DeclarationNameInfo &NameInfo,
6078 AttributeList *AttrList,
6079 bool IsInstantiation,
6081 SourceLocation TypenameLoc) {
6082 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
6083 SourceLocation IdentLoc = NameInfo.getLoc();
6084 assert(IdentLoc.isValid() && "Invalid TargetName location.");
6086 // FIXME: We ignore attributes for now.
6089 Diag(IdentLoc, diag::err_using_requires_qualname);
6093 // Do the redeclaration lookup in the current scope.
6094 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
6096 Previous.setHideTags(false);
6098 LookupName(Previous, S);
6100 // It is really dumb that we have to do this.
6101 LookupResult::Filter F = Previous.makeFilter();
6102 while (F.hasNext()) {
6103 NamedDecl *D = F.next();
6104 if (!isDeclInScope(D, CurContext, S))
6109 assert(IsInstantiation && "no scope in non-instantiation");
6110 assert(CurContext->isRecord() && "scope not record in instantiation");
6111 LookupQualifiedName(Previous, CurContext);
6114 // Check for invalid redeclarations.
6115 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6118 // Check for bad qualifiers.
6119 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6122 DeclContext *LookupContext = computeDeclContext(SS);
6124 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6125 if (!LookupContext) {
6127 // FIXME: not all declaration name kinds are legal here
6128 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6129 UsingLoc, TypenameLoc,
6131 IdentLoc, NameInfo.getName());
6133 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6134 QualifierLoc, NameInfo);
6137 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6138 NameInfo, IsTypeName);
6141 CurContext->addDecl(D);
6143 if (!LookupContext) return D;
6144 UsingDecl *UD = cast<UsingDecl>(D);
6146 if (RequireCompleteDeclContext(SS, LookupContext)) {
6147 UD->setInvalidDecl();
6151 // Constructor inheriting using decls get special treatment.
6152 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
6153 if (CheckInheritedConstructorUsingDecl(UD))
6154 UD->setInvalidDecl();
6158 // Otherwise, look up the target name.
6160 LookupResult R(*this, NameInfo, LookupOrdinaryName);
6162 // Unlike most lookups, we don't always want to hide tag
6163 // declarations: tag names are visible through the using declaration
6164 // even if hidden by ordinary names, *except* in a dependent context
6165 // where it's important for the sanity of two-phase lookup.
6166 if (!IsInstantiation)
6167 R.setHideTags(false);
6169 LookupQualifiedName(R, LookupContext);
6172 Diag(IdentLoc, diag::err_no_member)
6173 << NameInfo.getName() << LookupContext << SS.getRange();
6174 UD->setInvalidDecl();
6178 if (R.isAmbiguous()) {
6179 UD->setInvalidDecl();
6184 // If we asked for a typename and got a non-type decl, error out.
6185 if (!R.getAsSingle<TypeDecl>()) {
6186 Diag(IdentLoc, diag::err_using_typename_non_type);
6187 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6188 Diag((*I)->getUnderlyingDecl()->getLocation(),
6189 diag::note_using_decl_target);
6190 UD->setInvalidDecl();
6194 // If we asked for a non-typename and we got a type, error out,
6195 // but only if this is an instantiation of an unresolved using
6196 // decl. Otherwise just silently find the type name.
6197 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
6198 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6199 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
6200 UD->setInvalidDecl();
6205 // C++0x N2914 [namespace.udecl]p6:
6206 // A using-declaration shall not name a namespace.
6207 if (R.getAsSingle<NamespaceDecl>()) {
6208 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6210 UD->setInvalidDecl();
6214 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6215 if (!CheckUsingShadowDecl(UD, *I, Previous))
6216 BuildUsingShadowDecl(S, UD, *I);
6222 /// Additional checks for a using declaration referring to a constructor name.
6223 bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6224 if (UD->isTypeName()) {
6225 // FIXME: Cannot specify typename when specifying constructor
6229 const Type *SourceType = UD->getQualifier()->getAsType();
6230 assert(SourceType &&
6231 "Using decl naming constructor doesn't have type in scope spec.");
6232 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6234 // Check whether the named type is a direct base class.
6235 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6236 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6237 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6238 BaseIt != BaseE; ++BaseIt) {
6239 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6240 if (CanonicalSourceType == BaseType)
6244 if (BaseIt == BaseE) {
6245 // Did not find SourceType in the bases.
6246 Diag(UD->getUsingLocation(),
6247 diag::err_using_decl_constructor_not_in_direct_base)
6248 << UD->getNameInfo().getSourceRange()
6249 << QualType(SourceType, 0) << TargetClass;
6253 BaseIt->setInheritConstructors();
6258 /// Checks that the given using declaration is not an invalid
6259 /// redeclaration. Note that this is checking only for the using decl
6260 /// itself, not for any ill-formedness among the UsingShadowDecls.
6261 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6263 const CXXScopeSpec &SS,
6264 SourceLocation NameLoc,
6265 const LookupResult &Prev) {
6266 // C++03 [namespace.udecl]p8:
6267 // C++0x [namespace.udecl]p10:
6268 // A using-declaration is a declaration and can therefore be used
6269 // repeatedly where (and only where) multiple declarations are
6272 // That's in non-member contexts.
6273 if (!CurContext->getRedeclContext()->isRecord())
6276 NestedNameSpecifier *Qual
6277 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6279 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6283 NestedNameSpecifier *DQual;
6284 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6285 DTypename = UD->isTypeName();
6286 DQual = UD->getQualifier();
6287 } else if (UnresolvedUsingValueDecl *UD
6288 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6290 DQual = UD->getQualifier();
6291 } else if (UnresolvedUsingTypenameDecl *UD
6292 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6294 DQual = UD->getQualifier();
6297 // using decls differ if one says 'typename' and the other doesn't.
6298 // FIXME: non-dependent using decls?
6299 if (isTypeName != DTypename) continue;
6301 // using decls differ if they name different scopes (but note that
6302 // template instantiation can cause this check to trigger when it
6303 // didn't before instantiation).
6304 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6305 Context.getCanonicalNestedNameSpecifier(DQual))
6308 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
6309 Diag(D->getLocation(), diag::note_using_decl) << 1;
6317 /// Checks that the given nested-name qualifier used in a using decl
6318 /// in the current context is appropriately related to the current
6319 /// scope. If an error is found, diagnoses it and returns true.
6320 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6321 const CXXScopeSpec &SS,
6322 SourceLocation NameLoc) {
6323 DeclContext *NamedContext = computeDeclContext(SS);
6325 if (!CurContext->isRecord()) {
6326 // C++03 [namespace.udecl]p3:
6327 // C++0x [namespace.udecl]p8:
6328 // A using-declaration for a class member shall be a member-declaration.
6330 // If we weren't able to compute a valid scope, it must be a
6331 // dependent class scope.
6332 if (!NamedContext || NamedContext->isRecord()) {
6333 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6338 // Otherwise, everything is known to be fine.
6342 // The current scope is a record.
6344 // If the named context is dependent, we can't decide much.
6345 if (!NamedContext) {
6346 // FIXME: in C++0x, we can diagnose if we can prove that the
6347 // nested-name-specifier does not refer to a base class, which is
6348 // still possible in some cases.
6350 // Otherwise we have to conservatively report that things might be
6355 if (!NamedContext->isRecord()) {
6356 // Ideally this would point at the last name in the specifier,
6357 // but we don't have that level of source info.
6358 Diag(SS.getRange().getBegin(),
6359 diag::err_using_decl_nested_name_specifier_is_not_class)
6360 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6364 if (!NamedContext->isDependentContext() &&
6365 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6368 if (getLangOptions().CPlusPlus0x) {
6369 // C++0x [namespace.udecl]p3:
6370 // In a using-declaration used as a member-declaration, the
6371 // nested-name-specifier shall name a base class of the class
6374 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6375 cast<CXXRecordDecl>(NamedContext))) {
6376 if (CurContext == NamedContext) {
6378 diag::err_using_decl_nested_name_specifier_is_current_class)
6383 Diag(SS.getRange().getBegin(),
6384 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6385 << (NestedNameSpecifier*) SS.getScopeRep()
6386 << cast<CXXRecordDecl>(CurContext)
6394 // C++03 [namespace.udecl]p4:
6395 // A using-declaration used as a member-declaration shall refer
6396 // to a member of a base class of the class being defined [etc.].
6398 // Salient point: SS doesn't have to name a base class as long as
6399 // lookup only finds members from base classes. Therefore we can
6400 // diagnose here only if we can prove that that can't happen,
6401 // i.e. if the class hierarchies provably don't intersect.
6403 // TODO: it would be nice if "definitely valid" results were cached
6404 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6405 // need to be repeated.
6408 llvm::DenseSet<const CXXRecordDecl*> Bases;
6410 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6411 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6412 Data->Bases.insert(Base);
6416 bool hasDependentBases(const CXXRecordDecl *Class) {
6417 return !Class->forallBases(collect, this);
6420 /// Returns true if the base is dependent or is one of the
6421 /// accumulated base classes.
6422 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6423 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6424 return !Data->Bases.count(Base);
6427 bool mightShareBases(const CXXRecordDecl *Class) {
6428 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6434 // Returns false if we find a dependent base.
6435 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6438 // Returns false if the class has a dependent base or if it or one
6439 // of its bases is present in the base set of the current context.
6440 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6443 Diag(SS.getRange().getBegin(),
6444 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6445 << (NestedNameSpecifier*) SS.getScopeRep()
6446 << cast<CXXRecordDecl>(CurContext)
6452 Decl *Sema::ActOnAliasDeclaration(Scope *S,
6454 MultiTemplateParamsArg TemplateParamLists,
6455 SourceLocation UsingLoc,
6456 UnqualifiedId &Name,
6458 // Skip up to the relevant declaration scope.
6459 while (S->getFlags() & Scope::TemplateParamScope)
6461 assert((S->getFlags() & Scope::DeclScope) &&
6462 "got alias-declaration outside of declaration scope");
6464 if (Type.isInvalid())
6467 bool Invalid = false;
6468 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6469 TypeSourceInfo *TInfo = 0;
6470 GetTypeFromParser(Type.get(), &TInfo);
6472 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6475 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
6476 UPPC_DeclarationType)) {
6478 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6479 TInfo->getTypeLoc().getBeginLoc());
6482 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6483 LookupName(Previous, S);
6485 // Warn about shadowing the name of a template parameter.
6486 if (Previous.isSingleResult() &&
6487 Previous.getFoundDecl()->isTemplateParameter()) {
6488 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
6489 Previous.getFoundDecl()))
6494 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6495 "name in alias declaration must be an identifier");
6496 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6498 Name.Identifier, TInfo);
6500 NewTD->setAccess(AS);
6503 NewTD->setInvalidDecl();
6505 CheckTypedefForVariablyModifiedType(S, NewTD);
6506 Invalid |= NewTD->isInvalidDecl();
6508 bool Redeclaration = false;
6511 if (TemplateParamLists.size()) {
6512 TypeAliasTemplateDecl *OldDecl = 0;
6513 TemplateParameterList *OldTemplateParams = 0;
6515 if (TemplateParamLists.size() != 1) {
6516 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6517 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6518 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6520 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6522 // Only consider previous declarations in the same scope.
6523 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6524 /*ExplicitInstantiationOrSpecialization*/false);
6525 if (!Previous.empty()) {
6526 Redeclaration = true;
6528 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6529 if (!OldDecl && !Invalid) {
6530 Diag(UsingLoc, diag::err_redefinition_different_kind)
6533 NamedDecl *OldD = Previous.getRepresentativeDecl();
6534 if (OldD->getLocation().isValid())
6535 Diag(OldD->getLocation(), diag::note_previous_definition);
6540 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6541 if (TemplateParameterListsAreEqual(TemplateParams,
6542 OldDecl->getTemplateParameters(),
6545 OldTemplateParams = OldDecl->getTemplateParameters();
6549 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6551 !Context.hasSameType(OldTD->getUnderlyingType(),
6552 NewTD->getUnderlyingType())) {
6553 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6554 // but we can't reasonably accept it.
6555 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6556 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6557 if (OldTD->getLocation().isValid())
6558 Diag(OldTD->getLocation(), diag::note_previous_definition);
6564 // Merge any previous default template arguments into our parameters,
6565 // and check the parameter list.
6566 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6567 TPC_TypeAliasTemplate))
6570 TypeAliasTemplateDecl *NewDecl =
6571 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6572 Name.Identifier, TemplateParams,
6575 NewDecl->setAccess(AS);
6578 NewDecl->setInvalidDecl();
6580 NewDecl->setPreviousDeclaration(OldDecl);
6584 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6589 PushOnScopeChains(NewND, S);
6594 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
6595 SourceLocation NamespaceLoc,
6596 SourceLocation AliasLoc,
6597 IdentifierInfo *Alias,
6599 SourceLocation IdentLoc,
6600 IdentifierInfo *Ident) {
6602 // Lookup the namespace name.
6603 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6604 LookupParsedName(R, S, &SS);
6606 // Check if we have a previous declaration with the same name.
6608 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6610 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6614 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
6615 // We already have an alias with the same name that points to the same
6616 // namespace, so don't create a new one.
6617 // FIXME: At some point, we'll want to create the (redundant)
6618 // declaration to maintain better source information.
6619 if (!R.isAmbiguous() && !R.empty() &&
6620 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
6624 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6625 diag::err_redefinition_different_kind;
6626 Diag(AliasLoc, DiagID) << Alias;
6627 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6631 if (R.isAmbiguous())
6635 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
6636 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
6641 NamespaceAliasDecl *AliasDecl =
6642 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
6643 Alias, SS.getWithLocInContext(Context),
6644 IdentLoc, R.getFoundDecl());
6646 PushOnScopeChains(AliasDecl, S);
6651 /// \brief Scoped object used to handle the state changes required in Sema
6652 /// to implicitly define the body of a C++ member function;
6653 class ImplicitlyDefinedFunctionScope {
6655 Sema::ContextRAII SavedContext;
6658 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
6659 : S(S), SavedContext(S, Method)
6661 S.PushFunctionScope();
6662 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6665 ~ImplicitlyDefinedFunctionScope() {
6666 S.PopExpressionEvaluationContext();
6667 S.PopFunctionOrBlockScope();
6672 Sema::ImplicitExceptionSpecification
6673 Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6674 // C++ [except.spec]p14:
6675 // An implicitly declared special member function (Clause 12) shall have an
6676 // exception-specification. [...]
6677 ImplicitExceptionSpecification ExceptSpec(Context);
6678 if (ClassDecl->isInvalidDecl())
6681 // Direct base-class constructors.
6682 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6683 BEnd = ClassDecl->bases_end();
6685 if (B->isVirtual()) // Handled below.
6688 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6689 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6690 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6691 // If this is a deleted function, add it anyway. This might be conformant
6692 // with the standard. This might not. I'm not sure. It might not matter.
6694 ExceptSpec.CalledDecl(Constructor);
6698 // Virtual base-class constructors.
6699 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6700 BEnd = ClassDecl->vbases_end();
6702 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6703 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6704 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6705 // If this is a deleted function, add it anyway. This might be conformant
6706 // with the standard. This might not. I'm not sure. It might not matter.
6708 ExceptSpec.CalledDecl(Constructor);
6712 // Field constructors.
6713 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6714 FEnd = ClassDecl->field_end();
6716 if (F->hasInClassInitializer()) {
6717 if (Expr *E = F->getInClassInitializer())
6718 ExceptSpec.CalledExpr(E);
6719 else if (!F->isInvalidDecl())
6720 ExceptSpec.SetDelayed();
6721 } else if (const RecordType *RecordTy
6722 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6723 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6724 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6725 // If this is a deleted function, add it anyway. This might be conformant
6726 // with the standard. This might not. I'm not sure. It might not matter.
6727 // In particular, the problem is that this function never gets called. It
6728 // might just be ill-formed because this function attempts to refer to
6729 // a deleted function here.
6731 ExceptSpec.CalledDecl(Constructor);
6738 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6739 CXXRecordDecl *ClassDecl) {
6740 // C++ [class.ctor]p5:
6741 // A default constructor for a class X is a constructor of class X
6742 // that can be called without an argument. If there is no
6743 // user-declared constructor for class X, a default constructor is
6744 // implicitly declared. An implicitly-declared default constructor
6745 // is an inline public member of its class.
6746 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6747 "Should not build implicit default constructor!");
6749 ImplicitExceptionSpecification Spec =
6750 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6751 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6753 // Create the actual constructor declaration.
6754 CanQualType ClassType
6755 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6756 SourceLocation ClassLoc = ClassDecl->getLocation();
6757 DeclarationName Name
6758 = Context.DeclarationNames.getCXXConstructorName(ClassType);
6759 DeclarationNameInfo NameInfo(Name, ClassLoc);
6760 CXXConstructorDecl *DefaultCon
6761 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6762 Context.getFunctionType(Context.VoidTy,
6765 /*isExplicit=*/false,
6767 /*isImplicitlyDeclared=*/true,
6768 // FIXME: apply the rules for definitions here
6769 /*isConstexpr=*/false);
6770 DefaultCon->setAccess(AS_public);
6771 DefaultCon->setDefaulted();
6772 DefaultCon->setImplicit();
6773 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6775 // Note that we have declared this constructor.
6776 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6778 if (Scope *S = getScopeForContext(ClassDecl))
6779 PushOnScopeChains(DefaultCon, S, false);
6780 ClassDecl->addDecl(DefaultCon);
6782 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
6783 DefaultCon->setDeletedAsWritten();
6788 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6789 CXXConstructorDecl *Constructor) {
6790 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6791 !Constructor->doesThisDeclarationHaveABody() &&
6792 !Constructor->isDeleted()) &&
6793 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6795 CXXRecordDecl *ClassDecl = Constructor->getParent();
6796 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6798 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6799 DiagnosticErrorTrap Trap(Diags);
6800 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6801 Trap.hasErrorOccurred()) {
6802 Diag(CurrentLocation, diag::note_member_synthesized_at)
6803 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6804 Constructor->setInvalidDecl();
6808 SourceLocation Loc = Constructor->getLocation();
6809 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6811 Constructor->setUsed();
6812 MarkVTableUsed(CurrentLocation, ClassDecl);
6814 if (ASTMutationListener *L = getASTMutationListener()) {
6815 L->CompletedImplicitDefinition(Constructor);
6819 /// Get any existing defaulted default constructor for the given class. Do not
6820 /// implicitly define one if it does not exist.
6821 static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6823 ASTContext &Context = Self.Context;
6824 QualType ClassType = Context.getTypeDeclType(D);
6825 DeclarationName ConstructorName
6826 = Context.DeclarationNames.getCXXConstructorName(
6827 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6829 DeclContext::lookup_const_iterator Con, ConEnd;
6830 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6831 Con != ConEnd; ++Con) {
6832 // A function template cannot be defaulted.
6833 if (isa<FunctionTemplateDecl>(*Con))
6836 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6837 if (Constructor->isDefaultConstructor())
6838 return Constructor->isDefaulted() ? Constructor : 0;
6843 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6845 AdjustDeclIfTemplate(D);
6847 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6848 CXXConstructorDecl *CtorDecl
6849 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6851 if (!CtorDecl) return;
6853 // Compute the exception specification for the default constructor.
6854 const FunctionProtoType *CtorTy =
6855 CtorDecl->getType()->castAs<FunctionProtoType>();
6856 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6857 ImplicitExceptionSpecification Spec =
6858 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6859 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6860 assert(EPI.ExceptionSpecType != EST_Delayed);
6862 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6865 // If the default constructor is explicitly defaulted, checking the exception
6866 // specification is deferred until now.
6867 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6868 !ClassDecl->isDependentType())
6869 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6872 void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6873 // We start with an initial pass over the base classes to collect those that
6874 // inherit constructors from. If there are none, we can forgo all further
6876 typedef SmallVector<const RecordType *, 4> BasesVector;
6877 BasesVector BasesToInheritFrom;
6878 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6879 BaseE = ClassDecl->bases_end();
6880 BaseIt != BaseE; ++BaseIt) {
6881 if (BaseIt->getInheritConstructors()) {
6882 QualType Base = BaseIt->getType();
6883 if (Base->isDependentType()) {
6884 // If we inherit constructors from anything that is dependent, just
6885 // abort processing altogether. We'll get another chance for the
6889 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6892 if (BasesToInheritFrom.empty())
6895 // Now collect the constructors that we already have in the current class.
6896 // Those take precedence over inherited constructors.
6897 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6898 // unless there is a user-declared constructor with the same signature in
6899 // the class where the using-declaration appears.
6900 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6901 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6902 CtorE = ClassDecl->ctor_end();
6903 CtorIt != CtorE; ++CtorIt) {
6904 ExistingConstructors.insert(
6905 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6908 Scope *S = getScopeForContext(ClassDecl);
6909 DeclarationName CreatedCtorName =
6910 Context.DeclarationNames.getCXXConstructorName(
6911 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6913 // Now comes the true work.
6914 // First, we keep a map from constructor types to the base that introduced
6915 // them. Needed for finding conflicting constructors. We also keep the
6916 // actually inserted declarations in there, for pretty diagnostics.
6917 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6918 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6919 ConstructorToSourceMap InheritedConstructors;
6920 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6921 BaseE = BasesToInheritFrom.end();
6922 BaseIt != BaseE; ++BaseIt) {
6923 const RecordType *Base = *BaseIt;
6924 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6925 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6926 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6927 CtorE = BaseDecl->ctor_end();
6928 CtorIt != CtorE; ++CtorIt) {
6929 // Find the using declaration for inheriting this base's constructors.
6930 DeclarationName Name =
6931 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6932 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6933 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6934 SourceLocation UsingLoc = UD ? UD->getLocation() :
6935 ClassDecl->getLocation();
6937 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6938 // from the class X named in the using-declaration consists of actual
6939 // constructors and notional constructors that result from the
6940 // transformation of defaulted parameters as follows:
6941 // - all non-template default constructors of X, and
6942 // - for each non-template constructor of X that has at least one
6943 // parameter with a default argument, the set of constructors that
6944 // results from omitting any ellipsis parameter specification and
6945 // successively omitting parameters with a default argument from the
6946 // end of the parameter-type-list.
6947 CXXConstructorDecl *BaseCtor = *CtorIt;
6948 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6949 const FunctionProtoType *BaseCtorType =
6950 BaseCtor->getType()->getAs<FunctionProtoType>();
6952 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6953 maxParams = BaseCtor->getNumParams();
6954 params <= maxParams; ++params) {
6955 // Skip default constructors. They're never inherited.
6958 // Skip copy and move constructors for the same reason.
6959 if (CanBeCopyOrMove && params == 1)
6962 // Build up a function type for this particular constructor.
6963 // FIXME: The working paper does not consider that the exception spec
6964 // for the inheriting constructor might be larger than that of the
6965 // source. This code doesn't yet, either. When it does, this code will
6966 // need to be delayed until after exception specifications and in-class
6967 // member initializers are attached.
6968 const Type *NewCtorType;
6969 if (params == maxParams)
6970 NewCtorType = BaseCtorType;
6972 SmallVector<QualType, 16> Args;
6973 for (unsigned i = 0; i < params; ++i) {
6974 Args.push_back(BaseCtorType->getArgType(i));
6976 FunctionProtoType::ExtProtoInfo ExtInfo =
6977 BaseCtorType->getExtProtoInfo();
6978 ExtInfo.Variadic = false;
6979 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6980 Args.data(), params, ExtInfo)
6983 const Type *CanonicalNewCtorType =
6984 Context.getCanonicalType(NewCtorType);
6986 // Now that we have the type, first check if the class already has a
6987 // constructor with this signature.
6988 if (ExistingConstructors.count(CanonicalNewCtorType))
6991 // Then we check if we have already declared an inherited constructor
6992 // with this signature.
6993 std::pair<ConstructorToSourceMap::iterator, bool> result =
6994 InheritedConstructors.insert(std::make_pair(
6995 CanonicalNewCtorType,
6996 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6997 if (!result.second) {
6998 // Already in the map. If it came from a different class, that's an
6999 // error. Not if it's from the same.
7000 CanQualType PreviousBase = result.first->second.first;
7001 if (CanonicalBase != PreviousBase) {
7002 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7003 const CXXConstructorDecl *PrevBaseCtor =
7004 PrevCtor->getInheritedConstructor();
7005 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7007 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7008 Diag(BaseCtor->getLocation(),
7009 diag::note_using_decl_constructor_conflict_current_ctor);
7010 Diag(PrevBaseCtor->getLocation(),
7011 diag::note_using_decl_constructor_conflict_previous_ctor);
7012 Diag(PrevCtor->getLocation(),
7013 diag::note_using_decl_constructor_conflict_previous_using);
7018 // OK, we're there, now add the constructor.
7019 // C++0x [class.inhctor]p8: [...] that would be performed by a
7020 // user-written inline constructor [...]
7021 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7022 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
7023 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7024 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
7025 /*ImplicitlyDeclared=*/true,
7026 // FIXME: Due to a defect in the standard, we treat inherited
7027 // constructors as constexpr even if that makes them ill-formed.
7028 /*Constexpr=*/BaseCtor->isConstexpr());
7029 NewCtor->setAccess(BaseCtor->getAccess());
7031 // Build up the parameter decls and add them.
7032 SmallVector<ParmVarDecl *, 16> ParamDecls;
7033 for (unsigned i = 0; i < params; ++i) {
7034 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7036 /*IdentifierInfo=*/0,
7037 BaseCtorType->getArgType(i),
7038 /*TInfo=*/0, SC_None,
7039 SC_None, /*DefaultArg=*/0));
7041 NewCtor->setParams(ParamDecls);
7042 NewCtor->setInheritedConstructor(BaseCtor);
7044 PushOnScopeChains(NewCtor, S, false);
7045 ClassDecl->addDecl(NewCtor);
7046 result.first->second.second = NewCtor;
7052 Sema::ImplicitExceptionSpecification
7053 Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
7054 // C++ [except.spec]p14:
7055 // An implicitly declared special member function (Clause 12) shall have
7056 // an exception-specification.
7057 ImplicitExceptionSpecification ExceptSpec(Context);
7058 if (ClassDecl->isInvalidDecl())
7061 // Direct base-class destructors.
7062 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7063 BEnd = ClassDecl->bases_end();
7065 if (B->isVirtual()) // Handled below.
7068 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7069 ExceptSpec.CalledDecl(
7070 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7073 // Virtual base-class destructors.
7074 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7075 BEnd = ClassDecl->vbases_end();
7077 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7078 ExceptSpec.CalledDecl(
7079 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
7082 // Field destructors.
7083 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7084 FEnd = ClassDecl->field_end();
7086 if (const RecordType *RecordTy
7087 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7088 ExceptSpec.CalledDecl(
7089 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
7095 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7096 // C++ [class.dtor]p2:
7097 // If a class has no user-declared destructor, a destructor is
7098 // declared implicitly. An implicitly-declared destructor is an
7099 // inline public member of its class.
7101 ImplicitExceptionSpecification Spec =
7102 ComputeDefaultedDtorExceptionSpec(ClassDecl);
7103 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7105 // Create the actual destructor declaration.
7106 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
7108 CanQualType ClassType
7109 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
7110 SourceLocation ClassLoc = ClassDecl->getLocation();
7111 DeclarationName Name
7112 = Context.DeclarationNames.getCXXDestructorName(ClassType);
7113 DeclarationNameInfo NameInfo(Name, ClassLoc);
7114 CXXDestructorDecl *Destructor
7115 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7117 /*isImplicitlyDeclared=*/true);
7118 Destructor->setAccess(AS_public);
7119 Destructor->setDefaulted();
7120 Destructor->setImplicit();
7121 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
7123 // Note that we have declared this destructor.
7124 ++ASTContext::NumImplicitDestructorsDeclared;
7126 // Introduce this destructor into its scope.
7127 if (Scope *S = getScopeForContext(ClassDecl))
7128 PushOnScopeChains(Destructor, S, false);
7129 ClassDecl->addDecl(Destructor);
7131 // This could be uniqued if it ever proves significant.
7132 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
7134 if (ShouldDeleteDestructor(Destructor))
7135 Destructor->setDeletedAsWritten();
7137 AddOverriddenMethods(ClassDecl, Destructor);
7142 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
7143 CXXDestructorDecl *Destructor) {
7144 assert((Destructor->isDefaulted() &&
7145 !Destructor->doesThisDeclarationHaveABody()) &&
7146 "DefineImplicitDestructor - call it for implicit default dtor");
7147 CXXRecordDecl *ClassDecl = Destructor->getParent();
7148 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
7150 if (Destructor->isInvalidDecl())
7153 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
7155 DiagnosticErrorTrap Trap(Diags);
7156 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7157 Destructor->getParent());
7159 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
7160 Diag(CurrentLocation, diag::note_member_synthesized_at)
7161 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7163 Destructor->setInvalidDecl();
7167 SourceLocation Loc = Destructor->getLocation();
7168 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7169 Destructor->setImplicitlyDefined(true);
7170 Destructor->setUsed();
7171 MarkVTableUsed(CurrentLocation, ClassDecl);
7173 if (ASTMutationListener *L = getASTMutationListener()) {
7174 L->CompletedImplicitDefinition(Destructor);
7178 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7179 CXXDestructorDecl *destructor) {
7180 // C++11 [class.dtor]p3:
7181 // A declaration of a destructor that does not have an exception-
7182 // specification is implicitly considered to have the same exception-
7183 // specification as an implicit declaration.
7184 const FunctionProtoType *dtorType = destructor->getType()->
7185 getAs<FunctionProtoType>();
7186 if (dtorType->hasExceptionSpec())
7189 ImplicitExceptionSpecification exceptSpec =
7190 ComputeDefaultedDtorExceptionSpec(classDecl);
7192 // Replace the destructor's type, building off the existing one. Fortunately,
7193 // the only thing of interest in the destructor type is its extended info.
7194 // The return and arguments are fixed.
7195 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
7196 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7197 epi.NumExceptions = exceptSpec.size();
7198 epi.Exceptions = exceptSpec.data();
7199 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7201 destructor->setType(ty);
7203 // FIXME: If the destructor has a body that could throw, and the newly created
7204 // spec doesn't allow exceptions, we should emit a warning, because this
7205 // change in behavior can break conforming C++03 programs at runtime.
7206 // However, we don't have a body yet, so it needs to be done somewhere else.
7209 /// \brief Builds a statement that copies/moves the given entity from \p From to
7212 /// This routine is used to copy/move the members of a class with an
7213 /// implicitly-declared copy/move assignment operator. When the entities being
7214 /// copied are arrays, this routine builds for loops to copy them.
7216 /// \param S The Sema object used for type-checking.
7218 /// \param Loc The location where the implicit copy/move is being generated.
7220 /// \param T The type of the expressions being copied/moved. Both expressions
7221 /// must have this type.
7223 /// \param To The expression we are copying/moving to.
7225 /// \param From The expression we are copying/moving from.
7227 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
7228 /// Otherwise, it's a non-static member subobject.
7230 /// \param Copying Whether we're copying or moving.
7232 /// \param Depth Internal parameter recording the depth of the recursion.
7234 /// \returns A statement or a loop that copies the expressions.
7236 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
7237 Expr *To, Expr *From,
7238 bool CopyingBaseSubobject, bool Copying,
7239 unsigned Depth = 0) {
7240 // C++0x [class.copy]p28:
7241 // Each subobject is assigned in the manner appropriate to its type:
7243 // - if the subobject is of class type, as if by a call to operator= with
7244 // the subobject as the object expression and the corresponding
7245 // subobject of x as a single function argument (as if by explicit
7246 // qualification; that is, ignoring any possible virtual overriding
7247 // functions in more derived classes);
7248 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7249 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7251 // Look for operator=.
7252 DeclarationName Name
7253 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7254 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7255 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7257 // Filter out any result that isn't a copy/move-assignment operator.
7258 LookupResult::Filter F = OpLookup.makeFilter();
7259 while (F.hasNext()) {
7260 NamedDecl *D = F.next();
7261 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
7262 if (Copying ? Method->isCopyAssignmentOperator() :
7263 Method->isMoveAssignmentOperator())
7270 // Suppress the protected check (C++ [class.protected]) for each of the
7271 // assignment operators we found. This strange dance is required when
7272 // we're assigning via a base classes's copy-assignment operator. To
7273 // ensure that we're getting the right base class subobject (without
7274 // ambiguities), we need to cast "this" to that subobject type; to
7275 // ensure that we don't go through the virtual call mechanism, we need
7276 // to qualify the operator= name with the base class (see below). However,
7277 // this means that if the base class has a protected copy assignment
7278 // operator, the protected member access check will fail. So, we
7279 // rewrite "protected" access to "public" access in this case, since we
7280 // know by construction that we're calling from a derived class.
7281 if (CopyingBaseSubobject) {
7282 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7284 if (L.getAccess() == AS_protected)
7285 L.setAccess(AS_public);
7289 // Create the nested-name-specifier that will be used to qualify the
7290 // reference to operator=; this is required to suppress the virtual
7293 SS.MakeTrivial(S.Context,
7294 NestedNameSpecifier::Create(S.Context, 0, false,
7298 // Create the reference to operator=.
7299 ExprResult OpEqualRef
7300 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
7301 /*FirstQualifierInScope=*/0, OpLookup,
7303 /*SuppressQualifierCheck=*/true);
7304 if (OpEqualRef.isInvalid())
7307 // Build the call to the assignment operator.
7309 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
7310 OpEqualRef.takeAs<Expr>(),
7311 Loc, &From, 1, Loc);
7312 if (Call.isInvalid())
7315 return S.Owned(Call.takeAs<Stmt>());
7318 // - if the subobject is of scalar type, the built-in assignment
7319 // operator is used.
7320 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7322 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
7323 if (Assignment.isInvalid())
7326 return S.Owned(Assignment.takeAs<Stmt>());
7329 // - if the subobject is an array, each element is assigned, in the
7330 // manner appropriate to the element type;
7332 // Construct a loop over the array bounds, e.g.,
7334 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7336 // that will copy each of the array elements.
7337 QualType SizeType = S.Context.getSizeType();
7339 // Create the iteration variable.
7340 IdentifierInfo *IterationVarName = 0;
7342 llvm::SmallString<8> Str;
7343 llvm::raw_svector_ostream OS(Str);
7344 OS << "__i" << Depth;
7345 IterationVarName = &S.Context.Idents.get(OS.str());
7347 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
7348 IterationVarName, SizeType,
7349 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
7352 // Initialize the iteration variable to zero.
7353 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
7354 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
7356 // Create a reference to the iteration variable; we'll use this several
7357 // times throughout.
7358 Expr *IterationVarRef
7359 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
7360 assert(IterationVarRef && "Reference to invented variable cannot fail!");
7362 // Create the DeclStmt that holds the iteration variable.
7363 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7365 // Create the comparison against the array bound.
7367 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
7369 = new (S.Context) BinaryOperator(IterationVarRef,
7370 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7371 BO_NE, S.Context.BoolTy,
7372 VK_RValue, OK_Ordinary, Loc);
7374 // Create the pre-increment of the iteration variable.
7376 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7377 VK_LValue, OK_Ordinary, Loc);
7379 // Subscript the "from" and "to" expressions with the iteration variable.
7380 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
7381 IterationVarRef, Loc));
7382 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
7383 IterationVarRef, Loc));
7384 if (!Copying) // Cast to rvalue
7385 From = CastForMoving(S, From);
7387 // Build the copy/move for an individual element of the array.
7388 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7389 To, From, CopyingBaseSubobject,
7390 Copying, Depth + 1);
7391 if (Copy.isInvalid())
7394 // Construct the loop that copies all elements of this array.
7395 return S.ActOnForStmt(Loc, Loc, InitStmt,
7396 S.MakeFullExpr(Comparison),
7397 0, S.MakeFullExpr(Increment),
7401 std::pair<Sema::ImplicitExceptionSpecification, bool>
7402 Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7403 CXXRecordDecl *ClassDecl) {
7404 if (ClassDecl->isInvalidDecl())
7405 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7407 // C++ [class.copy]p10:
7408 // If the class definition does not explicitly declare a copy
7409 // assignment operator, one is declared implicitly.
7410 // The implicitly-defined copy assignment operator for a class X
7411 // will have the form
7413 // X& X::operator=(const X&)
7416 bool HasConstCopyAssignment = true;
7418 // -- each direct base class B of X has a copy assignment operator
7419 // whose parameter is of type const B&, const volatile B& or B,
7421 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7422 BaseEnd = ClassDecl->bases_end();
7423 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7424 // We'll handle this below
7425 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7428 assert(!Base->getType()->isDependentType() &&
7429 "Cannot generate implicit members for class with dependent bases.");
7430 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7431 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7432 &HasConstCopyAssignment);
7435 // In C++0x, the above citation has "or virtual added"
7436 if (LangOpts.CPlusPlus0x) {
7437 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7438 BaseEnd = ClassDecl->vbases_end();
7439 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7440 assert(!Base->getType()->isDependentType() &&
7441 "Cannot generate implicit members for class with dependent bases.");
7442 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7443 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7444 &HasConstCopyAssignment);
7448 // -- for all the nonstatic data members of X that are of a class
7449 // type M (or array thereof), each such class type has a copy
7450 // assignment operator whose parameter is of type const M&,
7451 // const volatile M& or M.
7452 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7453 FieldEnd = ClassDecl->field_end();
7454 HasConstCopyAssignment && Field != FieldEnd;
7456 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7457 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7458 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7459 &HasConstCopyAssignment);
7463 // Otherwise, the implicitly declared copy assignment operator will
7466 // X& X::operator=(X&)
7468 // C++ [except.spec]p14:
7469 // An implicitly declared special member function (Clause 12) shall have an
7470 // exception-specification. [...]
7472 // It is unspecified whether or not an implicit copy assignment operator
7473 // attempts to deduplicate calls to assignment operators of virtual bases are
7474 // made. As such, this exception specification is effectively unspecified.
7475 // Based on a similar decision made for constness in C++0x, we're erring on
7476 // the side of assuming such calls to be made regardless of whether they
7478 ImplicitExceptionSpecification ExceptSpec(Context);
7479 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
7480 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7481 BaseEnd = ClassDecl->bases_end();
7482 Base != BaseEnd; ++Base) {
7483 if (Base->isVirtual())
7486 CXXRecordDecl *BaseClassDecl
7487 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7488 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7489 ArgQuals, false, 0))
7490 ExceptSpec.CalledDecl(CopyAssign);
7493 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7494 BaseEnd = ClassDecl->vbases_end();
7495 Base != BaseEnd; ++Base) {
7496 CXXRecordDecl *BaseClassDecl
7497 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7498 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7499 ArgQuals, false, 0))
7500 ExceptSpec.CalledDecl(CopyAssign);
7503 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7504 FieldEnd = ClassDecl->field_end();
7507 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7508 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7509 if (CXXMethodDecl *CopyAssign =
7510 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7511 ExceptSpec.CalledDecl(CopyAssign);
7515 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7518 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7519 // Note: The following rules are largely analoguous to the copy
7520 // constructor rules. Note that virtual bases are not taken into account
7521 // for determining the argument type of the operator. Note also that
7522 // operators taking an object instead of a reference are allowed.
7524 ImplicitExceptionSpecification Spec(Context);
7526 llvm::tie(Spec, Const) =
7527 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7529 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7530 QualType RetType = Context.getLValueReferenceType(ArgType);
7532 ArgType = ArgType.withConst();
7533 ArgType = Context.getLValueReferenceType(ArgType);
7535 // An implicitly-declared copy assignment operator is an inline public
7536 // member of its class.
7537 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7538 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7539 SourceLocation ClassLoc = ClassDecl->getLocation();
7540 DeclarationNameInfo NameInfo(Name, ClassLoc);
7541 CXXMethodDecl *CopyAssignment
7542 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7543 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7544 /*TInfo=*/0, /*isStatic=*/false,
7545 /*StorageClassAsWritten=*/SC_None,
7546 /*isInline=*/true, /*isConstexpr=*/false,
7548 CopyAssignment->setAccess(AS_public);
7549 CopyAssignment->setDefaulted();
7550 CopyAssignment->setImplicit();
7551 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
7553 // Add the parameter to the operator.
7554 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
7555 ClassLoc, ClassLoc, /*Id=*/0,
7556 ArgType, /*TInfo=*/0,
7559 CopyAssignment->setParams(FromParam);
7561 // Note that we have added this copy-assignment operator.
7562 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
7564 if (Scope *S = getScopeForContext(ClassDecl))
7565 PushOnScopeChains(CopyAssignment, S, false);
7566 ClassDecl->addDecl(CopyAssignment);
7568 // C++0x [class.copy]p18:
7569 // ... If the class definition declares a move constructor or move
7570 // assignment operator, the implicitly declared copy assignment operator is
7571 // defined as deleted; ...
7572 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
7573 ClassDecl->hasUserDeclaredMoveAssignment() ||
7574 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
7575 CopyAssignment->setDeletedAsWritten();
7577 AddOverriddenMethods(ClassDecl, CopyAssignment);
7578 return CopyAssignment;
7581 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7582 CXXMethodDecl *CopyAssignOperator) {
7583 assert((CopyAssignOperator->isDefaulted() &&
7584 CopyAssignOperator->isOverloadedOperator() &&
7585 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
7586 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
7587 "DefineImplicitCopyAssignment called for wrong function");
7589 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7591 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7592 CopyAssignOperator->setInvalidDecl();
7596 CopyAssignOperator->setUsed();
7598 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
7599 DiagnosticErrorTrap Trap(Diags);
7601 // C++0x [class.copy]p30:
7602 // The implicitly-defined or explicitly-defaulted copy assignment operator
7603 // for a non-union class X performs memberwise copy assignment of its
7604 // subobjects. The direct base classes of X are assigned first, in the
7605 // order of their declaration in the base-specifier-list, and then the
7606 // immediate non-static data members of X are assigned, in the order in
7607 // which they were declared in the class definition.
7609 // The statements that form the synthesized function body.
7610 ASTOwningVector<Stmt*> Statements(*this);
7612 // The parameter for the "other" object, which we are copying from.
7613 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7614 Qualifiers OtherQuals = Other->getType().getQualifiers();
7615 QualType OtherRefType = Other->getType();
7616 if (const LValueReferenceType *OtherRef
7617 = OtherRefType->getAs<LValueReferenceType>()) {
7618 OtherRefType = OtherRef->getPointeeType();
7619 OtherQuals = OtherRefType.getQualifiers();
7622 // Our location for everything implicitly-generated.
7623 SourceLocation Loc = CopyAssignOperator->getLocation();
7625 // Construct a reference to the "other" object. We'll be using this
7626 // throughout the generated ASTs.
7627 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
7628 assert(OtherRef && "Reference to parameter cannot fail!");
7630 // Construct the "this" pointer. We'll be using this throughout the generated
7632 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7633 assert(This && "Reference to this cannot fail!");
7635 // Assign base classes.
7636 bool Invalid = false;
7637 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7638 E = ClassDecl->bases_end(); Base != E; ++Base) {
7639 // Form the assignment:
7640 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7641 QualType BaseType = Base->getType().getUnqualifiedType();
7642 if (!BaseType->isRecordType()) {
7647 CXXCastPath BasePath;
7648 BasePath.push_back(Base);
7650 // Construct the "from" expression, which is an implicit cast to the
7651 // appropriately-qualified base type.
7652 Expr *From = OtherRef;
7653 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7654 CK_UncheckedDerivedToBase,
7655 VK_LValue, &BasePath).take();
7657 // Dereference "this".
7658 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7660 // Implicitly cast "this" to the appropriately-qualified base type.
7661 To = ImpCastExprToType(To.take(),
7662 Context.getCVRQualifiedType(BaseType,
7663 CopyAssignOperator->getTypeQualifiers()),
7664 CK_UncheckedDerivedToBase,
7665 VK_LValue, &BasePath);
7668 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
7670 /*CopyingBaseSubobject=*/true,
7672 if (Copy.isInvalid()) {
7673 Diag(CurrentLocation, diag::note_member_synthesized_at)
7674 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7675 CopyAssignOperator->setInvalidDecl();
7679 // Success! Record the copy.
7680 Statements.push_back(Copy.takeAs<Expr>());
7683 // \brief Reference to the __builtin_memcpy function.
7684 Expr *BuiltinMemCpyRef = 0;
7685 // \brief Reference to the __builtin_objc_memmove_collectable function.
7686 Expr *CollectableMemCpyRef = 0;
7688 // Assign non-static members.
7689 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7690 FieldEnd = ClassDecl->field_end();
7691 Field != FieldEnd; ++Field) {
7692 if (Field->isUnnamedBitfield())
7695 // Check for members of reference type; we can't copy those.
7696 if (Field->getType()->isReferenceType()) {
7697 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7698 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
7699 Diag(Field->getLocation(), diag::note_declared_at);
7700 Diag(CurrentLocation, diag::note_member_synthesized_at)
7701 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7706 // Check for members of const-qualified, non-class type.
7707 QualType BaseType = Context.getBaseElementType(Field->getType());
7708 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7709 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7710 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7711 Diag(Field->getLocation(), diag::note_declared_at);
7712 Diag(CurrentLocation, diag::note_member_synthesized_at)
7713 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7718 // Suppress assigning zero-width bitfields.
7719 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
7722 QualType FieldType = Field->getType().getNonReferenceType();
7723 if (FieldType->isIncompleteArrayType()) {
7724 assert(ClassDecl->hasFlexibleArrayMember() &&
7725 "Incomplete array type is not valid");
7729 // Build references to the field in the object we're copying from and to.
7730 CXXScopeSpec SS; // Intentionally empty
7731 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7733 MemberLookup.addDecl(*Field);
7734 MemberLookup.resolveKind();
7735 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7736 Loc, /*IsArrow=*/false,
7737 SS, 0, MemberLookup, 0);
7738 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7739 Loc, /*IsArrow=*/true,
7740 SS, 0, MemberLookup, 0);
7741 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7742 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7744 // If the field should be copied with __builtin_memcpy rather than via
7745 // explicit assignments, do so. This optimization only applies for arrays
7746 // of scalars and arrays of class type with trivial copy-assignment
7748 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
7749 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
7750 // Compute the size of the memory buffer to be copied.
7751 QualType SizeType = Context.getSizeType();
7752 llvm::APInt Size(Context.getTypeSize(SizeType),
7753 Context.getTypeSizeInChars(BaseType).getQuantity());
7754 for (const ConstantArrayType *Array
7755 = Context.getAsConstantArrayType(FieldType);
7757 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7758 llvm::APInt ArraySize
7759 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7763 // Take the address of the field references for "from" and "to".
7764 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7765 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7767 bool NeedsCollectableMemCpy =
7768 (BaseType->isRecordType() &&
7769 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7771 if (NeedsCollectableMemCpy) {
7772 if (!CollectableMemCpyRef) {
7773 // Create a reference to the __builtin_objc_memmove_collectable function.
7774 LookupResult R(*this,
7775 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7776 Loc, LookupOrdinaryName);
7777 LookupName(R, TUScope, true);
7779 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7780 if (!CollectableMemCpy) {
7781 // Something went horribly wrong earlier, and we will have
7782 // complained about it.
7787 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7788 CollectableMemCpy->getType(),
7789 VK_LValue, Loc, 0).take();
7790 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7793 // Create a reference to the __builtin_memcpy builtin function.
7794 else if (!BuiltinMemCpyRef) {
7795 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7796 LookupOrdinaryName);
7797 LookupName(R, TUScope, true);
7799 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7800 if (!BuiltinMemCpy) {
7801 // Something went horribly wrong earlier, and we will have complained
7807 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7808 BuiltinMemCpy->getType(),
7809 VK_LValue, Loc, 0).take();
7810 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7813 ASTOwningVector<Expr*> CallArgs(*this);
7814 CallArgs.push_back(To.takeAs<Expr>());
7815 CallArgs.push_back(From.takeAs<Expr>());
7816 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7817 ExprResult Call = ExprError();
7818 if (NeedsCollectableMemCpy)
7819 Call = ActOnCallExpr(/*Scope=*/0,
7820 CollectableMemCpyRef,
7821 Loc, move_arg(CallArgs),
7824 Call = ActOnCallExpr(/*Scope=*/0,
7826 Loc, move_arg(CallArgs),
7829 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7830 Statements.push_back(Call.takeAs<Expr>());
7834 // Build the copy of this field.
7835 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7836 To.get(), From.get(),
7837 /*CopyingBaseSubobject=*/false,
7839 if (Copy.isInvalid()) {
7840 Diag(CurrentLocation, diag::note_member_synthesized_at)
7841 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7842 CopyAssignOperator->setInvalidDecl();
7846 // Success! Record the copy.
7847 Statements.push_back(Copy.takeAs<Stmt>());
7851 // Add a "return *this;"
7852 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7854 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7855 if (Return.isInvalid())
7858 Statements.push_back(Return.takeAs<Stmt>());
7860 if (Trap.hasErrorOccurred()) {
7861 Diag(CurrentLocation, diag::note_member_synthesized_at)
7862 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7869 CopyAssignOperator->setInvalidDecl();
7873 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7874 /*isStmtExpr=*/false);
7875 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7876 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7878 if (ASTMutationListener *L = getASTMutationListener()) {
7879 L->CompletedImplicitDefinition(CopyAssignOperator);
7883 Sema::ImplicitExceptionSpecification
7884 Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
7885 ImplicitExceptionSpecification ExceptSpec(Context);
7887 if (ClassDecl->isInvalidDecl())
7890 // C++0x [except.spec]p14:
7891 // An implicitly declared special member function (Clause 12) shall have an
7892 // exception-specification. [...]
7894 // It is unspecified whether or not an implicit move assignment operator
7895 // attempts to deduplicate calls to assignment operators of virtual bases are
7896 // made. As such, this exception specification is effectively unspecified.
7897 // Based on a similar decision made for constness in C++0x, we're erring on
7898 // the side of assuming such calls to be made regardless of whether they
7900 // Note that a move constructor is not implicitly declared when there are
7901 // virtual bases, but it can still be user-declared and explicitly defaulted.
7902 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7903 BaseEnd = ClassDecl->bases_end();
7904 Base != BaseEnd; ++Base) {
7905 if (Base->isVirtual())
7908 CXXRecordDecl *BaseClassDecl
7909 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7910 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7912 ExceptSpec.CalledDecl(MoveAssign);
7915 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7916 BaseEnd = ClassDecl->vbases_end();
7917 Base != BaseEnd; ++Base) {
7918 CXXRecordDecl *BaseClassDecl
7919 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7920 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
7922 ExceptSpec.CalledDecl(MoveAssign);
7925 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7926 FieldEnd = ClassDecl->field_end();
7929 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7930 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7931 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
7933 ExceptSpec.CalledDecl(MoveAssign);
7940 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
7941 // Note: The following rules are largely analoguous to the move
7942 // constructor rules.
7944 ImplicitExceptionSpecification Spec(
7945 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
7947 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7948 QualType RetType = Context.getLValueReferenceType(ArgType);
7949 ArgType = Context.getRValueReferenceType(ArgType);
7951 // An implicitly-declared move assignment operator is an inline public
7952 // member of its class.
7953 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7954 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7955 SourceLocation ClassLoc = ClassDecl->getLocation();
7956 DeclarationNameInfo NameInfo(Name, ClassLoc);
7957 CXXMethodDecl *MoveAssignment
7958 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7959 Context.getFunctionType(RetType, &ArgType, 1, EPI),
7960 /*TInfo=*/0, /*isStatic=*/false,
7961 /*StorageClassAsWritten=*/SC_None,
7963 /*isConstexpr=*/false,
7965 MoveAssignment->setAccess(AS_public);
7966 MoveAssignment->setDefaulted();
7967 MoveAssignment->setImplicit();
7968 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
7970 // Add the parameter to the operator.
7971 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
7972 ClassLoc, ClassLoc, /*Id=*/0,
7973 ArgType, /*TInfo=*/0,
7976 MoveAssignment->setParams(FromParam);
7978 // Note that we have added this copy-assignment operator.
7979 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
7981 // C++0x [class.copy]p9:
7982 // If the definition of a class X does not explicitly declare a move
7983 // assignment operator, one will be implicitly declared as defaulted if and
7986 // - the move assignment operator would not be implicitly defined as
7988 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
7989 // Cache this result so that we don't try to generate this over and over
7990 // on every lookup, leaking memory and wasting time.
7991 ClassDecl->setFailedImplicitMoveAssignment();
7995 if (Scope *S = getScopeForContext(ClassDecl))
7996 PushOnScopeChains(MoveAssignment, S, false);
7997 ClassDecl->addDecl(MoveAssignment);
7999 AddOverriddenMethods(ClassDecl, MoveAssignment);
8000 return MoveAssignment;
8003 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8004 CXXMethodDecl *MoveAssignOperator) {
8005 assert((MoveAssignOperator->isDefaulted() &&
8006 MoveAssignOperator->isOverloadedOperator() &&
8007 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8008 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8009 "DefineImplicitMoveAssignment called for wrong function");
8011 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8013 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8014 MoveAssignOperator->setInvalidDecl();
8018 MoveAssignOperator->setUsed();
8020 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8021 DiagnosticErrorTrap Trap(Diags);
8023 // C++0x [class.copy]p28:
8024 // The implicitly-defined or move assignment operator for a non-union class
8025 // X performs memberwise move assignment of its subobjects. The direct base
8026 // classes of X are assigned first, in the order of their declaration in the
8027 // base-specifier-list, and then the immediate non-static data members of X
8028 // are assigned, in the order in which they were declared in the class
8031 // The statements that form the synthesized function body.
8032 ASTOwningVector<Stmt*> Statements(*this);
8034 // The parameter for the "other" object, which we are move from.
8035 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8036 QualType OtherRefType = Other->getType()->
8037 getAs<RValueReferenceType>()->getPointeeType();
8038 assert(OtherRefType.getQualifiers() == 0 &&
8039 "Bad argument type of defaulted move assignment");
8041 // Our location for everything implicitly-generated.
8042 SourceLocation Loc = MoveAssignOperator->getLocation();
8044 // Construct a reference to the "other" object. We'll be using this
8045 // throughout the generated ASTs.
8046 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8047 assert(OtherRef && "Reference to parameter cannot fail!");
8049 OtherRef = CastForMoving(*this, OtherRef);
8051 // Construct the "this" pointer. We'll be using this throughout the generated
8053 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8054 assert(This && "Reference to this cannot fail!");
8056 // Assign base classes.
8057 bool Invalid = false;
8058 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8059 E = ClassDecl->bases_end(); Base != E; ++Base) {
8060 // Form the assignment:
8061 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8062 QualType BaseType = Base->getType().getUnqualifiedType();
8063 if (!BaseType->isRecordType()) {
8068 CXXCastPath BasePath;
8069 BasePath.push_back(Base);
8071 // Construct the "from" expression, which is an implicit cast to the
8072 // appropriately-qualified base type.
8073 Expr *From = OtherRef;
8074 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
8075 VK_XValue, &BasePath).take();
8077 // Dereference "this".
8078 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8080 // Implicitly cast "this" to the appropriately-qualified base type.
8081 To = ImpCastExprToType(To.take(),
8082 Context.getCVRQualifiedType(BaseType,
8083 MoveAssignOperator->getTypeQualifiers()),
8084 CK_UncheckedDerivedToBase,
8085 VK_LValue, &BasePath);
8088 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8090 /*CopyingBaseSubobject=*/true,
8092 if (Move.isInvalid()) {
8093 Diag(CurrentLocation, diag::note_member_synthesized_at)
8094 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8095 MoveAssignOperator->setInvalidDecl();
8099 // Success! Record the move.
8100 Statements.push_back(Move.takeAs<Expr>());
8103 // \brief Reference to the __builtin_memcpy function.
8104 Expr *BuiltinMemCpyRef = 0;
8105 // \brief Reference to the __builtin_objc_memmove_collectable function.
8106 Expr *CollectableMemCpyRef = 0;
8108 // Assign non-static members.
8109 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8110 FieldEnd = ClassDecl->field_end();
8111 Field != FieldEnd; ++Field) {
8112 if (Field->isUnnamedBitfield())
8115 // Check for members of reference type; we can't move those.
8116 if (Field->getType()->isReferenceType()) {
8117 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8118 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8119 Diag(Field->getLocation(), diag::note_declared_at);
8120 Diag(CurrentLocation, diag::note_member_synthesized_at)
8121 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8126 // Check for members of const-qualified, non-class type.
8127 QualType BaseType = Context.getBaseElementType(Field->getType());
8128 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8129 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8130 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8131 Diag(Field->getLocation(), diag::note_declared_at);
8132 Diag(CurrentLocation, diag::note_member_synthesized_at)
8133 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8138 // Suppress assigning zero-width bitfields.
8139 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8142 QualType FieldType = Field->getType().getNonReferenceType();
8143 if (FieldType->isIncompleteArrayType()) {
8144 assert(ClassDecl->hasFlexibleArrayMember() &&
8145 "Incomplete array type is not valid");
8149 // Build references to the field in the object we're copying from and to.
8150 CXXScopeSpec SS; // Intentionally empty
8151 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8153 MemberLookup.addDecl(*Field);
8154 MemberLookup.resolveKind();
8155 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8156 Loc, /*IsArrow=*/false,
8157 SS, 0, MemberLookup, 0);
8158 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8159 Loc, /*IsArrow=*/true,
8160 SS, 0, MemberLookup, 0);
8161 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8162 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8164 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8165 "Member reference with rvalue base must be rvalue except for reference "
8166 "members, which aren't allowed for move assignment.");
8168 // If the field should be copied with __builtin_memcpy rather than via
8169 // explicit assignments, do so. This optimization only applies for arrays
8170 // of scalars and arrays of class type with trivial move-assignment
8172 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8173 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8174 // Compute the size of the memory buffer to be copied.
8175 QualType SizeType = Context.getSizeType();
8176 llvm::APInt Size(Context.getTypeSize(SizeType),
8177 Context.getTypeSizeInChars(BaseType).getQuantity());
8178 for (const ConstantArrayType *Array
8179 = Context.getAsConstantArrayType(FieldType);
8181 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8182 llvm::APInt ArraySize
8183 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8187 // Take the address of the field references for "from" and "to". We
8188 // directly construct UnaryOperators here because semantic analysis
8189 // does not permit us to take the address of an xvalue.
8190 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8191 Context.getPointerType(From.get()->getType()),
8192 VK_RValue, OK_Ordinary, Loc);
8193 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8194 Context.getPointerType(To.get()->getType()),
8195 VK_RValue, OK_Ordinary, Loc);
8197 bool NeedsCollectableMemCpy =
8198 (BaseType->isRecordType() &&
8199 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8201 if (NeedsCollectableMemCpy) {
8202 if (!CollectableMemCpyRef) {
8203 // Create a reference to the __builtin_objc_memmove_collectable function.
8204 LookupResult R(*this,
8205 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8206 Loc, LookupOrdinaryName);
8207 LookupName(R, TUScope, true);
8209 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8210 if (!CollectableMemCpy) {
8211 // Something went horribly wrong earlier, and we will have
8212 // complained about it.
8217 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8218 CollectableMemCpy->getType(),
8219 VK_LValue, Loc, 0).take();
8220 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8223 // Create a reference to the __builtin_memcpy builtin function.
8224 else if (!BuiltinMemCpyRef) {
8225 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8226 LookupOrdinaryName);
8227 LookupName(R, TUScope, true);
8229 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8230 if (!BuiltinMemCpy) {
8231 // Something went horribly wrong earlier, and we will have complained
8237 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8238 BuiltinMemCpy->getType(),
8239 VK_LValue, Loc, 0).take();
8240 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8243 ASTOwningVector<Expr*> CallArgs(*this);
8244 CallArgs.push_back(To.takeAs<Expr>());
8245 CallArgs.push_back(From.takeAs<Expr>());
8246 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8247 ExprResult Call = ExprError();
8248 if (NeedsCollectableMemCpy)
8249 Call = ActOnCallExpr(/*Scope=*/0,
8250 CollectableMemCpyRef,
8251 Loc, move_arg(CallArgs),
8254 Call = ActOnCallExpr(/*Scope=*/0,
8256 Loc, move_arg(CallArgs),
8259 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8260 Statements.push_back(Call.takeAs<Expr>());
8264 // Build the move of this field.
8265 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8266 To.get(), From.get(),
8267 /*CopyingBaseSubobject=*/false,
8269 if (Move.isInvalid()) {
8270 Diag(CurrentLocation, diag::note_member_synthesized_at)
8271 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8272 MoveAssignOperator->setInvalidDecl();
8276 // Success! Record the copy.
8277 Statements.push_back(Move.takeAs<Stmt>());
8281 // Add a "return *this;"
8282 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8284 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8285 if (Return.isInvalid())
8288 Statements.push_back(Return.takeAs<Stmt>());
8290 if (Trap.hasErrorOccurred()) {
8291 Diag(CurrentLocation, diag::note_member_synthesized_at)
8292 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8299 MoveAssignOperator->setInvalidDecl();
8303 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8304 /*isStmtExpr=*/false);
8305 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8306 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8308 if (ASTMutationListener *L = getASTMutationListener()) {
8309 L->CompletedImplicitDefinition(MoveAssignOperator);
8313 std::pair<Sema::ImplicitExceptionSpecification, bool>
8314 Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
8315 if (ClassDecl->isInvalidDecl())
8316 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8318 // C++ [class.copy]p5:
8319 // The implicitly-declared copy constructor for a class X will
8325 // FIXME: It ought to be possible to store this on the record.
8326 bool HasConstCopyConstructor = true;
8328 // -- each direct or virtual base class B of X has a copy
8329 // constructor whose first parameter is of type const B& or
8330 // const volatile B&, and
8331 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8332 BaseEnd = ClassDecl->bases_end();
8333 HasConstCopyConstructor && Base != BaseEnd;
8335 // Virtual bases are handled below.
8336 if (Base->isVirtual())
8339 CXXRecordDecl *BaseClassDecl
8340 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8341 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8342 &HasConstCopyConstructor);
8345 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8346 BaseEnd = ClassDecl->vbases_end();
8347 HasConstCopyConstructor && Base != BaseEnd;
8349 CXXRecordDecl *BaseClassDecl
8350 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8351 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8352 &HasConstCopyConstructor);
8355 // -- for all the nonstatic data members of X that are of a
8356 // class type M (or array thereof), each such class type
8357 // has a copy constructor whose first parameter is of type
8358 // const M& or const volatile M&.
8359 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8360 FieldEnd = ClassDecl->field_end();
8361 HasConstCopyConstructor && Field != FieldEnd;
8363 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8364 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8365 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8366 &HasConstCopyConstructor);
8369 // Otherwise, the implicitly declared copy constructor will have
8374 // C++ [except.spec]p14:
8375 // An implicitly declared special member function (Clause 12) shall have an
8376 // exception-specification. [...]
8377 ImplicitExceptionSpecification ExceptSpec(Context);
8378 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8379 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8380 BaseEnd = ClassDecl->bases_end();
8383 // Virtual bases are handled below.
8384 if (Base->isVirtual())
8387 CXXRecordDecl *BaseClassDecl
8388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8389 if (CXXConstructorDecl *CopyConstructor =
8390 LookupCopyingConstructor(BaseClassDecl, Quals))
8391 ExceptSpec.CalledDecl(CopyConstructor);
8393 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8394 BaseEnd = ClassDecl->vbases_end();
8397 CXXRecordDecl *BaseClassDecl
8398 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8399 if (CXXConstructorDecl *CopyConstructor =
8400 LookupCopyingConstructor(BaseClassDecl, Quals))
8401 ExceptSpec.CalledDecl(CopyConstructor);
8403 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8404 FieldEnd = ClassDecl->field_end();
8407 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8408 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8409 if (CXXConstructorDecl *CopyConstructor =
8410 LookupCopyingConstructor(FieldClassDecl, Quals))
8411 ExceptSpec.CalledDecl(CopyConstructor);
8415 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8418 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8419 CXXRecordDecl *ClassDecl) {
8420 // C++ [class.copy]p4:
8421 // If the class definition does not explicitly declare a copy
8422 // constructor, one is declared implicitly.
8424 ImplicitExceptionSpecification Spec(Context);
8426 llvm::tie(Spec, Const) =
8427 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8429 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8430 QualType ArgType = ClassType;
8432 ArgType = ArgType.withConst();
8433 ArgType = Context.getLValueReferenceType(ArgType);
8435 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8437 DeclarationName Name
8438 = Context.DeclarationNames.getCXXConstructorName(
8439 Context.getCanonicalType(ClassType));
8440 SourceLocation ClassLoc = ClassDecl->getLocation();
8441 DeclarationNameInfo NameInfo(Name, ClassLoc);
8443 // An implicitly-declared copy constructor is an inline public
8444 // member of its class.
8445 CXXConstructorDecl *CopyConstructor
8446 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8447 Context.getFunctionType(Context.VoidTy,
8450 /*isExplicit=*/false,
8452 /*isImplicitlyDeclared=*/true,
8453 // FIXME: apply the rules for definitions here
8454 /*isConstexpr=*/false);
8455 CopyConstructor->setAccess(AS_public);
8456 CopyConstructor->setDefaulted();
8457 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
8459 // Note that we have declared this constructor.
8460 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8462 // Add the parameter to the constructor.
8463 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
8465 /*IdentifierInfo=*/0,
8466 ArgType, /*TInfo=*/0,
8469 CopyConstructor->setParams(FromParam);
8471 if (Scope *S = getScopeForContext(ClassDecl))
8472 PushOnScopeChains(CopyConstructor, S, false);
8473 ClassDecl->addDecl(CopyConstructor);
8475 // C++0x [class.copy]p7:
8476 // ... If the class definition declares a move constructor or move
8477 // assignment operator, the implicitly declared constructor is defined as
8479 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
8480 ClassDecl->hasUserDeclaredMoveAssignment() ||
8481 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
8482 CopyConstructor->setDeletedAsWritten();
8484 return CopyConstructor;
8487 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
8488 CXXConstructorDecl *CopyConstructor) {
8489 assert((CopyConstructor->isDefaulted() &&
8490 CopyConstructor->isCopyConstructor() &&
8491 !CopyConstructor->doesThisDeclarationHaveABody()) &&
8492 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
8494 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
8495 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
8497 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
8498 DiagnosticErrorTrap Trap(Diags);
8500 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
8501 Trap.hasErrorOccurred()) {
8502 Diag(CurrentLocation, diag::note_member_synthesized_at)
8503 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
8504 CopyConstructor->setInvalidDecl();
8506 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8507 CopyConstructor->getLocation(),
8508 MultiStmtArg(*this, 0, 0),
8509 /*isStmtExpr=*/false)
8511 CopyConstructor->setImplicitlyDefined(true);
8514 CopyConstructor->setUsed();
8515 if (ASTMutationListener *L = getASTMutationListener()) {
8516 L->CompletedImplicitDefinition(CopyConstructor);
8520 Sema::ImplicitExceptionSpecification
8521 Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8522 // C++ [except.spec]p14:
8523 // An implicitly declared special member function (Clause 12) shall have an
8524 // exception-specification. [...]
8525 ImplicitExceptionSpecification ExceptSpec(Context);
8526 if (ClassDecl->isInvalidDecl())
8529 // Direct base-class constructors.
8530 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8531 BEnd = ClassDecl->bases_end();
8533 if (B->isVirtual()) // Handled below.
8536 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8537 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8538 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8539 // If this is a deleted function, add it anyway. This might be conformant
8540 // with the standard. This might not. I'm not sure. It might not matter.
8542 ExceptSpec.CalledDecl(Constructor);
8546 // Virtual base-class constructors.
8547 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8548 BEnd = ClassDecl->vbases_end();
8550 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8551 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8552 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8553 // If this is a deleted function, add it anyway. This might be conformant
8554 // with the standard. This might not. I'm not sure. It might not matter.
8556 ExceptSpec.CalledDecl(Constructor);
8560 // Field constructors.
8561 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8562 FEnd = ClassDecl->field_end();
8564 if (F->hasInClassInitializer()) {
8565 if (Expr *E = F->getInClassInitializer())
8566 ExceptSpec.CalledExpr(E);
8567 else if (!F->isInvalidDecl())
8568 ExceptSpec.SetDelayed();
8569 } else if (const RecordType *RecordTy
8570 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8571 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8572 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8573 // If this is a deleted function, add it anyway. This might be conformant
8574 // with the standard. This might not. I'm not sure. It might not matter.
8575 // In particular, the problem is that this function never gets called. It
8576 // might just be ill-formed because this function attempts to refer to
8577 // a deleted function here.
8579 ExceptSpec.CalledDecl(Constructor);
8586 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8587 CXXRecordDecl *ClassDecl) {
8588 ImplicitExceptionSpecification Spec(
8589 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8591 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8592 QualType ArgType = Context.getRValueReferenceType(ClassType);
8594 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8596 DeclarationName Name
8597 = Context.DeclarationNames.getCXXConstructorName(
8598 Context.getCanonicalType(ClassType));
8599 SourceLocation ClassLoc = ClassDecl->getLocation();
8600 DeclarationNameInfo NameInfo(Name, ClassLoc);
8602 // C++0x [class.copy]p11:
8603 // An implicitly-declared copy/move constructor is an inline public
8604 // member of its class.
8605 CXXConstructorDecl *MoveConstructor
8606 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8607 Context.getFunctionType(Context.VoidTy,
8610 /*isExplicit=*/false,
8612 /*isImplicitlyDeclared=*/true,
8613 // FIXME: apply the rules for definitions here
8614 /*isConstexpr=*/false);
8615 MoveConstructor->setAccess(AS_public);
8616 MoveConstructor->setDefaulted();
8617 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
8619 // Add the parameter to the constructor.
8620 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8622 /*IdentifierInfo=*/0,
8623 ArgType, /*TInfo=*/0,
8626 MoveConstructor->setParams(FromParam);
8628 // C++0x [class.copy]p9:
8629 // If the definition of a class X does not explicitly declare a move
8630 // constructor, one will be implicitly declared as defaulted if and only if:
8632 // - the move constructor would not be implicitly defined as deleted.
8633 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
8634 // Cache this result so that we don't try to generate this over and over
8635 // on every lookup, leaking memory and wasting time.
8636 ClassDecl->setFailedImplicitMoveConstructor();
8640 // Note that we have declared this constructor.
8641 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8643 if (Scope *S = getScopeForContext(ClassDecl))
8644 PushOnScopeChains(MoveConstructor, S, false);
8645 ClassDecl->addDecl(MoveConstructor);
8647 return MoveConstructor;
8650 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8651 CXXConstructorDecl *MoveConstructor) {
8652 assert((MoveConstructor->isDefaulted() &&
8653 MoveConstructor->isMoveConstructor() &&
8654 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8655 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8657 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8658 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8660 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8661 DiagnosticErrorTrap Trap(Diags);
8663 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8664 Trap.hasErrorOccurred()) {
8665 Diag(CurrentLocation, diag::note_member_synthesized_at)
8666 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8667 MoveConstructor->setInvalidDecl();
8669 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8670 MoveConstructor->getLocation(),
8671 MultiStmtArg(*this, 0, 0),
8672 /*isStmtExpr=*/false)
8674 MoveConstructor->setImplicitlyDefined(true);
8677 MoveConstructor->setUsed();
8679 if (ASTMutationListener *L = getASTMutationListener()) {
8680 L->CompletedImplicitDefinition(MoveConstructor);
8685 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8686 CXXConstructorDecl *Constructor,
8687 MultiExprArg ExprArgs,
8688 bool HadMultipleCandidates,
8689 bool RequiresZeroInit,
8690 unsigned ConstructKind,
8691 SourceRange ParenRange) {
8692 bool Elidable = false;
8694 // C++0x [class.copy]p34:
8695 // When certain criteria are met, an implementation is allowed to
8696 // omit the copy/move construction of a class object, even if the
8697 // copy/move constructor and/or destructor for the object have
8698 // side effects. [...]
8699 // - when a temporary class object that has not been bound to a
8700 // reference (12.2) would be copied/moved to a class object
8701 // with the same cv-unqualified type, the copy/move operation
8702 // can be omitted by constructing the temporary object
8703 // directly into the target of the omitted copy/move
8704 if (ConstructKind == CXXConstructExpr::CK_Complete &&
8705 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
8706 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
8707 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
8710 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
8711 Elidable, move(ExprArgs), HadMultipleCandidates,
8712 RequiresZeroInit, ConstructKind, ParenRange);
8715 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
8716 /// including handling of its default argument expressions.
8718 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
8719 CXXConstructorDecl *Constructor, bool Elidable,
8720 MultiExprArg ExprArgs,
8721 bool HadMultipleCandidates,
8722 bool RequiresZeroInit,
8723 unsigned ConstructKind,
8724 SourceRange ParenRange) {
8725 unsigned NumExprs = ExprArgs.size();
8726 Expr **Exprs = (Expr **)ExprArgs.release();
8728 for (specific_attr_iterator<NonNullAttr>
8729 i = Constructor->specific_attr_begin<NonNullAttr>(),
8730 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
8731 const NonNullAttr *NonNull = *i;
8732 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
8735 MarkDeclarationReferenced(ConstructLoc, Constructor);
8736 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
8737 Constructor, Elidable, Exprs, NumExprs,
8738 HadMultipleCandidates, RequiresZeroInit,
8739 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
8743 bool Sema::InitializeVarWithConstructor(VarDecl *VD,
8744 CXXConstructorDecl *Constructor,
8746 bool HadMultipleCandidates) {
8747 // FIXME: Provide the correct paren SourceRange when available.
8748 ExprResult TempResult =
8749 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
8750 move(Exprs), HadMultipleCandidates, false,
8751 CXXConstructExpr::CK_Complete, SourceRange());
8752 if (TempResult.isInvalid())
8755 Expr *Temp = TempResult.takeAs<Expr>();
8756 CheckImplicitConversions(Temp, VD->getLocation());
8757 MarkDeclarationReferenced(VD->getLocation(), Constructor);
8758 Temp = MaybeCreateExprWithCleanups(Temp);
8764 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
8765 if (VD->isInvalidDecl()) return;
8767 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
8768 if (ClassDecl->isInvalidDecl()) return;
8769 if (ClassDecl->hasTrivialDestructor()) return;
8770 if (ClassDecl->isDependentContext()) return;
8772 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8773 MarkDeclarationReferenced(VD->getLocation(), Destructor);
8774 CheckDestructorAccess(VD->getLocation(), Destructor,
8775 PDiag(diag::err_access_dtor_var)
8776 << VD->getDeclName()
8779 if (!VD->hasGlobalStorage()) return;
8781 // Emit warning for non-trivial dtor in global scope (a real global,
8782 // class-static, function-static).
8783 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
8785 // TODO: this should be re-enabled for static locals by !CXAAtExit
8786 if (!VD->isStaticLocal())
8787 Diag(VD->getLocation(), diag::warn_global_destructor);
8790 /// AddCXXDirectInitializerToDecl - This action is called immediately after
8791 /// ActOnDeclarator, when a C++ direct initializer is present.
8792 /// e.g: "int x(1);"
8793 void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
8794 SourceLocation LParenLoc,
8796 SourceLocation RParenLoc,
8797 bool TypeMayContainAuto) {
8798 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
8800 // If there is no declaration, there was an error parsing it. Just ignore
8805 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8807 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8808 RealDecl->setInvalidDecl();
8812 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8813 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
8814 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
8815 if (Exprs.size() > 1) {
8816 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
8817 diag::err_auto_var_init_multiple_expressions)
8818 << VDecl->getDeclName() << VDecl->getType()
8819 << VDecl->getSourceRange();
8820 RealDecl->setInvalidDecl();
8824 Expr *Init = Exprs.get()[0];
8825 TypeSourceInfo *DeducedType = 0;
8826 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
8827 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
8828 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
8829 << Init->getSourceRange();
8831 RealDecl->setInvalidDecl();
8834 VDecl->setTypeSourceInfo(DeducedType);
8835 VDecl->setType(DeducedType->getType());
8837 // In ARC, infer lifetime.
8838 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8839 VDecl->setInvalidDecl();
8841 // If this is a redeclaration, check that the type we just deduced matches
8842 // the previously declared type.
8843 if (VarDecl *Old = VDecl->getPreviousDeclaration())
8844 MergeVarDeclTypes(VDecl, Old);
8847 // We will represent direct-initialization similarly to copy-initialization:
8848 // int x(1); -as-> int x = 1;
8849 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8851 // Clients that want to distinguish between the two forms, can check for
8852 // direct initializer using VarDecl::hasCXXDirectInitializer().
8853 // A major benefit is that clients that don't particularly care about which
8854 // exactly form was it (like the CodeGen) can handle both cases without
8855 // special case code.
8858 // The form of initialization (using parentheses or '=') is generally
8859 // insignificant, but does matter when the entity being initialized has a
8862 if (!VDecl->getType()->isDependentType() &&
8863 !VDecl->getType()->isIncompleteArrayType() &&
8864 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
8865 diag::err_typecheck_decl_incomplete_type)) {
8866 VDecl->setInvalidDecl();
8870 // The variable can not have an abstract class type.
8871 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8872 diag::err_abstract_type_in_decl,
8873 AbstractVariableType))
8874 VDecl->setInvalidDecl();
8877 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8878 Diag(VDecl->getLocation(), diag::err_redefinition)
8879 << VDecl->getDeclName();
8880 Diag(Def->getLocation(), diag::note_previous_definition);
8881 VDecl->setInvalidDecl();
8885 // C++ [class.static.data]p4
8886 // If a static data member is of const integral or const
8887 // enumeration type, its declaration in the class definition can
8888 // specify a constant-initializer which shall be an integral
8889 // constant expression (5.19). In that case, the member can appear
8890 // in integral constant expressions. The member shall still be
8891 // defined in a namespace scope if it is used in the program and the
8892 // namespace scope definition shall not contain an initializer.
8894 // We already performed a redefinition check above, but for static
8895 // data members we also need to check whether there was an in-class
8896 // declaration with an initializer.
8897 const VarDecl* PrevInit = 0;
8898 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8899 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
8900 Diag(PrevInit->getLocation(), diag::note_previous_definition);
8904 bool IsDependent = false;
8905 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
8906 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
8907 VDecl->setInvalidDecl();
8911 if (Exprs.get()[I]->isTypeDependent())
8915 // If either the declaration has a dependent type or if any of the
8916 // expressions is type-dependent, we represent the initialization
8917 // via a ParenListExpr for later use during template instantiation.
8918 if (VDecl->getType()->isDependentType() || IsDependent) {
8919 // Let clients know that initialization was done with a direct initializer.
8920 VDecl->setCXXDirectInitializer(true);
8922 // Store the initialization expressions as a ParenListExpr.
8923 unsigned NumExprs = Exprs.size();
8924 VDecl->setInit(new (Context) ParenListExpr(
8925 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
8926 VDecl->getType().getNonReferenceType()));
8930 // Capture the variable that is being initialized and the style of
8932 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8934 // FIXME: Poor source location information.
8935 InitializationKind Kind
8936 = InitializationKind::CreateDirect(VDecl->getLocation(),
8937 LParenLoc, RParenLoc);
8939 QualType T = VDecl->getType();
8940 InitializationSequence InitSeq(*this, Entity, Kind,
8941 Exprs.get(), Exprs.size());
8942 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
8943 if (Result.isInvalid()) {
8944 VDecl->setInvalidDecl();
8946 } else if (T != VDecl->getType()) {
8948 Result.get()->setType(T);
8952 Expr *Init = Result.get();
8953 CheckImplicitConversions(Init, LParenLoc);
8955 if (VDecl->isConstexpr() && !VDecl->isInvalidDecl() &&
8956 !Init->isValueDependent() &&
8957 !Init->isConstantInitializer(Context,
8958 VDecl->getType()->isReferenceType())) {
8959 // FIXME: Improve this diagnostic to explain why the initializer is not
8960 // a constant expression.
8961 Diag(VDecl->getLocation(), diag::err_constexpr_var_requires_const_init)
8962 << VDecl << Init->getSourceRange();
8965 Init = MaybeCreateExprWithCleanups(Init);
8966 VDecl->setInit(Init);
8967 VDecl->setCXXDirectInitializer(true);
8969 CheckCompleteVariableDeclaration(VDecl);
8972 /// \brief Given a constructor and the set of arguments provided for the
8973 /// constructor, convert the arguments and add any required default arguments
8974 /// to form a proper call to this constructor.
8976 /// \returns true if an error occurred, false otherwise.
8978 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
8979 MultiExprArg ArgsPtr,
8981 ASTOwningVector<Expr*> &ConvertedArgs) {
8982 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
8983 unsigned NumArgs = ArgsPtr.size();
8984 Expr **Args = (Expr **)ArgsPtr.get();
8986 const FunctionProtoType *Proto
8987 = Constructor->getType()->getAs<FunctionProtoType>();
8988 assert(Proto && "Constructor without a prototype?");
8989 unsigned NumArgsInProto = Proto->getNumArgs();
8991 // If too few arguments are available, we'll fill in the rest with defaults.
8992 if (NumArgs < NumArgsInProto)
8993 ConvertedArgs.reserve(NumArgsInProto);
8995 ConvertedArgs.reserve(NumArgs);
8997 VariadicCallType CallType =
8998 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
8999 SmallVector<Expr *, 8> AllArgs;
9000 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9001 Proto, 0, Args, NumArgs, AllArgs,
9003 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9004 ConvertedArgs.push_back(AllArgs[i]);
9009 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9010 const FunctionDecl *FnDecl) {
9011 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
9012 if (isa<NamespaceDecl>(DC)) {
9013 return SemaRef.Diag(FnDecl->getLocation(),
9014 diag::err_operator_new_delete_declared_in_namespace)
9015 << FnDecl->getDeclName();
9018 if (isa<TranslationUnitDecl>(DC) &&
9019 FnDecl->getStorageClass() == SC_Static) {
9020 return SemaRef.Diag(FnDecl->getLocation(),
9021 diag::err_operator_new_delete_declared_static)
9022 << FnDecl->getDeclName();
9029 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9030 CanQualType ExpectedResultType,
9031 CanQualType ExpectedFirstParamType,
9032 unsigned DependentParamTypeDiag,
9033 unsigned InvalidParamTypeDiag) {
9034 QualType ResultType =
9035 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9037 // Check that the result type is not dependent.
9038 if (ResultType->isDependentType())
9039 return SemaRef.Diag(FnDecl->getLocation(),
9040 diag::err_operator_new_delete_dependent_result_type)
9041 << FnDecl->getDeclName() << ExpectedResultType;
9043 // Check that the result type is what we expect.
9044 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9045 return SemaRef.Diag(FnDecl->getLocation(),
9046 diag::err_operator_new_delete_invalid_result_type)
9047 << FnDecl->getDeclName() << ExpectedResultType;
9049 // A function template must have at least 2 parameters.
9050 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9051 return SemaRef.Diag(FnDecl->getLocation(),
9052 diag::err_operator_new_delete_template_too_few_parameters)
9053 << FnDecl->getDeclName();
9055 // The function decl must have at least 1 parameter.
9056 if (FnDecl->getNumParams() == 0)
9057 return SemaRef.Diag(FnDecl->getLocation(),
9058 diag::err_operator_new_delete_too_few_parameters)
9059 << FnDecl->getDeclName();
9061 // Check the the first parameter type is not dependent.
9062 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9063 if (FirstParamType->isDependentType())
9064 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9065 << FnDecl->getDeclName() << ExpectedFirstParamType;
9067 // Check that the first parameter type is what we expect.
9068 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
9069 ExpectedFirstParamType)
9070 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9071 << FnDecl->getDeclName() << ExpectedFirstParamType;
9077 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9078 // C++ [basic.stc.dynamic.allocation]p1:
9079 // A program is ill-formed if an allocation function is declared in a
9080 // namespace scope other than global scope or declared static in global
9082 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9085 CanQualType SizeTy =
9086 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9088 // C++ [basic.stc.dynamic.allocation]p1:
9089 // The return type shall be void*. The first parameter shall have type
9091 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9093 diag::err_operator_new_dependent_param_type,
9094 diag::err_operator_new_param_type))
9097 // C++ [basic.stc.dynamic.allocation]p1:
9098 // The first parameter shall not have an associated default argument.
9099 if (FnDecl->getParamDecl(0)->hasDefaultArg())
9100 return SemaRef.Diag(FnDecl->getLocation(),
9101 diag::err_operator_new_default_arg)
9102 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9108 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9109 // C++ [basic.stc.dynamic.deallocation]p1:
9110 // A program is ill-formed if deallocation functions are declared in a
9111 // namespace scope other than global scope or declared static in global
9113 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9116 // C++ [basic.stc.dynamic.deallocation]p2:
9117 // Each deallocation function shall return void and its first parameter
9119 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9120 SemaRef.Context.VoidPtrTy,
9121 diag::err_operator_delete_dependent_param_type,
9122 diag::err_operator_delete_param_type))
9128 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
9129 /// of this overloaded operator is well-formed. If so, returns false;
9130 /// otherwise, emits appropriate diagnostics and returns true.
9131 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
9132 assert(FnDecl && FnDecl->isOverloadedOperator() &&
9133 "Expected an overloaded operator declaration");
9135 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9137 // C++ [over.oper]p5:
9138 // The allocation and deallocation functions, operator new,
9139 // operator new[], operator delete and operator delete[], are
9140 // described completely in 3.7.3. The attributes and restrictions
9141 // found in the rest of this subclause do not apply to them unless
9142 // explicitly stated in 3.7.3.
9143 if (Op == OO_Delete || Op == OO_Array_Delete)
9144 return CheckOperatorDeleteDeclaration(*this, FnDecl);
9146 if (Op == OO_New || Op == OO_Array_New)
9147 return CheckOperatorNewDeclaration(*this, FnDecl);
9149 // C++ [over.oper]p6:
9150 // An operator function shall either be a non-static member
9151 // function or be a non-member function and have at least one
9152 // parameter whose type is a class, a reference to a class, an
9153 // enumeration, or a reference to an enumeration.
9154 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9155 if (MethodDecl->isStatic())
9156 return Diag(FnDecl->getLocation(),
9157 diag::err_operator_overload_static) << FnDecl->getDeclName();
9159 bool ClassOrEnumParam = false;
9160 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9161 ParamEnd = FnDecl->param_end();
9162 Param != ParamEnd; ++Param) {
9163 QualType ParamType = (*Param)->getType().getNonReferenceType();
9164 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9165 ParamType->isEnumeralType()) {
9166 ClassOrEnumParam = true;
9171 if (!ClassOrEnumParam)
9172 return Diag(FnDecl->getLocation(),
9173 diag::err_operator_overload_needs_class_or_enum)
9174 << FnDecl->getDeclName();
9177 // C++ [over.oper]p8:
9178 // An operator function cannot have default arguments (8.3.6),
9179 // except where explicitly stated below.
9181 // Only the function-call operator allows default arguments
9182 // (C++ [over.call]p1).
9183 if (Op != OO_Call) {
9184 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9185 Param != FnDecl->param_end(); ++Param) {
9186 if ((*Param)->hasDefaultArg())
9187 return Diag((*Param)->getLocation(),
9188 diag::err_operator_overload_default_arg)
9189 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
9193 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9194 { false, false, false }
9195 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9196 , { Unary, Binary, MemberOnly }
9197 #include "clang/Basic/OperatorKinds.def"
9200 bool CanBeUnaryOperator = OperatorUses[Op][0];
9201 bool CanBeBinaryOperator = OperatorUses[Op][1];
9202 bool MustBeMemberOperator = OperatorUses[Op][2];
9204 // C++ [over.oper]p8:
9205 // [...] Operator functions cannot have more or fewer parameters
9206 // than the number required for the corresponding operator, as
9207 // described in the rest of this subclause.
9208 unsigned NumParams = FnDecl->getNumParams()
9209 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
9210 if (Op != OO_Call &&
9211 ((NumParams == 1 && !CanBeUnaryOperator) ||
9212 (NumParams == 2 && !CanBeBinaryOperator) ||
9213 (NumParams < 1) || (NumParams > 2))) {
9214 // We have the wrong number of parameters.
9216 if (CanBeUnaryOperator && CanBeBinaryOperator) {
9217 ErrorKind = 2; // 2 -> unary or binary.
9218 } else if (CanBeUnaryOperator) {
9219 ErrorKind = 0; // 0 -> unary
9221 assert(CanBeBinaryOperator &&
9222 "All non-call overloaded operators are unary or binary!");
9223 ErrorKind = 1; // 1 -> binary
9226 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
9227 << FnDecl->getDeclName() << NumParams << ErrorKind;
9230 // Overloaded operators other than operator() cannot be variadic.
9231 if (Op != OO_Call &&
9232 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
9233 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
9234 << FnDecl->getDeclName();
9237 // Some operators must be non-static member functions.
9238 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9239 return Diag(FnDecl->getLocation(),
9240 diag::err_operator_overload_must_be_member)
9241 << FnDecl->getDeclName();
9244 // C++ [over.inc]p1:
9245 // The user-defined function called operator++ implements the
9246 // prefix and postfix ++ operator. If this function is a member
9247 // function with no parameters, or a non-member function with one
9248 // parameter of class or enumeration type, it defines the prefix
9249 // increment operator ++ for objects of that type. If the function
9250 // is a member function with one parameter (which shall be of type
9251 // int) or a non-member function with two parameters (the second
9252 // of which shall be of type int), it defines the postfix
9253 // increment operator ++ for objects of that type.
9254 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9255 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9256 bool ParamIsInt = false;
9257 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
9258 ParamIsInt = BT->getKind() == BuiltinType::Int;
9261 return Diag(LastParam->getLocation(),
9262 diag::err_operator_overload_post_incdec_must_be_int)
9263 << LastParam->getType() << (Op == OO_MinusMinus);
9269 /// CheckLiteralOperatorDeclaration - Check whether the declaration
9270 /// of this literal operator function is well-formed. If so, returns
9271 /// false; otherwise, emits appropriate diagnostics and returns true.
9272 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9273 DeclContext *DC = FnDecl->getDeclContext();
9274 Decl::Kind Kind = DC->getDeclKind();
9275 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9276 Kind != Decl::LinkageSpec) {
9277 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9278 << FnDecl->getDeclName();
9284 // template <char...> type operator "" name() is the only valid template
9285 // signature, and the only valid signature with no parameters.
9286 if (FnDecl->param_size() == 0) {
9287 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9288 // Must have only one template parameter
9289 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9290 if (Params->size() == 1) {
9291 NonTypeTemplateParmDecl *PmDecl =
9292 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
9294 // The template parameter must be a char parameter pack.
9295 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9296 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9301 // Check the first parameter
9302 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9304 QualType T = (*Param)->getType();
9306 // unsigned long long int, long double, and any character type are allowed
9307 // as the only parameters.
9308 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9309 Context.hasSameType(T, Context.LongDoubleTy) ||
9310 Context.hasSameType(T, Context.CharTy) ||
9311 Context.hasSameType(T, Context.WCharTy) ||
9312 Context.hasSameType(T, Context.Char16Ty) ||
9313 Context.hasSameType(T, Context.Char32Ty)) {
9314 if (++Param == FnDecl->param_end())
9316 goto FinishedParams;
9319 // Otherwise it must be a pointer to const; let's strip those qualifiers.
9320 const PointerType *PT = T->getAs<PointerType>();
9322 goto FinishedParams;
9323 T = PT->getPointeeType();
9324 if (!T.isConstQualified())
9325 goto FinishedParams;
9326 T = T.getUnqualifiedType();
9328 // Move on to the second parameter;
9331 // If there is no second parameter, the first must be a const char *
9332 if (Param == FnDecl->param_end()) {
9333 if (Context.hasSameType(T, Context.CharTy))
9335 goto FinishedParams;
9338 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9339 // are allowed as the first parameter to a two-parameter function
9340 if (!(Context.hasSameType(T, Context.CharTy) ||
9341 Context.hasSameType(T, Context.WCharTy) ||
9342 Context.hasSameType(T, Context.Char16Ty) ||
9343 Context.hasSameType(T, Context.Char32Ty)))
9344 goto FinishedParams;
9346 // The second and final parameter must be an std::size_t
9347 T = (*Param)->getType().getUnqualifiedType();
9348 if (Context.hasSameType(T, Context.getSizeType()) &&
9349 ++Param == FnDecl->param_end())
9353 // FIXME: This diagnostic is absolutely terrible.
9356 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9357 << FnDecl->getDeclName();
9361 StringRef LiteralName
9362 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9363 if (LiteralName[0] != '_') {
9364 // C++0x [usrlit.suffix]p1:
9365 // Literal suffix identifiers that do not start with an underscore are
9366 // reserved for future standardization.
9367 bool IsHexFloat = true;
9368 if (LiteralName.size() > 1 &&
9369 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9370 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9371 if (!isdigit(LiteralName[I])) {
9379 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9382 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9388 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9389 /// linkage specification, including the language and (if present)
9390 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9391 /// the location of the language string literal, which is provided
9392 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9393 /// the '{' brace. Otherwise, this linkage specification does not
9394 /// have any braces.
9395 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9396 SourceLocation LangLoc,
9398 SourceLocation LBraceLoc) {
9399 LinkageSpecDecl::LanguageIDs Language;
9400 if (Lang == "\"C\"")
9401 Language = LinkageSpecDecl::lang_c;
9402 else if (Lang == "\"C++\"")
9403 Language = LinkageSpecDecl::lang_cxx;
9405 Diag(LangLoc, diag::err_bad_language);
9409 // FIXME: Add all the various semantics of linkage specifications
9411 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
9412 ExternLoc, LangLoc, Language);
9413 CurContext->addDecl(D);
9414 PushDeclContext(S, D);
9418 /// ActOnFinishLinkageSpecification - Complete the definition of
9419 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
9420 /// valid, it's the position of the closing '}' brace in a linkage
9421 /// specification that uses braces.
9422 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
9424 SourceLocation RBraceLoc) {
9426 if (RBraceLoc.isValid()) {
9427 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9428 LSDecl->setRBraceLoc(RBraceLoc);
9435 /// \brief Perform semantic analysis for the variable declaration that
9436 /// occurs within a C++ catch clause, returning the newly-created
9438 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
9439 TypeSourceInfo *TInfo,
9440 SourceLocation StartLoc,
9442 IdentifierInfo *Name) {
9443 bool Invalid = false;
9444 QualType ExDeclType = TInfo->getType();
9446 // Arrays and functions decay.
9447 if (ExDeclType->isArrayType())
9448 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9449 else if (ExDeclType->isFunctionType())
9450 ExDeclType = Context.getPointerType(ExDeclType);
9452 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9453 // The exception-declaration shall not denote a pointer or reference to an
9454 // incomplete type, other than [cv] void*.
9455 // N2844 forbids rvalue references.
9456 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
9457 Diag(Loc, diag::err_catch_rvalue_ref);
9461 // GCC allows catching pointers and references to incomplete types
9462 // as an extension; so do we, but we warn by default.
9464 QualType BaseType = ExDeclType;
9465 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
9466 unsigned DK = diag::err_catch_incomplete;
9467 bool IncompleteCatchIsInvalid = true;
9468 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
9469 BaseType = Ptr->getPointeeType();
9471 DK = diag::ext_catch_incomplete_ptr;
9472 IncompleteCatchIsInvalid = false;
9473 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
9474 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
9475 BaseType = Ref->getPointeeType();
9477 DK = diag::ext_catch_incomplete_ref;
9478 IncompleteCatchIsInvalid = false;
9480 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
9481 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
9482 IncompleteCatchIsInvalid)
9485 if (!Invalid && !ExDeclType->isDependentType() &&
9486 RequireNonAbstractType(Loc, ExDeclType,
9487 diag::err_abstract_type_in_decl,
9488 AbstractVariableType))
9491 // Only the non-fragile NeXT runtime currently supports C++ catches
9492 // of ObjC types, and no runtime supports catching ObjC types by value.
9493 if (!Invalid && getLangOptions().ObjC1) {
9494 QualType T = ExDeclType;
9495 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9496 T = RT->getPointeeType();
9498 if (T->isObjCObjectType()) {
9499 Diag(Loc, diag::err_objc_object_catch);
9501 } else if (T->isObjCObjectPointerType()) {
9502 if (!getLangOptions().ObjCNonFragileABI)
9503 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
9507 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9508 ExDeclType, TInfo, SC_None, SC_None);
9509 ExDecl->setExceptionVariable(true);
9511 if (!Invalid && !ExDeclType->isDependentType()) {
9512 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
9513 // C++ [except.handle]p16:
9514 // The object declared in an exception-declaration or, if the
9515 // exception-declaration does not specify a name, a temporary (12.2) is
9516 // copy-initialized (8.5) from the exception object. [...]
9517 // The object is destroyed when the handler exits, after the destruction
9518 // of any automatic objects initialized within the handler.
9520 // We just pretend to initialize the object with itself, then make sure
9521 // it can be destroyed later.
9522 QualType initType = ExDeclType;
9524 InitializedEntity entity =
9525 InitializedEntity::InitializeVariable(ExDecl);
9526 InitializationKind initKind =
9527 InitializationKind::CreateCopy(Loc, SourceLocation());
9530 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9531 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9532 ExprResult result = sequence.Perform(*this, entity, initKind,
9533 MultiExprArg(&opaqueValue, 1));
9534 if (result.isInvalid())
9537 // If the constructor used was non-trivial, set this as the
9539 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9540 if (!construct->getConstructor()->isTrivial()) {
9541 Expr *init = MaybeCreateExprWithCleanups(construct);
9542 ExDecl->setInit(init);
9545 // And make sure it's destructable.
9546 FinalizeVarWithDestructor(ExDecl, recordType);
9552 ExDecl->setInvalidDecl();
9557 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9559 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
9560 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9561 bool Invalid = D.isInvalidType();
9563 // Check for unexpanded parameter packs.
9564 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9565 UPPC_ExceptionType)) {
9566 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9567 D.getIdentifierLoc());
9571 IdentifierInfo *II = D.getIdentifier();
9572 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
9574 ForRedeclaration)) {
9575 // The scope should be freshly made just for us. There is just no way
9576 // it contains any previous declaration.
9577 assert(!S->isDeclScope(PrevDecl));
9578 if (PrevDecl->isTemplateParameter()) {
9579 // Maybe we will complain about the shadowed template parameter.
9580 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9584 if (D.getCXXScopeSpec().isSet() && !Invalid) {
9585 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9586 << D.getCXXScopeSpec().getRange();
9590 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
9591 D.getSourceRange().getBegin(),
9592 D.getIdentifierLoc(),
9595 ExDecl->setInvalidDecl();
9597 // Add the exception declaration into this scope.
9599 PushOnScopeChains(ExDecl, S);
9601 CurContext->addDecl(ExDecl);
9603 ProcessDeclAttributes(S, ExDecl, D);
9607 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
9609 Expr *AssertMessageExpr_,
9610 SourceLocation RParenLoc) {
9611 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
9613 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
9614 llvm::APSInt Value(32);
9615 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
9616 Diag(StaticAssertLoc,
9617 diag::err_static_assert_expression_is_not_constant) <<
9618 AssertExpr->getSourceRange();
9623 Diag(StaticAssertLoc, diag::err_static_assert_failed)
9624 << AssertMessage->getString() << AssertExpr->getSourceRange();
9628 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9631 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9632 AssertExpr, AssertMessage, RParenLoc);
9634 CurContext->addDecl(Decl);
9638 /// \brief Perform semantic analysis of the given friend type declaration.
9640 /// \returns A friend declaration that.
9641 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
9642 TypeSourceInfo *TSInfo) {
9643 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9645 QualType T = TSInfo->getType();
9646 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
9648 if (!getLangOptions().CPlusPlus0x) {
9649 // C++03 [class.friend]p2:
9650 // An elaborated-type-specifier shall be used in a friend declaration
9653 // * The class-key of the elaborated-type-specifier is required.
9654 if (!ActiveTemplateInstantiations.empty()) {
9655 // Do not complain about the form of friend template types during
9656 // template instantiation; we will already have complained when the
9657 // template was declared.
9658 } else if (!T->isElaboratedTypeSpecifier()) {
9659 // If we evaluated the type to a record type, suggest putting
9661 if (const RecordType *RT = T->getAs<RecordType>()) {
9662 RecordDecl *RD = RT->getDecl();
9664 std::string InsertionText = std::string(" ") + RD->getKindName();
9666 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
9667 << (unsigned) RD->getTagKind()
9669 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9672 Diag(FriendLoc, diag::ext_nonclass_type_friend)
9674 << SourceRange(FriendLoc, TypeRange.getEnd());
9676 } else if (T->getAs<EnumType>()) {
9677 Diag(FriendLoc, diag::ext_enum_friend)
9679 << SourceRange(FriendLoc, TypeRange.getEnd());
9683 // C++0x [class.friend]p3:
9684 // If the type specifier in a friend declaration designates a (possibly
9685 // cv-qualified) class type, that class is declared as a friend; otherwise,
9686 // the friend declaration is ignored.
9688 // FIXME: C++0x has some syntactic restrictions on friend type declarations
9689 // in [class.friend]p3 that we do not implement.
9691 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
9694 /// Handle a friend tag declaration where the scope specifier was
9696 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
9697 unsigned TagSpec, SourceLocation TagLoc,
9699 IdentifierInfo *Name, SourceLocation NameLoc,
9700 AttributeList *Attr,
9701 MultiTemplateParamsArg TempParamLists) {
9702 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9704 bool isExplicitSpecialization = false;
9705 bool Invalid = false;
9707 if (TemplateParameterList *TemplateParams
9708 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
9709 TempParamLists.get(),
9710 TempParamLists.size(),
9712 isExplicitSpecialization,
9714 if (TemplateParams->size() > 0) {
9715 // This is a declaration of a class template.
9719 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
9720 SS, Name, NameLoc, Attr,
9721 TemplateParams, AS_public,
9722 /*ModulePrivateLoc=*/SourceLocation(),
9723 TempParamLists.size() - 1,
9724 (TemplateParameterList**) TempParamLists.release()).take();
9726 // The "template<>" header is extraneous.
9727 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
9728 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
9729 isExplicitSpecialization = true;
9733 if (Invalid) return 0;
9735 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
9737 bool isAllExplicitSpecializations = true;
9738 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
9739 if (TempParamLists.get()[I]->size()) {
9740 isAllExplicitSpecializations = false;
9745 // FIXME: don't ignore attributes.
9747 // If it's explicit specializations all the way down, just forget
9748 // about the template header and build an appropriate non-templated
9749 // friend. TODO: for source fidelity, remember the headers.
9750 if (isAllExplicitSpecializations) {
9751 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9752 ElaboratedTypeKeyword Keyword
9753 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9754 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
9759 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9760 if (isa<DependentNameType>(T)) {
9761 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9762 TL.setKeywordLoc(TagLoc);
9763 TL.setQualifierLoc(QualifierLoc);
9764 TL.setNameLoc(NameLoc);
9766 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
9767 TL.setKeywordLoc(TagLoc);
9768 TL.setQualifierLoc(QualifierLoc);
9769 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
9772 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9774 Friend->setAccess(AS_public);
9775 CurContext->addDecl(Friend);
9779 // Handle the case of a templated-scope friend class. e.g.
9780 // template <class T> class A<T>::B;
9781 // FIXME: we don't support these right now.
9782 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9783 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
9784 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9785 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
9786 TL.setKeywordLoc(TagLoc);
9787 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9788 TL.setNameLoc(NameLoc);
9790 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
9792 Friend->setAccess(AS_public);
9793 Friend->setUnsupportedFriend(true);
9794 CurContext->addDecl(Friend);
9799 /// Handle a friend type declaration. This works in tandem with
9802 /// Notes on friend class templates:
9804 /// We generally treat friend class declarations as if they were
9805 /// declaring a class. So, for example, the elaborated type specifier
9806 /// in a friend declaration is required to obey the restrictions of a
9807 /// class-head (i.e. no typedefs in the scope chain), template
9808 /// parameters are required to match up with simple template-ids, &c.
9809 /// However, unlike when declaring a template specialization, it's
9810 /// okay to refer to a template specialization without an empty
9811 /// template parameter declaration, e.g.
9812 /// friend class A<T>::B<unsigned>;
9813 /// We permit this as a special case; if there are any template
9814 /// parameters present at all, require proper matching, i.e.
9815 /// template <> template <class T> friend class A<int>::B;
9816 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
9817 MultiTemplateParamsArg TempParams) {
9818 SourceLocation Loc = DS.getSourceRange().getBegin();
9820 assert(DS.isFriendSpecified());
9821 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9823 // Try to convert the decl specifier to a type. This works for
9824 // friend templates because ActOnTag never produces a ClassTemplateDecl
9825 // for a TUK_Friend.
9826 Declarator TheDeclarator(DS, Declarator::MemberContext);
9827 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
9828 QualType T = TSI->getType();
9829 if (TheDeclarator.isInvalidType())
9832 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
9835 // This is definitely an error in C++98. It's probably meant to
9836 // be forbidden in C++0x, too, but the specification is just
9839 // The problem is with declarations like the following:
9840 // template <T> friend A<T>::foo;
9841 // where deciding whether a class C is a friend or not now hinges
9842 // on whether there exists an instantiation of A that causes
9843 // 'foo' to equal C. There are restrictions on class-heads
9844 // (which we declare (by fiat) elaborated friend declarations to
9845 // be) that makes this tractable.
9847 // FIXME: handle "template <> friend class A<T>;", which
9848 // is possibly well-formed? Who even knows?
9849 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
9850 Diag(Loc, diag::err_tagless_friend_type_template)
9851 << DS.getSourceRange();
9855 // C++98 [class.friend]p1: A friend of a class is a function
9856 // or class that is not a member of the class . . .
9857 // This is fixed in DR77, which just barely didn't make the C++03
9858 // deadline. It's also a very silly restriction that seriously
9859 // affects inner classes and which nobody else seems to implement;
9860 // thus we never diagnose it, not even in -pedantic.
9862 // But note that we could warn about it: it's always useless to
9863 // friend one of your own members (it's not, however, worthless to
9864 // friend a member of an arbitrary specialization of your template).
9867 if (unsigned NumTempParamLists = TempParams.size())
9868 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
9870 TempParams.release(),
9872 DS.getFriendSpecLoc());
9874 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
9879 D->setAccess(AS_public);
9880 CurContext->addDecl(D);
9885 Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
9886 MultiTemplateParamsArg TemplateParams) {
9887 const DeclSpec &DS = D.getDeclSpec();
9889 assert(DS.isFriendSpecified());
9890 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
9892 SourceLocation Loc = D.getIdentifierLoc();
9893 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9895 // C++ [class.friend]p1
9896 // A friend of a class is a function or class....
9897 // Note that this sees through typedefs, which is intended.
9898 // It *doesn't* see through dependent types, which is correct
9899 // according to [temp.arg.type]p3:
9900 // If a declaration acquires a function type through a
9901 // type dependent on a template-parameter and this causes
9902 // a declaration that does not use the syntactic form of a
9903 // function declarator to have a function type, the program
9905 if (!TInfo->getType()->isFunctionType()) {
9906 Diag(Loc, diag::err_unexpected_friend);
9908 // It might be worthwhile to try to recover by creating an
9909 // appropriate declaration.
9913 // C++ [namespace.memdef]p3
9914 // - If a friend declaration in a non-local class first declares a
9915 // class or function, the friend class or function is a member
9916 // of the innermost enclosing namespace.
9917 // - The name of the friend is not found by simple name lookup
9918 // until a matching declaration is provided in that namespace
9919 // scope (either before or after the class declaration granting
9921 // - If a friend function is called, its name may be found by the
9922 // name lookup that considers functions from namespaces and
9923 // classes associated with the types of the function arguments.
9924 // - When looking for a prior declaration of a class or a function
9925 // declared as a friend, scopes outside the innermost enclosing
9926 // namespace scope are not considered.
9928 CXXScopeSpec &SS = D.getCXXScopeSpec();
9929 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9930 DeclarationName Name = NameInfo.getName();
9933 // Check for unexpanded parameter packs.
9934 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
9935 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
9936 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
9939 // The context we found the declaration in, or in which we should
9940 // create the declaration.
9943 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9946 // FIXME: there are different rules in local classes
9948 // There are four cases here.
9949 // - There's no scope specifier, in which case we just go to the
9950 // appropriate scope and look for a function or function template
9951 // there as appropriate.
9952 // Recover from invalid scope qualifiers as if they just weren't there.
9953 if (SS.isInvalid() || !SS.isSet()) {
9954 // C++0x [namespace.memdef]p3:
9955 // If the name in a friend declaration is neither qualified nor
9956 // a template-id and the declaration is a function or an
9957 // elaborated-type-specifier, the lookup to determine whether
9958 // the entity has been previously declared shall not consider
9959 // any scopes outside the innermost enclosing namespace.
9960 // C++0x [class.friend]p11:
9961 // If a friend declaration appears in a local class and the name
9962 // specified is an unqualified name, a prior declaration is
9963 // looked up without considering scopes that are outside the
9964 // innermost enclosing non-class scope. For a friend function
9965 // declaration, if there is no prior declaration, the program is
9967 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
9968 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
9970 // Find the appropriate context according to the above.
9973 // Skip class contexts. If someone can cite chapter and verse
9974 // for this behavior, that would be nice --- it's what GCC and
9975 // EDG do, and it seems like a reasonable intent, but the spec
9976 // really only says that checks for unqualified existing
9977 // declarations should stop at the nearest enclosing namespace,
9978 // not that they should only consider the nearest enclosing
9980 while (DC->isRecord())
9981 DC = DC->getParent();
9983 LookupQualifiedName(Previous, DC);
9985 // TODO: decide what we think about using declarations.
9986 if (isLocal || !Previous.empty())
9990 if (isa<TranslationUnitDecl>(DC)) break;
9992 if (DC->isFileContext()) break;
9994 DC = DC->getParent();
9997 // C++ [class.friend]p1: A friend of a class is a function or
9998 // class that is not a member of the class . . .
9999 // C++0x changes this for both friend types and functions.
10000 // Most C++ 98 compilers do seem to give an error here, so
10002 if (!Previous.empty() && DC->Equals(CurContext)
10003 && !getLangOptions().CPlusPlus0x)
10004 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
10006 DCScope = getScopeForDeclContext(S, DC);
10008 // C++ [class.friend]p6:
10009 // A function can be defined in a friend declaration of a class if and
10010 // only if the class is a non-local class (9.8), the function name is
10011 // unqualified, and the function has namespace scope.
10012 if (isLocal && D.isFunctionDefinition()) {
10013 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10016 // - There's a non-dependent scope specifier, in which case we
10017 // compute it and do a previous lookup there for a function
10018 // or function template.
10019 } else if (!SS.getScopeRep()->isDependent()) {
10020 DC = computeDeclContext(SS);
10023 if (RequireCompleteDeclContext(SS, DC)) return 0;
10025 LookupQualifiedName(Previous, DC);
10027 // Ignore things found implicitly in the wrong scope.
10028 // TODO: better diagnostics for this case. Suggesting the right
10029 // qualified scope would be nice...
10030 LookupResult::Filter F = Previous.makeFilter();
10031 while (F.hasNext()) {
10032 NamedDecl *D = F.next();
10033 if (!DC->InEnclosingNamespaceSetOf(
10034 D->getDeclContext()->getRedeclContext()))
10039 if (Previous.empty()) {
10040 D.setInvalidType();
10041 Diag(Loc, diag::err_qualified_friend_not_found)
10042 << Name << TInfo->getType();
10046 // C++ [class.friend]p1: A friend of a class is a function or
10047 // class that is not a member of the class . . .
10048 if (DC->Equals(CurContext))
10049 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
10051 if (D.isFunctionDefinition()) {
10052 // C++ [class.friend]p6:
10053 // A function can be defined in a friend declaration of a class if and
10054 // only if the class is a non-local class (9.8), the function name is
10055 // unqualified, and the function has namespace scope.
10056 SemaDiagnosticBuilder DB
10057 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10059 DB << SS.getScopeRep();
10060 if (DC->isFileContext())
10061 DB << FixItHint::CreateRemoval(SS.getRange());
10065 // - There's a scope specifier that does not match any template
10066 // parameter lists, in which case we use some arbitrary context,
10067 // create a method or method template, and wait for instantiation.
10068 // - There's a scope specifier that does match some template
10069 // parameter lists, which we don't handle right now.
10071 if (D.isFunctionDefinition()) {
10072 // C++ [class.friend]p6:
10073 // A function can be defined in a friend declaration of a class if and
10074 // only if the class is a non-local class (9.8), the function name is
10075 // unqualified, and the function has namespace scope.
10076 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10077 << SS.getScopeRep();
10081 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
10084 if (!DC->isRecord()) {
10085 // This implies that it has to be an operator or function.
10086 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10087 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10088 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
10089 Diag(Loc, diag::err_introducing_special_friend) <<
10090 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10091 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
10096 bool AddToScope = true;
10097 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10098 move(TemplateParams), AddToScope);
10101 assert(ND->getDeclContext() == DC);
10102 assert(ND->getLexicalDeclContext() == CurContext);
10104 // Add the function declaration to the appropriate lookup tables,
10105 // adjusting the redeclarations list as necessary. We don't
10106 // want to do this yet if the friending class is dependent.
10108 // Also update the scope-based lookup if the target context's
10109 // lookup context is in lexical scope.
10110 if (!CurContext->isDependentContext()) {
10111 DC = DC->getRedeclContext();
10112 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
10113 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
10114 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
10117 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
10118 D.getIdentifierLoc(), ND,
10119 DS.getFriendSpecLoc());
10120 FrD->setAccess(AS_public);
10121 CurContext->addDecl(FrD);
10123 if (ND->isInvalidDecl())
10124 FrD->setInvalidDecl();
10127 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10128 FD = FTD->getTemplatedDecl();
10130 FD = cast<FunctionDecl>(ND);
10132 // Mark templated-scope function declarations as unsupported.
10133 if (FD->getNumTemplateParameterLists())
10134 FrD->setUnsupportedFriend(true);
10140 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10141 AdjustDeclIfTemplate(Dcl);
10143 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10145 Diag(DelLoc, diag::err_deleted_non_function);
10148 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
10149 Diag(DelLoc, diag::err_deleted_decl_not_first);
10150 Diag(Prev->getLocation(), diag::note_previous_declaration);
10151 // If the declaration wasn't the first, we delete the function anyway for
10154 Fn->setDeletedAsWritten();
10157 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10158 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10161 if (MD->getParent()->isDependentType()) {
10162 MD->setDefaulted();
10163 MD->setExplicitlyDefaulted();
10167 CXXSpecialMember Member = getSpecialMember(MD);
10168 if (Member == CXXInvalid) {
10169 Diag(DefaultLoc, diag::err_default_special_members);
10173 MD->setDefaulted();
10174 MD->setExplicitlyDefaulted();
10176 // If this definition appears within the record, do the checking when
10177 // the record is complete.
10178 const FunctionDecl *Primary = MD;
10179 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10180 // Find the uninstantiated declaration that actually had the '= default'
10182 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10184 if (Primary == Primary->getCanonicalDecl())
10188 case CXXDefaultConstructor: {
10189 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10190 CheckExplicitlyDefaultedDefaultConstructor(CD);
10191 if (!CD->isInvalidDecl())
10192 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10196 case CXXCopyConstructor: {
10197 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10198 CheckExplicitlyDefaultedCopyConstructor(CD);
10199 if (!CD->isInvalidDecl())
10200 DefineImplicitCopyConstructor(DefaultLoc, CD);
10204 case CXXCopyAssignment: {
10205 CheckExplicitlyDefaultedCopyAssignment(MD);
10206 if (!MD->isInvalidDecl())
10207 DefineImplicitCopyAssignment(DefaultLoc, MD);
10211 case CXXDestructor: {
10212 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10213 CheckExplicitlyDefaultedDestructor(DD);
10214 if (!DD->isInvalidDecl())
10215 DefineImplicitDestructor(DefaultLoc, DD);
10219 case CXXMoveConstructor: {
10220 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10221 CheckExplicitlyDefaultedMoveConstructor(CD);
10222 if (!CD->isInvalidDecl())
10223 DefineImplicitMoveConstructor(DefaultLoc, CD);
10227 case CXXMoveAssignment: {
10228 CheckExplicitlyDefaultedMoveAssignment(MD);
10229 if (!MD->isInvalidDecl())
10230 DefineImplicitMoveAssignment(DefaultLoc, MD);
10235 llvm_unreachable("Invalid special member.");
10238 Diag(DefaultLoc, diag::err_default_special_members);
10242 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
10243 for (Stmt::child_range CI = S->children(); CI; ++CI) {
10244 Stmt *SubStmt = *CI;
10247 if (isa<ReturnStmt>(SubStmt))
10248 Self.Diag(SubStmt->getSourceRange().getBegin(),
10249 diag::err_return_in_constructor_handler);
10250 if (!isa<Expr>(SubStmt))
10251 SearchForReturnInStmt(Self, SubStmt);
10255 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10256 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10257 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10258 SearchForReturnInStmt(*this, Handler);
10262 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
10263 const CXXMethodDecl *Old) {
10264 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10265 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
10267 if (Context.hasSameType(NewTy, OldTy) ||
10268 NewTy->isDependentType() || OldTy->isDependentType())
10271 // Check if the return types are covariant
10272 QualType NewClassTy, OldClassTy;
10274 /// Both types must be pointers or references to classes.
10275 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10276 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
10277 NewClassTy = NewPT->getPointeeType();
10278 OldClassTy = OldPT->getPointeeType();
10280 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10281 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10282 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10283 NewClassTy = NewRT->getPointeeType();
10284 OldClassTy = OldRT->getPointeeType();
10289 // The return types aren't either both pointers or references to a class type.
10290 if (NewClassTy.isNull()) {
10291 Diag(New->getLocation(),
10292 diag::err_different_return_type_for_overriding_virtual_function)
10293 << New->getDeclName() << NewTy << OldTy;
10294 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10299 // C++ [class.virtual]p6:
10300 // If the return type of D::f differs from the return type of B::f, the
10301 // class type in the return type of D::f shall be complete at the point of
10302 // declaration of D::f or shall be the class type D.
10303 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10304 if (!RT->isBeingDefined() &&
10305 RequireCompleteType(New->getLocation(), NewClassTy,
10306 PDiag(diag::err_covariant_return_incomplete)
10307 << New->getDeclName()))
10311 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
10312 // Check if the new class derives from the old class.
10313 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10314 Diag(New->getLocation(),
10315 diag::err_covariant_return_not_derived)
10316 << New->getDeclName() << NewTy << OldTy;
10317 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10321 // Check if we the conversion from derived to base is valid.
10322 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
10323 diag::err_covariant_return_inaccessible_base,
10324 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10325 // FIXME: Should this point to the return type?
10326 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
10327 // FIXME: this note won't trigger for delayed access control
10328 // diagnostics, and it's impossible to get an undelayed error
10329 // here from access control during the original parse because
10330 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
10331 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10336 // The qualifiers of the return types must be the same.
10337 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
10338 Diag(New->getLocation(),
10339 diag::err_covariant_return_type_different_qualifications)
10340 << New->getDeclName() << NewTy << OldTy;
10341 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10346 // The new class type must have the same or less qualifiers as the old type.
10347 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10348 Diag(New->getLocation(),
10349 diag::err_covariant_return_type_class_type_more_qualified)
10350 << New->getDeclName() << NewTy << OldTy;
10351 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10358 /// \brief Mark the given method pure.
10360 /// \param Method the method to be marked pure.
10362 /// \param InitRange the source range that covers the "0" initializer.
10363 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
10364 SourceLocation EndLoc = InitRange.getEnd();
10365 if (EndLoc.isValid())
10366 Method->setRangeEnd(EndLoc);
10368 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10373 if (!Method->isInvalidDecl())
10374 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10375 << Method->getDeclName() << InitRange;
10379 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10380 /// an initializer for the out-of-line declaration 'Dcl'. The scope
10381 /// is a fresh scope pushed for just this purpose.
10383 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10384 /// static data member of class X, names should be looked up in the scope of
10386 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
10387 // If there is no declaration, there was an error parsing it.
10388 if (D == 0 || D->isInvalidDecl()) return;
10390 // We should only get called for declarations with scope specifiers, like:
10392 assert(D->isOutOfLine());
10393 EnterDeclaratorContext(S, D->getDeclContext());
10396 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
10397 /// initializer for the out-of-line declaration 'D'.
10398 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
10399 // If there is no declaration, there was an error parsing it.
10400 if (D == 0 || D->isInvalidDecl()) return;
10402 assert(D->isOutOfLine());
10403 ExitDeclaratorContext(S);
10406 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10407 /// C++ if/switch/while/for statement.
10408 /// e.g: "if (int x = f()) {...}"
10409 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
10411 // The declarator shall not specify a function or an array.
10412 // The type-specifier-seq shall not contain typedef and shall not declare a
10413 // new class or enumeration.
10414 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10415 "Parser allowed 'typedef' as storage class of condition decl.");
10417 Decl *Dcl = ActOnDeclarator(S, D);
10421 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10422 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
10423 << D.getSourceRange();
10430 void Sema::LoadExternalVTableUses() {
10431 if (!ExternalSource)
10434 SmallVector<ExternalVTableUse, 4> VTables;
10435 ExternalSource->ReadUsedVTables(VTables);
10436 SmallVector<VTableUse, 4> NewUses;
10437 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10438 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10439 = VTablesUsed.find(VTables[I].Record);
10440 // Even if a definition wasn't required before, it may be required now.
10441 if (Pos != VTablesUsed.end()) {
10442 if (!Pos->second && VTables[I].DefinitionRequired)
10443 Pos->second = true;
10447 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10448 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10451 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10454 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10455 bool DefinitionRequired) {
10456 // Ignore any vtable uses in unevaluated operands or for classes that do
10457 // not have a vtable.
10458 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10459 CurContext->isDependentContext() ||
10460 ExprEvalContexts.back().Context == Unevaluated)
10463 // Try to insert this class into the map.
10464 LoadExternalVTableUses();
10465 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10466 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10467 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10469 // If we already had an entry, check to see if we are promoting this vtable
10470 // to required a definition. If so, we need to reappend to the VTableUses
10471 // list, since we may have already processed the first entry.
10472 if (DefinitionRequired && !Pos.first->second) {
10473 Pos.first->second = true;
10475 // Otherwise, we can early exit.
10480 // Local classes need to have their virtual members marked
10481 // immediately. For all other classes, we mark their virtual members
10482 // at the end of the translation unit.
10483 if (Class->isLocalClass())
10484 MarkVirtualMembersReferenced(Loc, Class);
10486 VTableUses.push_back(std::make_pair(Class, Loc));
10489 bool Sema::DefineUsedVTables() {
10490 LoadExternalVTableUses();
10491 if (VTableUses.empty())
10494 // Note: The VTableUses vector could grow as a result of marking
10495 // the members of a class as "used", so we check the size each
10496 // time through the loop and prefer indices (with are stable) to
10497 // iterators (which are not).
10498 bool DefinedAnything = false;
10499 for (unsigned I = 0; I != VTableUses.size(); ++I) {
10500 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
10504 SourceLocation Loc = VTableUses[I].second;
10506 // If this class has a key function, but that key function is
10507 // defined in another translation unit, we don't need to emit the
10508 // vtable even though we're using it.
10509 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
10510 if (KeyFunction && !KeyFunction->hasBody()) {
10511 switch (KeyFunction->getTemplateSpecializationKind()) {
10512 case TSK_Undeclared:
10513 case TSK_ExplicitSpecialization:
10514 case TSK_ExplicitInstantiationDeclaration:
10515 // The key function is in another translation unit.
10518 case TSK_ExplicitInstantiationDefinition:
10519 case TSK_ImplicitInstantiation:
10520 // We will be instantiating the key function.
10523 } else if (!KeyFunction) {
10524 // If we have a class with no key function that is the subject
10525 // of an explicit instantiation declaration, suppress the
10526 // vtable; it will live with the explicit instantiation
10528 bool IsExplicitInstantiationDeclaration
10529 = Class->getTemplateSpecializationKind()
10530 == TSK_ExplicitInstantiationDeclaration;
10531 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10532 REnd = Class->redecls_end();
10534 TemplateSpecializationKind TSK
10535 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10536 if (TSK == TSK_ExplicitInstantiationDeclaration)
10537 IsExplicitInstantiationDeclaration = true;
10538 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10539 IsExplicitInstantiationDeclaration = false;
10544 if (IsExplicitInstantiationDeclaration)
10548 // Mark all of the virtual members of this class as referenced, so
10549 // that we can build a vtable. Then, tell the AST consumer that a
10550 // vtable for this class is required.
10551 DefinedAnything = true;
10552 MarkVirtualMembersReferenced(Loc, Class);
10553 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10554 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10556 // Optionally warn if we're emitting a weak vtable.
10557 if (Class->getLinkage() == ExternalLinkage &&
10558 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
10559 const FunctionDecl *KeyFunctionDef = 0;
10560 if (!KeyFunction ||
10561 (KeyFunction->hasBody(KeyFunctionDef) &&
10562 KeyFunctionDef->isInlined()))
10563 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
10566 VTableUses.clear();
10568 return DefinedAnything;
10571 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10572 const CXXRecordDecl *RD) {
10573 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10574 e = RD->method_end(); i != e; ++i) {
10575 CXXMethodDecl *MD = *i;
10577 // C++ [basic.def.odr]p2:
10578 // [...] A virtual member function is used if it is not pure. [...]
10579 if (MD->isVirtual() && !MD->isPure())
10580 MarkDeclarationReferenced(Loc, MD);
10583 // Only classes that have virtual bases need a VTT.
10584 if (RD->getNumVBases() == 0)
10587 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10588 e = RD->bases_end(); i != e; ++i) {
10589 const CXXRecordDecl *Base =
10590 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
10591 if (Base->getNumVBases() == 0)
10593 MarkVirtualMembersReferenced(Loc, Base);
10597 /// SetIvarInitializers - This routine builds initialization ASTs for the
10598 /// Objective-C implementation whose ivars need be initialized.
10599 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10600 if (!getLangOptions().CPlusPlus)
10602 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
10603 SmallVector<ObjCIvarDecl*, 8> ivars;
10604 CollectIvarsToConstructOrDestruct(OID, ivars);
10607 SmallVector<CXXCtorInitializer*, 32> AllToInit;
10608 for (unsigned i = 0; i < ivars.size(); i++) {
10609 FieldDecl *Field = ivars[i];
10610 if (Field->isInvalidDecl())
10613 CXXCtorInitializer *Member;
10614 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10615 InitializationKind InitKind =
10616 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10618 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
10619 ExprResult MemberInit =
10620 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
10621 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
10622 // Note, MemberInit could actually come back empty if no initialization
10623 // is required (e.g., because it would call a trivial default constructor)
10624 if (!MemberInit.get() || MemberInit.isInvalid())
10628 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10630 MemberInit.takeAs<Expr>(),
10632 AllToInit.push_back(Member);
10634 // Be sure that the destructor is accessible and is marked as referenced.
10635 if (const RecordType *RecordTy
10636 = Context.getBaseElementType(Field->getType())
10637 ->getAs<RecordType>()) {
10638 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
10639 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
10640 MarkDeclarationReferenced(Field->getLocation(), Destructor);
10641 CheckDestructorAccess(Field->getLocation(), Destructor,
10642 PDiag(diag::err_access_dtor_ivar)
10643 << Context.getBaseElementType(Field->getType()));
10647 ObjCImplementation->setIvarInitializers(Context,
10648 AllToInit.data(), AllToInit.size());
10653 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10654 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
10655 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
10656 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
10658 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10659 CE = Current.end();
10660 if (Ctor->isInvalidDecl())
10663 const FunctionDecl *FNTarget = 0;
10664 CXXConstructorDecl *Target;
10666 // We ignore the result here since if we don't have a body, Target will be
10668 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
10670 = const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
10672 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
10673 // Avoid dereferencing a null pointer here.
10674 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
10676 if (!Current.insert(Canonical))
10679 // We know that beyond here, we aren't chaining into a cycle.
10680 if (!Target || !Target->isDelegatingConstructor() ||
10681 Target->isInvalidDecl() || Valid.count(TCanonical)) {
10682 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10685 // We've hit a cycle.
10686 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
10687 Current.count(TCanonical)) {
10688 // If we haven't diagnosed this cycle yet, do so now.
10689 if (!Invalid.count(TCanonical)) {
10690 S.Diag((*Ctor->init_begin())->getSourceLocation(),
10691 diag::warn_delegating_ctor_cycle)
10694 // Don't add a note for a function delegating directo to itself.
10695 if (TCanonical != Canonical)
10696 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
10698 CXXConstructorDecl *C = Target;
10699 while (C->getCanonicalDecl() != Canonical) {
10700 (void)C->getTargetConstructor()->hasBody(FNTarget);
10701 assert(FNTarget && "Ctor cycle through bodiless function");
10704 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
10705 S.Diag(C->getLocation(), diag::note_which_delegates_to);
10709 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
10710 Invalid.insert(*CI);
10713 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
10718 void Sema::CheckDelegatingCtorCycles() {
10719 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
10721 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
10722 CE = Current.end();
10724 for (DelegatingCtorDeclsType::iterator
10725 I = DelegatingCtorDecls.begin(ExternalSource),
10726 E = DelegatingCtorDecls.end();
10728 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
10731 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
10732 (*CI)->setInvalidDecl();
10735 /// IdentifyCUDATarget - Determine the CUDA compilation target for this function
10736 Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
10737 // Implicitly declared functions (e.g. copy constructors) are
10738 // __host__ __device__
10739 if (D->isImplicit())
10740 return CFT_HostDevice;
10742 if (D->hasAttr<CUDAGlobalAttr>())
10745 if (D->hasAttr<CUDADeviceAttr>()) {
10746 if (D->hasAttr<CUDAHostAttr>())
10747 return CFT_HostDevice;
10755 bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
10756 CUDAFunctionTarget CalleeTarget) {
10757 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
10758 // Callable from the device only."
10759 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
10762 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
10763 // Callable from the host only."
10764 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
10765 // Callable from the host only."
10766 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
10767 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
10770 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)