1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for C++ declarations.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/ComparisonCategories.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtVisitor.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeOrdering.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/LiteralSupport.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Sema/CXXFieldCollector.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/Lookup.h"
36 #include "clang/Sema/ParsedTemplate.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaInternal.h"
40 #include "clang/Sema/Template.h"
41 #include "llvm/ADT/ScopeExit.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
48 using namespace clang;
50 //===----------------------------------------------------------------------===//
51 // CheckDefaultArgumentVisitor
52 //===----------------------------------------------------------------------===//
55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56 /// the default argument of a parameter to determine whether it
57 /// contains any ill-formed subexpressions. For example, this will
58 /// diagnose the use of local variables or parameters within the
59 /// default argument expression.
60 class CheckDefaultArgumentVisitor
61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
63 const Expr *DefaultArg;
66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67 : S(S), DefaultArg(DefaultArg) {}
69 bool VisitExpr(const Expr *Node);
70 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72 bool VisitLambdaExpr(const LambdaExpr *Lambda);
73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
76 /// VisitExpr - Visit all of the children of this expression.
77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78 bool IsInvalid = false;
79 for (const Stmt *SubStmt : Node->children())
80 IsInvalid |= Visit(SubStmt);
84 /// VisitDeclRefExpr - Visit a reference to a declaration, to
85 /// determine whether this declaration can be used in the default
86 /// argument expression.
87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88 const NamedDecl *Decl = DRE->getDecl();
89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90 // C++ [dcl.fct.default]p9:
91 // [...] parameters of a function shall not be used in default
92 // argument expressions, even if they are not evaluated. [...]
94 // C++17 [dcl.fct.default]p9 (by CWG 2082):
95 // [...] A parameter shall not appear as a potentially-evaluated
96 // expression in a default argument. [...]
98 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99 return S.Diag(DRE->getBeginLoc(),
100 diag::err_param_default_argument_references_param)
101 << Param->getDeclName() << DefaultArg->getSourceRange();
102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103 // C++ [dcl.fct.default]p7:
104 // Local variables shall not be used in default argument
107 // C++17 [dcl.fct.default]p7 (by CWG 2082):
108 // A local variable shall not appear as a potentially-evaluated
109 // expression in a default argument.
111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112 // Note: A local variable cannot be odr-used (6.3) in a default argument.
114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_local)
117 << VDecl->getDeclName() << DefaultArg->getSourceRange();
123 /// VisitCXXThisExpr - Visit a C++ "this" expression.
124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125 // C++ [dcl.fct.default]p8:
126 // The keyword this shall not be used in a default argument of a
128 return S.Diag(ThisE->getBeginLoc(),
129 diag::err_param_default_argument_references_this)
130 << ThisE->getSourceRange();
133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134 const PseudoObjectExpr *POE) {
135 bool Invalid = false;
136 for (const Expr *E : POE->semantics()) {
137 // Look through bindings.
138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139 E = OVE->getSourceExpr();
140 assert(E && "pseudo-object binding without source expression?");
148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149 // C++11 [expr.lambda.prim]p13:
150 // A lambda-expression appearing in a default argument shall not
151 // implicitly or explicitly capture any entity.
152 if (Lambda->capture_begin() == Lambda->capture_end())
155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161 const CXXMethodDecl *Method) {
162 // If we have an MSAny spec already, don't bother.
163 if (!Method || ComputedEST == EST_MSAny)
166 const FunctionProtoType *Proto
167 = Method->getType()->getAs<FunctionProtoType>();
168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
172 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
174 // If we have a throw-all spec at this point, ignore the function.
175 if (ComputedEST == EST_None)
178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179 EST = EST_BasicNoexcept;
183 case EST_Uninstantiated:
184 case EST_Unevaluated:
185 llvm_unreachable("should not see unresolved exception specs here");
187 // If this function can throw any exceptions, make a note of that.
190 // FIXME: Whichever we see last of MSAny and None determines our result.
191 // We should make a consistent, order-independent choice here.
195 case EST_NoexceptFalse:
197 ComputedEST = EST_None;
199 // FIXME: If the call to this decl is using any of its default arguments, we
200 // need to search them for potentially-throwing calls.
201 // If this function has a basic noexcept, it doesn't affect the outcome.
202 case EST_BasicNoexcept:
203 case EST_NoexceptTrue:
206 // If we're still at noexcept(true) and there's a throw() callee,
207 // change to that specification.
208 case EST_DynamicNone:
209 if (ComputedEST == EST_BasicNoexcept)
210 ComputedEST = EST_DynamicNone;
212 case EST_DependentNoexcept:
214 "should not generate implicit declarations for dependent cases");
218 assert(EST == EST_Dynamic && "EST case not considered earlier.");
219 assert(ComputedEST != EST_None &&
220 "Shouldn't collect exceptions when throw-all is guaranteed.");
221 ComputedEST = EST_Dynamic;
222 // Record the exceptions in this function's exception specification.
223 for (const auto &E : Proto->exceptions())
224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225 Exceptions.push_back(E);
228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229 if (!S || ComputedEST == EST_MSAny)
234 // C++0x [except.spec]p14:
235 // [An] implicit exception-specification specifies the type-id T if and
236 // only if T is allowed by the exception-specification of a function directly
237 // invoked by f's implicit definition; f shall allow all exceptions if any
238 // function it directly invokes allows all exceptions, and f shall allow no
239 // exceptions if every function it directly invokes allows no exceptions.
241 // Note in particular that if an implicit exception-specification is generated
242 // for a function containing a throw-expression, that specification can still
243 // be noexcept(true).
245 // Note also that 'directly invoked' is not defined in the standard, and there
246 // is no indication that we should only consider potentially-evaluated calls.
248 // Ultimately we should implement the intent of the standard: the exception
249 // specification should be the set of exceptions which can be thrown by the
250 // implicit definition. For now, we assume that any non-nothrow expression can
251 // throw any exception.
253 if (Self->canThrow(S))
254 ComputedEST = EST_None;
257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param,
259 SourceLocation EqualLoc) {
260 if (RequireCompleteType(Param->getLocation(), Param->getType(),
261 diag::err_typecheck_decl_incomplete_type))
264 // C++ [dcl.fct.default]p5
265 // A default argument expression is implicitly converted (clause
266 // 4) to the parameter type. The default argument expression has
267 // the same semantic constraints as the initializer expression in
268 // a declaration of a variable of the parameter type, using the
269 // copy-initialization semantics (8.5).
270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
274 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
276 if (Result.isInvalid())
278 Arg = Result.getAs<Expr>();
280 CheckCompletedExpr(Arg, EqualLoc);
281 Arg = MaybeCreateExprWithCleanups(Arg);
286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
287 SourceLocation EqualLoc) {
288 // Add the default argument to the parameter
289 Param->setDefaultArg(Arg);
291 // We have already instantiated this parameter; provide each of the
292 // instantiations with the uninstantiated default argument.
293 UnparsedDefaultArgInstantiationsMap::iterator InstPos
294 = UnparsedDefaultArgInstantiations.find(Param);
295 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
299 // We're done tracking this parameter's instantiations.
300 UnparsedDefaultArgInstantiations.erase(InstPos);
304 /// ActOnParamDefaultArgument - Check whether the default argument
305 /// provided for a function parameter is well-formed. If so, attach it
306 /// to the parameter declaration.
308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
310 if (!param || !DefaultArg)
313 ParmVarDecl *Param = cast<ParmVarDecl>(param);
314 UnparsedDefaultArgLocs.erase(Param);
317 Param->setInvalidDecl();
318 Param->setDefaultArg(new (Context) OpaqueValueExpr(
319 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue));
322 // Default arguments are only permitted in C++
323 if (!getLangOpts().CPlusPlus) {
324 Diag(EqualLoc, diag::err_param_default_argument)
325 << DefaultArg->getSourceRange();
329 // Check for unexpanded parameter packs.
330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
334 // C++11 [dcl.fct.default]p3
335 // A default argument expression [...] shall not be specified for a
337 if (Param->isParameterPack()) {
338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
339 << DefaultArg->getSourceRange();
340 // Recover by discarding the default argument.
341 Param->setDefaultArg(nullptr);
345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
346 if (Result.isInvalid())
349 DefaultArg = Result.getAs<Expr>();
351 // Check that the default argument is well-formed
352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
353 if (DefaultArgChecker.Visit(DefaultArg))
356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
359 /// ActOnParamUnparsedDefaultArgument - We've seen a default
360 /// argument for a function parameter, but we can't parse it yet
361 /// because we're inside a class definition. Note that this default
362 /// argument will be parsed later.
363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
364 SourceLocation EqualLoc,
365 SourceLocation ArgLoc) {
369 ParmVarDecl *Param = cast<ParmVarDecl>(param);
370 Param->setUnparsedDefaultArg();
371 UnparsedDefaultArgLocs[Param] = ArgLoc;
374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
375 /// the default argument for the parameter param failed.
376 void Sema::ActOnParamDefaultArgumentError(Decl *param,
377 SourceLocation EqualLoc) {
381 ParmVarDecl *Param = cast<ParmVarDecl>(param);
382 Param->setInvalidDecl();
383 UnparsedDefaultArgLocs.erase(Param);
384 Param->setDefaultArg(new(Context)
385 OpaqueValueExpr(EqualLoc,
386 Param->getType().getNonReferenceType(),
390 /// CheckExtraCXXDefaultArguments - Check for any extra default
391 /// arguments in the declarator, which is not a function declaration
392 /// or definition and therefore is not permitted to have default
393 /// arguments. This routine should be invoked for every declarator
394 /// that is not a function declaration or definition.
395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
396 // C++ [dcl.fct.default]p3
397 // A default argument expression shall be specified only in the
398 // parameter-declaration-clause of a function declaration or in a
399 // template-parameter (14.1). It shall not be specified for a
400 // parameter pack. If it is specified in a
401 // parameter-declaration-clause, it shall not occur within a
402 // declarator or abstract-declarator of a parameter-declaration.
403 bool MightBeFunction = D.isFunctionDeclarationContext();
404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
405 DeclaratorChunk &chunk = D.getTypeObject(i);
406 if (chunk.Kind == DeclaratorChunk::Function) {
407 if (MightBeFunction) {
408 // This is a function declaration. It can have default arguments, but
409 // keep looking in case its return type is a function type with default
411 MightBeFunction = false;
414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
417 if (Param->hasUnparsedDefaultArg()) {
418 std::unique_ptr<CachedTokens> Toks =
419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
421 if (Toks->size() > 1)
422 SR = SourceRange((*Toks)[1].getLocation(),
423 Toks->back().getLocation());
425 SR = UnparsedDefaultArgLocs[Param];
426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
428 } else if (Param->getDefaultArg()) {
429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
430 << Param->getDefaultArg()->getSourceRange();
431 Param->setDefaultArg(nullptr);
434 } else if (chunk.Kind != DeclaratorChunk::Paren) {
435 MightBeFunction = false;
440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
447 /// function, once we already know that they have the same
448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
449 /// error, false otherwise.
450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
452 bool Invalid = false;
454 // The declaration context corresponding to the scope is the semantic
455 // parent, unless this is a local function declaration, in which case
456 // it is that surrounding function.
457 DeclContext *ScopeDC = New->isLocalExternDecl()
458 ? New->getLexicalDeclContext()
459 : New->getDeclContext();
461 // Find the previous declaration for the purpose of default arguments.
462 FunctionDecl *PrevForDefaultArgs = Old;
463 for (/**/; PrevForDefaultArgs;
464 // Don't bother looking back past the latest decl if this is a local
465 // extern declaration; nothing else could work.
466 PrevForDefaultArgs = New->isLocalExternDecl()
468 : PrevForDefaultArgs->getPreviousDecl()) {
469 // Ignore hidden declarations.
470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
474 !New->isCXXClassMember()) {
475 // Ignore default arguments of old decl if they are not in
476 // the same scope and this is not an out-of-line definition of
477 // a member function.
481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
482 // If only one of these is a local function declaration, then they are
483 // declared in different scopes, even though isDeclInScope may think
484 // they're in the same scope. (If both are local, the scope check is
485 // sufficient, and if neither is local, then they are in the same scope.)
489 // We found the right previous declaration.
493 // C++ [dcl.fct.default]p4:
494 // For non-template functions, default arguments can be added in
495 // later declarations of a function in the same
496 // scope. Declarations in different scopes have completely
497 // distinct sets of default arguments. That is, declarations in
498 // inner scopes do not acquire default arguments from
499 // declarations in outer scopes, and vice versa. In a given
500 // function declaration, all parameters subsequent to a
501 // parameter with a default argument shall have default
502 // arguments supplied in this or previous declarations. A
503 // default argument shall not be redefined by a later
504 // declaration (not even to the same value).
506 // C++ [dcl.fct.default]p6:
507 // Except for member functions of class templates, the default arguments
508 // in a member function definition that appears outside of the class
509 // definition are added to the set of default arguments provided by the
510 // member function declaration in the class definition.
511 for (unsigned p = 0, NumParams = PrevForDefaultArgs
512 ? PrevForDefaultArgs->getNumParams()
514 p < NumParams; ++p) {
515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
516 ParmVarDecl *NewParam = New->getParamDecl(p);
518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
519 bool NewParamHasDfl = NewParam->hasDefaultArg();
521 if (OldParamHasDfl && NewParamHasDfl) {
522 unsigned DiagDefaultParamID =
523 diag::err_param_default_argument_redefinition;
525 // MSVC accepts that default parameters be redefined for member functions
526 // of template class. The new default parameter's value is ignored.
528 if (getLangOpts().MicrosoftExt) {
529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
530 if (MD && MD->getParent()->getDescribedClassTemplate()) {
531 // Merge the old default argument into the new parameter.
532 NewParam->setHasInheritedDefaultArg();
533 if (OldParam->hasUninstantiatedDefaultArg())
534 NewParam->setUninstantiatedDefaultArg(
535 OldParam->getUninstantiatedDefaultArg());
537 NewParam->setDefaultArg(OldParam->getInit());
538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
544 // hint here. Alternatively, we could walk the type-source information
545 // for NewParam to find the last source location in the type... but it
546 // isn't worth the effort right now. This is the kind of test case that
547 // is hard to get right:
549 // void g(int (*fp)(int) = f);
550 // void g(int (*fp)(int) = &f);
551 Diag(NewParam->getLocation(), DiagDefaultParamID)
552 << NewParam->getDefaultArgRange();
554 // Look for the function declaration where the default argument was
555 // actually written, which may be a declaration prior to Old.
556 for (auto Older = PrevForDefaultArgs;
557 OldParam->hasInheritedDefaultArg(); /**/) {
558 Older = Older->getPreviousDecl();
559 OldParam = Older->getParamDecl(p);
562 Diag(OldParam->getLocation(), diag::note_previous_definition)
563 << OldParam->getDefaultArgRange();
564 } else if (OldParamHasDfl) {
565 // Merge the old default argument into the new parameter unless the new
566 // function is a friend declaration in a template class. In the latter
567 // case the default arguments will be inherited when the friend
568 // declaration will be instantiated.
569 if (New->getFriendObjectKind() == Decl::FOK_None ||
570 !New->getLexicalDeclContext()->isDependentContext()) {
571 // It's important to use getInit() here; getDefaultArg()
572 // strips off any top-level ExprWithCleanups.
573 NewParam->setHasInheritedDefaultArg();
574 if (OldParam->hasUnparsedDefaultArg())
575 NewParam->setUnparsedDefaultArg();
576 else if (OldParam->hasUninstantiatedDefaultArg())
577 NewParam->setUninstantiatedDefaultArg(
578 OldParam->getUninstantiatedDefaultArg());
580 NewParam->setDefaultArg(OldParam->getInit());
582 } else if (NewParamHasDfl) {
583 if (New->getDescribedFunctionTemplate()) {
584 // Paragraph 4, quoted above, only applies to non-template functions.
585 Diag(NewParam->getLocation(),
586 diag::err_param_default_argument_template_redecl)
587 << NewParam->getDefaultArgRange();
588 Diag(PrevForDefaultArgs->getLocation(),
589 diag::note_template_prev_declaration)
591 } else if (New->getTemplateSpecializationKind()
592 != TSK_ImplicitInstantiation &&
593 New->getTemplateSpecializationKind() != TSK_Undeclared) {
594 // C++ [temp.expr.spec]p21:
595 // Default function arguments shall not be specified in a declaration
596 // or a definition for one of the following explicit specializations:
597 // - the explicit specialization of a function template;
598 // - the explicit specialization of a member function template;
599 // - the explicit specialization of a member function of a class
600 // template where the class template specialization to which the
601 // member function specialization belongs is implicitly
603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
605 << New->getDeclName()
606 << NewParam->getDefaultArgRange();
607 } else if (New->getDeclContext()->isDependentContext()) {
608 // C++ [dcl.fct.default]p6 (DR217):
609 // Default arguments for a member function of a class template shall
610 // be specified on the initial declaration of the member function
611 // within the class template.
613 // Reading the tea leaves a bit in DR217 and its reference to DR205
614 // leads me to the conclusion that one cannot add default function
615 // arguments for an out-of-line definition of a member function of a
618 if (CXXRecordDecl *Record
619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
620 if (Record->getDescribedClassTemplate())
622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
628 Diag(NewParam->getLocation(),
629 diag::err_param_default_argument_member_template_redecl)
631 << NewParam->getDefaultArgRange();
636 // DR1344: If a default argument is added outside a class definition and that
637 // default argument makes the function a special member function, the program
638 // is ill-formed. This can only happen for constructors.
639 if (isa<CXXConstructorDecl>(New) &&
640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
643 if (NewSM != OldSM) {
644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
645 assert(NewParam->hasDefaultArg());
646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
647 << NewParam->getDefaultArgRange() << NewSM;
648 Diag(Old->getLocation(), diag::note_previous_declaration);
652 const FunctionDecl *Def;
653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
654 // template has a constexpr specifier then all its declarations shall
655 // contain the constexpr specifier.
656 if (New->getConstexprKind() != Old->getConstexprKind()) {
657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
658 << New << New->getConstexprKind() << Old->getConstexprKind();
659 Diag(Old->getLocation(), diag::note_previous_declaration);
661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
662 Old->isDefined(Def) &&
663 // If a friend function is inlined but does not have 'inline'
664 // specifier, it is a definition. Do not report attribute conflict
665 // in this case, redefinition will be diagnosed later.
666 (New->isInlineSpecified() ||
667 New->getFriendObjectKind() == Decl::FOK_None)) {
668 // C++11 [dcl.fcn.spec]p4:
669 // If the definition of a function appears in a translation unit before its
670 // first declaration as inline, the program is ill-formed.
671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
672 Diag(Def->getLocation(), diag::note_previous_definition);
676 // C++17 [temp.deduct.guide]p3:
677 // Two deduction guide declarations in the same translation unit
678 // for the same class template shall not have equivalent
679 // parameter-declaration-clauses.
680 if (isa<CXXDeductionGuideDecl>(New) &&
681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
683 Diag(Old->getLocation(), diag::note_previous_declaration);
686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
687 // argument expression, that declaration shall be a definition and shall be
688 // the only declaration of the function or function template in the
690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
691 functionDeclHasDefaultArgument(Old)) {
692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
693 Diag(Old->getLocation(), diag::note_previous_declaration);
701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
702 MultiTemplateParamsArg TemplateParamLists) {
703 assert(D.isDecompositionDeclarator());
704 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
706 // The syntax only allows a decomposition declarator as a simple-declaration,
707 // a for-range-declaration, or a condition in Clang, but we parse it in more
709 if (!D.mayHaveDecompositionDeclarator()) {
710 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
711 << Decomp.getSourceRange();
715 if (!TemplateParamLists.empty()) {
716 // FIXME: There's no rule against this, but there are also no rules that
717 // would actually make it usable, so we reject it for now.
718 Diag(TemplateParamLists.front()->getTemplateLoc(),
719 diag::err_decomp_decl_template);
723 Diag(Decomp.getLSquareLoc(),
724 !getLangOpts().CPlusPlus17
725 ? diag::ext_decomp_decl
726 : D.getContext() == DeclaratorContext::ConditionContext
727 ? diag::ext_decomp_decl_cond
728 : diag::warn_cxx14_compat_decomp_decl)
729 << Decomp.getSourceRange();
731 // The semantic context is always just the current context.
732 DeclContext *const DC = CurContext;
734 // C++17 [dcl.dcl]/8:
735 // The decl-specifier-seq shall contain only the type-specifier auto
736 // and cv-qualifiers.
737 // C++2a [dcl.dcl]/8:
738 // If decl-specifier-seq contains any decl-specifier other than static,
739 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
740 auto &DS = D.getDeclSpec();
742 SmallVector<StringRef, 8> BadSpecifiers;
743 SmallVector<SourceLocation, 8> BadSpecifierLocs;
744 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
745 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
746 if (auto SCS = DS.getStorageClassSpec()) {
747 if (SCS == DeclSpec::SCS_static) {
748 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
749 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
751 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
752 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
755 if (auto TSCS = DS.getThreadStorageClassSpec()) {
756 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
757 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
759 if (DS.hasConstexprSpecifier()) {
760 BadSpecifiers.push_back(
761 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
762 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
764 if (DS.isInlineSpecified()) {
765 BadSpecifiers.push_back("inline");
766 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
768 if (!BadSpecifiers.empty()) {
769 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
770 Err << (int)BadSpecifiers.size()
771 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
772 // Don't add FixItHints to remove the specifiers; we do still respect
773 // them when building the underlying variable.
774 for (auto Loc : BadSpecifierLocs)
775 Err << SourceRange(Loc, Loc);
776 } else if (!CPlusPlus20Specifiers.empty()) {
777 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
778 getLangOpts().CPlusPlus20
779 ? diag::warn_cxx17_compat_decomp_decl_spec
780 : diag::ext_decomp_decl_spec);
781 Warn << (int)CPlusPlus20Specifiers.size()
782 << llvm::join(CPlusPlus20Specifiers.begin(),
783 CPlusPlus20Specifiers.end(), " ");
784 for (auto Loc : CPlusPlus20SpecifierLocs)
785 Warn << SourceRange(Loc, Loc);
787 // We can't recover from it being declared as a typedef.
788 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
792 // C++2a [dcl.struct.bind]p1:
793 // A cv that includes volatile is deprecated
794 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
795 getLangOpts().CPlusPlus20)
796 Diag(DS.getVolatileSpecLoc(),
797 diag::warn_deprecated_volatile_structured_binding);
799 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
800 QualType R = TInfo->getType();
802 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
803 UPPC_DeclarationType))
806 // The syntax only allows a single ref-qualifier prior to the decomposition
807 // declarator. No other declarator chunks are permitted. Also check the type
809 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
810 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
811 (D.getNumTypeObjects() == 1 &&
812 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
813 Diag(Decomp.getLSquareLoc(),
814 (D.hasGroupingParens() ||
815 (D.getNumTypeObjects() &&
816 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
817 ? diag::err_decomp_decl_parens
818 : diag::err_decomp_decl_type)
821 // In most cases, there's no actual problem with an explicitly-specified
822 // type, but a function type won't work here, and ActOnVariableDeclarator
823 // shouldn't be called for such a type.
824 if (R->isFunctionType())
828 // Build the BindingDecls.
829 SmallVector<BindingDecl*, 8> Bindings;
831 // Build the BindingDecls.
832 for (auto &B : D.getDecompositionDeclarator().bindings()) {
833 // Check for name conflicts.
834 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
835 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
836 ForVisibleRedeclaration);
837 LookupName(Previous, S,
838 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
840 // It's not permitted to shadow a template parameter name.
841 if (Previous.isSingleResult() &&
842 Previous.getFoundDecl()->isTemplateParameter()) {
843 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
844 Previous.getFoundDecl());
848 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
849 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
850 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
851 /*AllowInlineNamespace*/false);
852 if (!Previous.empty()) {
853 auto *Old = Previous.getRepresentativeDecl();
854 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
855 Diag(Old->getLocation(), diag::note_previous_definition);
858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
859 PushOnScopeChains(BD, S, true);
860 Bindings.push_back(BD);
861 ParsingInitForAutoVars.insert(BD);
864 // There are no prior lookup results for the variable itself, because it
866 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
867 Decomp.getLSquareLoc());
868 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
869 ForVisibleRedeclaration);
871 // Build the variable that holds the non-decomposed object.
872 bool AddToScope = true;
874 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
875 MultiTemplateParamsArg(), AddToScope, Bindings);
878 CurContext->addHiddenDecl(New);
881 if (isInOpenMPDeclareTargetContext())
882 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
887 static bool checkSimpleDecomposition(
888 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
889 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
890 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
891 if ((int64_t)Bindings.size() != NumElems) {
892 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
893 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
894 << (NumElems < Bindings.size());
899 for (auto *B : Bindings) {
900 SourceLocation Loc = B->getLocation();
901 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
904 E = GetInit(Loc, E.get(), I++);
907 B->setBinding(ElemType, E.get());
913 static bool checkArrayLikeDecomposition(Sema &S,
914 ArrayRef<BindingDecl *> Bindings,
915 ValueDecl *Src, QualType DecompType,
916 const llvm::APSInt &NumElems,
918 return checkSimpleDecomposition(
919 S, Bindings, Src, DecompType, NumElems, ElemType,
920 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
921 ExprResult E = S.ActOnIntegerConstant(Loc, I);
924 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
929 ValueDecl *Src, QualType DecompType,
930 const ConstantArrayType *CAT) {
931 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
932 llvm::APSInt(CAT->getSize()),
933 CAT->getElementType());
936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
937 ValueDecl *Src, QualType DecompType,
938 const VectorType *VT) {
939 return checkArrayLikeDecomposition(
940 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
941 S.Context.getQualifiedType(VT->getElementType(),
942 DecompType.getQualifiers()));
945 static bool checkComplexDecomposition(Sema &S,
946 ArrayRef<BindingDecl *> Bindings,
947 ValueDecl *Src, QualType DecompType,
948 const ComplexType *CT) {
949 return checkSimpleDecomposition(
950 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
951 S.Context.getQualifiedType(CT->getElementType(),
952 DecompType.getQualifiers()),
953 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
954 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
959 TemplateArgumentListInfo &Args) {
961 llvm::raw_svector_ostream OS(SS);
963 for (auto &Arg : Args.arguments()) {
966 Arg.getArgument().print(PrintingPolicy, OS);
969 return std::string(OS.str());
972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
973 SourceLocation Loc, StringRef Trait,
974 TemplateArgumentListInfo &Args,
976 auto DiagnoseMissing = [&] {
978 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
983 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
984 NamespaceDecl *Std = S.getStdNamespace();
986 return DiagnoseMissing();
988 // Look up the trait itself, within namespace std. We can diagnose various
989 // problems with this lookup even if we've been asked to not diagnose a
990 // missing specialization, because this can only fail if the user has been
991 // declaring their own names in namespace std or we don't support the
992 // standard library implementation in use.
993 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
994 Loc, Sema::LookupOrdinaryName);
995 if (!S.LookupQualifiedName(Result, Std))
996 return DiagnoseMissing();
997 if (Result.isAmbiguous())
1000 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1002 Result.suppressDiagnostics();
1003 NamedDecl *Found = *Result.begin();
1004 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1005 S.Diag(Found->getLocation(), diag::note_declared_at);
1009 // Build the template-id.
1010 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1011 if (TraitTy.isNull())
1013 if (!S.isCompleteType(Loc, TraitTy)) {
1015 S.RequireCompleteType(
1016 Loc, TraitTy, DiagID,
1017 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
1021 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1022 assert(RD && "specialization of class template is not a class?");
1024 // Look up the member of the trait type.
1025 S.LookupQualifiedName(TraitMemberLookup, RD);
1026 return TraitMemberLookup.isAmbiguous();
1029 static TemplateArgumentLoc
1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1032 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1033 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1036 static TemplateArgumentLoc
1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1038 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1044 llvm::APSInt &Size) {
1045 EnterExpressionEvaluationContext ContextRAII(
1046 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1048 DeclarationName Value = S.PP.getIdentifierInfo("value");
1049 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1051 // Form template argument list for tuple_size<T>.
1052 TemplateArgumentListInfo Args(Loc, Loc);
1053 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1055 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1056 // it's not tuple-like.
1057 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1059 return IsTupleLike::NotTupleLike;
1061 // If we get this far, we've committed to the tuple interpretation, but
1062 // we can still fail if there actually isn't a usable ::value.
1064 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1066 TemplateArgumentListInfo &Args;
1067 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1068 : R(R), Args(Args) {}
1069 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1070 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1071 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1073 } Diagnoser(R, Args);
1076 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1078 return IsTupleLike::Error;
1080 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1082 return IsTupleLike::Error;
1084 return IsTupleLike::TupleLike;
1087 /// \return std::tuple_element<I, T>::type.
1088 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1089 unsigned I, QualType T) {
1090 // Form template argument list for tuple_element<I, T>.
1091 TemplateArgumentListInfo Args(Loc, Loc);
1093 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1094 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1096 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1097 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1098 if (lookupStdTypeTraitMember(
1099 S, R, Loc, "tuple_element", Args,
1100 diag::err_decomp_decl_std_tuple_element_not_specialized))
1103 auto *TD = R.getAsSingle<TypeDecl>();
1105 R.suppressDiagnostics();
1106 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1107 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1109 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1113 return S.Context.getTypeDeclType(TD);
1117 struct InitializingBinding {
1119 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1120 Sema::CodeSynthesisContext Ctx;
1121 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1122 Ctx.PointOfInstantiation = BD->getLocation();
1124 S.pushCodeSynthesisContext(Ctx);
1126 ~InitializingBinding() {
1127 S.popCodeSynthesisContext();
1132 static bool checkTupleLikeDecomposition(Sema &S,
1133 ArrayRef<BindingDecl *> Bindings,
1134 VarDecl *Src, QualType DecompType,
1135 const llvm::APSInt &TupleSize) {
1136 if ((int64_t)Bindings.size() != TupleSize) {
1137 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1138 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1139 << (TupleSize < Bindings.size());
1143 if (Bindings.empty())
1146 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1149 // The unqualified-id get is looked up in the scope of E by class member
1150 // access lookup ...
1151 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1152 bool UseMemberGet = false;
1153 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1154 if (auto *RD = DecompType->getAsCXXRecordDecl())
1155 S.LookupQualifiedName(MemberGet, RD);
1156 if (MemberGet.isAmbiguous())
1158 // ... and if that finds at least one declaration that is a function
1159 // template whose first template parameter is a non-type parameter ...
1160 for (NamedDecl *D : MemberGet) {
1161 if (FunctionTemplateDecl *FTD =
1162 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1163 TemplateParameterList *TPL = FTD->getTemplateParameters();
1164 if (TPL->size() != 0 &&
1165 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1166 // ... the initializer is e.get<i>().
1167 UseMemberGet = true;
1175 for (auto *B : Bindings) {
1176 InitializingBinding InitContext(S, B);
1177 SourceLocation Loc = B->getLocation();
1179 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1183 // e is an lvalue if the type of the entity is an lvalue reference and
1184 // an xvalue otherwise
1185 if (!Src->getType()->isLValueReferenceType())
1186 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1187 E.get(), nullptr, VK_XValue);
1189 TemplateArgumentListInfo Args(Loc, Loc);
1191 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1194 // if [lookup of member get] finds at least one declaration, the
1195 // initializer is e.get<i-1>().
1196 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1197 CXXScopeSpec(), SourceLocation(), nullptr,
1198 MemberGet, &Args, nullptr);
1202 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1204 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1205 // in the associated namespaces.
1206 Expr *Get = UnresolvedLookupExpr::Create(
1207 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1208 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1209 UnresolvedSetIterator(), UnresolvedSetIterator());
1211 Expr *Arg = E.get();
1212 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1216 Expr *Init = E.get();
1218 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1219 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1223 // each vi is a variable of type "reference to T" initialized with the
1224 // initializer, where the reference is an lvalue reference if the
1225 // initializer is an lvalue and an rvalue reference otherwise
1227 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1228 if (RefType.isNull())
1230 auto *RefVD = VarDecl::Create(
1231 S.Context, Src->getDeclContext(), Loc, Loc,
1232 B->getDeclName().getAsIdentifierInfo(), RefType,
1233 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1234 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1235 RefVD->setTSCSpec(Src->getTSCSpec());
1236 RefVD->setImplicit();
1237 if (Src->isInlineSpecified())
1238 RefVD->setInlineSpecified();
1239 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1241 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1242 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1243 InitializationSequence Seq(S, Entity, Kind, Init);
1244 E = Seq.Perform(S, Entity, Kind, Init);
1247 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1250 RefVD->setInit(E.get());
1251 if (!E.get()->isValueDependent())
1252 RefVD->checkInitIsICE();
1254 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1255 DeclarationNameInfo(B->getDeclName(), Loc),
1260 B->setBinding(T, E.get());
1267 /// Find the base class to decompose in a built-in decomposition of a class type.
1268 /// This base class search is, unfortunately, not quite like any other that we
1269 /// perform anywhere else in C++.
1270 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1271 const CXXRecordDecl *RD,
1272 CXXCastPath &BasePath) {
1273 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1274 CXXBasePath &Path) {
1275 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1278 const CXXRecordDecl *ClassWithFields = nullptr;
1279 AccessSpecifier AS = AS_public;
1280 if (RD->hasDirectFields())
1282 // Otherwise, all of E's non-static data members shall be public direct
1284 ClassWithFields = RD;
1288 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1289 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1290 // If no classes have fields, just decompose RD itself. (This will work
1291 // if and only if zero bindings were provided.)
1292 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1295 CXXBasePath *BestPath = nullptr;
1296 for (auto &P : Paths) {
1299 else if (!S.Context.hasSameType(P.back().Base->getType(),
1300 BestPath->back().Base->getType())) {
1302 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1303 << false << RD << BestPath->back().Base->getType()
1304 << P.back().Base->getType();
1305 return DeclAccessPair();
1306 } else if (P.Access < BestPath->Access) {
1311 // ... unambiguous ...
1312 QualType BaseType = BestPath->back().Base->getType();
1313 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1314 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1315 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1316 return DeclAccessPair();
1319 // ... [accessible, implied by other rules] base class of E.
1320 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1321 *BestPath, diag::err_decomp_decl_inaccessible_base);
1322 AS = BestPath->Access;
1324 ClassWithFields = BaseType->getAsCXXRecordDecl();
1325 S.BuildBasePathArray(Paths, BasePath);
1328 // The above search did not check whether the selected class itself has base
1329 // classes with fields, so check that now.
1331 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1332 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1333 << (ClassWithFields == RD) << RD << ClassWithFields
1334 << Paths.front().back().Base->getType();
1335 return DeclAccessPair();
1338 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1341 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1342 ValueDecl *Src, QualType DecompType,
1343 const CXXRecordDecl *OrigRD) {
1344 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1345 diag::err_incomplete_type))
1348 CXXCastPath BasePath;
1349 DeclAccessPair BasePair =
1350 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1351 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1354 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1355 DecompType.getQualifiers());
1357 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1358 unsigned NumFields =
1359 std::count_if(RD->field_begin(), RD->field_end(),
1360 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1361 assert(Bindings.size() != NumFields);
1362 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1363 << DecompType << (unsigned)Bindings.size() << NumFields
1364 << (NumFields < Bindings.size());
1368 // all of E's non-static data members shall be [...] well-formed
1369 // when named as e.name in the context of the structured binding,
1370 // E shall not have an anonymous union member, ...
1372 for (auto *FD : RD->fields()) {
1373 if (FD->isUnnamedBitfield())
1376 if (FD->isAnonymousStructOrUnion()) {
1377 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1378 << DecompType << FD->getType()->isUnionType();
1379 S.Diag(FD->getLocation(), diag::note_declared_at);
1383 // We have a real field to bind.
1384 if (I >= Bindings.size())
1385 return DiagnoseBadNumberOfBindings();
1386 auto *B = Bindings[I++];
1387 SourceLocation Loc = B->getLocation();
1389 // The field must be accessible in the context of the structured binding.
1390 // We already checked that the base class is accessible.
1391 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1393 S.CheckStructuredBindingMemberAccess(
1394 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1395 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1396 BasePair.getAccess(), FD->getAccess())));
1398 // Initialize the binding to Src.FD.
1399 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1402 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1403 VK_LValue, &BasePath);
1406 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1408 DeclAccessPair::make(FD, FD->getAccess()),
1409 DeclarationNameInfo(FD->getDeclName(), Loc));
1413 // If the type of the member is T, the referenced type is cv T, where cv is
1414 // the cv-qualification of the decomposition expression.
1416 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1417 // 'const' to the type of the field.
1418 Qualifiers Q = DecompType.getQualifiers();
1419 if (FD->isMutable())
1421 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1424 if (I != Bindings.size())
1425 return DiagnoseBadNumberOfBindings();
1430 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1431 QualType DecompType = DD->getType();
1433 // If the type of the decomposition is dependent, then so is the type of
1435 if (DecompType->isDependentType()) {
1436 for (auto *B : DD->bindings())
1437 B->setType(Context.DependentTy);
1441 DecompType = DecompType.getNonReferenceType();
1442 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1444 // C++1z [dcl.decomp]/2:
1445 // If E is an array type [...]
1446 // As an extension, we also support decomposition of built-in complex and
1448 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1449 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1450 DD->setInvalidDecl();
1453 if (auto *VT = DecompType->getAs<VectorType>()) {
1454 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1455 DD->setInvalidDecl();
1458 if (auto *CT = DecompType->getAs<ComplexType>()) {
1459 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1460 DD->setInvalidDecl();
1464 // C++1z [dcl.decomp]/3:
1465 // if the expression std::tuple_size<E>::value is a well-formed integral
1466 // constant expression, [...]
1467 llvm::APSInt TupleSize(32);
1468 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1469 case IsTupleLike::Error:
1470 DD->setInvalidDecl();
1473 case IsTupleLike::TupleLike:
1474 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1475 DD->setInvalidDecl();
1478 case IsTupleLike::NotTupleLike:
1482 // C++1z [dcl.dcl]/8:
1483 // [E shall be of array or non-union class type]
1484 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1485 if (!RD || RD->isUnion()) {
1486 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1487 << DD << !RD << DecompType;
1488 DD->setInvalidDecl();
1492 // C++1z [dcl.decomp]/4:
1493 // all of E's non-static data members shall be [...] direct members of
1494 // E or of the same unambiguous public base class of E, ...
1495 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1496 DD->setInvalidDecl();
1499 /// Merge the exception specifications of two variable declarations.
1501 /// This is called when there's a redeclaration of a VarDecl. The function
1502 /// checks if the redeclaration might have an exception specification and
1503 /// validates compatibility and merges the specs if necessary.
1504 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1505 // Shortcut if exceptions are disabled.
1506 if (!getLangOpts().CXXExceptions)
1509 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1510 "Should only be called if types are otherwise the same.");
1512 QualType NewType = New->getType();
1513 QualType OldType = Old->getType();
1515 // We're only interested in pointers and references to functions, as well
1516 // as pointers to member functions.
1517 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1518 NewType = R->getPointeeType();
1519 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1520 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1521 NewType = P->getPointeeType();
1522 OldType = OldType->castAs<PointerType>()->getPointeeType();
1523 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1524 NewType = M->getPointeeType();
1525 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1528 if (!NewType->isFunctionProtoType())
1531 // There's lots of special cases for functions. For function pointers, system
1532 // libraries are hopefully not as broken so that we don't need these
1534 if (CheckEquivalentExceptionSpec(
1535 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1536 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1537 New->setInvalidDecl();
1541 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1542 /// function declaration are well-formed according to C++
1543 /// [dcl.fct.default].
1544 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1545 unsigned NumParams = FD->getNumParams();
1546 unsigned ParamIdx = 0;
1548 // This checking doesn't make sense for explicit specializations; their
1549 // default arguments are determined by the declaration we're specializing,
1551 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1553 if (auto *FTD = FD->getDescribedFunctionTemplate())
1554 if (FTD->isMemberSpecialization())
1557 // Find first parameter with a default argument
1558 for (; ParamIdx < NumParams; ++ParamIdx) {
1559 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1560 if (Param->hasDefaultArg())
1564 // C++20 [dcl.fct.default]p4:
1565 // In a given function declaration, each parameter subsequent to a parameter
1566 // with a default argument shall have a default argument supplied in this or
1567 // a previous declaration, unless the parameter was expanded from a
1568 // parameter pack, or shall be a function parameter pack.
1569 for (; ParamIdx < NumParams; ++ParamIdx) {
1570 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1571 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1572 !(CurrentInstantiationScope &&
1573 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1574 if (Param->isInvalidDecl())
1575 /* We already complained about this parameter. */;
1576 else if (Param->getIdentifier())
1577 Diag(Param->getLocation(),
1578 diag::err_param_default_argument_missing_name)
1579 << Param->getIdentifier();
1581 Diag(Param->getLocation(),
1582 diag::err_param_default_argument_missing);
1587 /// Check that the given type is a literal type. Issue a diagnostic if not,
1588 /// if Kind is Diagnose.
1589 /// \return \c true if a problem has been found (and optionally diagnosed).
1590 template <typename... Ts>
1591 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1592 SourceLocation Loc, QualType T, unsigned DiagID,
1594 if (T->isDependentType())
1598 case Sema::CheckConstexprKind::Diagnose:
1599 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1600 std::forward<Ts>(DiagArgs)...);
1602 case Sema::CheckConstexprKind::CheckValid:
1603 return !T->isLiteralType(SemaRef.Context);
1606 llvm_unreachable("unknown CheckConstexprKind");
1609 /// Determine whether a destructor cannot be constexpr due to
1610 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1611 const CXXDestructorDecl *DD,
1612 Sema::CheckConstexprKind Kind) {
1613 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1614 const CXXRecordDecl *RD =
1615 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1616 if (!RD || RD->hasConstexprDestructor())
1619 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1620 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1621 << DD->getConstexprKind() << !FD
1622 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1623 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1624 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1629 const CXXRecordDecl *RD = DD->getParent();
1630 for (const CXXBaseSpecifier &B : RD->bases())
1631 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1633 for (const FieldDecl *FD : RD->fields())
1634 if (!Check(FD->getLocation(), FD->getType(), FD))
1639 /// Check whether a function's parameter types are all literal types. If so,
1640 /// return true. If not, produce a suitable diagnostic and return false.
1641 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1642 const FunctionDecl *FD,
1643 Sema::CheckConstexprKind Kind) {
1644 unsigned ArgIndex = 0;
1645 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1646 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1647 e = FT->param_type_end();
1648 i != e; ++i, ++ArgIndex) {
1649 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1650 SourceLocation ParamLoc = PD->getLocation();
1651 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1652 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1653 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1660 /// Check whether a function's return type is a literal type. If so, return
1661 /// true. If not, produce a suitable diagnostic and return false.
1662 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1663 Sema::CheckConstexprKind Kind) {
1664 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1665 diag::err_constexpr_non_literal_return,
1671 /// Get diagnostic %select index for tag kind for
1672 /// record diagnostic message.
1673 /// WARNING: Indexes apply to particular diagnostics only!
1675 /// \returns diagnostic %select index.
1676 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1678 case TTK_Struct: return 0;
1679 case TTK_Interface: return 1;
1680 case TTK_Class: return 2;
1681 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1685 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1687 Sema::CheckConstexprKind Kind);
1689 // Check whether a function declaration satisfies the requirements of a
1690 // constexpr function definition or a constexpr constructor definition. If so,
1691 // return true. If not, produce appropriate diagnostics (unless asked not to by
1692 // Kind) and return false.
1694 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1695 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1696 CheckConstexprKind Kind) {
1697 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1698 if (MD && MD->isInstance()) {
1699 // C++11 [dcl.constexpr]p4:
1700 // The definition of a constexpr constructor shall satisfy the following
1702 // - the class shall not have any virtual base classes;
1704 // FIXME: This only applies to constructors and destructors, not arbitrary
1705 // member functions.
1706 const CXXRecordDecl *RD = MD->getParent();
1707 if (RD->getNumVBases()) {
1708 if (Kind == CheckConstexprKind::CheckValid)
1711 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1712 << isa<CXXConstructorDecl>(NewFD)
1713 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1714 for (const auto &I : RD->vbases())
1715 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1716 << I.getSourceRange();
1721 if (!isa<CXXConstructorDecl>(NewFD)) {
1722 // C++11 [dcl.constexpr]p3:
1723 // The definition of a constexpr function shall satisfy the following
1725 // - it shall not be virtual; (removed in C++20)
1726 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1727 if (Method && Method->isVirtual()) {
1728 if (getLangOpts().CPlusPlus20) {
1729 if (Kind == CheckConstexprKind::Diagnose)
1730 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1732 if (Kind == CheckConstexprKind::CheckValid)
1735 Method = Method->getCanonicalDecl();
1736 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1738 // If it's not obvious why this function is virtual, find an overridden
1739 // function which uses the 'virtual' keyword.
1740 const CXXMethodDecl *WrittenVirtual = Method;
1741 while (!WrittenVirtual->isVirtualAsWritten())
1742 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1743 if (WrittenVirtual != Method)
1744 Diag(WrittenVirtual->getLocation(),
1745 diag::note_overridden_virtual_function);
1750 // - its return type shall be a literal type;
1751 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1755 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1756 // A destructor can be constexpr only if the defaulted destructor could be;
1757 // we don't need to check the members and bases if we already know they all
1758 // have constexpr destructors.
1759 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1760 if (Kind == CheckConstexprKind::CheckValid)
1762 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1767 // - each of its parameter types shall be a literal type;
1768 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1771 Stmt *Body = NewFD->getBody();
1773 "CheckConstexprFunctionDefinition called on function with no body");
1774 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1777 /// Check the given declaration statement is legal within a constexpr function
1778 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1780 /// \return true if the body is OK (maybe only as an extension), false if we
1781 /// have diagnosed a problem.
1782 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1783 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1784 Sema::CheckConstexprKind Kind) {
1785 // C++11 [dcl.constexpr]p3 and p4:
1786 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1788 for (const auto *DclIt : DS->decls()) {
1789 switch (DclIt->getKind()) {
1790 case Decl::StaticAssert:
1792 case Decl::UsingShadow:
1793 case Decl::UsingDirective:
1794 case Decl::UnresolvedUsingTypename:
1795 case Decl::UnresolvedUsingValue:
1796 // - static_assert-declarations
1797 // - using-declarations,
1798 // - using-directives,
1802 case Decl::TypeAlias: {
1803 // - typedef declarations and alias-declarations that do not define
1804 // classes or enumerations,
1805 const auto *TN = cast<TypedefNameDecl>(DclIt);
1806 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1807 // Don't allow variably-modified types in constexpr functions.
1808 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1809 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1810 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1811 << TL.getSourceRange() << TL.getType()
1812 << isa<CXXConstructorDecl>(Dcl);
1820 case Decl::CXXRecord:
1821 // C++1y allows types to be defined, not just declared.
1822 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1823 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1824 SemaRef.Diag(DS->getBeginLoc(),
1825 SemaRef.getLangOpts().CPlusPlus14
1826 ? diag::warn_cxx11_compat_constexpr_type_definition
1827 : diag::ext_constexpr_type_definition)
1828 << isa<CXXConstructorDecl>(Dcl);
1829 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1835 case Decl::EnumConstant:
1836 case Decl::IndirectField:
1838 // These can only appear with other declarations which are banned in
1839 // C++11 and permitted in C++1y, so ignore them.
1843 case Decl::Decomposition: {
1844 // C++1y [dcl.constexpr]p3 allows anything except:
1845 // a definition of a variable of non-literal type or of static or
1846 // thread storage duration or [before C++2a] for which no
1847 // initialization is performed.
1848 const auto *VD = cast<VarDecl>(DclIt);
1849 if (VD->isThisDeclarationADefinition()) {
1850 if (VD->isStaticLocal()) {
1851 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1852 SemaRef.Diag(VD->getLocation(),
1853 diag::err_constexpr_local_var_static)
1854 << isa<CXXConstructorDecl>(Dcl)
1855 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1859 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1860 diag::err_constexpr_local_var_non_literal_type,
1861 isa<CXXConstructorDecl>(Dcl)))
1863 if (!VD->getType()->isDependentType() &&
1864 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1865 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1868 SemaRef.getLangOpts().CPlusPlus20
1869 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1870 : diag::ext_constexpr_local_var_no_init)
1871 << isa<CXXConstructorDecl>(Dcl);
1872 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1878 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1879 SemaRef.Diag(VD->getLocation(),
1880 SemaRef.getLangOpts().CPlusPlus14
1881 ? diag::warn_cxx11_compat_constexpr_local_var
1882 : diag::ext_constexpr_local_var)
1883 << isa<CXXConstructorDecl>(Dcl);
1884 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1890 case Decl::NamespaceAlias:
1891 case Decl::Function:
1892 // These are disallowed in C++11 and permitted in C++1y. Allow them
1893 // everywhere as an extension.
1894 if (!Cxx1yLoc.isValid())
1895 Cxx1yLoc = DS->getBeginLoc();
1899 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1900 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1901 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1910 /// Check that the given field is initialized within a constexpr constructor.
1912 /// \param Dcl The constexpr constructor being checked.
1913 /// \param Field The field being checked. This may be a member of an anonymous
1914 /// struct or union nested within the class being checked.
1915 /// \param Inits All declarations, including anonymous struct/union members and
1916 /// indirect members, for which any initialization was provided.
1917 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1918 /// multiple notes for different members to the same error.
1919 /// \param Kind Whether we're diagnosing a constructor as written or determining
1920 /// whether the formal requirements are satisfied.
1921 /// \return \c false if we're checking for validity and the constructor does
1922 /// not satisfy the requirements on a constexpr constructor.
1923 static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1924 const FunctionDecl *Dcl,
1926 llvm::SmallSet<Decl*, 16> &Inits,
1928 Sema::CheckConstexprKind Kind) {
1929 // In C++20 onwards, there's nothing to check for validity.
1930 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1931 SemaRef.getLangOpts().CPlusPlus20)
1934 if (Field->isInvalidDecl())
1937 if (Field->isUnnamedBitfield())
1940 // Anonymous unions with no variant members and empty anonymous structs do not
1941 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1942 // indirect fields don't need initializing.
1943 if (Field->isAnonymousStructOrUnion() &&
1944 (Field->getType()->isUnionType()
1945 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1946 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1949 if (!Inits.count(Field)) {
1950 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1952 SemaRef.Diag(Dcl->getLocation(),
1953 SemaRef.getLangOpts().CPlusPlus20
1954 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1955 : diag::ext_constexpr_ctor_missing_init);
1958 SemaRef.Diag(Field->getLocation(),
1959 diag::note_constexpr_ctor_missing_init);
1960 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1963 } else if (Field->isAnonymousStructOrUnion()) {
1964 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1965 for (auto *I : RD->fields())
1966 // If an anonymous union contains an anonymous struct of which any member
1967 // is initialized, all members must be initialized.
1968 if (!RD->isUnion() || Inits.count(I))
1969 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
1976 /// Check the provided statement is allowed in a constexpr function
1979 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1980 SmallVectorImpl<SourceLocation> &ReturnStmts,
1981 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
1982 Sema::CheckConstexprKind Kind) {
1983 // - its function-body shall be [...] a compound-statement that contains only
1984 switch (S->getStmtClass()) {
1985 case Stmt::NullStmtClass:
1986 // - null statements,
1989 case Stmt::DeclStmtClass:
1990 // - static_assert-declarations
1991 // - using-declarations,
1992 // - using-directives,
1993 // - typedef declarations and alias-declarations that do not define
1994 // classes or enumerations,
1995 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
1999 case Stmt::ReturnStmtClass:
2000 // - and exactly one return statement;
2001 if (isa<CXXConstructorDecl>(Dcl)) {
2002 // C++1y allows return statements in constexpr constructors.
2003 if (!Cxx1yLoc.isValid())
2004 Cxx1yLoc = S->getBeginLoc();
2008 ReturnStmts.push_back(S->getBeginLoc());
2011 case Stmt::CompoundStmtClass: {
2012 // C++1y allows compound-statements.
2013 if (!Cxx1yLoc.isValid())
2014 Cxx1yLoc = S->getBeginLoc();
2016 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2017 for (auto *BodyIt : CompStmt->body()) {
2018 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2019 Cxx1yLoc, Cxx2aLoc, Kind))
2025 case Stmt::AttributedStmtClass:
2026 if (!Cxx1yLoc.isValid())
2027 Cxx1yLoc = S->getBeginLoc();
2030 case Stmt::IfStmtClass: {
2031 // C++1y allows if-statements.
2032 if (!Cxx1yLoc.isValid())
2033 Cxx1yLoc = S->getBeginLoc();
2035 IfStmt *If = cast<IfStmt>(S);
2036 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2037 Cxx1yLoc, Cxx2aLoc, Kind))
2039 if (If->getElse() &&
2040 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2041 Cxx1yLoc, Cxx2aLoc, Kind))
2046 case Stmt::WhileStmtClass:
2047 case Stmt::DoStmtClass:
2048 case Stmt::ForStmtClass:
2049 case Stmt::CXXForRangeStmtClass:
2050 case Stmt::ContinueStmtClass:
2051 // C++1y allows all of these. We don't allow them as extensions in C++11,
2052 // because they don't make sense without variable mutation.
2053 if (!SemaRef.getLangOpts().CPlusPlus14)
2055 if (!Cxx1yLoc.isValid())
2056 Cxx1yLoc = S->getBeginLoc();
2057 for (Stmt *SubStmt : S->children())
2059 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2060 Cxx1yLoc, Cxx2aLoc, Kind))
2064 case Stmt::SwitchStmtClass:
2065 case Stmt::CaseStmtClass:
2066 case Stmt::DefaultStmtClass:
2067 case Stmt::BreakStmtClass:
2068 // C++1y allows switch-statements, and since they don't need variable
2069 // mutation, we can reasonably allow them in C++11 as an extension.
2070 if (!Cxx1yLoc.isValid())
2071 Cxx1yLoc = S->getBeginLoc();
2072 for (Stmt *SubStmt : S->children())
2074 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2075 Cxx1yLoc, Cxx2aLoc, Kind))
2079 case Stmt::GCCAsmStmtClass:
2080 case Stmt::MSAsmStmtClass:
2081 // C++2a allows inline assembly statements.
2082 case Stmt::CXXTryStmtClass:
2083 if (Cxx2aLoc.isInvalid())
2084 Cxx2aLoc = S->getBeginLoc();
2085 for (Stmt *SubStmt : S->children()) {
2087 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2088 Cxx1yLoc, Cxx2aLoc, Kind))
2093 case Stmt::CXXCatchStmtClass:
2094 // Do not bother checking the language mode (already covered by the
2095 // try block check).
2096 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2097 cast<CXXCatchStmt>(S)->getHandlerBlock(),
2098 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2106 // C++1y allows expression-statements.
2107 if (!Cxx1yLoc.isValid())
2108 Cxx1yLoc = S->getBeginLoc();
2112 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2113 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2114 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2119 /// Check the body for the given constexpr function declaration only contains
2120 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2122 /// \return true if the body is OK, false if we have found or diagnosed a
2124 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2126 Sema::CheckConstexprKind Kind) {
2127 SmallVector<SourceLocation, 4> ReturnStmts;
2129 if (isa<CXXTryStmt>(Body)) {
2130 // C++11 [dcl.constexpr]p3:
2131 // The definition of a constexpr function shall satisfy the following
2132 // constraints: [...]
2133 // - its function-body shall be = delete, = default, or a
2134 // compound-statement
2136 // C++11 [dcl.constexpr]p4:
2137 // In the definition of a constexpr constructor, [...]
2138 // - its function-body shall not be a function-try-block;
2140 // This restriction is lifted in C++2a, as long as inner statements also
2141 // apply the general constexpr rules.
2143 case Sema::CheckConstexprKind::CheckValid:
2144 if (!SemaRef.getLangOpts().CPlusPlus20)
2148 case Sema::CheckConstexprKind::Diagnose:
2149 SemaRef.Diag(Body->getBeginLoc(),
2150 !SemaRef.getLangOpts().CPlusPlus20
2151 ? diag::ext_constexpr_function_try_block_cxx20
2152 : diag::warn_cxx17_compat_constexpr_function_try_block)
2153 << isa<CXXConstructorDecl>(Dcl);
2158 // - its function-body shall be [...] a compound-statement that contains only
2159 // [... list of cases ...]
2161 // Note that walking the children here is enough to properly check for
2162 // CompoundStmt and CXXTryStmt body.
2163 SourceLocation Cxx1yLoc, Cxx2aLoc;
2164 for (Stmt *SubStmt : Body->children()) {
2166 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2167 Cxx1yLoc, Cxx2aLoc, Kind))
2171 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2172 // If this is only valid as an extension, report that we don't satisfy the
2173 // constraints of the current language.
2174 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2175 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2177 } else if (Cxx2aLoc.isValid()) {
2178 SemaRef.Diag(Cxx2aLoc,
2179 SemaRef.getLangOpts().CPlusPlus20
2180 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2181 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2182 << isa<CXXConstructorDecl>(Dcl);
2183 } else if (Cxx1yLoc.isValid()) {
2184 SemaRef.Diag(Cxx1yLoc,
2185 SemaRef.getLangOpts().CPlusPlus14
2186 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2187 : diag::ext_constexpr_body_invalid_stmt)
2188 << isa<CXXConstructorDecl>(Dcl);
2191 if (const CXXConstructorDecl *Constructor
2192 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2193 const CXXRecordDecl *RD = Constructor->getParent();
2195 // - every non-variant non-static data member and base class sub-object
2196 // shall be initialized;
2198 // - if the class is a union having variant members, exactly one of them
2199 // shall be initialized;
2200 if (RD->isUnion()) {
2201 if (Constructor->getNumCtorInitializers() == 0 &&
2202 RD->hasVariantMembers()) {
2203 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2206 SemaRef.getLangOpts().CPlusPlus20
2207 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2208 : diag::ext_constexpr_union_ctor_no_init);
2209 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2213 } else if (!Constructor->isDependentContext() &&
2214 !Constructor->isDelegatingConstructor()) {
2215 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2217 // Skip detailed checking if we have enough initializers, and we would
2218 // allow at most one initializer per member.
2219 bool AnyAnonStructUnionMembers = false;
2220 unsigned Fields = 0;
2221 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2222 E = RD->field_end(); I != E; ++I, ++Fields) {
2223 if (I->isAnonymousStructOrUnion()) {
2224 AnyAnonStructUnionMembers = true;
2229 // - if the class is a union-like class, but is not a union, for each of
2230 // its anonymous union members having variant members, exactly one of
2231 // them shall be initialized;
2232 if (AnyAnonStructUnionMembers ||
2233 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2234 // Check initialization of non-static data members. Base classes are
2235 // always initialized so do not need to be checked. Dependent bases
2236 // might not have initializers in the member initializer list.
2237 llvm::SmallSet<Decl*, 16> Inits;
2238 for (const auto *I: Constructor->inits()) {
2239 if (FieldDecl *FD = I->getMember())
2241 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2242 Inits.insert(ID->chain_begin(), ID->chain_end());
2245 bool Diagnosed = false;
2246 for (auto *I : RD->fields())
2247 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2253 if (ReturnStmts.empty()) {
2254 // C++1y doesn't require constexpr functions to contain a 'return'
2255 // statement. We still do, unless the return type might be void, because
2256 // otherwise if there's no return statement, the function cannot
2257 // be used in a core constant expression.
2258 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2259 (Dcl->getReturnType()->isVoidType() ||
2260 Dcl->getReturnType()->isDependentType());
2262 case Sema::CheckConstexprKind::Diagnose:
2263 SemaRef.Diag(Dcl->getLocation(),
2264 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2265 : diag::err_constexpr_body_no_return)
2266 << Dcl->isConsteval();
2271 case Sema::CheckConstexprKind::CheckValid:
2272 // The formal requirements don't include this rule in C++14, even
2273 // though the "must be able to produce a constant expression" rules
2274 // still imply it in some cases.
2275 if (!SemaRef.getLangOpts().CPlusPlus14)
2279 } else if (ReturnStmts.size() > 1) {
2281 case Sema::CheckConstexprKind::Diagnose:
2284 SemaRef.getLangOpts().CPlusPlus14
2285 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2286 : diag::ext_constexpr_body_multiple_return);
2287 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2288 SemaRef.Diag(ReturnStmts[I],
2289 diag::note_constexpr_body_previous_return);
2292 case Sema::CheckConstexprKind::CheckValid:
2293 if (!SemaRef.getLangOpts().CPlusPlus14)
2300 // C++11 [dcl.constexpr]p5:
2301 // if no function argument values exist such that the function invocation
2302 // substitution would produce a constant expression, the program is
2303 // ill-formed; no diagnostic required.
2304 // C++11 [dcl.constexpr]p3:
2305 // - every constructor call and implicit conversion used in initializing the
2306 // return value shall be one of those allowed in a constant expression.
2307 // C++11 [dcl.constexpr]p4:
2308 // - every constructor involved in initializing non-static data members and
2309 // base class sub-objects shall be a constexpr constructor.
2311 // Note that this rule is distinct from the "requirements for a constexpr
2312 // function", so is not checked in CheckValid mode.
2313 SmallVector<PartialDiagnosticAt, 8> Diags;
2314 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2315 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2316 SemaRef.Diag(Dcl->getLocation(),
2317 diag::ext_constexpr_function_never_constant_expr)
2318 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2319 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2320 SemaRef.Diag(Diags[I].first, Diags[I].second);
2321 // Don't return false here: we allow this for compatibility in
2328 /// Get the class that is directly named by the current context. This is the
2329 /// class for which an unqualified-id in this scope could name a constructor
2332 /// If the scope specifier denotes a class, this will be that class.
2333 /// If the scope specifier is empty, this will be the class whose
2334 /// member-specification we are currently within. Otherwise, there
2335 /// is no such class.
2336 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2337 assert(getLangOpts().CPlusPlus && "No class names in C!");
2339 if (SS && SS->isInvalid())
2342 if (SS && SS->isNotEmpty()) {
2343 DeclContext *DC = computeDeclContext(*SS, true);
2344 return dyn_cast_or_null<CXXRecordDecl>(DC);
2347 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2350 /// isCurrentClassName - Determine whether the identifier II is the
2351 /// name of the class type currently being defined. In the case of
2352 /// nested classes, this will only return true if II is the name of
2353 /// the innermost class.
2354 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2355 const CXXScopeSpec *SS) {
2356 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2357 return CurDecl && &II == CurDecl->getIdentifier();
2360 /// Determine whether the identifier II is a typo for the name of
2361 /// the class type currently being defined. If so, update it to the identifier
2362 /// that should have been used.
2363 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2364 assert(getLangOpts().CPlusPlus && "No class names in C!");
2366 if (!getLangOpts().SpellChecking)
2369 CXXRecordDecl *CurDecl;
2370 if (SS && SS->isSet() && !SS->isInvalid()) {
2371 DeclContext *DC = computeDeclContext(*SS, true);
2372 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2374 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2376 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2377 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2378 < II->getLength()) {
2379 II = CurDecl->getIdentifier();
2386 /// Determine whether the given class is a base class of the given
2387 /// class, including looking at dependent bases.
2388 static bool findCircularInheritance(const CXXRecordDecl *Class,
2389 const CXXRecordDecl *Current) {
2390 SmallVector<const CXXRecordDecl*, 8> Queue;
2392 Class = Class->getCanonicalDecl();
2394 for (const auto &I : Current->bases()) {
2395 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2399 Base = Base->getDefinition();
2403 if (Base->getCanonicalDecl() == Class)
2406 Queue.push_back(Base);
2412 Current = Queue.pop_back_val();
2418 /// Check the validity of a C++ base class specifier.
2420 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2421 /// and returns NULL otherwise.
2423 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2424 SourceRange SpecifierRange,
2425 bool Virtual, AccessSpecifier Access,
2426 TypeSourceInfo *TInfo,
2427 SourceLocation EllipsisLoc) {
2428 QualType BaseType = TInfo->getType();
2429 if (BaseType->containsErrors()) {
2430 // Already emitted a diagnostic when parsing the error type.
2433 // C++ [class.union]p1:
2434 // A union shall not have base classes.
2435 if (Class->isUnion()) {
2436 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2441 if (EllipsisLoc.isValid() &&
2442 !TInfo->getType()->containsUnexpandedParameterPack()) {
2443 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2444 << TInfo->getTypeLoc().getSourceRange();
2445 EllipsisLoc = SourceLocation();
2448 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2450 if (BaseType->isDependentType()) {
2451 // Make sure that we don't have circular inheritance among our dependent
2452 // bases. For non-dependent bases, the check for completeness below handles
2454 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2455 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2456 ((BaseDecl = BaseDecl->getDefinition()) &&
2457 findCircularInheritance(Class, BaseDecl))) {
2458 Diag(BaseLoc, diag::err_circular_inheritance)
2459 << BaseType << Context.getTypeDeclType(Class);
2461 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2462 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2469 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2470 Class->getTagKind() == TTK_Class,
2471 Access, TInfo, EllipsisLoc);
2474 // Base specifiers must be record types.
2475 if (!BaseType->isRecordType()) {
2476 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2480 // C++ [class.union]p1:
2481 // A union shall not be used as a base class.
2482 if (BaseType->isUnionType()) {
2483 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2487 // For the MS ABI, propagate DLL attributes to base class templates.
2488 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2489 if (Attr *ClassAttr = getDLLAttr(Class)) {
2490 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2491 BaseType->getAsCXXRecordDecl())) {
2492 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2498 // C++ [class.derived]p2:
2499 // The class-name in a base-specifier shall not be an incompletely
2501 if (RequireCompleteType(BaseLoc, BaseType,
2502 diag::err_incomplete_base_class, SpecifierRange)) {
2503 Class->setInvalidDecl();
2507 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2508 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2509 assert(BaseDecl && "Record type has no declaration");
2510 BaseDecl = BaseDecl->getDefinition();
2511 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2512 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2513 assert(CXXBaseDecl && "Base type is not a C++ type");
2515 // Microsoft docs say:
2516 // "If a base-class has a code_seg attribute, derived classes must have the
2518 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2519 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2520 if ((DerivedCSA || BaseCSA) &&
2521 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2522 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2523 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2528 // A class which contains a flexible array member is not suitable for use as a
2530 // - If the layout determines that a base comes before another base,
2531 // the flexible array member would index into the subsequent base.
2532 // - If the layout determines that base comes before the derived class,
2533 // the flexible array member would index into the derived class.
2534 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2535 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2536 << CXXBaseDecl->getDeclName();
2541 // If a class is marked final and it appears as a base-type-specifier in
2542 // base-clause, the program is ill-formed.
2543 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2544 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2545 << CXXBaseDecl->getDeclName()
2546 << FA->isSpelledAsSealed();
2547 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2548 << CXXBaseDecl->getDeclName() << FA->getRange();
2552 if (BaseDecl->isInvalidDecl())
2553 Class->setInvalidDecl();
2555 // Create the base specifier.
2556 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2557 Class->getTagKind() == TTK_Class,
2558 Access, TInfo, EllipsisLoc);
2561 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2562 /// one entry in the base class list of a class specifier, for
2564 /// class foo : public bar, virtual private baz {
2565 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2567 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2568 ParsedAttributes &Attributes,
2569 bool Virtual, AccessSpecifier Access,
2570 ParsedType basetype, SourceLocation BaseLoc,
2571 SourceLocation EllipsisLoc) {
2575 AdjustDeclIfTemplate(classdecl);
2576 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2580 // We haven't yet attached the base specifiers.
2581 Class->setIsParsingBaseSpecifiers();
2583 // We do not support any C++11 attributes on base-specifiers yet.
2584 // Diagnose any attributes we see.
2585 for (const ParsedAttr &AL : Attributes) {
2586 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2588 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2589 ? (unsigned)diag::warn_unknown_attribute_ignored
2590 : (unsigned)diag::err_base_specifier_attribute)
2594 TypeSourceInfo *TInfo = nullptr;
2595 GetTypeFromParser(basetype, &TInfo);
2597 if (EllipsisLoc.isInvalid() &&
2598 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2602 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2603 Virtual, Access, TInfo,
2607 Class->setInvalidDecl();
2612 /// Use small set to collect indirect bases. As this is only used
2613 /// locally, there's no need to abstract the small size parameter.
2614 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2616 /// Recursively add the bases of Type. Don't add Type itself.
2618 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2619 const QualType &Type)
2621 // Even though the incoming type is a base, it might not be
2622 // a class -- it could be a template parm, for instance.
2623 if (auto Rec = Type->getAs<RecordType>()) {
2624 auto Decl = Rec->getAsCXXRecordDecl();
2626 // Iterate over its bases.
2627 for (const auto &BaseSpec : Decl->bases()) {
2628 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2629 .getUnqualifiedType();
2630 if (Set.insert(Base).second)
2631 // If we've not already seen it, recurse.
2632 NoteIndirectBases(Context, Set, Base);
2637 /// Performs the actual work of attaching the given base class
2638 /// specifiers to a C++ class.
2639 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2640 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2644 // Used to keep track of which base types we have already seen, so
2645 // that we can properly diagnose redundant direct base types. Note
2646 // that the key is always the unqualified canonical type of the base
2648 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2650 // Used to track indirect bases so we can see if a direct base is
2652 IndirectBaseSet IndirectBaseTypes;
2654 // Copy non-redundant base specifiers into permanent storage.
2655 unsigned NumGoodBases = 0;
2656 bool Invalid = false;
2657 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2658 QualType NewBaseType
2659 = Context.getCanonicalType(Bases[idx]->getType());
2660 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2662 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2664 // C++ [class.mi]p3:
2665 // A class shall not be specified as a direct base class of a
2666 // derived class more than once.
2667 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2668 << KnownBase->getType() << Bases[idx]->getSourceRange();
2670 // Delete the duplicate base class specifier; we're going to
2671 // overwrite its pointer later.
2672 Context.Deallocate(Bases[idx]);
2676 // Okay, add this new base class.
2677 KnownBase = Bases[idx];
2678 Bases[NumGoodBases++] = Bases[idx];
2680 // Note this base's direct & indirect bases, if there could be ambiguity.
2681 if (Bases.size() > 1)
2682 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2684 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2685 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2686 if (Class->isInterface() &&
2687 (!RD->isInterfaceLike() ||
2688 KnownBase->getAccessSpecifier() != AS_public)) {
2689 // The Microsoft extension __interface does not permit bases that
2690 // are not themselves public interfaces.
2691 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2692 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2693 << RD->getSourceRange();
2696 if (RD->hasAttr<WeakAttr>())
2697 Class->addAttr(WeakAttr::CreateImplicit(Context));
2702 // Attach the remaining base class specifiers to the derived class.
2703 Class->setBases(Bases.data(), NumGoodBases);
2705 // Check that the only base classes that are duplicate are virtual.
2706 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2707 // Check whether this direct base is inaccessible due to ambiguity.
2708 QualType BaseType = Bases[idx]->getType();
2710 // Skip all dependent types in templates being used as base specifiers.
2711 // Checks below assume that the base specifier is a CXXRecord.
2712 if (BaseType->isDependentType())
2715 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2716 .getUnqualifiedType();
2718 if (IndirectBaseTypes.count(CanonicalBase)) {
2719 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2720 /*DetectVirtual=*/true);
2722 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2726 if (Paths.isAmbiguous(CanonicalBase))
2727 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2728 << BaseType << getAmbiguousPathsDisplayString(Paths)
2729 << Bases[idx]->getSourceRange();
2731 assert(Bases[idx]->isVirtual());
2734 // Delete the base class specifier, since its data has been copied
2735 // into the CXXRecordDecl.
2736 Context.Deallocate(Bases[idx]);
2742 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2743 /// class, after checking whether there are any duplicate base
2745 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2746 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2747 if (!ClassDecl || Bases.empty())
2750 AdjustDeclIfTemplate(ClassDecl);
2751 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2754 /// Determine whether the type \p Derived is a C++ class that is
2755 /// derived from the type \p Base.
2756 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2757 if (!getLangOpts().CPlusPlus)
2760 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2764 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2768 // If either the base or the derived type is invalid, don't try to
2769 // check whether one is derived from the other.
2770 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2773 // FIXME: In a modules build, do we need the entire path to be visible for us
2774 // to be able to use the inheritance relationship?
2775 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2778 return DerivedRD->isDerivedFrom(BaseRD);
2781 /// Determine whether the type \p Derived is a C++ class that is
2782 /// derived from the type \p Base.
2783 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2784 CXXBasePaths &Paths) {
2785 if (!getLangOpts().CPlusPlus)
2788 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2792 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2796 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2799 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2802 static void BuildBasePathArray(const CXXBasePath &Path,
2803 CXXCastPath &BasePathArray) {
2804 // We first go backward and check if we have a virtual base.
2805 // FIXME: It would be better if CXXBasePath had the base specifier for
2806 // the nearest virtual base.
2808 for (unsigned I = Path.size(); I != 0; --I) {
2809 if (Path[I - 1].Base->isVirtual()) {
2815 // Now add all bases.
2816 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2817 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2821 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2822 CXXCastPath &BasePathArray) {
2823 assert(BasePathArray.empty() && "Base path array must be empty!");
2824 assert(Paths.isRecordingPaths() && "Must record paths!");
2825 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2827 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2828 /// conversion (where Derived and Base are class types) is
2829 /// well-formed, meaning that the conversion is unambiguous (and
2830 /// that all of the base classes are accessible). Returns true
2831 /// and emits a diagnostic if the code is ill-formed, returns false
2832 /// otherwise. Loc is the location where this routine should point to
2833 /// if there is an error, and Range is the source range to highlight
2834 /// if there is an error.
2836 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2837 /// diagnostic for the respective type of error will be suppressed, but the
2838 /// check for ill-formed code will still be performed.
2840 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2841 unsigned InaccessibleBaseID,
2842 unsigned AmbiguousBaseConvID,
2843 SourceLocation Loc, SourceRange Range,
2844 DeclarationName Name,
2845 CXXCastPath *BasePath,
2846 bool IgnoreAccess) {
2847 // First, determine whether the path from Derived to Base is
2848 // ambiguous. This is slightly more expensive than checking whether
2849 // the Derived to Base conversion exists, because here we need to
2850 // explore multiple paths to determine if there is an ambiguity.
2851 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2852 /*DetectVirtual=*/false);
2853 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2854 if (!DerivationOkay)
2857 const CXXBasePath *Path = nullptr;
2858 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2859 Path = &Paths.front();
2861 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2862 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2863 // user to access such bases.
2864 if (!Path && getLangOpts().MSVCCompat) {
2865 for (const CXXBasePath &PossiblePath : Paths) {
2866 if (PossiblePath.size() == 1) {
2867 Path = &PossiblePath;
2868 if (AmbiguousBaseConvID)
2869 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2870 << Base << Derived << Range;
2877 if (!IgnoreAccess) {
2878 // Check that the base class can be accessed.
2880 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2881 case AR_inaccessible:
2890 // Build a base path if necessary.
2892 ::BuildBasePathArray(*Path, *BasePath);
2896 if (AmbiguousBaseConvID) {
2897 // We know that the derived-to-base conversion is ambiguous, and
2898 // we're going to produce a diagnostic. Perform the derived-to-base
2899 // search just one more time to compute all of the possible paths so
2900 // that we can print them out. This is more expensive than any of
2901 // the previous derived-to-base checks we've done, but at this point
2902 // performance isn't as much of an issue.
2904 Paths.setRecordingPaths(true);
2905 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2906 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2909 // Build up a textual representation of the ambiguous paths, e.g.,
2910 // D -> B -> A, that will be used to illustrate the ambiguous
2911 // conversions in the diagnostic. We only print one of the paths
2912 // to each base class subobject.
2913 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2915 Diag(Loc, AmbiguousBaseConvID)
2916 << Derived << Base << PathDisplayStr << Range << Name;
2922 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2923 SourceLocation Loc, SourceRange Range,
2924 CXXCastPath *BasePath,
2925 bool IgnoreAccess) {
2926 return CheckDerivedToBaseConversion(
2927 Derived, Base, diag::err_upcast_to_inaccessible_base,
2928 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2929 BasePath, IgnoreAccess);
2933 /// Builds a string representing ambiguous paths from a
2934 /// specific derived class to different subobjects of the same base
2937 /// This function builds a string that can be used in error messages
2938 /// to show the different paths that one can take through the
2939 /// inheritance hierarchy to go from the derived class to different
2940 /// subobjects of a base class. The result looks something like this:
2942 /// struct D -> struct B -> struct A
2943 /// struct D -> struct C -> struct A
2945 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2946 std::string PathDisplayStr;
2947 std::set<unsigned> DisplayedPaths;
2948 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2949 Path != Paths.end(); ++Path) {
2950 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2951 // We haven't displayed a path to this particular base
2952 // class subobject yet.
2953 PathDisplayStr += "\n ";
2954 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2955 for (CXXBasePath::const_iterator Element = Path->begin();
2956 Element != Path->end(); ++Element)
2957 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2961 return PathDisplayStr;
2964 //===----------------------------------------------------------------------===//
2965 // C++ class member Handling
2966 //===----------------------------------------------------------------------===//
2968 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2969 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2970 SourceLocation ColonLoc,
2971 const ParsedAttributesView &Attrs) {
2972 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2973 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2975 CurContext->addHiddenDecl(ASDecl);
2976 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2979 /// CheckOverrideControl - Check C++11 override control semantics.
2980 void Sema::CheckOverrideControl(NamedDecl *D) {
2981 if (D->isInvalidDecl())
2984 // We only care about "override" and "final" declarations.
2985 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2988 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2990 // We can't check dependent instance methods.
2991 if (MD && MD->isInstance() &&
2992 (MD->getParent()->hasAnyDependentBases() ||
2993 MD->getType()->isDependentType()))
2996 if (MD && !MD->isVirtual()) {
2997 // If we have a non-virtual method, check if if hides a virtual method.
2998 // (In that case, it's most likely the method has the wrong type.)
2999 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3000 FindHiddenVirtualMethods(MD, OverloadedMethods);
3002 if (!OverloadedMethods.empty()) {
3003 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3004 Diag(OA->getLocation(),
3005 diag::override_keyword_hides_virtual_member_function)
3006 << "override" << (OverloadedMethods.size() > 1);
3007 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3008 Diag(FA->getLocation(),
3009 diag::override_keyword_hides_virtual_member_function)
3010 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3011 << (OverloadedMethods.size() > 1);
3013 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3014 MD->setInvalidDecl();
3017 // Fall through into the general case diagnostic.
3018 // FIXME: We might want to attempt typo correction here.
3021 if (!MD || !MD->isVirtual()) {
3022 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3023 Diag(OA->getLocation(),
3024 diag::override_keyword_only_allowed_on_virtual_member_functions)
3025 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3026 D->dropAttr<OverrideAttr>();
3028 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3029 Diag(FA->getLocation(),
3030 diag::override_keyword_only_allowed_on_virtual_member_functions)
3031 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3032 << FixItHint::CreateRemoval(FA->getLocation());
3033 D->dropAttr<FinalAttr>();
3038 // C++11 [class.virtual]p5:
3039 // If a function is marked with the virt-specifier override and
3040 // does not override a member function of a base class, the program is
3042 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3043 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3044 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3045 << MD->getDeclName();
3048 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3049 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3051 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3052 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3055 SourceLocation Loc = MD->getLocation();
3056 SourceLocation SpellingLoc = Loc;
3057 if (getSourceManager().isMacroArgExpansion(Loc))
3058 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3059 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3060 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3063 if (MD->size_overridden_methods() > 0) {
3064 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3066 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3069 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3070 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3071 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3073 if (isa<CXXDestructorDecl>(MD))
3075 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3076 diag::warn_suggest_destructor_marked_not_override_overriding);
3078 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3079 diag::warn_suggest_function_marked_not_override_overriding);
3083 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3084 /// function overrides a virtual member function marked 'final', according to
3085 /// C++11 [class.virtual]p4.
3086 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3087 const CXXMethodDecl *Old) {
3088 FinalAttr *FA = Old->getAttr<FinalAttr>();
3092 Diag(New->getLocation(), diag::err_final_function_overridden)
3093 << New->getDeclName()
3094 << FA->isSpelledAsSealed();
3095 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3099 static bool InitializationHasSideEffects(const FieldDecl &FD) {
3100 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3101 // FIXME: Destruction of ObjC lifetime types has side-effects.
3102 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3103 return !RD->isCompleteDefinition() ||
3104 !RD->hasTrivialDefaultConstructor() ||
3105 !RD->hasTrivialDestructor();
3109 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3110 ParsedAttributesView::const_iterator Itr =
3111 llvm::find_if(list, [](const ParsedAttr &AL) {
3112 return AL.isDeclspecPropertyAttribute();
3114 if (Itr != list.end())
3119 // Check if there is a field shadowing.
3120 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3121 DeclarationName FieldName,
3122 const CXXRecordDecl *RD,
3124 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3127 // To record a shadowed field in a base
3128 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3129 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3130 CXXBasePath &Path) {
3131 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3132 // Record an ambiguous path directly
3133 if (Bases.find(Base) != Bases.end())
3135 for (const auto Field : Base->lookup(FieldName)) {
3136 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3137 Field->getAccess() != AS_private) {
3138 assert(Field->getAccess() != AS_none);
3139 assert(Bases.find(Base) == Bases.end());
3140 Bases[Base] = Field;
3147 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3148 /*DetectVirtual=*/true);
3149 if (!RD->lookupInBases(FieldShadowed, Paths))
3152 for (const auto &P : Paths) {
3153 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3154 auto It = Bases.find(Base);
3155 // Skip duplicated bases
3156 if (It == Bases.end())
3158 auto BaseField = It->second;
3159 assert(BaseField->getAccess() != AS_private);
3161 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3162 Diag(Loc, diag::warn_shadow_field)
3163 << FieldName << RD << Base << DeclIsField;
3164 Diag(BaseField->getLocation(), diag::note_shadow_field);
3170 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3171 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3172 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
3173 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3174 /// present (but parsing it has been deferred).
3176 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3177 MultiTemplateParamsArg TemplateParameterLists,
3178 Expr *BW, const VirtSpecifiers &VS,
3179 InClassInitStyle InitStyle) {
3180 const DeclSpec &DS = D.getDeclSpec();
3181 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3182 DeclarationName Name = NameInfo.getName();
3183 SourceLocation Loc = NameInfo.getLoc();
3185 // For anonymous bitfields, the location should point to the type.
3186 if (Loc.isInvalid())
3187 Loc = D.getBeginLoc();
3189 Expr *BitWidth = static_cast<Expr*>(BW);
3191 assert(isa<CXXRecordDecl>(CurContext));
3192 assert(!DS.isFriendSpecified());
3194 bool isFunc = D.isDeclarationOfFunction();
3195 const ParsedAttr *MSPropertyAttr =
3196 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3198 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3199 // The Microsoft extension __interface only permits public member functions
3200 // and prohibits constructors, destructors, operators, non-public member
3201 // functions, static methods and data members.
3202 unsigned InvalidDecl;
3203 bool ShowDeclName = true;
3205 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3209 else if (AS != AS_public)
3211 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3213 else switch (Name.getNameKind()) {
3214 case DeclarationName::CXXConstructorName:
3216 ShowDeclName = false;
3219 case DeclarationName::CXXDestructorName:
3221 ShowDeclName = false;
3224 case DeclarationName::CXXOperatorName:
3225 case DeclarationName::CXXConversionFunctionName:
3236 Diag(Loc, diag::err_invalid_member_in_interface)
3237 << (InvalidDecl-1) << Name;
3239 Diag(Loc, diag::err_invalid_member_in_interface)
3240 << (InvalidDecl-1) << "";
3245 // C++ 9.2p6: A member shall not be declared to have automatic storage
3246 // duration (auto, register) or with the extern storage-class-specifier.
3247 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3248 // data members and cannot be applied to names declared const or static,
3249 // and cannot be applied to reference members.
3250 switch (DS.getStorageClassSpec()) {
3251 case DeclSpec::SCS_unspecified:
3252 case DeclSpec::SCS_typedef:
3253 case DeclSpec::SCS_static:
3255 case DeclSpec::SCS_mutable:
3257 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3259 // FIXME: It would be nicer if the keyword was ignored only for this
3260 // declarator. Otherwise we could get follow-up errors.
3261 D.getMutableDeclSpec().ClearStorageClassSpecs();
3265 Diag(DS.getStorageClassSpecLoc(),
3266 diag::err_storageclass_invalid_for_member);
3267 D.getMutableDeclSpec().ClearStorageClassSpecs();
3271 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3272 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3275 if (DS.hasConstexprSpecifier() && isInstField) {
3276 SemaDiagnosticBuilder B =
3277 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3278 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3279 if (InitStyle == ICIS_NoInit) {
3281 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3282 B << FixItHint::CreateRemoval(ConstexprLoc);
3284 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3285 D.getMutableDeclSpec().ClearConstexprSpec();
3286 const char *PrevSpec;
3288 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3289 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3291 assert(!Failed && "Making a constexpr member const shouldn't fail");
3295 const char *PrevSpec;
3297 if (D.getMutableDeclSpec().SetStorageClassSpec(
3298 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3299 Context.getPrintingPolicy())) {
3300 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3301 "This is the only DeclSpec that should fail to be applied");
3304 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3305 isInstField = false;
3312 CXXScopeSpec &SS = D.getCXXScopeSpec();
3314 // Data members must have identifiers for names.
3315 if (!Name.isIdentifier()) {
3316 Diag(Loc, diag::err_bad_variable_name)
3321 IdentifierInfo *II = Name.getAsIdentifierInfo();
3323 // Member field could not be with "template" keyword.
3324 // So TemplateParameterLists should be empty in this case.
3325 if (TemplateParameterLists.size()) {
3326 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3327 if (TemplateParams->size()) {
3328 // There is no such thing as a member field template.
3329 Diag(D.getIdentifierLoc(), diag::err_template_member)
3331 << SourceRange(TemplateParams->getTemplateLoc(),
3332 TemplateParams->getRAngleLoc());
3334 // There is an extraneous 'template<>' for this member.
3335 Diag(TemplateParams->getTemplateLoc(),
3336 diag::err_template_member_noparams)
3338 << SourceRange(TemplateParams->getTemplateLoc(),
3339 TemplateParams->getRAngleLoc());
3344 if (SS.isSet() && !SS.isInvalid()) {
3345 // The user provided a superfluous scope specifier inside a class
3351 if (DeclContext *DC = computeDeclContext(SS, false))
3352 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3353 D.getName().getKind() ==
3354 UnqualifiedIdKind::IK_TemplateId);
3356 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3357 << Name << SS.getRange();
3362 if (MSPropertyAttr) {
3363 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3364 BitWidth, InitStyle, AS, *MSPropertyAttr);
3367 isInstField = false;
3369 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3370 BitWidth, InitStyle, AS);
3375 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3377 Member = HandleDeclarator(S, D, TemplateParameterLists);
3381 // Non-instance-fields can't have a bitfield.
3383 if (Member->isInvalidDecl()) {
3384 // don't emit another diagnostic.
3385 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3386 // C++ 9.6p3: A bit-field shall not be a static member.
3387 // "static member 'A' cannot be a bit-field"
3388 Diag(Loc, diag::err_static_not_bitfield)
3389 << Name << BitWidth->getSourceRange();
3390 } else if (isa<TypedefDecl>(Member)) {
3391 // "typedef member 'x' cannot be a bit-field"
3392 Diag(Loc, diag::err_typedef_not_bitfield)
3393 << Name << BitWidth->getSourceRange();
3395 // A function typedef ("typedef int f(); f a;").
3396 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3397 Diag(Loc, diag::err_not_integral_type_bitfield)
3398 << Name << cast<ValueDecl>(Member)->getType()
3399 << BitWidth->getSourceRange();
3403 Member->setInvalidDecl();
3406 NamedDecl *NonTemplateMember = Member;
3407 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3408 NonTemplateMember = FunTmpl->getTemplatedDecl();
3409 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3410 NonTemplateMember = VarTmpl->getTemplatedDecl();
3412 Member->setAccess(AS);
3414 // If we have declared a member function template or static data member
3415 // template, set the access of the templated declaration as well.
3416 if (NonTemplateMember != Member)
3417 NonTemplateMember->setAccess(AS);
3419 // C++ [temp.deduct.guide]p3:
3420 // A deduction guide [...] for a member class template [shall be
3421 // declared] with the same access [as the template].
3422 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3423 auto *TD = DG->getDeducedTemplate();
3424 // Access specifiers are only meaningful if both the template and the
3425 // deduction guide are from the same scope.
3426 if (AS != TD->getAccess() &&
3427 TD->getDeclContext()->getRedeclContext()->Equals(
3428 DG->getDeclContext()->getRedeclContext())) {
3429 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3430 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3432 const AccessSpecDecl *LastAccessSpec = nullptr;
3433 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3434 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3435 LastAccessSpec = AccessSpec;
3437 assert(LastAccessSpec && "differing access with no access specifier");
3438 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3444 if (VS.isOverrideSpecified())
3445 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3446 AttributeCommonInfo::AS_Keyword));
3447 if (VS.isFinalSpecified())
3448 Member->addAttr(FinalAttr::Create(
3449 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3450 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3452 if (VS.getLastLocation().isValid()) {
3453 // Update the end location of a method that has a virt-specifiers.
3454 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3455 MD->setRangeEnd(VS.getLastLocation());
3458 CheckOverrideControl(Member);
3460 assert((Name || isInstField) && "No identifier for non-field ?");
3463 FieldDecl *FD = cast<FieldDecl>(Member);
3464 FieldCollector->Add(FD);
3466 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3467 // Remember all explicit private FieldDecls that have a name, no side
3468 // effects and are not part of a dependent type declaration.
3469 if (!FD->isImplicit() && FD->getDeclName() &&
3470 FD->getAccess() == AS_private &&
3471 !FD->hasAttr<UnusedAttr>() &&
3472 !FD->getParent()->isDependentContext() &&
3473 !InitializationHasSideEffects(*FD))
3474 UnusedPrivateFields.insert(FD);
3482 class UninitializedFieldVisitor
3483 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3485 // List of Decls to generate a warning on. Also remove Decls that become
3487 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3488 // List of base classes of the record. Classes are removed after their
3490 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3491 // Vector of decls to be removed from the Decl set prior to visiting the
3492 // nodes. These Decls may have been initialized in the prior initializer.
3493 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3494 // If non-null, add a note to the warning pointing back to the constructor.
3495 const CXXConstructorDecl *Constructor;
3496 // Variables to hold state when processing an initializer list. When
3497 // InitList is true, special case initialization of FieldDecls matching
3498 // InitListFieldDecl.
3500 FieldDecl *InitListFieldDecl;
3501 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3504 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3505 UninitializedFieldVisitor(Sema &S,
3506 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3507 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3508 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3509 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3511 // Returns true if the use of ME is not an uninitialized use.
3512 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3513 bool CheckReferenceOnly) {
3514 llvm::SmallVector<FieldDecl*, 4> Fields;
3515 bool ReferenceField = false;
3517 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3520 Fields.push_back(FD);
3521 if (FD->getType()->isReferenceType())
3522 ReferenceField = true;
3523 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3526 // Binding a reference to an uninitialized field is not an
3527 // uninitialized use.
3528 if (CheckReferenceOnly && !ReferenceField)
3531 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3532 // Discard the first field since it is the field decl that is being
3534 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3535 UsedFieldIndex.push_back((*I)->getFieldIndex());
3538 for (auto UsedIter = UsedFieldIndex.begin(),
3539 UsedEnd = UsedFieldIndex.end(),
3540 OrigIter = InitFieldIndex.begin(),
3541 OrigEnd = InitFieldIndex.end();
3542 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3543 if (*UsedIter < *OrigIter)
3545 if (*UsedIter > *OrigIter)
3552 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3554 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3557 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3559 MemberExpr *FieldME = ME;
3561 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3564 while (MemberExpr *SubME =
3565 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3567 if (isa<VarDecl>(SubME->getMemberDecl()))
3570 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3571 if (!FD->isAnonymousStructOrUnion())
3574 if (!FieldME->getType().isPODType(S.Context))
3575 AllPODFields = false;
3577 Base = SubME->getBase();
3580 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3583 if (AddressOf && AllPODFields)
3586 ValueDecl* FoundVD = FieldME->getMemberDecl();
3588 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3589 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3590 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3593 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3594 QualType T = BaseCast->getType();
3595 if (T->isPointerType() &&
3596 BaseClasses.count(T->getPointeeType())) {
3597 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3598 << T->getPointeeType() << FoundVD;
3603 if (!Decls.count(FoundVD))
3606 const bool IsReference = FoundVD->getType()->isReferenceType();
3608 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3609 // Special checking for initializer lists.
3610 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3614 // Prevent double warnings on use of unbounded references.
3615 if (CheckReferenceOnly && !IsReference)
3619 unsigned diag = IsReference
3620 ? diag::warn_reference_field_is_uninit
3621 : diag::warn_field_is_uninit;
3622 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3624 S.Diag(Constructor->getLocation(),
3625 diag::note_uninit_in_this_constructor)
3626 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3630 void HandleValue(Expr *E, bool AddressOf) {
3631 E = E->IgnoreParens();
3633 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3634 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3635 AddressOf /*AddressOf*/);
3639 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3640 Visit(CO->getCond());
3641 HandleValue(CO->getTrueExpr(), AddressOf);
3642 HandleValue(CO->getFalseExpr(), AddressOf);
3646 if (BinaryConditionalOperator *BCO =
3647 dyn_cast<BinaryConditionalOperator>(E)) {
3648 Visit(BCO->getCond());
3649 HandleValue(BCO->getFalseExpr(), AddressOf);
3653 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3654 HandleValue(OVE->getSourceExpr(), AddressOf);
3658 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3659 switch (BO->getOpcode()) {
3664 HandleValue(BO->getLHS(), AddressOf);
3665 Visit(BO->getRHS());
3668 Visit(BO->getLHS());
3669 HandleValue(BO->getRHS(), AddressOf);
3677 void CheckInitListExpr(InitListExpr *ILE) {
3678 InitFieldIndex.push_back(0);
3679 for (auto Child : ILE->children()) {
3680 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3681 CheckInitListExpr(SubList);
3685 ++InitFieldIndex.back();
3687 InitFieldIndex.pop_back();
3690 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3691 FieldDecl *Field, const Type *BaseClass) {
3692 // Remove Decls that may have been initialized in the previous
3694 for (ValueDecl* VD : DeclsToRemove)
3696 DeclsToRemove.clear();
3698 Constructor = FieldConstructor;
3699 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3703 InitListFieldDecl = Field;
3704 InitFieldIndex.clear();
3705 CheckInitListExpr(ILE);
3714 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3717 void VisitMemberExpr(MemberExpr *ME) {
3718 // All uses of unbounded reference fields will warn.
3719 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3722 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3723 if (E->getCastKind() == CK_LValueToRValue) {
3724 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3728 Inherited::VisitImplicitCastExpr(E);
3731 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3732 if (E->getConstructor()->isCopyConstructor()) {
3733 Expr *ArgExpr = E->getArg(0);
3734 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3735 if (ILE->getNumInits() == 1)
3736 ArgExpr = ILE->getInit(0);
3737 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3738 if (ICE->getCastKind() == CK_NoOp)
3739 ArgExpr = ICE->getSubExpr();
3740 HandleValue(ArgExpr, false /*AddressOf*/);
3743 Inherited::VisitCXXConstructExpr(E);
3746 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3747 Expr *Callee = E->getCallee();
3748 if (isa<MemberExpr>(Callee)) {
3749 HandleValue(Callee, false /*AddressOf*/);
3750 for (auto Arg : E->arguments())
3755 Inherited::VisitCXXMemberCallExpr(E);
3758 void VisitCallExpr(CallExpr *E) {
3759 // Treat std::move as a use.
3760 if (E->isCallToStdMove()) {
3761 HandleValue(E->getArg(0), /*AddressOf=*/false);
3765 Inherited::VisitCallExpr(E);
3768 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3769 Expr *Callee = E->getCallee();
3771 if (isa<UnresolvedLookupExpr>(Callee))
3772 return Inherited::VisitCXXOperatorCallExpr(E);
3775 for (auto Arg : E->arguments())
3776 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3779 void VisitBinaryOperator(BinaryOperator *E) {
3780 // If a field assignment is detected, remove the field from the
3781 // uninitiailized field set.
3782 if (E->getOpcode() == BO_Assign)
3783 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3784 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3785 if (!FD->getType()->isReferenceType())
3786 DeclsToRemove.push_back(FD);
3788 if (E->isCompoundAssignmentOp()) {
3789 HandleValue(E->getLHS(), false /*AddressOf*/);
3794 Inherited::VisitBinaryOperator(E);
3797 void VisitUnaryOperator(UnaryOperator *E) {
3798 if (E->isIncrementDecrementOp()) {
3799 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3802 if (E->getOpcode() == UO_AddrOf) {
3803 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3804 HandleValue(ME->getBase(), true /*AddressOf*/);
3809 Inherited::VisitUnaryOperator(E);
3813 // Diagnose value-uses of fields to initialize themselves, e.g.
3815 // where foo is not also a parameter to the constructor.
3816 // Also diagnose across field uninitialized use such as
3818 // TODO: implement -Wuninitialized and fold this into that framework.
3819 static void DiagnoseUninitializedFields(
3820 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3822 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3823 Constructor->getLocation())) {
3827 if (Constructor->isInvalidDecl())
3830 const CXXRecordDecl *RD = Constructor->getParent();
3832 if (RD->isDependentContext())
3835 // Holds fields that are uninitialized.
3836 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3838 // At the beginning, all fields are uninitialized.
3839 for (auto *I : RD->decls()) {
3840 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3841 UninitializedFields.insert(FD);
3842 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3843 UninitializedFields.insert(IFD->getAnonField());
3847 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3848 for (auto I : RD->bases())
3849 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3851 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3854 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3855 UninitializedFields,
3856 UninitializedBaseClasses);
3858 for (const auto *FieldInit : Constructor->inits()) {
3859 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3862 Expr *InitExpr = FieldInit->getInit();
3866 if (CXXDefaultInitExpr *Default =
3867 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3868 InitExpr = Default->getExpr();
3871 // In class initializers will point to the constructor.
3872 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3873 FieldInit->getAnyMember(),
3874 FieldInit->getBaseClass());
3876 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3877 FieldInit->getAnyMember(),
3878 FieldInit->getBaseClass());
3884 /// Enter a new C++ default initializer scope. After calling this, the
3885 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3886 /// parsing or instantiating the initializer failed.
3887 void Sema::ActOnStartCXXInClassMemberInitializer() {
3888 // Create a synthetic function scope to represent the call to the constructor
3889 // that notionally surrounds a use of this initializer.
3890 PushFunctionScope();
3893 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3894 if (!D.isFunctionDeclarator())
3896 auto &FTI = D.getFunctionTypeInfo();
3899 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3901 auto *ParamDecl = cast<NamedDecl>(Param.Param);
3902 if (ParamDecl->getDeclName())
3903 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3907 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3908 if (ConstraintExpr.isInvalid())
3910 return CorrectDelayedTyposInExpr(ConstraintExpr);
3913 /// This is invoked after parsing an in-class initializer for a
3914 /// non-static C++ class member, and after instantiating an in-class initializer
3915 /// in a class template. Such actions are deferred until the class is complete.
3916 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3917 SourceLocation InitLoc,
3919 // Pop the notional constructor scope we created earlier.
3920 PopFunctionScopeInfo(nullptr, D);
3922 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3923 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3924 "must set init style when field is created");
3927 D->setInvalidDecl();
3929 FD->removeInClassInitializer();
3933 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3934 FD->setInvalidDecl();
3935 FD->removeInClassInitializer();
3939 ExprResult Init = InitExpr;
3940 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3941 InitializedEntity Entity =
3942 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3943 InitializationKind Kind =
3944 FD->getInClassInitStyle() == ICIS_ListInit
3945 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3946 InitExpr->getBeginLoc(),
3947 InitExpr->getEndLoc())
3948 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3949 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3950 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3951 if (Init.isInvalid()) {
3952 FD->setInvalidDecl();
3957 // C++11 [class.base.init]p7:
3958 // The initialization of each base and member constitutes a
3960 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3961 if (Init.isInvalid()) {
3962 FD->setInvalidDecl();
3966 InitExpr = Init.get();
3968 FD->setInClassInitializer(InitExpr);
3971 /// Find the direct and/or virtual base specifiers that
3972 /// correspond to the given base type, for use in base initialization
3973 /// within a constructor.
3974 static bool FindBaseInitializer(Sema &SemaRef,
3975 CXXRecordDecl *ClassDecl,
3977 const CXXBaseSpecifier *&DirectBaseSpec,
3978 const CXXBaseSpecifier *&VirtualBaseSpec) {
3979 // First, check for a direct base class.
3980 DirectBaseSpec = nullptr;
3981 for (const auto &Base : ClassDecl->bases()) {
3982 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3983 // We found a direct base of this type. That's what we're
3985 DirectBaseSpec = &Base;
3990 // Check for a virtual base class.
3991 // FIXME: We might be able to short-circuit this if we know in advance that
3992 // there are no virtual bases.
3993 VirtualBaseSpec = nullptr;
3994 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3995 // We haven't found a base yet; search the class hierarchy for a
3996 // virtual base class.
3997 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3998 /*DetectVirtual=*/false);
3999 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4000 SemaRef.Context.getTypeDeclType(ClassDecl),
4002 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4003 Path != Paths.end(); ++Path) {
4004 if (Path->back().Base->isVirtual()) {
4005 VirtualBaseSpec = Path->back().Base;
4012 return DirectBaseSpec || VirtualBaseSpec;
4015 /// Handle a C++ member initializer using braced-init-list syntax.
4017 Sema::ActOnMemInitializer(Decl *ConstructorD,
4020 IdentifierInfo *MemberOrBase,
4021 ParsedType TemplateTypeTy,
4023 SourceLocation IdLoc,
4025 SourceLocation EllipsisLoc) {
4026 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4027 DS, IdLoc, InitList,
4031 /// Handle a C++ member initializer using parentheses syntax.
4033 Sema::ActOnMemInitializer(Decl *ConstructorD,
4036 IdentifierInfo *MemberOrBase,
4037 ParsedType TemplateTypeTy,
4039 SourceLocation IdLoc,
4040 SourceLocation LParenLoc,
4041 ArrayRef<Expr *> Args,
4042 SourceLocation RParenLoc,
4043 SourceLocation EllipsisLoc) {
4044 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4045 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4046 DS, IdLoc, List, EllipsisLoc);
4051 // Callback to only accept typo corrections that can be a valid C++ member
4052 // intializer: either a non-static field member or a base class.
4053 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4055 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4056 : ClassDecl(ClassDecl) {}
4058 bool ValidateCandidate(const TypoCorrection &candidate) override {
4059 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4060 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4061 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4062 return isa<TypeDecl>(ND);
4067 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4068 return std::make_unique<MemInitializerValidatorCCC>(*this);
4072 CXXRecordDecl *ClassDecl;
4077 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4079 ParsedType TemplateTypeTy,
4080 IdentifierInfo *MemberOrBase) {
4081 if (SS.getScopeRep() || TemplateTypeTy)
4083 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
4087 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
4088 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
4093 /// Handle a C++ member initializer.
4095 Sema::BuildMemInitializer(Decl *ConstructorD,
4098 IdentifierInfo *MemberOrBase,
4099 ParsedType TemplateTypeTy,
4101 SourceLocation IdLoc,
4103 SourceLocation EllipsisLoc) {
4104 ExprResult Res = CorrectDelayedTyposInExpr(Init);
4105 if (!Res.isUsable())
4112 AdjustDeclIfTemplate(ConstructorD);
4114 CXXConstructorDecl *Constructor
4115 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4117 // The user wrote a constructor initializer on a function that is
4118 // not a C++ constructor. Ignore the error for now, because we may
4119 // have more member initializers coming; we'll diagnose it just
4120 // once in ActOnMemInitializers.
4124 CXXRecordDecl *ClassDecl = Constructor->getParent();
4126 // C++ [class.base.init]p2:
4127 // Names in a mem-initializer-id are looked up in the scope of the
4128 // constructor's class and, if not found in that scope, are looked
4129 // up in the scope containing the constructor's definition.
4130 // [Note: if the constructor's class contains a member with the
4131 // same name as a direct or virtual base class of the class, a
4132 // mem-initializer-id naming the member or base class and composed
4133 // of a single identifier refers to the class member. A
4134 // mem-initializer-id for the hidden base class may be specified
4135 // using a qualified name. ]
4137 // Look for a member, first.
4138 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4139 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4140 if (EllipsisLoc.isValid())
4141 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4143 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4145 return BuildMemberInitializer(Member, Init, IdLoc);
4147 // It didn't name a member, so see if it names a class.
4149 TypeSourceInfo *TInfo = nullptr;
4151 if (TemplateTypeTy) {
4152 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4153 if (BaseType.isNull())
4155 } else if (DS.getTypeSpecType() == TST_decltype) {
4156 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4157 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4158 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4161 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4162 LookupParsedName(R, S, &SS);
4164 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4166 if (R.isAmbiguous()) return true;
4168 // We don't want access-control diagnostics here.
4169 R.suppressDiagnostics();
4171 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4172 bool NotUnknownSpecialization = false;
4173 DeclContext *DC = computeDeclContext(SS, false);
4174 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4175 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4177 if (!NotUnknownSpecialization) {
4178 // When the scope specifier can refer to a member of an unknown
4179 // specialization, we take it as a type name.
4180 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4181 SS.getWithLocInContext(Context),
4182 *MemberOrBase, IdLoc);
4183 if (BaseType.isNull())
4186 TInfo = Context.CreateTypeSourceInfo(BaseType);
4187 DependentNameTypeLoc TL =
4188 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4190 TL.setNameLoc(IdLoc);
4191 TL.setElaboratedKeywordLoc(SourceLocation());
4192 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4196 R.setLookupName(MemberOrBase);
4200 // If no results were found, try to correct typos.
4201 TypoCorrection Corr;
4202 MemInitializerValidatorCCC CCC(ClassDecl);
4203 if (R.empty() && BaseType.isNull() &&
4204 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4205 CCC, CTK_ErrorRecovery, ClassDecl))) {
4206 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4207 // We have found a non-static data member with a similar
4208 // name to what was typed; complain and initialize that
4211 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4212 << MemberOrBase << true);
4213 return BuildMemberInitializer(Member, Init, IdLoc);
4214 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4215 const CXXBaseSpecifier *DirectBaseSpec;
4216 const CXXBaseSpecifier *VirtualBaseSpec;
4217 if (FindBaseInitializer(*this, ClassDecl,
4218 Context.getTypeDeclType(Type),
4219 DirectBaseSpec, VirtualBaseSpec)) {
4220 // We have found a direct or virtual base class with a
4221 // similar name to what was typed; complain and initialize
4224 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4225 << MemberOrBase << false,
4226 PDiag() /*Suppress note, we provide our own.*/);
4228 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4230 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4231 << BaseSpec->getType() << BaseSpec->getSourceRange();
4238 if (!TyD && BaseType.isNull()) {
4239 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4240 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4245 if (BaseType.isNull()) {
4246 BaseType = Context.getTypeDeclType(TyD);
4247 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4249 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4251 TInfo = Context.CreateTypeSourceInfo(BaseType);
4252 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4253 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4254 TL.setElaboratedKeywordLoc(SourceLocation());
4255 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4261 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4263 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4267 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4268 SourceLocation IdLoc) {
4269 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4270 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4271 assert((DirectMember || IndirectMember) &&
4272 "Member must be a FieldDecl or IndirectFieldDecl");
4274 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4277 if (Member->isInvalidDecl())
4281 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4282 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4283 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4284 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4286 // Template instantiation doesn't reconstruct ParenListExprs for us.
4290 SourceRange InitRange = Init->getSourceRange();
4292 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4293 // Can't check initialization for a member of dependent type or when
4294 // any of the arguments are type-dependent expressions.
4295 DiscardCleanupsInEvaluationContext();
4297 bool InitList = false;
4298 if (isa<InitListExpr>(Init)) {
4303 // Initialize the member.
4304 InitializedEntity MemberEntity =
4305 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4306 : InitializedEntity::InitializeMember(IndirectMember,
4308 InitializationKind Kind =
4309 InitList ? InitializationKind::CreateDirectList(
4310 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4311 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4312 InitRange.getEnd());
4314 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4315 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4317 if (MemberInit.isInvalid())
4320 // C++11 [class.base.init]p7:
4321 // The initialization of each base and member constitutes a
4323 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4324 /*DiscardedValue*/ false);
4325 if (MemberInit.isInvalid())
4328 Init = MemberInit.get();
4332 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4333 InitRange.getBegin(), Init,
4334 InitRange.getEnd());
4336 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4337 InitRange.getBegin(), Init,
4338 InitRange.getEnd());
4343 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4344 CXXRecordDecl *ClassDecl) {
4345 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4346 if (!LangOpts.CPlusPlus11)
4347 return Diag(NameLoc, diag::err_delegating_ctor)
4348 << TInfo->getTypeLoc().getLocalSourceRange();
4349 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4351 bool InitList = true;
4352 MultiExprArg Args = Init;
4353 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4355 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4358 SourceRange InitRange = Init->getSourceRange();
4359 // Initialize the object.
4360 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4361 QualType(ClassDecl->getTypeForDecl(), 0));
4362 InitializationKind Kind =
4363 InitList ? InitializationKind::CreateDirectList(
4364 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4365 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4366 InitRange.getEnd());
4367 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4368 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4370 if (DelegationInit.isInvalid())
4373 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4374 "Delegating constructor with no target?");
4376 // C++11 [class.base.init]p7:
4377 // The initialization of each base and member constitutes a
4379 DelegationInit = ActOnFinishFullExpr(
4380 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4381 if (DelegationInit.isInvalid())
4384 // If we are in a dependent context, template instantiation will
4385 // perform this type-checking again. Just save the arguments that we
4386 // received in a ParenListExpr.
4387 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4388 // of the information that we have about the base
4389 // initializer. However, deconstructing the ASTs is a dicey process,
4390 // and this approach is far more likely to get the corner cases right.
4391 if (CurContext->isDependentContext())
4392 DelegationInit = Init;
4394 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4395 DelegationInit.getAs<Expr>(),
4396 InitRange.getEnd());
4400 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4401 Expr *Init, CXXRecordDecl *ClassDecl,
4402 SourceLocation EllipsisLoc) {
4403 SourceLocation BaseLoc
4404 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4406 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4407 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4408 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4410 // C++ [class.base.init]p2:
4411 // [...] Unless the mem-initializer-id names a nonstatic data
4412 // member of the constructor's class or a direct or virtual base
4413 // of that class, the mem-initializer is ill-formed. A
4414 // mem-initializer-list can initialize a base class using any
4415 // name that denotes that base class type.
4416 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4418 SourceRange InitRange = Init->getSourceRange();
4419 if (EllipsisLoc.isValid()) {
4420 // This is a pack expansion.
4421 if (!BaseType->containsUnexpandedParameterPack()) {
4422 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4423 << SourceRange(BaseLoc, InitRange.getEnd());
4425 EllipsisLoc = SourceLocation();
4428 // Check for any unexpanded parameter packs.
4429 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4432 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4436 // Check for direct and virtual base classes.
4437 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4438 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4440 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4442 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4444 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4447 // C++ [base.class.init]p2:
4448 // Unless the mem-initializer-id names a nonstatic data member of the
4449 // constructor's class or a direct or virtual base of that class, the
4450 // mem-initializer is ill-formed.
4451 if (!DirectBaseSpec && !VirtualBaseSpec) {
4452 // If the class has any dependent bases, then it's possible that
4453 // one of those types will resolve to the same type as
4454 // BaseType. Therefore, just treat this as a dependent base
4455 // class initialization. FIXME: Should we try to check the
4456 // initialization anyway? It seems odd.
4457 if (ClassDecl->hasAnyDependentBases())
4460 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4461 << BaseType << Context.getTypeDeclType(ClassDecl)
4462 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4467 DiscardCleanupsInEvaluationContext();
4469 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4470 /*IsVirtual=*/false,
4471 InitRange.getBegin(), Init,
4472 InitRange.getEnd(), EllipsisLoc);
4475 // C++ [base.class.init]p2:
4476 // If a mem-initializer-id is ambiguous because it designates both
4477 // a direct non-virtual base class and an inherited virtual base
4478 // class, the mem-initializer is ill-formed.
4479 if (DirectBaseSpec && VirtualBaseSpec)
4480 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4481 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4483 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4485 BaseSpec = VirtualBaseSpec;
4487 // Initialize the base.
4488 bool InitList = true;
4489 MultiExprArg Args = Init;
4490 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4492 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4495 InitializedEntity BaseEntity =
4496 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4497 InitializationKind Kind =
4498 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4499 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4500 InitRange.getEnd());
4501 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4502 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4503 if (BaseInit.isInvalid())
4506 // C++11 [class.base.init]p7:
4507 // The initialization of each base and member constitutes a
4509 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4510 /*DiscardedValue*/ false);
4511 if (BaseInit.isInvalid())
4514 // If we are in a dependent context, template instantiation will
4515 // perform this type-checking again. Just save the arguments that we
4516 // received in a ParenListExpr.
4517 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4518 // of the information that we have about the base
4519 // initializer. However, deconstructing the ASTs is a dicey process,
4520 // and this approach is far more likely to get the corner cases right.
4521 if (CurContext->isDependentContext())
4524 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4525 BaseSpec->isVirtual(),
4526 InitRange.getBegin(),
4527 BaseInit.getAs<Expr>(),
4528 InitRange.getEnd(), EllipsisLoc);
4531 // Create a static_cast\<T&&>(expr).
4532 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4533 if (T.isNull()) T = E->getType();
4534 QualType TargetType = SemaRef.BuildReferenceType(
4535 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4536 SourceLocation ExprLoc = E->getBeginLoc();
4537 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4538 TargetType, ExprLoc);
4540 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4541 SourceRange(ExprLoc, ExprLoc),
4542 E->getSourceRange()).get();
4545 /// ImplicitInitializerKind - How an implicit base or member initializer should
4546 /// initialize its base or member.
4547 enum ImplicitInitializerKind {
4555 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4556 ImplicitInitializerKind ImplicitInitKind,
4557 CXXBaseSpecifier *BaseSpec,
4558 bool IsInheritedVirtualBase,
4559 CXXCtorInitializer *&CXXBaseInit) {
4560 InitializedEntity InitEntity
4561 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4562 IsInheritedVirtualBase);
4564 ExprResult BaseInit;
4566 switch (ImplicitInitKind) {
4569 InitializationKind InitKind
4570 = InitializationKind::CreateDefault(Constructor->getLocation());
4571 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4572 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4578 bool Moving = ImplicitInitKind == IIK_Move;
4579 ParmVarDecl *Param = Constructor->getParamDecl(0);
4580 QualType ParamType = Param->getType().getNonReferenceType();
4583 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4584 SourceLocation(), Param, false,
4585 Constructor->getLocation(), ParamType,
4586 VK_LValue, nullptr);
4588 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4590 // Cast to the base class to avoid ambiguities.
4592 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4593 ParamType.getQualifiers());
4596 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4599 CXXCastPath BasePath;
4600 BasePath.push_back(BaseSpec);
4601 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4602 CK_UncheckedDerivedToBase,
4603 Moving ? VK_XValue : VK_LValue,
4606 InitializationKind InitKind
4607 = InitializationKind::CreateDirect(Constructor->getLocation(),
4608 SourceLocation(), SourceLocation());
4609 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4610 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4615 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4616 if (BaseInit.isInvalid())
4620 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4621 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4623 BaseSpec->isVirtual(),
4625 BaseInit.getAs<Expr>(),
4632 static bool RefersToRValueRef(Expr *MemRef) {
4633 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4634 return Referenced->getType()->isRValueReferenceType();
4638 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4639 ImplicitInitializerKind ImplicitInitKind,
4640 FieldDecl *Field, IndirectFieldDecl *Indirect,
4641 CXXCtorInitializer *&CXXMemberInit) {
4642 if (Field->isInvalidDecl())
4645 SourceLocation Loc = Constructor->getLocation();
4647 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4648 bool Moving = ImplicitInitKind == IIK_Move;
4649 ParmVarDecl *Param = Constructor->getParamDecl(0);
4650 QualType ParamType = Param->getType().getNonReferenceType();
4652 // Suppress copying zero-width bitfields.
4653 if (Field->isZeroLengthBitField(SemaRef.Context))
4656 Expr *MemberExprBase =
4657 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4658 SourceLocation(), Param, false,
4659 Loc, ParamType, VK_LValue, nullptr);
4661 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4664 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4667 // Build a reference to this field within the parameter.
4669 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4670 Sema::LookupMemberName);
4671 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4672 : cast<ValueDecl>(Field), AS_public);
4673 MemberLookup.resolveKind();
4675 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4679 /*TemplateKWLoc=*/SourceLocation(),
4680 /*FirstQualifierInScope=*/nullptr,
4682 /*TemplateArgs=*/nullptr,
4684 if (CtorArg.isInvalid())
4687 // C++11 [class.copy]p15:
4688 // - if a member m has rvalue reference type T&&, it is direct-initialized
4689 // with static_cast<T&&>(x.m);
4690 if (RefersToRValueRef(CtorArg.get())) {
4691 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4694 InitializedEntity Entity =
4695 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4697 : InitializedEntity::InitializeMember(Field, nullptr,
4700 // Direct-initialize to use the copy constructor.
4701 InitializationKind InitKind =
4702 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4704 Expr *CtorArgE = CtorArg.getAs<Expr>();
4705 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4706 ExprResult MemberInit =
4707 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4708 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4709 if (MemberInit.isInvalid())
4713 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4714 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4716 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4717 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4721 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4722 "Unhandled implicit init kind!");
4724 QualType FieldBaseElementType =
4725 SemaRef.Context.getBaseElementType(Field->getType());
4727 if (FieldBaseElementType->isRecordType()) {
4728 InitializedEntity InitEntity =
4729 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4731 : InitializedEntity::InitializeMember(Field, nullptr,
4733 InitializationKind InitKind =
4734 InitializationKind::CreateDefault(Loc);
4736 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4737 ExprResult MemberInit =
4738 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4740 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4741 if (MemberInit.isInvalid())
4745 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4751 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4758 if (!Field->getParent()->isUnion()) {
4759 if (FieldBaseElementType->isReferenceType()) {
4760 SemaRef.Diag(Constructor->getLocation(),
4761 diag::err_uninitialized_member_in_ctor)
4762 << (int)Constructor->isImplicit()
4763 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4764 << 0 << Field->getDeclName();
4765 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4769 if (FieldBaseElementType.isConstQualified()) {
4770 SemaRef.Diag(Constructor->getLocation(),
4771 diag::err_uninitialized_member_in_ctor)
4772 << (int)Constructor->isImplicit()
4773 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4774 << 1 << Field->getDeclName();
4775 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4780 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4782 // Default-initialize Objective-C pointers to NULL.
4784 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4786 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4791 // Nothing to initialize.
4792 CXXMemberInit = nullptr;
4797 struct BaseAndFieldInfo {
4799 CXXConstructorDecl *Ctor;
4800 bool AnyErrorsInInits;
4801 ImplicitInitializerKind IIK;
4802 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4803 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4804 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4806 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4807 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4808 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4809 if (Ctor->getInheritedConstructor())
4811 else if (Generated && Ctor->isCopyConstructor())
4813 else if (Generated && Ctor->isMoveConstructor())
4819 bool isImplicitCopyOrMove() const {
4830 llvm_unreachable("Invalid ImplicitInitializerKind!");
4833 bool addFieldInitializer(CXXCtorInitializer *Init) {
4834 AllToInit.push_back(Init);
4836 // Check whether this initializer makes the field "used".
4837 if (Init->getInit()->HasSideEffects(S.Context))
4838 S.UnusedPrivateFields.remove(Init->getAnyMember());
4843 bool isInactiveUnionMember(FieldDecl *Field) {
4844 RecordDecl *Record = Field->getParent();
4845 if (!Record->isUnion())
4848 if (FieldDecl *Active =
4849 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4850 return Active != Field->getCanonicalDecl();
4852 // In an implicit copy or move constructor, ignore any in-class initializer.
4853 if (isImplicitCopyOrMove())
4856 // If there's no explicit initialization, the field is active only if it
4857 // has an in-class initializer...
4858 if (Field->hasInClassInitializer())
4860 // ... or it's an anonymous struct or union whose class has an in-class
4862 if (!Field->isAnonymousStructOrUnion())
4864 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4865 return !FieldRD->hasInClassInitializer();
4868 /// Determine whether the given field is, or is within, a union member
4869 /// that is inactive (because there was an initializer given for a different
4870 /// member of the union, or because the union was not initialized at all).
4871 bool isWithinInactiveUnionMember(FieldDecl *Field,
4872 IndirectFieldDecl *Indirect) {
4874 return isInactiveUnionMember(Field);
4876 for (auto *C : Indirect->chain()) {
4877 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4878 if (Field && isInactiveUnionMember(Field))
4886 /// Determine whether the given type is an incomplete or zero-lenfgth
4888 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4889 if (T->isIncompleteArrayType())
4892 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4893 if (!ArrayT->getSize())
4896 T = ArrayT->getElementType();
4902 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4904 IndirectFieldDecl *Indirect = nullptr) {
4905 if (Field->isInvalidDecl())
4908 // Overwhelmingly common case: we have a direct initializer for this field.
4909 if (CXXCtorInitializer *Init =
4910 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4911 return Info.addFieldInitializer(Init);
4913 // C++11 [class.base.init]p8:
4914 // if the entity is a non-static data member that has a
4915 // brace-or-equal-initializer and either
4916 // -- the constructor's class is a union and no other variant member of that
4917 // union is designated by a mem-initializer-id or
4918 // -- the constructor's class is not a union, and, if the entity is a member
4919 // of an anonymous union, no other member of that union is designated by
4920 // a mem-initializer-id,
4921 // the entity is initialized as specified in [dcl.init].
4923 // We also apply the same rules to handle anonymous structs within anonymous
4925 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4928 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4930 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4931 if (DIE.isInvalid())
4934 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4935 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4937 CXXCtorInitializer *Init;
4939 Init = new (SemaRef.Context)
4940 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4941 SourceLocation(), DIE.get(), SourceLocation());
4943 Init = new (SemaRef.Context)
4944 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4945 SourceLocation(), DIE.get(), SourceLocation());
4946 return Info.addFieldInitializer(Init);
4949 // Don't initialize incomplete or zero-length arrays.
4950 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4953 // Don't try to build an implicit initializer if there were semantic
4954 // errors in any of the initializers (and therefore we might be
4955 // missing some that the user actually wrote).
4956 if (Info.AnyErrorsInInits)
4959 CXXCtorInitializer *Init = nullptr;
4960 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4967 return Info.addFieldInitializer(Init);
4971 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4972 CXXCtorInitializer *Initializer) {
4973 assert(Initializer->isDelegatingInitializer());
4974 Constructor->setNumCtorInitializers(1);
4975 CXXCtorInitializer **initializer =
4976 new (Context) CXXCtorInitializer*[1];
4977 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4978 Constructor->setCtorInitializers(initializer);
4980 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4981 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4982 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4985 DelegatingCtorDecls.push_back(Constructor);
4987 DiagnoseUninitializedFields(*this, Constructor);
4992 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4993 ArrayRef<CXXCtorInitializer *> Initializers) {
4994 if (Constructor->isDependentContext()) {
4995 // Just store the initializers as written, they will be checked during
4997 if (!Initializers.empty()) {
4998 Constructor->setNumCtorInitializers(Initializers.size());
4999 CXXCtorInitializer **baseOrMemberInitializers =
5000 new (Context) CXXCtorInitializer*[Initializers.size()];
5001 memcpy(baseOrMemberInitializers, Initializers.data(),
5002 Initializers.size() * sizeof(CXXCtorInitializer*));
5003 Constructor->setCtorInitializers(baseOrMemberInitializers);
5006 // Let template instantiation know whether we had errors.
5008 Constructor->setInvalidDecl();
5013 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5015 // We need to build the initializer AST according to order of construction
5016 // and not what user specified in the Initializers list.
5017 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5021 bool HadError = false;
5023 for (unsigned i = 0; i < Initializers.size(); i++) {
5024 CXXCtorInitializer *Member = Initializers[i];
5026 if (Member->isBaseInitializer())
5027 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5029 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5031 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5032 for (auto *C : F->chain()) {
5033 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5034 if (FD && FD->getParent()->isUnion())
5035 Info.ActiveUnionMember.insert(std::make_pair(
5036 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5038 } else if (FieldDecl *FD = Member->getMember()) {
5039 if (FD->getParent()->isUnion())
5040 Info.ActiveUnionMember.insert(std::make_pair(
5041 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5046 // Keep track of the direct virtual bases.
5047 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5048 for (auto &I : ClassDecl->bases()) {
5050 DirectVBases.insert(&I);
5053 // Push virtual bases before others.
5054 for (auto &VBase : ClassDecl->vbases()) {
5055 if (CXXCtorInitializer *Value
5056 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5057 // [class.base.init]p7, per DR257:
5058 // A mem-initializer where the mem-initializer-id names a virtual base
5059 // class is ignored during execution of a constructor of any class that
5060 // is not the most derived class.
5061 if (ClassDecl->isAbstract()) {
5062 // FIXME: Provide a fixit to remove the base specifier. This requires
5063 // tracking the location of the associated comma for a base specifier.
5064 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5065 << VBase.getType() << ClassDecl;
5066 DiagnoseAbstractType(ClassDecl);
5069 Info.AllToInit.push_back(Value);
5070 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5071 // [class.base.init]p8, per DR257:
5072 // If a given [...] base class is not named by a mem-initializer-id
5073 // [...] and the entity is not a virtual base class of an abstract
5074 // class, then [...] the entity is default-initialized.
5075 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5076 CXXCtorInitializer *CXXBaseInit;
5077 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5078 &VBase, IsInheritedVirtualBase,
5084 Info.AllToInit.push_back(CXXBaseInit);
5088 // Non-virtual bases.
5089 for (auto &Base : ClassDecl->bases()) {
5090 // Virtuals are in the virtual base list and already constructed.
5091 if (Base.isVirtual())
5094 if (CXXCtorInitializer *Value
5095 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5096 Info.AllToInit.push_back(Value);
5097 } else if (!AnyErrors) {
5098 CXXCtorInitializer *CXXBaseInit;
5099 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5100 &Base, /*IsInheritedVirtualBase=*/false,
5106 Info.AllToInit.push_back(CXXBaseInit);
5111 for (auto *Mem : ClassDecl->decls()) {
5112 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5113 // C++ [class.bit]p2:
5114 // A declaration for a bit-field that omits the identifier declares an
5115 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5117 if (F->isUnnamedBitfield())
5120 // If we're not generating the implicit copy/move constructor, then we'll
5121 // handle anonymous struct/union fields based on their individual
5123 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5126 if (CollectFieldInitializer(*this, Info, F))
5131 // Beyond this point, we only consider default initialization.
5132 if (Info.isImplicitCopyOrMove())
5135 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5136 if (F->getType()->isIncompleteArrayType()) {
5137 assert(ClassDecl->hasFlexibleArrayMember() &&
5138 "Incomplete array type is not valid");
5142 // Initialize each field of an anonymous struct individually.
5143 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5150 unsigned NumInitializers = Info.AllToInit.size();
5151 if (NumInitializers > 0) {
5152 Constructor->setNumCtorInitializers(NumInitializers);
5153 CXXCtorInitializer **baseOrMemberInitializers =
5154 new (Context) CXXCtorInitializer*[NumInitializers];
5155 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5156 NumInitializers * sizeof(CXXCtorInitializer*));
5157 Constructor->setCtorInitializers(baseOrMemberInitializers);
5159 // Constructors implicitly reference the base and member
5161 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5162 Constructor->getParent());
5168 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5169 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5170 const RecordDecl *RD = RT->getDecl();
5171 if (RD->isAnonymousStructOrUnion()) {
5172 for (auto *Field : RD->fields())
5173 PopulateKeysForFields(Field, IdealInits);
5177 IdealInits.push_back(Field->getCanonicalDecl());
5180 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5181 return Context.getCanonicalType(BaseType).getTypePtr();
5184 static const void *GetKeyForMember(ASTContext &Context,
5185 CXXCtorInitializer *Member) {
5186 if (!Member->isAnyMemberInitializer())
5187 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5189 return Member->getAnyMember()->getCanonicalDecl();
5192 static void DiagnoseBaseOrMemInitializerOrder(
5193 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5194 ArrayRef<CXXCtorInitializer *> Inits) {
5195 if (Constructor->getDeclContext()->isDependentContext())
5198 // Don't check initializers order unless the warning is enabled at the
5199 // location of at least one initializer.
5200 bool ShouldCheckOrder = false;
5201 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5202 CXXCtorInitializer *Init = Inits[InitIndex];
5203 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5204 Init->getSourceLocation())) {
5205 ShouldCheckOrder = true;
5209 if (!ShouldCheckOrder)
5212 // Build the list of bases and members in the order that they'll
5213 // actually be initialized. The explicit initializers should be in
5214 // this same order but may be missing things.
5215 SmallVector<const void*, 32> IdealInitKeys;
5217 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5219 // 1. Virtual bases.
5220 for (const auto &VBase : ClassDecl->vbases())
5221 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5223 // 2. Non-virtual bases.
5224 for (const auto &Base : ClassDecl->bases()) {
5225 if (Base.isVirtual())
5227 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5230 // 3. Direct fields.
5231 for (auto *Field : ClassDecl->fields()) {
5232 if (Field->isUnnamedBitfield())
5235 PopulateKeysForFields(Field, IdealInitKeys);
5238 unsigned NumIdealInits = IdealInitKeys.size();
5239 unsigned IdealIndex = 0;
5241 CXXCtorInitializer *PrevInit = nullptr;
5242 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5243 CXXCtorInitializer *Init = Inits[InitIndex];
5244 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5246 // Scan forward to try to find this initializer in the idealized
5247 // initializers list.
5248 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5249 if (InitKey == IdealInitKeys[IdealIndex])
5252 // If we didn't find this initializer, it must be because we
5253 // scanned past it on a previous iteration. That can only
5254 // happen if we're out of order; emit a warning.
5255 if (IdealIndex == NumIdealInits && PrevInit) {
5256 Sema::SemaDiagnosticBuilder D =
5257 SemaRef.Diag(PrevInit->getSourceLocation(),
5258 diag::warn_initializer_out_of_order);
5260 if (PrevInit->isAnyMemberInitializer())
5261 D << 0 << PrevInit->getAnyMember()->getDeclName();
5263 D << 1 << PrevInit->getTypeSourceInfo()->getType();
5265 if (Init->isAnyMemberInitializer())
5266 D << 0 << Init->getAnyMember()->getDeclName();
5268 D << 1 << Init->getTypeSourceInfo()->getType();
5270 // Move back to the initializer's location in the ideal list.
5271 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5272 if (InitKey == IdealInitKeys[IdealIndex])
5275 assert(IdealIndex < NumIdealInits &&
5276 "initializer not found in initializer list");
5284 bool CheckRedundantInit(Sema &S,
5285 CXXCtorInitializer *Init,
5286 CXXCtorInitializer *&PrevInit) {
5292 if (FieldDecl *Field = Init->getAnyMember())
5293 S.Diag(Init->getSourceLocation(),
5294 diag::err_multiple_mem_initialization)
5295 << Field->getDeclName()
5296 << Init->getSourceRange();
5298 const Type *BaseClass = Init->getBaseClass();
5299 assert(BaseClass && "neither field nor base");
5300 S.Diag(Init->getSourceLocation(),
5301 diag::err_multiple_base_initialization)
5302 << QualType(BaseClass, 0)
5303 << Init->getSourceRange();
5305 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5306 << 0 << PrevInit->getSourceRange();
5311 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5312 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5314 bool CheckRedundantUnionInit(Sema &S,
5315 CXXCtorInitializer *Init,
5316 RedundantUnionMap &Unions) {
5317 FieldDecl *Field = Init->getAnyMember();
5318 RecordDecl *Parent = Field->getParent();
5319 NamedDecl *Child = Field;
5321 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5322 if (Parent->isUnion()) {
5323 UnionEntry &En = Unions[Parent];
5324 if (En.first && En.first != Child) {
5325 S.Diag(Init->getSourceLocation(),
5326 diag::err_multiple_mem_union_initialization)
5327 << Field->getDeclName()
5328 << Init->getSourceRange();
5329 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5330 << 0 << En.second->getSourceRange();
5337 if (!Parent->isAnonymousStructOrUnion())
5342 Parent = cast<RecordDecl>(Parent->getDeclContext());
5349 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5350 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5351 SourceLocation ColonLoc,
5352 ArrayRef<CXXCtorInitializer*> MemInits,
5354 if (!ConstructorDecl)
5357 AdjustDeclIfTemplate(ConstructorDecl);
5359 CXXConstructorDecl *Constructor
5360 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5363 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5367 // Mapping for the duplicate initializers check.
5368 // For member initializers, this is keyed with a FieldDecl*.
5369 // For base initializers, this is keyed with a Type*.
5370 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5372 // Mapping for the inconsistent anonymous-union initializers check.
5373 RedundantUnionMap MemberUnions;
5375 bool HadError = false;
5376 for (unsigned i = 0; i < MemInits.size(); i++) {
5377 CXXCtorInitializer *Init = MemInits[i];
5379 // Set the source order index.
5380 Init->setSourceOrder(i);
5382 if (Init->isAnyMemberInitializer()) {
5383 const void *Key = GetKeyForMember(Context, Init);
5384 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5385 CheckRedundantUnionInit(*this, Init, MemberUnions))
5387 } else if (Init->isBaseInitializer()) {
5388 const void *Key = GetKeyForMember(Context, Init);
5389 if (CheckRedundantInit(*this, Init, Members[Key]))
5392 assert(Init->isDelegatingInitializer());
5393 // This must be the only initializer
5394 if (MemInits.size() != 1) {
5395 Diag(Init->getSourceLocation(),
5396 diag::err_delegating_initializer_alone)
5397 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5398 // We will treat this as being the only initializer.
5400 SetDelegatingInitializer(Constructor, MemInits[i]);
5401 // Return immediately as the initializer is set.
5409 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5411 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5413 DiagnoseUninitializedFields(*this, Constructor);
5417 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5418 CXXRecordDecl *ClassDecl) {
5419 // Ignore dependent contexts. Also ignore unions, since their members never
5420 // have destructors implicitly called.
5421 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5424 // FIXME: all the access-control diagnostics are positioned on the
5425 // field/base declaration. That's probably good; that said, the
5426 // user might reasonably want to know why the destructor is being
5427 // emitted, and we currently don't say.
5429 // Non-static data members.
5430 for (auto *Field : ClassDecl->fields()) {
5431 if (Field->isInvalidDecl())
5434 // Don't destroy incomplete or zero-length arrays.
5435 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5438 QualType FieldType = Context.getBaseElementType(Field->getType());
5440 const RecordType* RT = FieldType->getAs<RecordType>();
5444 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5445 if (FieldClassDecl->isInvalidDecl())
5447 if (FieldClassDecl->hasIrrelevantDestructor())
5449 // The destructor for an implicit anonymous union member is never invoked.
5450 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5453 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5454 assert(Dtor && "No dtor found for FieldClassDecl!");
5455 CheckDestructorAccess(Field->getLocation(), Dtor,
5456 PDiag(diag::err_access_dtor_field)
5457 << Field->getDeclName()
5460 MarkFunctionReferenced(Location, Dtor);
5461 DiagnoseUseOfDecl(Dtor, Location);
5464 // We only potentially invoke the destructors of potentially constructed
5466 bool VisitVirtualBases = !ClassDecl->isAbstract();
5468 // If the destructor exists and has already been marked used in the MS ABI,
5469 // then virtual base destructors have already been checked and marked used.
5470 // Skip checking them again to avoid duplicate diagnostics.
5471 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5472 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5473 if (Dtor && Dtor->isUsed())
5474 VisitVirtualBases = false;
5477 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5480 for (const auto &Base : ClassDecl->bases()) {
5481 // Bases are always records in a well-formed non-dependent class.
5482 const RecordType *RT = Base.getType()->getAs<RecordType>();
5484 // Remember direct virtual bases.
5485 if (Base.isVirtual()) {
5486 if (!VisitVirtualBases)
5488 DirectVirtualBases.insert(RT);
5491 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5492 // If our base class is invalid, we probably can't get its dtor anyway.
5493 if (BaseClassDecl->isInvalidDecl())
5495 if (BaseClassDecl->hasIrrelevantDestructor())
5498 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5499 assert(Dtor && "No dtor found for BaseClassDecl!");
5501 // FIXME: caret should be on the start of the class name
5502 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5503 PDiag(diag::err_access_dtor_base)
5504 << Base.getType() << Base.getSourceRange(),
5505 Context.getTypeDeclType(ClassDecl));
5507 MarkFunctionReferenced(Location, Dtor);
5508 DiagnoseUseOfDecl(Dtor, Location);
5511 if (VisitVirtualBases)
5512 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5513 &DirectVirtualBases);
5516 void Sema::MarkVirtualBaseDestructorsReferenced(
5517 SourceLocation Location, CXXRecordDecl *ClassDecl,
5518 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5520 for (const auto &VBase : ClassDecl->vbases()) {
5521 // Bases are always records in a well-formed non-dependent class.
5522 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5524 // Ignore already visited direct virtual bases.
5525 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5528 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5529 // If our base class is invalid, we probably can't get its dtor anyway.
5530 if (BaseClassDecl->isInvalidDecl())
5532 if (BaseClassDecl->hasIrrelevantDestructor())
5535 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5536 assert(Dtor && "No dtor found for BaseClassDecl!");
5537 if (CheckDestructorAccess(
5538 ClassDecl->getLocation(), Dtor,
5539 PDiag(diag::err_access_dtor_vbase)
5540 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5541 Context.getTypeDeclType(ClassDecl)) ==
5543 CheckDerivedToBaseConversion(
5544 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5545 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5546 SourceRange(), DeclarationName(), nullptr);
5549 MarkFunctionReferenced(Location, Dtor);
5550 DiagnoseUseOfDecl(Dtor, Location);
5554 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5558 if (CXXConstructorDecl *Constructor
5559 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5560 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5561 DiagnoseUninitializedFields(*this, Constructor);
5565 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5566 if (!getLangOpts().CPlusPlus)
5569 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5573 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5574 // class template specialization here, but doing so breaks a lot of code.
5576 // We can't answer whether something is abstract until it has a
5577 // definition. If it's currently being defined, we'll walk back
5578 // over all the declarations when we have a full definition.
5579 const CXXRecordDecl *Def = RD->getDefinition();
5580 if (!Def || Def->isBeingDefined())
5583 return RD->isAbstract();
5586 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5587 TypeDiagnoser &Diagnoser) {
5588 if (!isAbstractType(Loc, T))
5591 T = Context.getBaseElementType(T);
5592 Diagnoser.diagnose(*this, Loc, T);
5593 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5597 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5598 // Check if we've already emitted the list of pure virtual functions
5600 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5603 // If the diagnostic is suppressed, don't emit the notes. We're only
5604 // going to emit them once, so try to attach them to a diagnostic we're
5605 // actually going to show.
5606 if (Diags.isLastDiagnosticIgnored())
5609 CXXFinalOverriderMap FinalOverriders;
5610 RD->getFinalOverriders(FinalOverriders);
5612 // Keep a set of seen pure methods so we won't diagnose the same method
5614 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5616 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5617 MEnd = FinalOverriders.end();
5620 for (OverridingMethods::iterator SO = M->second.begin(),
5621 SOEnd = M->second.end();
5622 SO != SOEnd; ++SO) {
5623 // C++ [class.abstract]p4:
5624 // A class is abstract if it contains or inherits at least one
5625 // pure virtual function for which the final overrider is pure
5629 if (SO->second.size() != 1)
5632 if (!SO->second.front().Method->isPure())
5635 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5638 Diag(SO->second.front().Method->getLocation(),
5639 diag::note_pure_virtual_function)
5640 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5644 if (!PureVirtualClassDiagSet)
5645 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5646 PureVirtualClassDiagSet->insert(RD);
5650 struct AbstractUsageInfo {
5652 CXXRecordDecl *Record;
5653 CanQualType AbstractType;
5656 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5657 : S(S), Record(Record),
5658 AbstractType(S.Context.getCanonicalType(
5659 S.Context.getTypeDeclType(Record))),
5662 void DiagnoseAbstractType() {
5663 if (Invalid) return;
5664 S.DiagnoseAbstractType(Record);
5668 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5671 struct CheckAbstractUsage {
5672 AbstractUsageInfo &Info;
5673 const NamedDecl *Ctx;
5675 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5676 : Info(Info), Ctx(Ctx) {}
5678 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5679 switch (TL.getTypeLocClass()) {
5680 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5681 #define TYPELOC(CLASS, PARENT) \
5682 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5683 #include "clang/AST/TypeLocNodes.def"
5687 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5688 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5689 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5690 if (!TL.getParam(I))
5693 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5694 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5698 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5699 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5702 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5703 // Visit the type parameters from a permissive context.
5704 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5705 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5706 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5707 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5708 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5709 // TODO: other template argument types?
5713 // Visit pointee types from a permissive context.
5714 #define CheckPolymorphic(Type) \
5715 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5716 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5718 CheckPolymorphic(PointerTypeLoc)
5719 CheckPolymorphic(ReferenceTypeLoc)
5720 CheckPolymorphic(MemberPointerTypeLoc)
5721 CheckPolymorphic(BlockPointerTypeLoc)
5722 CheckPolymorphic(AtomicTypeLoc)
5724 /// Handle all the types we haven't given a more specific
5725 /// implementation for above.
5726 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5727 // Every other kind of type that we haven't called out already
5728 // that has an inner type is either (1) sugar or (2) contains that
5729 // inner type in some way as a subobject.
5730 if (TypeLoc Next = TL.getNextTypeLoc())
5731 return Visit(Next, Sel);
5733 // If there's no inner type and we're in a permissive context,
5735 if (Sel == Sema::AbstractNone) return;
5737 // Check whether the type matches the abstract type.
5738 QualType T = TL.getType();
5739 if (T->isArrayType()) {
5740 Sel = Sema::AbstractArrayType;
5741 T = Info.S.Context.getBaseElementType(T);
5743 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5744 if (CT != Info.AbstractType) return;
5746 // It matched; do some magic.
5747 if (Sel == Sema::AbstractArrayType) {
5748 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5749 << T << TL.getSourceRange();
5751 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5752 << Sel << T << TL.getSourceRange();
5754 Info.DiagnoseAbstractType();
5758 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5759 Sema::AbstractDiagSelID Sel) {
5760 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5765 /// Check for invalid uses of an abstract type in a method declaration.
5766 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5767 CXXMethodDecl *MD) {
5768 // No need to do the check on definitions, which require that
5769 // the return/param types be complete.
5770 if (MD->doesThisDeclarationHaveABody())
5773 // For safety's sake, just ignore it if we don't have type source
5774 // information. This should never happen for non-implicit methods,
5776 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5777 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5780 /// Check for invalid uses of an abstract type within a class definition.
5781 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5782 CXXRecordDecl *RD) {
5783 for (auto *D : RD->decls()) {
5784 if (D->isImplicit()) continue;
5786 // Methods and method templates.
5787 if (isa<CXXMethodDecl>(D)) {
5788 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5789 } else if (isa<FunctionTemplateDecl>(D)) {
5790 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5791 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5793 // Fields and static variables.
5794 } else if (isa<FieldDecl>(D)) {
5795 FieldDecl *FD = cast<FieldDecl>(D);
5796 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5797 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5798 } else if (isa<VarDecl>(D)) {
5799 VarDecl *VD = cast<VarDecl>(D);
5800 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5801 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5803 // Nested classes and class templates.
5804 } else if (isa<CXXRecordDecl>(D)) {
5805 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5806 } else if (isa<ClassTemplateDecl>(D)) {
5807 CheckAbstractClassUsage(Info,
5808 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5813 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5814 Attr *ClassAttr = getDLLAttr(Class);
5818 assert(ClassAttr->getKind() == attr::DLLExport);
5820 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5822 if (TSK == TSK_ExplicitInstantiationDeclaration)
5823 // Don't go any further if this is just an explicit instantiation
5827 // Add a context note to explain how we got to any diagnostics produced below.
5828 struct MarkingClassDllexported {
5830 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5831 SourceLocation AttrLoc)
5833 Sema::CodeSynthesisContext Ctx;
5834 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5835 Ctx.PointOfInstantiation = AttrLoc;
5837 S.pushCodeSynthesisContext(Ctx);
5839 ~MarkingClassDllexported() {
5840 S.popCodeSynthesisContext();
5842 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5844 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5845 S.MarkVTableUsed(Class->getLocation(), Class, true);
5847 for (Decl *Member : Class->decls()) {
5848 // Defined static variables that are members of an exported base
5849 // class must be marked export too.
5850 auto *VD = dyn_cast<VarDecl>(Member);
5851 if (VD && Member->getAttr<DLLExportAttr>() &&
5852 VD->getStorageClass() == SC_Static &&
5853 TSK == TSK_ImplicitInstantiation)
5854 S.MarkVariableReferenced(VD->getLocation(), VD);
5856 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5860 if (Member->getAttr<DLLExportAttr>()) {
5861 if (MD->isUserProvided()) {
5862 // Instantiate non-default class member functions ...
5864 // .. except for certain kinds of template specializations.
5865 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5868 S.MarkFunctionReferenced(Class->getLocation(), MD);
5870 // The function will be passed to the consumer when its definition is
5872 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5873 MD->isCopyAssignmentOperator() ||
5874 MD->isMoveAssignmentOperator()) {
5875 // Synthesize and instantiate non-trivial implicit methods, explicitly
5876 // defaulted methods, and the copy and move assignment operators. The
5877 // latter are exported even if they are trivial, because the address of
5878 // an operator can be taken and should compare equal across libraries.
5879 S.MarkFunctionReferenced(Class->getLocation(), MD);
5881 // There is no later point when we will see the definition of this
5882 // function, so pass it to the consumer now.
5883 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5889 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5890 CXXRecordDecl *Class) {
5891 // Only the MS ABI has default constructor closures, so we don't need to do
5892 // this semantic checking anywhere else.
5893 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5896 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5897 for (Decl *Member : Class->decls()) {
5898 // Look for exported default constructors.
5899 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5900 if (!CD || !CD->isDefaultConstructor())
5902 auto *Attr = CD->getAttr<DLLExportAttr>();
5906 // If the class is non-dependent, mark the default arguments as ODR-used so
5907 // that we can properly codegen the constructor closure.
5908 if (!Class->isDependentContext()) {
5909 for (ParmVarDecl *PD : CD->parameters()) {
5910 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5911 S.DiscardCleanupsInEvaluationContext();
5915 if (LastExportedDefaultCtor) {
5916 S.Diag(LastExportedDefaultCtor->getLocation(),
5917 diag::err_attribute_dll_ambiguous_default_ctor)
5919 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5920 << CD->getDeclName();
5923 LastExportedDefaultCtor = CD;
5927 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
5928 CXXRecordDecl *Class) {
5929 bool ErrorReported = false;
5930 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5931 ClassTemplateDecl *TD) {
5934 S.Diag(TD->getLocation(),
5935 diag::err_cuda_device_builtin_surftex_cls_template)
5936 << /*surface*/ 0 << TD;
5937 ErrorReported = true;
5940 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5942 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5944 S.Diag(Class->getLocation(),
5945 diag::err_cuda_device_builtin_surftex_ref_decl)
5946 << /*surface*/ 0 << Class;
5947 S.Diag(Class->getLocation(),
5948 diag::note_cuda_device_builtin_surftex_should_be_template_class)
5952 TD = SD->getSpecializedTemplate();
5955 TemplateParameterList *Params = TD->getTemplateParameters();
5956 unsigned N = Params->size();
5959 reportIllegalClassTemplate(S, TD);
5960 S.Diag(TD->getLocation(),
5961 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
5964 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
5965 reportIllegalClassTemplate(S, TD);
5966 S.Diag(TD->getLocation(),
5967 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5968 << TD << /*1st*/ 0 << /*type*/ 0;
5971 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
5972 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
5973 reportIllegalClassTemplate(S, TD);
5974 S.Diag(TD->getLocation(),
5975 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
5976 << TD << /*2nd*/ 1 << /*integer*/ 1;
5981 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
5982 CXXRecordDecl *Class) {
5983 bool ErrorReported = false;
5984 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
5985 ClassTemplateDecl *TD) {
5988 S.Diag(TD->getLocation(),
5989 diag::err_cuda_device_builtin_surftex_cls_template)
5990 << /*texture*/ 1 << TD;
5991 ErrorReported = true;
5994 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
5996 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
5998 S.Diag(Class->getLocation(),
5999 diag::err_cuda_device_builtin_surftex_ref_decl)
6000 << /*texture*/ 1 << Class;
6001 S.Diag(Class->getLocation(),
6002 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6006 TD = SD->getSpecializedTemplate();
6009 TemplateParameterList *Params = TD->getTemplateParameters();
6010 unsigned N = Params->size();
6013 reportIllegalClassTemplate(S, TD);
6014 S.Diag(TD->getLocation(),
6015 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6018 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6019 reportIllegalClassTemplate(S, TD);
6020 S.Diag(TD->getLocation(),
6021 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6022 << TD << /*1st*/ 0 << /*type*/ 0;
6025 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6026 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6027 reportIllegalClassTemplate(S, TD);
6028 S.Diag(TD->getLocation(),
6029 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6030 << TD << /*2nd*/ 1 << /*integer*/ 1;
6034 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6035 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6036 reportIllegalClassTemplate(S, TD);
6037 S.Diag(TD->getLocation(),
6038 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6039 << TD << /*3rd*/ 2 << /*integer*/ 1;
6044 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6045 // Mark any compiler-generated routines with the implicit code_seg attribute.
6046 for (auto *Method : Class->methods()) {
6047 if (Method->isUserProvided())
6049 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6054 /// Check class-level dllimport/dllexport attribute.
6055 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6056 Attr *ClassAttr = getDLLAttr(Class);
6058 // MSVC inherits DLL attributes to partial class template specializations.
6059 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
6060 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6061 if (Attr *TemplateAttr =
6062 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6063 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6064 A->setInherited(true);
6073 if (!Class->isExternallyVisible()) {
6074 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6075 << Class << ClassAttr;
6079 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6080 !ClassAttr->isInherited()) {
6081 // Diagnose dll attributes on members of class with dll attribute.
6082 for (Decl *Member : Class->decls()) {
6083 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6085 InheritableAttr *MemberAttr = getDLLAttr(Member);
6086 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6089 Diag(MemberAttr->getLocation(),
6090 diag::err_attribute_dll_member_of_dll_class)
6091 << MemberAttr << ClassAttr;
6092 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6093 Member->setInvalidDecl();
6097 if (Class->getDescribedClassTemplate())
6098 // Don't inherit dll attribute until the template is instantiated.
6101 // The class is either imported or exported.
6102 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6104 // Check if this was a dllimport attribute propagated from a derived class to
6105 // a base class template specialization. We don't apply these attributes to
6106 // static data members.
6107 const bool PropagatedImport =
6109 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6111 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6113 // Ignore explicit dllexport on explicit class template instantiation
6114 // declarations, except in MinGW mode.
6115 if (ClassExported && !ClassAttr->isInherited() &&
6116 TSK == TSK_ExplicitInstantiationDeclaration &&
6117 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6118 Class->dropAttr<DLLExportAttr>();
6122 // Force declaration of implicit members so they can inherit the attribute.
6123 ForceDeclarationOfImplicitMembers(Class);
6125 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6126 // seem to be true in practice?
6128 for (Decl *Member : Class->decls()) {
6129 VarDecl *VD = dyn_cast<VarDecl>(Member);
6130 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6132 // Only methods and static fields inherit the attributes.
6137 // Don't process deleted methods.
6138 if (MD->isDeleted())
6141 if (MD->isInlined()) {
6142 // MinGW does not import or export inline methods. But do it for
6143 // template instantiations.
6144 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6145 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
6146 TSK != TSK_ExplicitInstantiationDeclaration &&
6147 TSK != TSK_ExplicitInstantiationDefinition)
6150 // MSVC versions before 2015 don't export the move assignment operators
6151 // and move constructor, so don't attempt to import/export them if
6152 // we have a definition.
6153 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6154 if ((MD->isMoveAssignmentOperator() ||
6155 (Ctor && Ctor->isMoveConstructor())) &&
6156 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6159 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6160 // operator is exported anyway.
6161 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6162 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6167 // Don't apply dllimport attributes to static data members of class template
6168 // instantiations when the attribute is propagated from a derived class.
6169 if (VD && PropagatedImport)
6172 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6175 if (!getDLLAttr(Member)) {
6176 InheritableAttr *NewAttr = nullptr;
6178 // Do not export/import inline function when -fno-dllexport-inlines is
6179 // passed. But add attribute for later local static var check.
6180 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6181 TSK != TSK_ExplicitInstantiationDeclaration &&
6182 TSK != TSK_ExplicitInstantiationDefinition) {
6183 if (ClassExported) {
6184 NewAttr = ::new (getASTContext())
6185 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6187 NewAttr = ::new (getASTContext())
6188 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6191 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6194 NewAttr->setInherited(true);
6195 Member->addAttr(NewAttr);
6198 // Propagate DLLAttr to friend re-declarations of MD that have already
6199 // been constructed.
6200 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6201 FD = FD->getPreviousDecl()) {
6202 if (FD->getFriendObjectKind() == Decl::FOK_None)
6204 assert(!getDLLAttr(FD) &&
6205 "friend re-decl should not already have a DLLAttr");
6206 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6207 NewAttr->setInherited(true);
6208 FD->addAttr(NewAttr);
6215 DelayedDllExportClasses.push_back(Class);
6218 /// Perform propagation of DLL attributes from a derived class to a
6219 /// templated base class for MS compatibility.
6220 void Sema::propagateDLLAttrToBaseClassTemplate(
6221 CXXRecordDecl *Class, Attr *ClassAttr,
6222 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6224 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6225 // If the base class template has a DLL attribute, don't try to change it.
6229 auto TSK = BaseTemplateSpec->getSpecializationKind();
6230 if (!getDLLAttr(BaseTemplateSpec) &&
6231 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6232 TSK == TSK_ImplicitInstantiation)) {
6233 // The template hasn't been instantiated yet (or it has, but only as an
6234 // explicit instantiation declaration or implicit instantiation, which means
6235 // we haven't codegenned any members yet), so propagate the attribute.
6236 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6237 NewAttr->setInherited(true);
6238 BaseTemplateSpec->addAttr(NewAttr);
6240 // If this was an import, mark that we propagated it from a derived class to
6241 // a base class template specialization.
6242 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6243 ImportAttr->setPropagatedToBaseTemplate();
6245 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6246 // needs to be run again to work see the new attribute. Otherwise this will
6247 // get run whenever the template is instantiated.
6248 if (TSK != TSK_Undeclared)
6249 checkClassLevelDLLAttribute(BaseTemplateSpec);
6254 if (getDLLAttr(BaseTemplateSpec)) {
6255 // The template has already been specialized or instantiated with an
6256 // attribute, explicitly or through propagation. We should not try to change
6261 // The template was previously instantiated or explicitly specialized without
6262 // a dll attribute, It's too late for us to add an attribute, so warn that
6263 // this is unsupported.
6264 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6265 << BaseTemplateSpec->isExplicitSpecialization();
6266 Diag(ClassAttr->getLocation(), diag::note_attribute);
6267 if (BaseTemplateSpec->isExplicitSpecialization()) {
6268 Diag(BaseTemplateSpec->getLocation(),
6269 diag::note_template_class_explicit_specialization_was_here)
6270 << BaseTemplateSpec;
6272 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6273 diag::note_template_class_instantiation_was_here)
6274 << BaseTemplateSpec;
6278 /// Determine the kind of defaulting that would be done for a given function.
6280 /// If the function is both a default constructor and a copy / move constructor
6281 /// (due to having a default argument for the first parameter), this picks
6282 /// CXXDefaultConstructor.
6284 /// FIXME: Check that case is properly handled by all callers.
6285 Sema::DefaultedFunctionKind
6286 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6287 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6288 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6289 if (Ctor->isDefaultConstructor())
6290 return Sema::CXXDefaultConstructor;
6292 if (Ctor->isCopyConstructor())
6293 return Sema::CXXCopyConstructor;
6295 if (Ctor->isMoveConstructor())
6296 return Sema::CXXMoveConstructor;
6299 if (MD->isCopyAssignmentOperator())
6300 return Sema::CXXCopyAssignment;
6302 if (MD->isMoveAssignmentOperator())
6303 return Sema::CXXMoveAssignment;
6305 if (isa<CXXDestructorDecl>(FD))
6306 return Sema::CXXDestructor;
6309 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6311 return DefaultedComparisonKind::Equal;
6313 case OO_ExclaimEqual:
6314 return DefaultedComparisonKind::NotEqual;
6317 // No point allowing this if <=> doesn't exist in the current language mode.
6318 if (!getLangOpts().CPlusPlus20)
6320 return DefaultedComparisonKind::ThreeWay;
6325 case OO_GreaterEqual:
6326 // No point allowing this if <=> doesn't exist in the current language mode.
6327 if (!getLangOpts().CPlusPlus20)
6329 return DefaultedComparisonKind::Relational;
6336 return DefaultedFunctionKind();
6339 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6340 SourceLocation DefaultLoc) {
6341 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6342 if (DFK.isComparison())
6343 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6345 switch (DFK.asSpecialMember()) {
6346 case Sema::CXXDefaultConstructor:
6347 S.DefineImplicitDefaultConstructor(DefaultLoc,
6348 cast<CXXConstructorDecl>(FD));
6350 case Sema::CXXCopyConstructor:
6351 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6353 case Sema::CXXCopyAssignment:
6354 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6356 case Sema::CXXDestructor:
6357 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6359 case Sema::CXXMoveConstructor:
6360 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6362 case Sema::CXXMoveAssignment:
6363 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6365 case Sema::CXXInvalid:
6366 llvm_unreachable("Invalid special member.");
6370 /// Determine whether a type is permitted to be passed or returned in
6371 /// registers, per C++ [class.temporary]p3.
6372 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6373 TargetInfo::CallingConvKind CCK) {
6374 if (D->isDependentType() || D->isInvalidDecl())
6377 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6378 // The PS4 platform ABI follows the behavior of Clang 3.2.
6379 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6380 return !D->hasNonTrivialDestructorForCall() &&
6381 !D->hasNonTrivialCopyConstructorForCall();
6383 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6384 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6385 bool DtorIsTrivialForCall = false;
6387 // If a class has at least one non-deleted, trivial copy constructor, it
6388 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6390 // Note: This permits classes with non-trivial copy or move ctors to be
6391 // passed in registers, so long as they *also* have a trivial copy ctor,
6392 // which is non-conforming.
6393 if (D->needsImplicitCopyConstructor()) {
6394 if (!D->defaultedCopyConstructorIsDeleted()) {
6395 if (D->hasTrivialCopyConstructor())
6396 CopyCtorIsTrivial = true;
6397 if (D->hasTrivialCopyConstructorForCall())
6398 CopyCtorIsTrivialForCall = true;
6401 for (const CXXConstructorDecl *CD : D->ctors()) {
6402 if (CD->isCopyConstructor() && !CD->isDeleted()) {
6403 if (CD->isTrivial())
6404 CopyCtorIsTrivial = true;
6405 if (CD->isTrivialForCall())
6406 CopyCtorIsTrivialForCall = true;
6411 if (D->needsImplicitDestructor()) {
6412 if (!D->defaultedDestructorIsDeleted() &&
6413 D->hasTrivialDestructorForCall())
6414 DtorIsTrivialForCall = true;
6415 } else if (const auto *DD = D->getDestructor()) {
6416 if (!DD->isDeleted() && DD->isTrivialForCall())
6417 DtorIsTrivialForCall = true;
6420 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6421 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6424 // If a class has a destructor, we'd really like to pass it indirectly
6425 // because it allows us to elide copies. Unfortunately, MSVC makes that
6426 // impossible for small types, which it will pass in a single register or
6427 // stack slot. Most objects with dtors are large-ish, so handle that early.
6428 // We can't call out all large objects as being indirect because there are
6429 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6430 // how we pass large POD types.
6432 // Note: This permits small classes with nontrivial destructors to be
6433 // passed in registers, which is non-conforming.
6434 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6435 uint64_t TypeSize = isAArch64 ? 128 : 64;
6437 if (CopyCtorIsTrivial &&
6438 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6443 // Per C++ [class.temporary]p3, the relevant condition is:
6444 // each copy constructor, move constructor, and destructor of X is
6445 // either trivial or deleted, and X has at least one non-deleted copy
6446 // or move constructor
6447 bool HasNonDeletedCopyOrMove = false;
6449 if (D->needsImplicitCopyConstructor() &&
6450 !D->defaultedCopyConstructorIsDeleted()) {
6451 if (!D->hasTrivialCopyConstructorForCall())
6453 HasNonDeletedCopyOrMove = true;
6456 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6457 !D->defaultedMoveConstructorIsDeleted()) {
6458 if (!D->hasTrivialMoveConstructorForCall())
6460 HasNonDeletedCopyOrMove = true;
6463 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6464 !D->hasTrivialDestructorForCall())
6467 for (const CXXMethodDecl *MD : D->methods()) {
6468 if (MD->isDeleted())
6471 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6472 if (CD && CD->isCopyOrMoveConstructor())
6473 HasNonDeletedCopyOrMove = true;
6474 else if (!isa<CXXDestructorDecl>(MD))
6477 if (!MD->isTrivialForCall())
6481 return HasNonDeletedCopyOrMove;
6484 /// Report an error regarding overriding, along with any relevant
6485 /// overridden methods.
6487 /// \param DiagID the primary error to report.
6488 /// \param MD the overriding method.
6490 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6491 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6492 bool IssuedDiagnostic = false;
6493 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6495 if (!IssuedDiagnostic) {
6496 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6497 IssuedDiagnostic = true;
6499 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6502 return IssuedDiagnostic;
6505 /// Perform semantic checks on a class definition that has been
6506 /// completing, introducing implicitly-declared members, checking for
6507 /// abstract types, etc.
6509 /// \param S The scope in which the class was parsed. Null if we didn't just
6510 /// parse a class definition.
6511 /// \param Record The completed class.
6512 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6516 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6517 AbstractUsageInfo Info(*this, Record);
6518 CheckAbstractClassUsage(Info, Record);
6521 // If this is not an aggregate type and has no user-declared constructor,
6522 // complain about any non-static data members of reference or const scalar
6523 // type, since they will never get initializers.
6524 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6525 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6526 !Record->isLambda()) {
6527 bool Complained = false;
6528 for (const auto *F : Record->fields()) {
6529 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6532 if (F->getType()->isReferenceType() ||
6533 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6535 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6536 << Record->getTagKind() << Record;
6540 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6541 << F->getType()->isReferenceType()
6542 << F->getDeclName();
6547 if (Record->getIdentifier()) {
6548 // C++ [class.mem]p13:
6549 // If T is the name of a class, then each of the following shall have a
6550 // name different from T:
6551 // - every member of every anonymous union that is a member of class T.
6553 // C++ [class.mem]p14:
6554 // In addition, if class T has a user-declared constructor (12.1), every
6555 // non-static data member of class T shall have a name different from T.
6556 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6557 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6559 NamedDecl *D = (*I)->getUnderlyingDecl();
6560 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6561 Record->hasUserDeclaredConstructor()) ||
6562 isa<IndirectFieldDecl>(D)) {
6563 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6564 << D->getDeclName();
6570 // Warn if the class has virtual methods but non-virtual public destructor.
6571 if (Record->isPolymorphic() && !Record->isDependentType()) {
6572 CXXDestructorDecl *dtor = Record->getDestructor();
6573 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6574 !Record->hasAttr<FinalAttr>())
6575 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6576 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6579 if (Record->isAbstract()) {
6580 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6581 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6582 << FA->isSpelledAsSealed();
6583 DiagnoseAbstractType(Record);
6587 // Warn if the class has a final destructor but is not itself marked final.
6588 if (!Record->hasAttr<FinalAttr>()) {
6589 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6590 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6591 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6592 << FA->isSpelledAsSealed()
6593 << FixItHint::CreateInsertion(
6594 getLocForEndOfToken(Record->getLocation()),
6595 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6596 Diag(Record->getLocation(),
6597 diag::note_final_dtor_non_final_class_silence)
6598 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6603 // See if trivial_abi has to be dropped.
6604 if (Record->hasAttr<TrivialABIAttr>())
6605 checkIllFormedTrivialABIStruct(*Record);
6607 // Set HasTrivialSpecialMemberForCall if the record has attribute
6609 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6612 Record->setHasTrivialSpecialMemberForCall();
6614 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6615 // We check these last because they can depend on the properties of the
6616 // primary comparison functions (==, <=>).
6617 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6619 // Perform checks that can't be done until we know all the properties of a
6620 // member function (whether it's defaulted, deleted, virtual, overriding,
6622 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6623 // A static function cannot override anything.
6624 if (MD->getStorageClass() == SC_Static) {
6625 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6626 [](const CXXMethodDecl *) { return true; }))
6630 // A deleted function cannot override a non-deleted function and vice
6632 if (ReportOverrides(*this,
6633 MD->isDeleted() ? diag::err_deleted_override
6634 : diag::err_non_deleted_override,
6635 MD, [&](const CXXMethodDecl *V) {
6636 return MD->isDeleted() != V->isDeleted();
6638 if (MD->isDefaulted() && MD->isDeleted())
6639 // Explain why this defaulted function was deleted.
6640 DiagnoseDeletedDefaultedFunction(MD);
6644 // A consteval function cannot override a non-consteval function and vice
6646 if (ReportOverrides(*this,
6647 MD->isConsteval() ? diag::err_consteval_override
6648 : diag::err_non_consteval_override,
6649 MD, [&](const CXXMethodDecl *V) {
6650 return MD->isConsteval() != V->isConsteval();
6652 if (MD->isDefaulted() && MD->isDeleted())
6653 // Explain why this defaulted function was deleted.
6654 DiagnoseDeletedDefaultedFunction(MD);
6659 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6660 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6663 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6664 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6665 DFK.asComparison() == DefaultedComparisonKind::Relational) {
6666 DefaultedSecondaryComparisons.push_back(FD);
6670 CheckExplicitlyDefaultedFunction(S, FD);
6674 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6675 // Check whether the explicitly-defaulted members are valid.
6676 bool Incomplete = CheckForDefaultedFunction(M);
6678 // Skip the rest of the checks for a member of a dependent class.
6679 if (Record->isDependentType())
6682 // For an explicitly defaulted or deleted special member, we defer
6683 // determining triviality until the class is complete. That time is now!
6684 CXXSpecialMember CSM = getSpecialMember(M);
6685 if (!M->isImplicit() && !M->isUserProvided()) {
6686 if (CSM != CXXInvalid) {
6687 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6688 // Inform the class that we've finished declaring this member.
6689 Record->finishedDefaultedOrDeletedMember(M);
6690 M->setTrivialForCall(
6692 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6693 Record->setTrivialForCallFlags(M);
6697 // Set triviality for the purpose of calls if this is a user-provided
6698 // copy/move constructor or destructor.
6699 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6700 CSM == CXXDestructor) && M->isUserProvided()) {
6701 M->setTrivialForCall(HasTrivialABI);
6702 Record->setTrivialForCallFlags(M);
6705 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6706 M->hasAttr<DLLExportAttr>()) {
6707 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6709 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6710 CSM == CXXDestructor))
6711 M->dropAttr<DLLExportAttr>();
6713 if (M->hasAttr<DLLExportAttr>()) {
6714 // Define after any fields with in-class initializers have been parsed.
6715 DelayedDllExportMemberFunctions.push_back(M);
6719 // Define defaulted constexpr virtual functions that override a base class
6720 // function right away.
6721 // FIXME: We can defer doing this until the vtable is marked as used.
6722 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6723 DefineDefaultedFunction(*this, M, M->getLocation());
6726 CheckCompletedMemberFunction(M);
6729 // Check the destructor before any other member function. We need to
6730 // determine whether it's trivial in order to determine whether the claas
6731 // type is a literal type, which is a prerequisite for determining whether
6732 // other special member functions are valid and whether they're implicitly
6734 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6735 CompleteMemberFunction(Dtor);
6737 bool HasMethodWithOverrideControl = false,
6738 HasOverridingMethodWithoutOverrideControl = false;
6739 for (auto *D : Record->decls()) {
6740 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6741 // FIXME: We could do this check for dependent types with non-dependent
6743 if (!Record->isDependentType()) {
6744 // See if a method overloads virtual methods in a base
6745 // class without overriding any.
6747 DiagnoseHiddenVirtualMethods(M);
6748 if (M->hasAttr<OverrideAttr>())
6749 HasMethodWithOverrideControl = true;
6750 else if (M->size_overridden_methods() > 0)
6751 HasOverridingMethodWithoutOverrideControl = true;
6754 if (!isa<CXXDestructorDecl>(M))
6755 CompleteMemberFunction(M);
6756 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6757 CheckForDefaultedFunction(
6758 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6762 if (HasOverridingMethodWithoutOverrideControl) {
6763 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6764 for (auto *M : Record->methods())
6765 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6768 // Check the defaulted secondary comparisons after any other member functions.
6769 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6770 CheckExplicitlyDefaultedFunction(S, FD);
6772 // If this is a member function, we deferred checking it until now.
6773 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6774 CheckCompletedMemberFunction(MD);
6777 // ms_struct is a request to use the same ABI rules as MSVC. Check
6778 // whether this class uses any C++ features that are implemented
6779 // completely differently in MSVC, and if so, emit a diagnostic.
6780 // That diagnostic defaults to an error, but we allow projects to
6781 // map it down to a warning (or ignore it). It's a fairly common
6782 // practice among users of the ms_struct pragma to mass-annotate
6783 // headers, sweeping up a bunch of types that the project doesn't
6784 // really rely on MSVC-compatible layout for. We must therefore
6785 // support "ms_struct except for C++ stuff" as a secondary ABI.
6786 // Don't emit this diagnostic if the feature was enabled as a
6787 // language option (as opposed to via a pragma or attribute), as
6788 // the option -mms-bitfields otherwise essentially makes it impossible
6789 // to build C++ code, unless this diagnostic is turned off.
6790 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6791 (Record->isPolymorphic() || Record->getNumBases())) {
6792 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6795 checkClassLevelDLLAttribute(Record);
6796 checkClassLevelCodeSegAttribute(Record);
6798 bool ClangABICompat4 =
6799 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6800 TargetInfo::CallingConvKind CCK =
6801 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6802 bool CanPass = canPassInRegisters(*this, Record, CCK);
6804 // Do not change ArgPassingRestrictions if it has already been set to
6805 // APK_CanNeverPassInRegs.
6806 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6807 Record->setArgPassingRestrictions(CanPass
6808 ? RecordDecl::APK_CanPassInRegs
6809 : RecordDecl::APK_CannotPassInRegs);
6811 // If canPassInRegisters returns true despite the record having a non-trivial
6812 // destructor, the record is destructed in the callee. This happens only when
6813 // the record or one of its subobjects has a field annotated with trivial_abi
6814 // or a field qualified with ObjC __strong/__weak.
6815 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6816 Record->setParamDestroyedInCallee(true);
6817 else if (Record->hasNonTrivialDestructor())
6818 Record->setParamDestroyedInCallee(CanPass);
6820 if (getLangOpts().ForceEmitVTables) {
6821 // If we want to emit all the vtables, we need to mark it as used. This
6822 // is especially required for cases like vtable assumption loads.
6823 MarkVTableUsed(Record->getInnerLocStart(), Record);
6826 if (getLangOpts().CUDA) {
6827 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6828 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6829 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6830 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6834 /// Look up the special member function that would be called by a special
6835 /// member function for a subobject of class type.
6837 /// \param Class The class type of the subobject.
6838 /// \param CSM The kind of special member function.
6839 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6840 /// \param ConstRHS True if this is a copy operation with a const object
6841 /// on its RHS, that is, if the argument to the outer special member
6842 /// function is 'const' and this is not a field marked 'mutable'.
6843 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6844 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6845 unsigned FieldQuals, bool ConstRHS) {
6846 unsigned LHSQuals = 0;
6847 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6848 LHSQuals = FieldQuals;
6850 unsigned RHSQuals = FieldQuals;
6851 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6854 RHSQuals |= Qualifiers::Const;
6856 return S.LookupSpecialMember(Class, CSM,
6857 RHSQuals & Qualifiers::Const,
6858 RHSQuals & Qualifiers::Volatile,
6860 LHSQuals & Qualifiers::Const,
6861 LHSQuals & Qualifiers::Volatile);
6864 class Sema::InheritedConstructorInfo {
6866 SourceLocation UseLoc;
6868 /// A mapping from the base classes through which the constructor was
6869 /// inherited to the using shadow declaration in that base class (or a null
6870 /// pointer if the constructor was declared in that base class).
6871 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6875 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6876 ConstructorUsingShadowDecl *Shadow)
6877 : S(S), UseLoc(UseLoc) {
6878 bool DiagnosedMultipleConstructedBases = false;
6879 CXXRecordDecl *ConstructedBase = nullptr;
6880 UsingDecl *ConstructedBaseUsing = nullptr;
6882 // Find the set of such base class subobjects and check that there's a
6883 // unique constructed subobject.
6884 for (auto *D : Shadow->redecls()) {
6885 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6886 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6887 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6889 InheritedFromBases.insert(
6890 std::make_pair(DNominatedBase->getCanonicalDecl(),
6891 DShadow->getNominatedBaseClassShadowDecl()));
6892 if (DShadow->constructsVirtualBase())
6893 InheritedFromBases.insert(
6894 std::make_pair(DConstructedBase->getCanonicalDecl(),
6895 DShadow->getConstructedBaseClassShadowDecl()));
6897 assert(DNominatedBase == DConstructedBase);
6899 // [class.inhctor.init]p2:
6900 // If the constructor was inherited from multiple base class subobjects
6901 // of type B, the program is ill-formed.
6902 if (!ConstructedBase) {
6903 ConstructedBase = DConstructedBase;
6904 ConstructedBaseUsing = D->getUsingDecl();
6905 } else if (ConstructedBase != DConstructedBase &&
6906 !Shadow->isInvalidDecl()) {
6907 if (!DiagnosedMultipleConstructedBases) {
6908 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6909 << Shadow->getTargetDecl();
6910 S.Diag(ConstructedBaseUsing->getLocation(),
6911 diag::note_ambiguous_inherited_constructor_using)
6913 DiagnosedMultipleConstructedBases = true;
6915 S.Diag(D->getUsingDecl()->getLocation(),
6916 diag::note_ambiguous_inherited_constructor_using)
6917 << DConstructedBase;
6921 if (DiagnosedMultipleConstructedBases)
6922 Shadow->setInvalidDecl();
6925 /// Find the constructor to use for inherited construction of a base class,
6926 /// and whether that base class constructor inherits the constructor from a
6927 /// virtual base class (in which case it won't actually invoke it).
6928 std::pair<CXXConstructorDecl *, bool>
6929 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6930 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6931 if (It == InheritedFromBases.end())
6932 return std::make_pair(nullptr, false);
6934 // This is an intermediary class.
6936 return std::make_pair(
6937 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6938 It->second->constructsVirtualBase());
6940 // This is the base class from which the constructor was inherited.
6941 return std::make_pair(Ctor, false);
6945 /// Is the special member function which would be selected to perform the
6946 /// specified operation on the specified class type a constexpr constructor?
6948 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6949 Sema::CXXSpecialMember CSM, unsigned Quals,
6951 CXXConstructorDecl *InheritedCtor = nullptr,
6952 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6953 // If we're inheriting a constructor, see if we need to call it for this base
6955 if (InheritedCtor) {
6956 assert(CSM == Sema::CXXDefaultConstructor);
6958 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6960 return BaseCtor->isConstexpr();
6963 if (CSM == Sema::CXXDefaultConstructor)
6964 return ClassDecl->hasConstexprDefaultConstructor();
6965 if (CSM == Sema::CXXDestructor)
6966 return ClassDecl->hasConstexprDestructor();
6968 Sema::SpecialMemberOverloadResult SMOR =
6969 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6970 if (!SMOR.getMethod())
6971 // A constructor we wouldn't select can't be "involved in initializing"
6974 return SMOR.getMethod()->isConstexpr();
6977 /// Determine whether the specified special member function would be constexpr
6978 /// if it were implicitly defined.
6979 static bool defaultedSpecialMemberIsConstexpr(
6980 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6981 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6982 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6983 if (!S.getLangOpts().CPlusPlus11)
6986 // C++11 [dcl.constexpr]p4:
6987 // In the definition of a constexpr constructor [...]
6990 case Sema::CXXDefaultConstructor:
6993 // Since default constructor lookup is essentially trivial (and cannot
6994 // involve, for instance, template instantiation), we compute whether a
6995 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6997 // This is important for performance; we need to know whether the default
6998 // constructor is constexpr to determine whether the type is a literal type.
6999 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7001 case Sema::CXXCopyConstructor:
7002 case Sema::CXXMoveConstructor:
7003 // For copy or move constructors, we need to perform overload resolution.
7006 case Sema::CXXCopyAssignment:
7007 case Sema::CXXMoveAssignment:
7008 if (!S.getLangOpts().CPlusPlus14)
7010 // In C++1y, we need to perform overload resolution.
7014 case Sema::CXXDestructor:
7015 return ClassDecl->defaultedDestructorIsConstexpr();
7017 case Sema::CXXInvalid:
7021 // -- if the class is a non-empty union, or for each non-empty anonymous
7022 // union member of a non-union class, exactly one non-static data member
7023 // shall be initialized; [DR1359]
7025 // If we squint, this is guaranteed, since exactly one non-static data member
7026 // will be initialized (if the constructor isn't deleted), we just don't know
7028 if (Ctor && ClassDecl->isUnion())
7029 return CSM == Sema::CXXDefaultConstructor
7030 ? ClassDecl->hasInClassInitializer() ||
7031 !ClassDecl->hasVariantMembers()
7034 // -- the class shall not have any virtual base classes;
7035 if (Ctor && ClassDecl->getNumVBases())
7038 // C++1y [class.copy]p26:
7039 // -- [the class] is a literal type, and
7040 if (!Ctor && !ClassDecl->isLiteral())
7043 // -- every constructor involved in initializing [...] base class
7044 // sub-objects shall be a constexpr constructor;
7045 // -- the assignment operator selected to copy/move each direct base
7046 // class is a constexpr function, and
7047 for (const auto &B : ClassDecl->bases()) {
7048 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7049 if (!BaseType) continue;
7051 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7052 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7053 InheritedCtor, Inherited))
7057 // -- every constructor involved in initializing non-static data members
7058 // [...] shall be a constexpr constructor;
7059 // -- every non-static data member and base class sub-object shall be
7061 // -- for each non-static data member of X that is of class type (or array
7062 // thereof), the assignment operator selected to copy/move that member is
7063 // a constexpr function
7064 for (const auto *F : ClassDecl->fields()) {
7065 if (F->isInvalidDecl())
7067 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7069 QualType BaseType = S.Context.getBaseElementType(F->getType());
7070 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7071 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7072 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7073 BaseType.getCVRQualifiers(),
7074 ConstArg && !F->isMutable()))
7076 } else if (CSM == Sema::CXXDefaultConstructor) {
7081 // All OK, it's constexpr!
7086 /// RAII object to register a defaulted function as having its exception
7087 /// specification computed.
7088 struct ComputingExceptionSpec {
7091 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7093 Sema::CodeSynthesisContext Ctx;
7094 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7095 Ctx.PointOfInstantiation = Loc;
7097 S.pushCodeSynthesisContext(Ctx);
7099 ~ComputingExceptionSpec() {
7100 S.popCodeSynthesisContext();
7105 static Sema::ImplicitExceptionSpecification
7106 ComputeDefaultedSpecialMemberExceptionSpec(
7107 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7108 Sema::InheritedConstructorInfo *ICI);
7110 static Sema::ImplicitExceptionSpecification
7111 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7113 Sema::DefaultedComparisonKind DCK);
7115 static Sema::ImplicitExceptionSpecification
7116 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7117 auto DFK = S.getDefaultedFunctionKind(FD);
7118 if (DFK.isSpecialMember())
7119 return ComputeDefaultedSpecialMemberExceptionSpec(
7120 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7121 if (DFK.isComparison())
7122 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7123 DFK.asComparison());
7125 auto *CD = cast<CXXConstructorDecl>(FD);
7126 assert(CD->getInheritedConstructor() &&
7127 "only defaulted functions and inherited constructors have implicit "
7129 Sema::InheritedConstructorInfo ICI(
7130 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7131 return ComputeDefaultedSpecialMemberExceptionSpec(
7132 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7135 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7136 CXXMethodDecl *MD) {
7137 FunctionProtoType::ExtProtoInfo EPI;
7139 // Build an exception specification pointing back at this member.
7140 EPI.ExceptionSpec.Type = EST_Unevaluated;
7141 EPI.ExceptionSpec.SourceDecl = MD;
7143 // Set the calling convention to the default for C++ instance methods.
7144 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7145 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7146 /*IsCXXMethod=*/true));
7150 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7151 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7152 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7155 // Evaluate the exception specification.
7156 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7157 auto ESI = IES.getExceptionSpec();
7159 // Update the type of the special member to use it.
7160 UpdateExceptionSpec(FD, ESI);
7163 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7164 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7166 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7168 assert(FD->getDeclContext()->isDependentContext());
7172 if (DefKind.isSpecialMember()
7173 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7174 DefKind.asSpecialMember())
7175 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7176 FD->setInvalidDecl();
7179 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7180 CXXSpecialMember CSM) {
7181 CXXRecordDecl *RD = MD->getParent();
7183 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
7184 "not an explicitly-defaulted special member");
7186 // Defer all checking for special members of a dependent type.
7187 if (RD->isDependentType())
7190 // Whether this was the first-declared instance of the constructor.
7191 // This affects whether we implicitly add an exception spec and constexpr.
7192 bool First = MD == MD->getCanonicalDecl();
7194 bool HadError = false;
7196 // C++11 [dcl.fct.def.default]p1:
7197 // A function that is explicitly defaulted shall
7198 // -- be a special member function [...] (checked elsewhere),
7199 // -- have the same type (except for ref-qualifiers, and except that a
7200 // copy operation can take a non-const reference) as an implicit
7202 // -- not have default arguments.
7203 // C++2a changes the second bullet to instead delete the function if it's
7204 // defaulted on its first declaration, unless it's "an assignment operator,
7205 // and its return type differs or its parameter type is not a reference".
7206 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7207 bool ShouldDeleteForTypeMismatch = false;
7208 unsigned ExpectedParams = 1;
7209 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7211 if (MD->getNumParams() != ExpectedParams) {
7212 // This checks for default arguments: a copy or move constructor with a
7213 // default argument is classified as a default constructor, and assignment
7214 // operations and destructors can't have default arguments.
7215 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7216 << CSM << MD->getSourceRange();
7218 } else if (MD->isVariadic()) {
7219 if (DeleteOnTypeMismatch)
7220 ShouldDeleteForTypeMismatch = true;
7222 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7223 << CSM << MD->getSourceRange();
7228 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7230 bool CanHaveConstParam = false;
7231 if (CSM == CXXCopyConstructor)
7232 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7233 else if (CSM == CXXCopyAssignment)
7234 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7236 QualType ReturnType = Context.VoidTy;
7237 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7238 // Check for return type matching.
7239 ReturnType = Type->getReturnType();
7241 QualType DeclType = Context.getTypeDeclType(RD);
7242 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7243 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7245 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7246 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7247 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7251 // A defaulted special member cannot have cv-qualifiers.
7252 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7253 if (DeleteOnTypeMismatch)
7254 ShouldDeleteForTypeMismatch = true;
7256 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7257 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7263 // Check for parameter type matching.
7264 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7265 bool HasConstParam = false;
7266 if (ExpectedParams && ArgType->isReferenceType()) {
7267 // Argument must be reference to possibly-const T.
7268 QualType ReferentType = ArgType->getPointeeType();
7269 HasConstParam = ReferentType.isConstQualified();
7271 if (ReferentType.isVolatileQualified()) {
7272 if (DeleteOnTypeMismatch)
7273 ShouldDeleteForTypeMismatch = true;
7275 Diag(MD->getLocation(),
7276 diag::err_defaulted_special_member_volatile_param) << CSM;
7281 if (HasConstParam && !CanHaveConstParam) {
7282 if (DeleteOnTypeMismatch)
7283 ShouldDeleteForTypeMismatch = true;
7284 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7285 Diag(MD->getLocation(),
7286 diag::err_defaulted_special_member_copy_const_param)
7287 << (CSM == CXXCopyAssignment);
7288 // FIXME: Explain why this special member can't be const.
7291 Diag(MD->getLocation(),
7292 diag::err_defaulted_special_member_move_const_param)
7293 << (CSM == CXXMoveAssignment);
7297 } else if (ExpectedParams) {
7298 // A copy assignment operator can take its argument by value, but a
7299 // defaulted one cannot.
7300 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
7301 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7305 // C++11 [dcl.fct.def.default]p2:
7306 // An explicitly-defaulted function may be declared constexpr only if it
7307 // would have been implicitly declared as constexpr,
7308 // Do not apply this rule to members of class templates, since core issue 1358
7309 // makes such functions always instantiate to constexpr functions. For
7310 // functions which cannot be constexpr (for non-constructors in C++11 and for
7311 // destructors in C++14 and C++17), this is checked elsewhere.
7313 // FIXME: This should not apply if the member is deleted.
7314 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7316 if ((getLangOpts().CPlusPlus20 ||
7317 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7318 : isa<CXXConstructorDecl>(MD))) &&
7319 MD->isConstexpr() && !Constexpr &&
7320 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7321 Diag(MD->getBeginLoc(), MD->isConsteval()
7322 ? diag::err_incorrect_defaulted_consteval
7323 : diag::err_incorrect_defaulted_constexpr)
7325 // FIXME: Explain why the special member can't be constexpr.
7330 // C++2a [dcl.fct.def.default]p3:
7331 // If a function is explicitly defaulted on its first declaration, it is
7332 // implicitly considered to be constexpr if the implicit declaration
7334 MD->setConstexprKind(
7335 Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr)
7338 if (!Type->hasExceptionSpec()) {
7339 // C++2a [except.spec]p3:
7340 // If a declaration of a function does not have a noexcept-specifier
7341 // [and] is defaulted on its first declaration, [...] the exception
7342 // specification is as specified below
7343 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7344 EPI.ExceptionSpec.Type = EST_Unevaluated;
7345 EPI.ExceptionSpec.SourceDecl = MD;
7346 MD->setType(Context.getFunctionType(ReturnType,
7347 llvm::makeArrayRef(&ArgType,
7353 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7355 SetDeclDeleted(MD, MD->getLocation());
7356 if (!inTemplateInstantiation() && !HadError) {
7357 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7358 if (ShouldDeleteForTypeMismatch) {
7359 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7361 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7364 if (ShouldDeleteForTypeMismatch && !HadError) {
7365 Diag(MD->getLocation(),
7366 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7369 // C++11 [dcl.fct.def.default]p4:
7370 // [For a] user-provided explicitly-defaulted function [...] if such a
7371 // function is implicitly defined as deleted, the program is ill-formed.
7372 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7373 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
7374 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7383 /// Helper class for building and checking a defaulted comparison.
7385 /// Defaulted functions are built in two phases:
7387 /// * First, the set of operations that the function will perform are
7388 /// identified, and some of them are checked. If any of the checked
7389 /// operations is invalid in certain ways, the comparison function is
7390 /// defined as deleted and no body is built.
7391 /// * Then, if the function is not defined as deleted, the body is built.
7393 /// This is accomplished by performing two visitation steps over the eventual
7394 /// body of the function.
7395 template<typename Derived, typename ResultList, typename Result,
7397 class DefaultedComparisonVisitor {
7399 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7401 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7402 DefaultedComparisonKind DCK)
7403 : S(S), RD(RD), FD(FD), DCK(DCK) {
7404 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7405 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7406 // UnresolvedSet to avoid this copy.
7407 Fns.assign(Info->getUnqualifiedLookups().begin(),
7408 Info->getUnqualifiedLookups().end());
7412 ResultList visit() {
7413 // The type of an lvalue naming a parameter of this function.
7414 QualType ParamLvalType =
7415 FD->getParamDecl(0)->getType().getNonReferenceType();
7420 case DefaultedComparisonKind::None:
7421 llvm_unreachable("not a defaulted comparison");
7423 case DefaultedComparisonKind::Equal:
7424 case DefaultedComparisonKind::ThreeWay:
7425 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7428 case DefaultedComparisonKind::NotEqual:
7429 case DefaultedComparisonKind::Relational:
7430 Results.add(getDerived().visitExpandedSubobject(
7431 ParamLvalType, getDerived().getCompleteObject()));
7434 llvm_unreachable("");
7438 Derived &getDerived() { return static_cast<Derived&>(*this); }
7440 /// Visit the expanded list of subobjects of the given type, as specified in
7441 /// C++2a [class.compare.default].
7443 /// \return \c true if the ResultList object said we're done, \c false if not.
7444 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7446 // C++2a [class.compare.default]p4:
7447 // The direct base class subobjects of C
7448 for (CXXBaseSpecifier &Base : Record->bases())
7449 if (Results.add(getDerived().visitSubobject(
7450 S.Context.getQualifiedType(Base.getType(), Quals),
7451 getDerived().getBase(&Base))))
7454 // followed by the non-static data members of C
7455 for (FieldDecl *Field : Record->fields()) {
7456 // Recursively expand anonymous structs.
7457 if (Field->isAnonymousStructOrUnion()) {
7458 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7464 // Figure out the type of an lvalue denoting this field.
7465 Qualifiers FieldQuals = Quals;
7466 if (Field->isMutable())
7467 FieldQuals.removeConst();
7468 QualType FieldType =
7469 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7471 if (Results.add(getDerived().visitSubobject(
7472 FieldType, getDerived().getField(Field))))
7476 // form a list of subobjects.
7480 Result visitSubobject(QualType Type, Subobject Subobj) {
7481 // In that list, any subobject of array type is recursively expanded
7482 const ArrayType *AT = S.Context.getAsArrayType(Type);
7483 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7484 return getDerived().visitSubobjectArray(CAT->getElementType(),
7485 CAT->getSize(), Subobj);
7486 return getDerived().visitExpandedSubobject(Type, Subobj);
7489 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7491 return getDerived().visitSubobject(Type, Subobj);
7498 DefaultedComparisonKind DCK;
7499 UnresolvedSet<16> Fns;
7502 /// Information about a defaulted comparison, as determined by
7503 /// DefaultedComparisonAnalyzer.
7504 struct DefaultedComparisonInfo {
7505 bool Deleted = false;
7506 bool Constexpr = true;
7507 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7509 static DefaultedComparisonInfo deleted() {
7510 DefaultedComparisonInfo Deleted;
7511 Deleted.Deleted = true;
7515 bool add(const DefaultedComparisonInfo &R) {
7516 Deleted |= R.Deleted;
7517 Constexpr &= R.Constexpr;
7518 Category = commonComparisonType(Category, R.Category);
7523 /// An element in the expanded list of subobjects of a defaulted comparison, as
7524 /// specified in C++2a [class.compare.default]p4.
7525 struct DefaultedComparisonSubobject {
7526 enum { CompleteObject, Member, Base } Kind;
7531 /// A visitor over the notional body of a defaulted comparison that determines
7532 /// whether that body would be deleted or constexpr.
7533 class DefaultedComparisonAnalyzer
7534 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7535 DefaultedComparisonInfo,
7536 DefaultedComparisonInfo,
7537 DefaultedComparisonSubobject> {
7539 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7542 DiagnosticKind Diagnose;
7545 using Base = DefaultedComparisonVisitor;
7546 using Result = DefaultedComparisonInfo;
7547 using Subobject = DefaultedComparisonSubobject;
7551 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7552 DefaultedComparisonKind DCK,
7553 DiagnosticKind Diagnose = NoDiagnostics)
7554 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7557 if ((DCK == DefaultedComparisonKind::Equal ||
7558 DCK == DefaultedComparisonKind::ThreeWay) &&
7559 RD->hasVariantMembers()) {
7560 // C++2a [class.compare.default]p2 [P2002R0]:
7561 // A defaulted comparison operator function for class C is defined as
7562 // deleted if [...] C has variant members.
7563 if (Diagnose == ExplainDeleted) {
7564 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7565 << FD << RD->isUnion() << RD;
7567 return Result::deleted();
7570 return Base::visit();
7574 Subobject getCompleteObject() {
7575 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()};
7578 Subobject getBase(CXXBaseSpecifier *Base) {
7579 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7580 Base->getBaseTypeLoc()};
7583 Subobject getField(FieldDecl *Field) {
7584 return Subobject{Subobject::Member, Field, Field->getLocation()};
7587 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7588 // C++2a [class.compare.default]p2 [P2002R0]:
7589 // A defaulted <=> or == operator function for class C is defined as
7590 // deleted if any non-static data member of C is of reference type
7591 if (Type->isReferenceType()) {
7592 if (Diagnose == ExplainDeleted) {
7593 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7596 return Result::deleted();
7599 // [...] Let xi be an lvalue denoting the ith element [...]
7600 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7601 Expr *Args[] = {&Xi, &Xi};
7603 // All operators start by trying to apply that same operator recursively.
7604 OverloadedOperatorKind OO = FD->getOverloadedOperator();
7605 assert(OO != OO_None && "not an overloaded operator!");
7606 return visitBinaryOperator(OO, Args, Subobj);
7610 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7612 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7613 // Note that there is no need to consider rewritten candidates here if
7614 // we've already found there is no viable 'operator<=>' candidate (and are
7615 // considering synthesizing a '<=>' from '==' and '<').
7616 OverloadCandidateSet CandidateSet(
7617 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7618 OverloadCandidateSet::OperatorRewriteInfo(
7619 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7621 /// C++2a [class.compare.default]p1 [P2002R0]:
7622 /// [...] the defaulted function itself is never a candidate for overload
7623 /// resolution [...]
7624 CandidateSet.exclude(FD);
7626 if (Args[0]->getType()->isOverloadableType())
7627 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7629 // FIXME: We determine whether this is a valid expression by checking to
7630 // see if there's a viable builtin operator candidate for it. That isn't
7631 // really what the rules ask us to do, but should give the right results.
7632 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7637 OverloadCandidateSet::iterator Best;
7638 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7640 // C++2a [class.compare.secondary]p2 [P2002R0]:
7641 // The operator function [...] is defined as deleted if [...] the
7642 // candidate selected by overload resolution is not a rewritten
7644 if ((DCK == DefaultedComparisonKind::NotEqual ||
7645 DCK == DefaultedComparisonKind::Relational) &&
7646 !Best->RewriteKind) {
7647 if (Diagnose == ExplainDeleted) {
7648 S.Diag(Best->Function->getLocation(),
7649 diag::note_defaulted_comparison_not_rewritten_callee)
7652 return Result::deleted();
7655 // Throughout C++2a [class.compare]: if overload resolution does not
7656 // result in a usable function, the candidate function is defined as
7657 // deleted. This requires that we selected an accessible function.
7659 // Note that this only considers the access of the function when named
7660 // within the type of the subobject, and not the access path for any
7661 // derived-to-base conversion.
7662 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7663 if (ArgClass && Best->FoundDecl.getDecl() &&
7664 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7665 QualType ObjectType = Subobj.Kind == Subobject::Member
7666 ? Args[0]->getType()
7667 : S.Context.getRecordType(RD);
7668 if (!S.isMemberAccessibleForDeletion(
7669 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7670 Diagnose == ExplainDeleted
7671 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7672 << FD << Subobj.Kind << Subobj.Decl
7674 return Result::deleted();
7677 // C++2a [class.compare.default]p3 [P2002R0]:
7678 // A defaulted comparison function is constexpr-compatible if [...]
7679 // no overlod resolution performed [...] results in a non-constexpr
7681 if (FunctionDecl *BestFD = Best->Function) {
7682 assert(!BestFD->isDeleted() && "wrong overload resolution result");
7683 // If it's not constexpr, explain why not.
7684 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7685 if (Subobj.Kind != Subobject::CompleteObject)
7686 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7687 << Subobj.Kind << Subobj.Decl;
7688 S.Diag(BestFD->getLocation(),
7689 diag::note_defaulted_comparison_not_constexpr_here);
7690 // Bail out after explaining; we don't want any more notes.
7691 return Result::deleted();
7693 R.Constexpr &= BestFD->isConstexpr();
7696 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) {
7697 if (auto *BestFD = Best->Function) {
7698 // If any callee has an undeduced return type, deduce it now.
7699 // FIXME: It's not clear how a failure here should be handled. For
7700 // now, we produce an eager diagnostic, because that is forward
7701 // compatible with most (all?) other reasonable options.
7702 if (BestFD->getReturnType()->isUndeducedType() &&
7703 S.DeduceReturnType(BestFD, FD->getLocation(),
7704 /*Diagnose=*/false)) {
7705 // Don't produce a duplicate error when asked to explain why the
7706 // comparison is deleted: we diagnosed that when initially checking
7707 // the defaulted operator.
7708 if (Diagnose == NoDiagnostics) {
7711 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7712 << Subobj.Kind << Subobj.Decl;
7715 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7716 << Subobj.Kind << Subobj.Decl;
7717 S.Diag(BestFD->getLocation(),
7718 diag::note_defaulted_comparison_cannot_deduce_callee)
7719 << Subobj.Kind << Subobj.Decl;
7721 return Result::deleted();
7723 if (auto *Info = S.Context.CompCategories.lookupInfoForType(
7724 BestFD->getCallResultType())) {
7725 R.Category = Info->Kind;
7727 if (Diagnose == ExplainDeleted) {
7728 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7729 << Subobj.Kind << Subobj.Decl
7730 << BestFD->getCallResultType().withoutLocalFastQualifiers();
7731 S.Diag(BestFD->getLocation(),
7732 diag::note_defaulted_comparison_cannot_deduce_callee)
7733 << Subobj.Kind << Subobj.Decl;
7735 return Result::deleted();
7738 Optional<ComparisonCategoryType> Cat =
7739 getComparisonCategoryForBuiltinCmp(Args[0]->getType());
7740 assert(Cat && "no category for builtin comparison?");
7745 // Note that we might be rewriting to a different operator. That call is
7746 // not considered until we come to actually build the comparison function.
7751 if (Diagnose == ExplainDeleted) {
7753 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7754 Kind = OO == OO_EqualEqual ? 1 : 2;
7755 CandidateSet.NoteCandidates(
7756 PartialDiagnosticAt(
7757 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7758 << FD << Kind << Subobj.Kind << Subobj.Decl),
7759 S, OCD_AmbiguousCandidates, Args);
7761 R = Result::deleted();
7765 if (Diagnose == ExplainDeleted) {
7766 if ((DCK == DefaultedComparisonKind::NotEqual ||
7767 DCK == DefaultedComparisonKind::Relational) &&
7768 !Best->RewriteKind) {
7769 S.Diag(Best->Function->getLocation(),
7770 diag::note_defaulted_comparison_not_rewritten_callee)
7774 diag::note_defaulted_comparison_calls_deleted)
7775 << FD << Subobj.Kind << Subobj.Decl;
7776 S.NoteDeletedFunction(Best->Function);
7779 R = Result::deleted();
7782 case OR_No_Viable_Function:
7783 // If there's no usable candidate, we're done unless we can rewrite a
7784 // '<=>' in terms of '==' and '<'.
7785 if (OO == OO_Spaceship &&
7786 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7787 // For any kind of comparison category return type, we need a usable
7788 // '==' and a usable '<'.
7789 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7791 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7795 if (Diagnose == ExplainDeleted) {
7796 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7797 << FD << Subobj.Kind << Subobj.Decl;
7799 // For a three-way comparison, list both the candidates for the
7800 // original operator and the candidates for the synthesized operator.
7801 if (SpaceshipCandidates) {
7802 SpaceshipCandidates->NoteCandidates(
7804 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7805 Args, FD->getLocation()));
7807 diag::note_defaulted_comparison_no_viable_function_synthesized)
7808 << (OO == OO_EqualEqual ? 0 : 1);
7811 CandidateSet.NoteCandidates(
7813 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7814 FD->getLocation()));
7816 R = Result::deleted();
7824 /// A list of statements.
7825 struct StmtListResult {
7826 bool IsInvalid = false;
7827 llvm::SmallVector<Stmt*, 16> Stmts;
7829 bool add(const StmtResult &S) {
7830 IsInvalid |= S.isInvalid();
7833 Stmts.push_back(S.get());
7838 /// A visitor over the notional body of a defaulted comparison that synthesizes
7839 /// the actual body.
7840 class DefaultedComparisonSynthesizer
7841 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
7842 StmtListResult, StmtResult,
7843 std::pair<ExprResult, ExprResult>> {
7845 unsigned ArrayDepth = 0;
7848 using Base = DefaultedComparisonVisitor;
7849 using ExprPair = std::pair<ExprResult, ExprResult>;
7853 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7854 DefaultedComparisonKind DCK,
7855 SourceLocation BodyLoc)
7856 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
7858 /// Build a suitable function body for this defaulted comparison operator.
7859 StmtResult build() {
7860 Sema::CompoundScopeRAII CompoundScope(S);
7862 StmtListResult Stmts = visit();
7863 if (Stmts.IsInvalid)
7868 case DefaultedComparisonKind::None:
7869 llvm_unreachable("not a defaulted comparison");
7871 case DefaultedComparisonKind::Equal: {
7872 // C++2a [class.eq]p3:
7873 // [...] compar[e] the corresponding elements [...] until the first
7874 // index i where xi == yi yields [...] false. If no such index exists,
7875 // V is true. Otherwise, V is false.
7877 // Join the comparisons with '&&'s and return the result. Use a right
7878 // fold (traversing the conditions right-to-left), because that
7879 // short-circuits more naturally.
7880 auto OldStmts = std::move(Stmts.Stmts);
7881 Stmts.Stmts.clear();
7882 ExprResult CmpSoFar;
7883 // Finish a particular comparison chain.
7884 auto FinishCmp = [&] {
7885 if (Expr *Prior = CmpSoFar.get()) {
7886 // Convert the last expression to 'return ...;'
7887 if (RetVal.isUnset() && Stmts.Stmts.empty())
7889 // Convert any prior comparison to 'if (!(...)) return false;'
7890 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
7892 CmpSoFar = ExprResult();
7896 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
7897 Expr *E = dyn_cast<Expr>(EAsStmt);
7899 // Found an array comparison.
7900 if (FinishCmp() || Stmts.add(EAsStmt))
7905 if (CmpSoFar.isUnset()) {
7909 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
7910 if (CmpSoFar.isInvalid())
7915 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
7916 // If no such index exists, V is true.
7917 if (RetVal.isUnset())
7918 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
7922 case DefaultedComparisonKind::ThreeWay: {
7923 // Per C++2a [class.spaceship]p3, as a fallback add:
7924 // return static_cast<R>(std::strong_ordering::equal);
7925 QualType StrongOrdering = S.CheckComparisonCategoryType(
7926 ComparisonCategoryType::StrongOrdering, Loc,
7927 Sema::ComparisonCategoryUsage::DefaultedOperator);
7928 if (StrongOrdering.isNull())
7930 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
7931 .getValueInfo(ComparisonCategoryResult::Equal)
7933 RetVal = getDecl(EqualVD);
7934 if (RetVal.isInvalid())
7936 RetVal = buildStaticCastToR(RetVal.get());
7940 case DefaultedComparisonKind::NotEqual:
7941 case DefaultedComparisonKind::Relational:
7942 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
7946 // Build the final return statement.
7947 if (RetVal.isInvalid())
7949 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
7950 if (ReturnStmt.isInvalid())
7952 Stmts.Stmts.push_back(ReturnStmt.get());
7954 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
7958 ExprResult getDecl(ValueDecl *VD) {
7959 return S.BuildDeclarationNameExpr(
7960 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7963 ExprResult getParam(unsigned I) {
7964 ParmVarDecl *PD = FD->getParamDecl(I);
7968 ExprPair getCompleteObject() {
7971 if (isa<CXXMethodDecl>(FD)) {
7973 LHS = S.ActOnCXXThis(Loc);
7974 if (!LHS.isInvalid())
7975 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
7977 LHS = getParam(Param++);
7979 ExprResult RHS = getParam(Param++);
7980 assert(Param == FD->getNumParams());
7984 ExprPair getBase(CXXBaseSpecifier *Base) {
7985 ExprPair Obj = getCompleteObject();
7986 if (Obj.first.isInvalid() || Obj.second.isInvalid())
7987 return {ExprError(), ExprError()};
7988 CXXCastPath Path = {Base};
7989 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
7990 CK_DerivedToBase, VK_LValue, &Path),
7991 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
7992 CK_DerivedToBase, VK_LValue, &Path)};
7995 ExprPair getField(FieldDecl *Field) {
7996 ExprPair Obj = getCompleteObject();
7997 if (Obj.first.isInvalid() || Obj.second.isInvalid())
7998 return {ExprError(), ExprError()};
8000 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8001 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8002 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8003 CXXScopeSpec(), Field, Found, NameInfo),
8004 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8005 CXXScopeSpec(), Field, Found, NameInfo)};
8008 // FIXME: When expanding a subobject, register a note in the code synthesis
8009 // stack to say which subobject we're comparing.
8011 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8012 if (Cond.isInvalid())
8015 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8016 if (NotCond.isInvalid())
8019 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8020 assert(!False.isInvalid() && "should never fail");
8021 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8022 if (ReturnFalse.isInvalid())
8025 return S.ActOnIfStmt(Loc, false, nullptr,
8026 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8027 Sema::ConditionKind::Boolean),
8028 ReturnFalse.get(), SourceLocation(), nullptr);
8031 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8033 QualType SizeType = S.Context.getSizeType();
8034 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8036 // Build 'size_t i$n = 0'.
8037 IdentifierInfo *IterationVarName = nullptr;
8040 llvm::raw_svector_ostream OS(Str);
8041 OS << "i" << ArrayDepth;
8042 IterationVarName = &S.Context.Idents.get(OS.str());
8044 VarDecl *IterationVar = VarDecl::Create(
8045 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8046 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8047 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8048 IterationVar->setInit(
8049 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8050 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8052 auto IterRef = [&] {
8053 ExprResult Ref = S.BuildDeclarationNameExpr(
8054 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8056 assert(!Ref.isInvalid() && "can't reference our own variable?");
8060 // Build 'i$n != Size'.
8061 ExprResult Cond = S.CreateBuiltinBinOp(
8062 Loc, BO_NE, IterRef(),
8063 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8064 assert(!Cond.isInvalid() && "should never fail");
8067 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8068 assert(!Inc.isInvalid() && "should never fail");
8070 // Build 'a[i$n]' and 'b[i$n]'.
8071 auto Index = [&](ExprResult E) {
8074 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8076 Subobj.first = Index(Subobj.first);
8077 Subobj.second = Index(Subobj.second);
8079 // Compare the array elements.
8081 StmtResult Substmt = visitSubobject(Type, Subobj);
8084 if (Substmt.isInvalid())
8087 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8088 // For outer levels or for an 'operator<=>' we already have a suitable
8089 // statement that returns as necessary.
8090 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8091 assert(DCK == DefaultedComparisonKind::Equal &&
8092 "should have non-expression statement");
8093 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8094 if (Substmt.isInvalid())
8098 // Build 'for (...) ...'
8099 return S.ActOnForStmt(Loc, Loc, Init,
8100 S.ActOnCondition(nullptr, Loc, Cond.get(),
8101 Sema::ConditionKind::Boolean),
8102 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8106 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8107 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8110 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8111 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8113 if (Type->isOverloadableType())
8114 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8115 Obj.second.get(), /*PerformADL=*/true,
8116 /*AllowRewrittenCandidates=*/true, FD);
8118 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8123 case DefaultedComparisonKind::None:
8124 llvm_unreachable("not a defaulted comparison");
8126 case DefaultedComparisonKind::Equal:
8127 // Per C++2a [class.eq]p2, each comparison is individually contextually
8128 // converted to bool.
8129 Op = S.PerformContextuallyConvertToBool(Op.get());
8134 case DefaultedComparisonKind::ThreeWay: {
8135 // Per C++2a [class.spaceship]p3, form:
8136 // if (R cmp = static_cast<R>(op); cmp != 0)
8138 QualType R = FD->getReturnType();
8139 Op = buildStaticCastToR(Op.get());
8144 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8146 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8147 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8148 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8149 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8152 ExprResult VDRef = getDecl(VD);
8153 if (VDRef.isInvalid())
8155 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8157 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8159 if (VDRef.get()->getType()->isOverloadableType())
8160 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8163 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8164 if (Comp.isInvalid())
8166 Sema::ConditionResult Cond = S.ActOnCondition(
8167 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8168 if (Cond.isInvalid())
8172 VDRef = getDecl(VD);
8173 if (VDRef.isInvalid())
8175 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8176 if (ReturnStmt.isInvalid())
8180 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond,
8181 ReturnStmt.get(), /*ElseLoc=*/SourceLocation(),
8185 case DefaultedComparisonKind::NotEqual:
8186 case DefaultedComparisonKind::Relational:
8187 // C++2a [class.compare.secondary]p2:
8188 // Otherwise, the operator function yields x @ y.
8191 llvm_unreachable("");
8194 /// Build "static_cast<R>(E)".
8195 ExprResult buildStaticCastToR(Expr *E) {
8196 QualType R = FD->getReturnType();
8197 assert(!R->isUndeducedType() && "type should have been deduced already");
8199 // Don't bother forming a no-op cast in the common case.
8200 if (E->isRValue() && S.Context.hasSameType(E->getType(), R))
8202 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8203 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8204 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8209 /// Perform the unqualified lookups that might be needed to form a defaulted
8210 /// comparison function for the given operator.
8211 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8212 UnresolvedSetImpl &Operators,
8213 OverloadedOperatorKind Op) {
8214 auto Lookup = [&](OverloadedOperatorKind OO) {
8215 Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators);
8218 // Every defaulted operator looks up itself.
8220 // ... and the rewritten form of itself, if any.
8221 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8224 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8225 // synthesize a three-way comparison from '<' and '=='. In a dependent
8226 // context, we also need to look up '==' in case we implicitly declare a
8227 // defaulted 'operator=='.
8228 if (Op == OO_Spaceship) {
8229 Lookup(OO_ExclaimEqual);
8231 Lookup(OO_EqualEqual);
8235 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8236 DefaultedComparisonKind DCK) {
8237 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8239 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8240 assert(RD && "defaulted comparison is not defaulted in a class");
8242 // Perform any unqualified lookups we're going to need to default this
8245 UnresolvedSet<32> Operators;
8246 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8247 FD->getOverloadedOperator());
8248 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8249 Context, Operators.pairs()));
8252 // C++2a [class.compare.default]p1:
8253 // A defaulted comparison operator function for some class C shall be a
8254 // non-template function declared in the member-specification of C that is
8255 // -- a non-static const member of C having one parameter of type
8257 // -- a friend of C having two parameters of type const C& or two
8258 // parameters of type C.
8259 QualType ExpectedParmType1 = Context.getRecordType(RD);
8260 QualType ExpectedParmType2 =
8261 Context.getLValueReferenceType(ExpectedParmType1.withConst());
8262 if (isa<CXXMethodDecl>(FD))
8263 ExpectedParmType1 = ExpectedParmType2;
8264 for (const ParmVarDecl *Param : FD->parameters()) {
8265 if (!Param->getType()->isDependentType() &&
8266 !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8267 !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8268 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8269 // corresponding defaulted 'operator<=>' already.
8270 if (!FD->isImplicit()) {
8271 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8272 << (int)DCK << Param->getType() << ExpectedParmType1
8273 << !isa<CXXMethodDecl>(FD)
8274 << ExpectedParmType2 << Param->getSourceRange();
8279 if (FD->getNumParams() == 2 &&
8280 !Context.hasSameType(FD->getParamDecl(0)->getType(),
8281 FD->getParamDecl(1)->getType())) {
8282 if (!FD->isImplicit()) {
8283 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8285 << FD->getParamDecl(0)->getType()
8286 << FD->getParamDecl(0)->getSourceRange()
8287 << FD->getParamDecl(1)->getType()
8288 << FD->getParamDecl(1)->getSourceRange();
8293 // ... non-static const member ...
8294 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8295 assert(!MD->isStatic() && "comparison function cannot be a static member");
8296 if (!MD->isConst()) {
8297 SourceLocation InsertLoc;
8298 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8299 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8300 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8301 // corresponding defaulted 'operator<=>' already.
8302 if (!MD->isImplicit()) {
8303 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8304 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8307 // Add the 'const' to the type to recover.
8308 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8309 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8310 EPI.TypeQuals.addConst();
8311 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8312 FPT->getParamTypes(), EPI));
8315 // A non-member function declared in a class must be a friend.
8316 assert(FD->getFriendObjectKind() && "expected a friend declaration");
8319 // C++2a [class.eq]p1, [class.rel]p1:
8320 // A [defaulted comparison other than <=>] shall have a declared return
8322 if (DCK != DefaultedComparisonKind::ThreeWay &&
8323 !FD->getDeclaredReturnType()->isDependentType() &&
8324 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8325 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8326 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8327 << FD->getReturnTypeSourceRange();
8330 // C++2a [class.spaceship]p2 [P2002R0]:
8331 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8332 // R shall not contain a placeholder type.
8333 if (DCK == DefaultedComparisonKind::ThreeWay &&
8334 FD->getDeclaredReturnType()->getContainedDeducedType() &&
8335 !Context.hasSameType(FD->getDeclaredReturnType(),
8336 Context.getAutoDeductType())) {
8337 Diag(FD->getLocation(),
8338 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8339 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8340 << FD->getReturnTypeSourceRange();
8344 // For a defaulted function in a dependent class, defer all remaining checks
8345 // until instantiation.
8346 if (RD->isDependentType())
8349 // Determine whether the function should be defined as deleted.
8350 DefaultedComparisonInfo Info =
8351 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8353 bool First = FD == FD->getCanonicalDecl();
8355 // If we want to delete the function, then do so; there's nothing else to
8356 // check in that case.
8359 // C++11 [dcl.fct.def.default]p4:
8360 // [For a] user-provided explicitly-defaulted function [...] if such a
8361 // function is implicitly defined as deleted, the program is ill-formed.
8363 // This is really just a consequence of the general rule that you can
8364 // only delete a function on its first declaration.
8365 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8366 << FD->isImplicit() << (int)DCK;
8367 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8368 DefaultedComparisonAnalyzer::ExplainDeleted)
8373 SetDeclDeleted(FD, FD->getLocation());
8374 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8375 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8377 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8378 DefaultedComparisonAnalyzer::ExplainDeleted)
8384 // C++2a [class.spaceship]p2:
8385 // The return type is deduced as the common comparison type of R0, R1, ...
8386 if (DCK == DefaultedComparisonKind::ThreeWay &&
8387 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8388 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8389 if (RetLoc.isInvalid())
8390 RetLoc = FD->getBeginLoc();
8391 // FIXME: Should we really care whether we have the complete type and the
8392 // 'enumerator' constants here? A forward declaration seems sufficient.
8393 QualType Cat = CheckComparisonCategoryType(
8394 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8397 Context.adjustDeducedFunctionResultType(
8398 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8401 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8402 // An explicitly-defaulted function that is not defined as deleted may be
8403 // declared constexpr or consteval only if it is constexpr-compatible.
8404 // C++2a [class.compare.default]p3 [P2002R0]:
8405 // A defaulted comparison function is constexpr-compatible if it satisfies
8406 // the requirements for a constexpr function [...]
8407 // The only relevant requirements are that the parameter and return types are
8408 // literal types. The remaining conditions are checked by the analyzer.
8409 if (FD->isConstexpr()) {
8410 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8411 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8413 Diag(FD->getBeginLoc(),
8414 diag::err_incorrect_defaulted_comparison_constexpr)
8415 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8416 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8417 DefaultedComparisonAnalyzer::ExplainConstexpr)
8422 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8423 // If a constexpr-compatible function is explicitly defaulted on its first
8424 // declaration, it is implicitly considered to be constexpr.
8425 // FIXME: Only applying this to the first declaration seems problematic, as
8426 // simple reorderings can affect the meaning of the program.
8427 if (First && !FD->isConstexpr() && Info.Constexpr)
8428 FD->setConstexprKind(CSK_constexpr);
8430 // C++2a [except.spec]p3:
8431 // If a declaration of a function does not have a noexcept-specifier
8432 // [and] is defaulted on its first declaration, [...] the exception
8433 // specification is as specified below
8434 if (FD->getExceptionSpecType() == EST_None) {
8435 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8436 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8437 EPI.ExceptionSpec.Type = EST_Unevaluated;
8438 EPI.ExceptionSpec.SourceDecl = FD;
8439 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8440 FPT->getParamTypes(), EPI));
8446 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8447 FunctionDecl *Spaceship) {
8448 Sema::CodeSynthesisContext Ctx;
8449 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8450 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8451 Ctx.Entity = Spaceship;
8452 pushCodeSynthesisContext(Ctx);
8454 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8455 EqualEqual->setImplicit();
8457 popCodeSynthesisContext();
8460 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8461 DefaultedComparisonKind DCK) {
8462 assert(FD->isDefaulted() && !FD->isDeleted() &&
8463 !FD->doesThisDeclarationHaveABody());
8464 if (FD->willHaveBody() || FD->isInvalidDecl())
8467 SynthesizedFunctionScope Scope(*this, FD);
8469 // Add a context note for diagnostics produced after this point.
8470 Scope.addContextNote(UseLoc);
8473 // Build and set up the function body.
8474 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8475 SourceLocation BodyLoc =
8476 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8478 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8479 if (Body.isInvalid()) {
8480 FD->setInvalidDecl();
8483 FD->setBody(Body.get());
8484 FD->markUsed(Context);
8487 // The exception specification is needed because we are defining the
8488 // function. Note that this will reuse the body we just built.
8489 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8491 if (ASTMutationListener *L = getASTMutationListener())
8492 L->CompletedImplicitDefinition(FD);
8495 static Sema::ImplicitExceptionSpecification
8496 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8498 Sema::DefaultedComparisonKind DCK) {
8499 ComputingExceptionSpec CES(S, FD, Loc);
8500 Sema::ImplicitExceptionSpecification ExceptSpec(S);
8502 if (FD->isInvalidDecl())
8505 // The common case is that we just defined the comparison function. In that
8506 // case, just look at whether the body can throw.
8507 if (FD->hasBody()) {
8508 ExceptSpec.CalledStmt(FD->getBody());
8510 // Otherwise, build a body so we can check it. This should ideally only
8511 // happen when we're not actually marking the function referenced. (This is
8512 // only really important for efficiency: we don't want to build and throw
8513 // away bodies for comparison functions more than we strictly need to.)
8515 // Pretend to synthesize the function body in an unevaluated context.
8516 // Note that we can't actually just go ahead and define the function here:
8517 // we are not permitted to mark its callees as referenced.
8518 Sema::SynthesizedFunctionScope Scope(S, FD);
8519 EnterExpressionEvaluationContext Context(
8520 S, Sema::ExpressionEvaluationContext::Unevaluated);
8522 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8523 SourceLocation BodyLoc =
8524 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8526 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8527 if (!Body.isInvalid())
8528 ExceptSpec.CalledStmt(Body.get());
8530 // FIXME: Can we hold onto this body and just transform it to potentially
8531 // evaluated when we're asked to define the function rather than rebuilding
8532 // it? Either that, or we should only build the bits of the body that we
8533 // need (the expressions, not the statements).
8539 void Sema::CheckDelayedMemberExceptionSpecs() {
8540 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8541 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8543 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8544 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8546 // Perform any deferred checking of exception specifications for virtual
8548 for (auto &Check : Overriding)
8549 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8551 // Perform any deferred checking of exception specifications for befriended
8553 for (auto &Check : Equivalent)
8554 CheckEquivalentExceptionSpec(Check.second, Check.first);
8558 /// CRTP base class for visiting operations performed by a special member
8559 /// function (or inherited constructor).
8560 template<typename Derived>
8561 struct SpecialMemberVisitor {
8564 Sema::CXXSpecialMember CSM;
8565 Sema::InheritedConstructorInfo *ICI;
8567 // Properties of the special member, computed for convenience.
8568 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8570 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8571 Sema::InheritedConstructorInfo *ICI)
8572 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8574 case Sema::CXXDefaultConstructor:
8575 case Sema::CXXCopyConstructor:
8576 case Sema::CXXMoveConstructor:
8577 IsConstructor = true;
8579 case Sema::CXXCopyAssignment:
8580 case Sema::CXXMoveAssignment:
8581 IsAssignment = true;
8583 case Sema::CXXDestructor:
8585 case Sema::CXXInvalid:
8586 llvm_unreachable("invalid special member kind");
8589 if (MD->getNumParams()) {
8590 if (const ReferenceType *RT =
8591 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8592 ConstArg = RT->getPointeeType().isConstQualified();
8596 Derived &getDerived() { return static_cast<Derived&>(*this); }
8598 /// Is this a "move" special member?
8599 bool isMove() const {
8600 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8603 /// Look up the corresponding special member in the given class.
8604 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8605 unsigned Quals, bool IsMutable) {
8606 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8607 ConstArg && !IsMutable);
8610 /// Look up the constructor for the specified base class to see if it's
8611 /// overridden due to this being an inherited constructor.
8612 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8615 assert(CSM == Sema::CXXDefaultConstructor);
8617 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8618 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8623 /// A base or member subobject.
8624 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8626 /// Get the location to use for a subobject in diagnostics.
8627 static SourceLocation getSubobjectLoc(Subobject Subobj) {
8628 // FIXME: For an indirect virtual base, the direct base leading to
8629 // the indirect virtual base would be a more useful choice.
8630 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8631 return B->getBaseTypeLoc();
8633 return Subobj.get<FieldDecl*>()->getLocation();
8637 /// Visit all non-virtual (direct) bases.
8638 VisitNonVirtualBases,
8639 /// Visit all direct bases, virtual or not.
8641 /// Visit all non-virtual bases, and all virtual bases if the class
8642 /// is not abstract.
8643 VisitPotentiallyConstructedBases,
8644 /// Visit all direct or virtual bases.
8648 // Visit the bases and members of the class.
8649 bool visit(BasesToVisit Bases) {
8650 CXXRecordDecl *RD = MD->getParent();
8652 if (Bases == VisitPotentiallyConstructedBases)
8653 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8655 for (auto &B : RD->bases())
8656 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8657 getDerived().visitBase(&B))
8660 if (Bases == VisitAllBases)
8661 for (auto &B : RD->vbases())
8662 if (getDerived().visitBase(&B))
8665 for (auto *F : RD->fields())
8666 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8667 getDerived().visitField(F))
8676 struct SpecialMemberDeletionInfo
8677 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8682 bool AllFieldsAreConst;
8684 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8685 Sema::CXXSpecialMember CSM,
8686 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8687 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8688 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8690 bool inUnion() const { return MD->getParent()->isUnion(); }
8692 Sema::CXXSpecialMember getEffectiveCSM() {
8693 return ICI ? Sema::CXXInvalid : CSM;
8696 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8698 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8699 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8701 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8702 bool shouldDeleteForField(FieldDecl *FD);
8703 bool shouldDeleteForAllConstMembers();
8705 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8707 bool shouldDeleteForSubobjectCall(Subobject Subobj,
8708 Sema::SpecialMemberOverloadResult SMOR,
8709 bool IsDtorCallInCtor);
8711 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8715 /// Is the given special member inaccessible when used on the given
8717 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8718 CXXMethodDecl *target) {
8719 /// If we're operating on a base class, the object type is the
8720 /// type of this special member.
8722 AccessSpecifier access = target->getAccess();
8723 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8724 objectTy = S.Context.getTypeDeclType(MD->getParent());
8725 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8727 // If we're operating on a field, the object type is the type of the field.
8729 objectTy = S.Context.getTypeDeclType(target->getParent());
8732 return S.isMemberAccessibleForDeletion(
8733 target->getParent(), DeclAccessPair::make(target, access), objectTy);
8736 /// Check whether we should delete a special member due to the implicit
8737 /// definition containing a call to a special member of a subobject.
8738 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8739 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8740 bool IsDtorCallInCtor) {
8741 CXXMethodDecl *Decl = SMOR.getMethod();
8742 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8746 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8747 DiagKind = !Decl ? 0 : 1;
8748 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8750 else if (!isAccessible(Subobj, Decl))
8752 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8753 !Decl->isTrivial()) {
8754 // A member of a union must have a trivial corresponding special member.
8755 // As a weird special case, a destructor call from a union's constructor
8756 // must be accessible and non-deleted, but need not be trivial. Such a
8757 // destructor is never actually called, but is semantically checked as
8767 S.Diag(Field->getLocation(),
8768 diag::note_deleted_special_member_class_subobject)
8769 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8770 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8772 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8773 S.Diag(Base->getBeginLoc(),
8774 diag::note_deleted_special_member_class_subobject)
8775 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8776 << Base->getType() << DiagKind << IsDtorCallInCtor
8777 << /*IsObjCPtr*/false;
8781 S.NoteDeletedFunction(Decl);
8782 // FIXME: Explain inaccessibility if DiagKind == 3.
8788 /// Check whether we should delete a special member function due to having a
8789 /// direct or virtual base class or non-static data member of class type M.
8790 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8791 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8792 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8793 bool IsMutable = Field && Field->isMutable();
8795 // C++11 [class.ctor]p5:
8796 // -- any direct or virtual base class, or non-static data member with no
8797 // brace-or-equal-initializer, has class type M (or array thereof) and
8798 // either M has no default constructor or overload resolution as applied
8799 // to M's default constructor results in an ambiguity or in a function
8800 // that is deleted or inaccessible
8801 // C++11 [class.copy]p11, C++11 [class.copy]p23:
8802 // -- a direct or virtual base class B that cannot be copied/moved because
8803 // overload resolution, as applied to B's corresponding special member,
8804 // results in an ambiguity or a function that is deleted or inaccessible
8805 // from the defaulted special member
8806 // C++11 [class.dtor]p5:
8807 // -- any direct or virtual base class [...] has a type with a destructor
8808 // that is deleted or inaccessible
8809 if (!(CSM == Sema::CXXDefaultConstructor &&
8810 Field && Field->hasInClassInitializer()) &&
8811 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8815 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8816 // -- any direct or virtual base class or non-static data member has a
8817 // type with a destructor that is deleted or inaccessible
8818 if (IsConstructor) {
8819 Sema::SpecialMemberOverloadResult SMOR =
8820 S.LookupSpecialMember(Class, Sema::CXXDestructor,
8821 false, false, false, false, false);
8822 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8829 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8830 FieldDecl *FD, QualType FieldType) {
8831 // The defaulted special functions are defined as deleted if this is a variant
8832 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
8834 if (!FieldType.hasNonTrivialObjCLifetime())
8837 // Don't make the defaulted default constructor defined as deleted if the
8838 // member has an in-class initializer.
8839 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
8843 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
8844 S.Diag(FD->getLocation(),
8845 diag::note_deleted_special_member_class_subobject)
8846 << getEffectiveCSM() << ParentClass << /*IsField*/true
8847 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
8853 /// Check whether we should delete a special member function due to the class
8854 /// having a particular direct or virtual base class.
8855 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
8856 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
8857 // If program is correct, BaseClass cannot be null, but if it is, the error
8858 // must be reported elsewhere.
8861 // If we have an inheriting constructor, check whether we're calling an
8862 // inherited constructor instead of a default constructor.
8863 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
8864 if (auto *BaseCtor = SMOR.getMethod()) {
8865 // Note that we do not check access along this path; other than that,
8866 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
8867 // FIXME: Check that the base has a usable destructor! Sink this into
8868 // shouldDeleteForClassSubobject.
8869 if (BaseCtor->isDeleted() && Diagnose) {
8870 S.Diag(Base->getBeginLoc(),
8871 diag::note_deleted_special_member_class_subobject)
8872 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8873 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
8874 << /*IsObjCPtr*/false;
8875 S.NoteDeletedFunction(BaseCtor);
8877 return BaseCtor->isDeleted();
8879 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
8882 /// Check whether we should delete a special member function due to the class
8883 /// having a particular non-static data member.
8884 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
8885 QualType FieldType = S.Context.getBaseElementType(FD->getType());
8886 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
8888 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
8891 if (CSM == Sema::CXXDefaultConstructor) {
8892 // For a default constructor, all references must be initialized in-class
8893 // and, if a union, it must have a non-const member.
8894 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
8896 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8897 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
8900 // C++11 [class.ctor]p5: any non-variant non-static data member of
8901 // const-qualified type (or array thereof) with no
8902 // brace-or-equal-initializer does not have a user-provided default
8904 if (!inUnion() && FieldType.isConstQualified() &&
8905 !FD->hasInClassInitializer() &&
8906 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
8908 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
8909 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
8913 if (inUnion() && !FieldType.isConstQualified())
8914 AllFieldsAreConst = false;
8915 } else if (CSM == Sema::CXXCopyConstructor) {
8916 // For a copy constructor, data members must not be of rvalue reference
8918 if (FieldType->isRValueReferenceType()) {
8920 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
8921 << MD->getParent() << FD << FieldType;
8924 } else if (IsAssignment) {
8925 // For an assignment operator, data members must not be of reference type.
8926 if (FieldType->isReferenceType()) {
8928 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8929 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
8932 if (!FieldRecord && FieldType.isConstQualified()) {
8933 // C++11 [class.copy]p23:
8934 // -- a non-static data member of const non-class type (or array thereof)
8936 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
8937 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
8943 // Some additional restrictions exist on the variant members.
8944 if (!inUnion() && FieldRecord->isUnion() &&
8945 FieldRecord->isAnonymousStructOrUnion()) {
8946 bool AllVariantFieldsAreConst = true;
8948 // FIXME: Handle anonymous unions declared within anonymous unions.
8949 for (auto *UI : FieldRecord->fields()) {
8950 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
8952 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
8955 if (!UnionFieldType.isConstQualified())
8956 AllVariantFieldsAreConst = false;
8958 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
8959 if (UnionFieldRecord &&
8960 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
8961 UnionFieldType.getCVRQualifiers()))
8965 // At least one member in each anonymous union must be non-const
8966 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
8967 !FieldRecord->field_empty()) {
8969 S.Diag(FieldRecord->getLocation(),
8970 diag::note_deleted_default_ctor_all_const)
8971 << !!ICI << MD->getParent() << /*anonymous union*/1;
8975 // Don't check the implicit member of the anonymous union type.
8976 // This is technically non-conformant, but sanity demands it.
8980 if (shouldDeleteForClassSubobject(FieldRecord, FD,
8981 FieldType.getCVRQualifiers()))
8988 /// C++11 [class.ctor] p5:
8989 /// A defaulted default constructor for a class X is defined as deleted if
8990 /// X is a union and all of its variant members are of const-qualified type.
8991 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
8992 // This is a silly definition, because it gives an empty union a deleted
8993 // default constructor. Don't do that.
8994 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
8995 bool AnyFields = false;
8996 for (auto *F : MD->getParent()->fields())
8997 if ((AnyFields = !F->isUnnamedBitfield()))
9002 S.Diag(MD->getParent()->getLocation(),
9003 diag::note_deleted_default_ctor_all_const)
9004 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9010 /// Determine whether a defaulted special member function should be defined as
9011 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9012 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9013 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9014 InheritedConstructorInfo *ICI,
9016 if (MD->isInvalidDecl())
9018 CXXRecordDecl *RD = MD->getParent();
9019 assert(!RD->isDependentType() && "do deletion after instantiation");
9020 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9023 // C++11 [expr.lambda.prim]p19:
9024 // The closure type associated with a lambda-expression has a
9025 // deleted (8.4.3) default constructor and a deleted copy
9026 // assignment operator.
9027 // C++2a adds back these operators if the lambda has no lambda-capture.
9028 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9029 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9031 Diag(RD->getLocation(), diag::note_lambda_decl);
9035 // For an anonymous struct or union, the copy and assignment special members
9036 // will never be used, so skip the check. For an anonymous union declared at
9037 // namespace scope, the constructor and destructor are used.
9038 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9039 RD->isAnonymousStructOrUnion())
9042 // C++11 [class.copy]p7, p18:
9043 // If the class definition declares a move constructor or move assignment
9044 // operator, an implicitly declared copy constructor or copy assignment
9045 // operator is defined as deleted.
9046 if (MD->isImplicit() &&
9047 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9048 CXXMethodDecl *UserDeclaredMove = nullptr;
9050 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9051 // deletion of the corresponding copy operation, not both copy operations.
9052 // MSVC 2015 has adopted the standards conforming behavior.
9053 bool DeletesOnlyMatchingCopy =
9054 getLangOpts().MSVCCompat &&
9055 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9057 if (RD->hasUserDeclaredMoveConstructor() &&
9058 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9059 if (!Diagnose) return true;
9061 // Find any user-declared move constructor.
9062 for (auto *I : RD->ctors()) {
9063 if (I->isMoveConstructor()) {
9064 UserDeclaredMove = I;
9068 assert(UserDeclaredMove);
9069 } else if (RD->hasUserDeclaredMoveAssignment() &&
9070 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9071 if (!Diagnose) return true;
9073 // Find any user-declared move assignment operator.
9074 for (auto *I : RD->methods()) {
9075 if (I->isMoveAssignmentOperator()) {
9076 UserDeclaredMove = I;
9080 assert(UserDeclaredMove);
9083 if (UserDeclaredMove) {
9084 Diag(UserDeclaredMove->getLocation(),
9085 diag::note_deleted_copy_user_declared_move)
9086 << (CSM == CXXCopyAssignment) << RD
9087 << UserDeclaredMove->isMoveAssignmentOperator();
9092 // Do access control from the special member function
9093 ContextRAII MethodContext(*this, MD);
9095 // C++11 [class.dtor]p5:
9096 // -- for a virtual destructor, lookup of the non-array deallocation function
9097 // results in an ambiguity or in a function that is deleted or inaccessible
9098 if (CSM == CXXDestructor && MD->isVirtual()) {
9099 FunctionDecl *OperatorDelete = nullptr;
9100 DeclarationName Name =
9101 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9102 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9103 OperatorDelete, /*Diagnose*/false)) {
9105 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9110 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9112 // Per DR1611, do not consider virtual bases of constructors of abstract
9113 // classes, since we are not going to construct them.
9114 // Per DR1658, do not consider virtual bases of destructors of abstract
9116 // Per DR2180, for assignment operators we only assign (and thus only
9117 // consider) direct bases.
9118 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9119 : SMI.VisitPotentiallyConstructedBases))
9122 if (SMI.shouldDeleteForAllConstMembers())
9125 if (getLangOpts().CUDA) {
9126 // We should delete the special member in CUDA mode if target inference
9128 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9129 // is treated as certain special member, which may not reflect what special
9130 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9131 // expects CSM to match MD, therefore recalculate CSM.
9132 assert(ICI || CSM == getSpecialMember(MD));
9135 RealCSM = getSpecialMember(MD);
9137 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9138 SMI.ConstArg, Diagnose);
9144 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9145 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9146 assert(DFK && "not a defaultable function");
9147 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
9149 if (DFK.isSpecialMember()) {
9150 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9151 nullptr, /*Diagnose=*/true);
9153 DefaultedComparisonAnalyzer(
9154 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9155 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9160 /// Perform lookup for a special member of the specified kind, and determine
9161 /// whether it is trivial. If the triviality can be determined without the
9162 /// lookup, skip it. This is intended for use when determining whether a
9163 /// special member of a containing object is trivial, and thus does not ever
9164 /// perform overload resolution for default constructors.
9166 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9167 /// member that was most likely to be intended to be trivial, if any.
9169 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9170 /// determine whether the special member is trivial.
9171 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9172 Sema::CXXSpecialMember CSM, unsigned Quals,
9174 Sema::TrivialABIHandling TAH,
9175 CXXMethodDecl **Selected) {
9177 *Selected = nullptr;
9180 case Sema::CXXInvalid:
9181 llvm_unreachable("not a special member");
9183 case Sema::CXXDefaultConstructor:
9184 // C++11 [class.ctor]p5:
9185 // A default constructor is trivial if:
9186 // - all the [direct subobjects] have trivial default constructors
9188 // Note, no overload resolution is performed in this case.
9189 if (RD->hasTrivialDefaultConstructor())
9193 // If there's a default constructor which could have been trivial, dig it
9194 // out. Otherwise, if there's any user-provided default constructor, point
9195 // to that as an example of why there's not a trivial one.
9196 CXXConstructorDecl *DefCtor = nullptr;
9197 if (RD->needsImplicitDefaultConstructor())
9198 S.DeclareImplicitDefaultConstructor(RD);
9199 for (auto *CI : RD->ctors()) {
9200 if (!CI->isDefaultConstructor())
9203 if (!DefCtor->isUserProvided())
9207 *Selected = DefCtor;
9212 case Sema::CXXDestructor:
9213 // C++11 [class.dtor]p5:
9214 // A destructor is trivial if:
9215 // - all the direct [subobjects] have trivial destructors
9216 if (RD->hasTrivialDestructor() ||
9217 (TAH == Sema::TAH_ConsiderTrivialABI &&
9218 RD->hasTrivialDestructorForCall()))
9222 if (RD->needsImplicitDestructor())
9223 S.DeclareImplicitDestructor(RD);
9224 *Selected = RD->getDestructor();
9229 case Sema::CXXCopyConstructor:
9230 // C++11 [class.copy]p12:
9231 // A copy constructor is trivial if:
9232 // - the constructor selected to copy each direct [subobject] is trivial
9233 if (RD->hasTrivialCopyConstructor() ||
9234 (TAH == Sema::TAH_ConsiderTrivialABI &&
9235 RD->hasTrivialCopyConstructorForCall())) {
9236 if (Quals == Qualifiers::Const)
9237 // We must either select the trivial copy constructor or reach an
9238 // ambiguity; no need to actually perform overload resolution.
9240 } else if (!Selected) {
9243 // In C++98, we are not supposed to perform overload resolution here, but we
9244 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9245 // cases like B as having a non-trivial copy constructor:
9246 // struct A { template<typename T> A(T&); };
9247 // struct B { mutable A a; };
9248 goto NeedOverloadResolution;
9250 case Sema::CXXCopyAssignment:
9251 // C++11 [class.copy]p25:
9252 // A copy assignment operator is trivial if:
9253 // - the assignment operator selected to copy each direct [subobject] is
9255 if (RD->hasTrivialCopyAssignment()) {
9256 if (Quals == Qualifiers::Const)
9258 } else if (!Selected) {
9261 // In C++98, we are not supposed to perform overload resolution here, but we
9262 // treat that as a language defect.
9263 goto NeedOverloadResolution;
9265 case Sema::CXXMoveConstructor:
9266 case Sema::CXXMoveAssignment:
9267 NeedOverloadResolution:
9268 Sema::SpecialMemberOverloadResult SMOR =
9269 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9271 // The standard doesn't describe how to behave if the lookup is ambiguous.
9272 // We treat it as not making the member non-trivial, just like the standard
9273 // mandates for the default constructor. This should rarely matter, because
9274 // the member will also be deleted.
9275 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9278 if (!SMOR.getMethod()) {
9279 assert(SMOR.getKind() ==
9280 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
9284 // We deliberately don't check if we found a deleted special member. We're
9287 *Selected = SMOR.getMethod();
9289 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9290 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9291 return SMOR.getMethod()->isTrivialForCall();
9292 return SMOR.getMethod()->isTrivial();
9295 llvm_unreachable("unknown special method kind");
9298 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9299 for (auto *CI : RD->ctors())
9300 if (!CI->isImplicit())
9303 // Look for constructor templates.
9304 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9305 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9306 if (CXXConstructorDecl *CD =
9307 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9314 /// The kind of subobject we are checking for triviality. The values of this
9315 /// enumeration are used in diagnostics.
9316 enum TrivialSubobjectKind {
9317 /// The subobject is a base class.
9319 /// The subobject is a non-static data member.
9321 /// The object is actually the complete object.
9325 /// Check whether the special member selected for a given type would be trivial.
9326 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9327 QualType SubType, bool ConstRHS,
9328 Sema::CXXSpecialMember CSM,
9329 TrivialSubobjectKind Kind,
9330 Sema::TrivialABIHandling TAH, bool Diagnose) {
9331 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9335 CXXMethodDecl *Selected;
9336 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9337 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9344 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9345 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9346 << Kind << SubType.getUnqualifiedType();
9347 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9348 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9349 } else if (!Selected)
9350 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9351 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9352 else if (Selected->isUserProvided()) {
9353 if (Kind == TSK_CompleteObject)
9354 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9355 << Kind << SubType.getUnqualifiedType() << CSM;
9357 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9358 << Kind << SubType.getUnqualifiedType() << CSM;
9359 S.Diag(Selected->getLocation(), diag::note_declared_at);
9362 if (Kind != TSK_CompleteObject)
9363 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9364 << Kind << SubType.getUnqualifiedType() << CSM;
9366 // Explain why the defaulted or deleted special member isn't trivial.
9367 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9375 /// Check whether the members of a class type allow a special member to be
9377 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9378 Sema::CXXSpecialMember CSM,
9380 Sema::TrivialABIHandling TAH,
9382 for (const auto *FI : RD->fields()) {
9383 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9386 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9388 // Pretend anonymous struct or union members are members of this class.
9389 if (FI->isAnonymousStructOrUnion()) {
9390 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9391 CSM, ConstArg, TAH, Diagnose))
9396 // C++11 [class.ctor]p5:
9397 // A default constructor is trivial if [...]
9398 // -- no non-static data member of its class has a
9399 // brace-or-equal-initializer
9400 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9402 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
9406 // Objective C ARC 4.3.5:
9407 // [...] nontrivally ownership-qualified types are [...] not trivially
9408 // default constructible, copy constructible, move constructible, copy
9409 // assignable, move assignable, or destructible [...]
9410 if (FieldType.hasNonTrivialObjCLifetime()) {
9412 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9413 << RD << FieldType.getObjCLifetime();
9417 bool ConstRHS = ConstArg && !FI->isMutable();
9418 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9419 CSM, TSK_Field, TAH, Diagnose))
9426 /// Diagnose why the specified class does not have a trivial special member of
9428 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9429 QualType Ty = Context.getRecordType(RD);
9431 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9432 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9433 TSK_CompleteObject, TAH_IgnoreTrivialABI,
9437 /// Determine whether a defaulted or deleted special member function is trivial,
9438 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9439 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9440 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9441 TrivialABIHandling TAH, bool Diagnose) {
9442 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
9444 CXXRecordDecl *RD = MD->getParent();
9446 bool ConstArg = false;
9448 // C++11 [class.copy]p12, p25: [DR1593]
9449 // A [special member] is trivial if [...] its parameter-type-list is
9450 // equivalent to the parameter-type-list of an implicit declaration [...]
9452 case CXXDefaultConstructor:
9454 // Trivial default constructors and destructors cannot have parameters.
9457 case CXXCopyConstructor:
9458 case CXXCopyAssignment: {
9459 // Trivial copy operations always have const, non-volatile parameter types.
9461 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9462 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9463 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9465 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9466 << Param0->getSourceRange() << Param0->getType()
9467 << Context.getLValueReferenceType(
9468 Context.getRecordType(RD).withConst());
9474 case CXXMoveConstructor:
9475 case CXXMoveAssignment: {
9476 // Trivial move operations always have non-cv-qualified parameters.
9477 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9478 const RValueReferenceType *RT =
9479 Param0->getType()->getAs<RValueReferenceType>();
9480 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9482 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9483 << Param0->getSourceRange() << Param0->getType()
9484 << Context.getRValueReferenceType(Context.getRecordType(RD));
9491 llvm_unreachable("not a special member");
9494 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9496 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9497 diag::note_nontrivial_default_arg)
9498 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9501 if (MD->isVariadic()) {
9503 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9507 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9508 // A copy/move [constructor or assignment operator] is trivial if
9509 // -- the [member] selected to copy/move each direct base class subobject
9512 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9513 // A [default constructor or destructor] is trivial if
9514 // -- all the direct base classes have trivial [default constructors or
9516 for (const auto &BI : RD->bases())
9517 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9518 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9521 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9522 // A copy/move [constructor or assignment operator] for a class X is
9524 // -- for each non-static data member of X that is of class type (or array
9525 // thereof), the constructor selected to copy/move that member is
9528 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9529 // A [default constructor or destructor] is trivial if
9530 // -- for all of the non-static data members of its class that are of class
9531 // type (or array thereof), each such class has a trivial [default
9532 // constructor or destructor]
9533 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9536 // C++11 [class.dtor]p5:
9537 // A destructor is trivial if [...]
9538 // -- the destructor is not virtual
9539 if (CSM == CXXDestructor && MD->isVirtual()) {
9541 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9545 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9546 // A [special member] for class X is trivial if [...]
9547 // -- class X has no virtual functions and no virtual base classes
9548 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9552 if (RD->getNumVBases()) {
9553 // Check for virtual bases. We already know that the corresponding
9554 // member in all bases is trivial, so vbases must all be direct.
9555 CXXBaseSpecifier &BS = *RD->vbases_begin();
9556 assert(BS.isVirtual());
9557 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9561 // Must have a virtual method.
9562 for (const auto *MI : RD->methods()) {
9563 if (MI->isVirtual()) {
9564 SourceLocation MLoc = MI->getBeginLoc();
9565 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9570 llvm_unreachable("dynamic class with no vbases and no virtual functions");
9573 // Looks like it's trivial!
9578 struct FindHiddenVirtualMethod {
9580 CXXMethodDecl *Method;
9581 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9582 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9585 /// Check whether any most overridden method from MD in Methods
9586 static bool CheckMostOverridenMethods(
9587 const CXXMethodDecl *MD,
9588 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9589 if (MD->size_overridden_methods() == 0)
9590 return Methods.count(MD->getCanonicalDecl());
9591 for (const CXXMethodDecl *O : MD->overridden_methods())
9592 if (CheckMostOverridenMethods(O, Methods))
9598 /// Member lookup function that determines whether a given C++
9599 /// method overloads virtual methods in a base class without overriding any,
9600 /// to be used with CXXRecordDecl::lookupInBases().
9601 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9602 RecordDecl *BaseRecord =
9603 Specifier->getType()->castAs<RecordType>()->getDecl();
9605 DeclarationName Name = Method->getDeclName();
9606 assert(Name.getNameKind() == DeclarationName::Identifier);
9608 bool foundSameNameMethod = false;
9609 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9610 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
9611 Path.Decls = Path.Decls.slice(1)) {
9612 NamedDecl *D = Path.Decls.front();
9613 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9614 MD = MD->getCanonicalDecl();
9615 foundSameNameMethod = true;
9616 // Interested only in hidden virtual methods.
9617 if (!MD->isVirtual())
9619 // If the method we are checking overrides a method from its base
9620 // don't warn about the other overloaded methods. Clang deviates from
9621 // GCC by only diagnosing overloads of inherited virtual functions that
9622 // do not override any other virtual functions in the base. GCC's
9623 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9624 // function from a base class. These cases may be better served by a
9625 // warning (not specific to virtual functions) on call sites when the
9626 // call would select a different function from the base class, were it
9628 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9629 if (!S->IsOverload(Method, MD, false))
9631 // Collect the overload only if its hidden.
9632 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9633 overloadedMethods.push_back(MD);
9637 if (foundSameNameMethod)
9638 OverloadedMethods.append(overloadedMethods.begin(),
9639 overloadedMethods.end());
9640 return foundSameNameMethod;
9643 } // end anonymous namespace
9645 /// Add the most overriden methods from MD to Methods
9646 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9647 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9648 if (MD->size_overridden_methods() == 0)
9649 Methods.insert(MD->getCanonicalDecl());
9651 for (const CXXMethodDecl *O : MD->overridden_methods())
9652 AddMostOverridenMethods(O, Methods);
9655 /// Check if a method overloads virtual methods in a base class without
9657 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9658 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9659 if (!MD->getDeclName().isIdentifier())
9662 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9663 /*bool RecordPaths=*/false,
9664 /*bool DetectVirtual=*/false);
9665 FindHiddenVirtualMethod FHVM;
9669 // Keep the base methods that were overridden or introduced in the subclass
9670 // by 'using' in a set. A base method not in this set is hidden.
9671 CXXRecordDecl *DC = MD->getParent();
9672 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9673 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9675 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9676 ND = shad->getTargetDecl();
9677 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9678 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9681 if (DC->lookupInBases(FHVM, Paths))
9682 OverloadedMethods = FHVM.OverloadedMethods;
9685 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9686 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9687 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9688 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9689 PartialDiagnostic PD = PDiag(
9690 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9691 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9692 Diag(overloadedMD->getLocation(), PD);
9696 /// Diagnose methods which overload virtual methods in a base class
9697 /// without overriding any.
9698 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9699 if (MD->isInvalidDecl())
9702 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9705 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9706 FindHiddenVirtualMethods(MD, OverloadedMethods);
9707 if (!OverloadedMethods.empty()) {
9708 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9709 << MD << (OverloadedMethods.size() > 1);
9711 NoteHiddenVirtualMethods(MD, OverloadedMethods);
9715 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9716 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9717 // No diagnostics if this is a template instantiation.
9718 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9719 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9720 diag::ext_cannot_use_trivial_abi) << &RD;
9721 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9722 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9724 RD.dropAttr<TrivialABIAttr>();
9727 // Ill-formed if the copy and move constructors are deleted.
9728 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9729 // If the type is dependent, then assume it might have
9730 // implicit copy or move ctor because we won't know yet at this point.
9731 if (RD.isDependentType())
9733 if (RD.needsImplicitCopyConstructor() &&
9734 !RD.defaultedCopyConstructorIsDeleted())
9736 if (RD.needsImplicitMoveConstructor() &&
9737 !RD.defaultedMoveConstructorIsDeleted())
9739 for (const CXXConstructorDecl *CD : RD.ctors())
9740 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9745 if (!HasNonDeletedCopyOrMoveConstructor()) {
9746 PrintDiagAndRemoveAttr(0);
9750 // Ill-formed if the struct has virtual functions.
9751 if (RD.isPolymorphic()) {
9752 PrintDiagAndRemoveAttr(1);
9756 for (const auto &B : RD.bases()) {
9757 // Ill-formed if the base class is non-trivial for the purpose of calls or a
9759 if (!B.getType()->isDependentType() &&
9760 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9761 PrintDiagAndRemoveAttr(2);
9765 if (B.isVirtual()) {
9766 PrintDiagAndRemoveAttr(3);
9771 for (const auto *FD : RD.fields()) {
9772 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9773 // non-trivial for the purpose of calls.
9774 QualType FT = FD->getType();
9775 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9776 PrintDiagAndRemoveAttr(4);
9780 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9781 if (!RT->isDependentType() &&
9782 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9783 PrintDiagAndRemoveAttr(5);
9789 void Sema::ActOnFinishCXXMemberSpecification(
9790 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9791 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9795 AdjustDeclIfTemplate(TagDecl);
9797 for (const ParsedAttr &AL : AttrList) {
9798 if (AL.getKind() != ParsedAttr::AT_Visibility)
9801 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9804 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9805 // strict aliasing violation!
9806 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9807 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9809 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9812 /// Find the equality comparison functions that should be implicitly declared
9813 /// in a given class definition, per C++2a [class.compare.default]p3.
9814 static void findImplicitlyDeclaredEqualityComparisons(
9815 ASTContext &Ctx, CXXRecordDecl *RD,
9816 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9817 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9818 if (!RD->lookup(EqEq).empty())
9819 // Member operator== explicitly declared: no implicit operator==s.
9822 // Traverse friends looking for an '==' or a '<=>'.
9823 for (FriendDecl *Friend : RD->friends()) {
9824 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9827 if (FD->getOverloadedOperator() == OO_EqualEqual) {
9828 // Friend operator== explicitly declared: no implicit operator==s.
9833 if (FD->getOverloadedOperator() == OO_Spaceship &&
9834 FD->isExplicitlyDefaulted())
9835 Spaceships.push_back(FD);
9838 // Look for members named 'operator<=>'.
9839 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
9840 for (NamedDecl *ND : RD->lookup(Cmp)) {
9841 // Note that we could find a non-function here (either a function template
9842 // or a using-declaration). Neither case results in an implicit
9844 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9845 if (FD->isExplicitlyDefaulted())
9846 Spaceships.push_back(FD);
9850 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
9851 /// special functions, such as the default constructor, copy
9852 /// constructor, or destructor, to the given C++ class (C++
9853 /// [special]p1). This routine can only be executed just before the
9854 /// definition of the class is complete.
9855 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
9856 // Don't add implicit special members to templated classes.
9857 // FIXME: This means unqualified lookups for 'operator=' within a class
9858 // template don't work properly.
9859 if (!ClassDecl->isDependentType()) {
9860 if (ClassDecl->needsImplicitDefaultConstructor()) {
9861 ++getASTContext().NumImplicitDefaultConstructors;
9863 if (ClassDecl->hasInheritedConstructor())
9864 DeclareImplicitDefaultConstructor(ClassDecl);
9867 if (ClassDecl->needsImplicitCopyConstructor()) {
9868 ++getASTContext().NumImplicitCopyConstructors;
9870 // If the properties or semantics of the copy constructor couldn't be
9871 // determined while the class was being declared, force a declaration
9873 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
9874 ClassDecl->hasInheritedConstructor())
9875 DeclareImplicitCopyConstructor(ClassDecl);
9876 // For the MS ABI we need to know whether the copy ctor is deleted. A
9877 // prerequisite for deleting the implicit copy ctor is that the class has
9878 // a move ctor or move assignment that is either user-declared or whose
9879 // semantics are inherited from a subobject. FIXME: We should provide a
9880 // more direct way for CodeGen to ask whether the constructor was deleted.
9881 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9882 (ClassDecl->hasUserDeclaredMoveConstructor() ||
9883 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9884 ClassDecl->hasUserDeclaredMoveAssignment() ||
9885 ClassDecl->needsOverloadResolutionForMoveAssignment()))
9886 DeclareImplicitCopyConstructor(ClassDecl);
9889 if (getLangOpts().CPlusPlus11 &&
9890 ClassDecl->needsImplicitMoveConstructor()) {
9891 ++getASTContext().NumImplicitMoveConstructors;
9893 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
9894 ClassDecl->hasInheritedConstructor())
9895 DeclareImplicitMoveConstructor(ClassDecl);
9898 if (ClassDecl->needsImplicitCopyAssignment()) {
9899 ++getASTContext().NumImplicitCopyAssignmentOperators;
9901 // If we have a dynamic class, then the copy assignment operator may be
9902 // virtual, so we have to declare it immediately. This ensures that, e.g.,
9903 // it shows up in the right place in the vtable and that we diagnose
9904 // problems with the implicit exception specification.
9905 if (ClassDecl->isDynamicClass() ||
9906 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
9907 ClassDecl->hasInheritedAssignment())
9908 DeclareImplicitCopyAssignment(ClassDecl);
9911 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
9912 ++getASTContext().NumImplicitMoveAssignmentOperators;
9914 // Likewise for the move assignment operator.
9915 if (ClassDecl->isDynamicClass() ||
9916 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
9917 ClassDecl->hasInheritedAssignment())
9918 DeclareImplicitMoveAssignment(ClassDecl);
9921 if (ClassDecl->needsImplicitDestructor()) {
9922 ++getASTContext().NumImplicitDestructors;
9924 // If we have a dynamic class, then the destructor may be virtual, so we
9925 // have to declare the destructor immediately. This ensures that, e.g., it
9926 // shows up in the right place in the vtable and that we diagnose problems
9927 // with the implicit exception specification.
9928 if (ClassDecl->isDynamicClass() ||
9929 ClassDecl->needsOverloadResolutionForDestructor())
9930 DeclareImplicitDestructor(ClassDecl);
9934 // C++2a [class.compare.default]p3:
9935 // If the member-specification does not explicitly declare any member or
9936 // friend named operator==, an == operator function is declared implicitly
9937 // for each defaulted three-way comparison operator function defined in
9938 // the member-specification
9939 // FIXME: Consider doing this lazily.
9940 // We do this during the initial parse for a class template, not during
9941 // instantiation, so that we can handle unqualified lookups for 'operator=='
9942 // when parsing the template.
9943 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
9944 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
9945 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
9946 DefaultedSpaceships);
9947 for (auto *FD : DefaultedSpaceships)
9948 DeclareImplicitEqualityComparison(ClassDecl, FD);
9953 Sema::ActOnReenterTemplateScope(Decl *D,
9954 llvm::function_ref<Scope *()> EnterScope) {
9957 AdjustDeclIfTemplate(D);
9959 // In order to get name lookup right, reenter template scopes in order from
9960 // outermost to innermost.
9961 SmallVector<TemplateParameterList *, 4> ParameterLists;
9962 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
9964 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
9965 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
9966 ParameterLists.push_back(DD->getTemplateParameterList(i));
9968 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9969 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
9970 ParameterLists.push_back(FTD->getTemplateParameters());
9971 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
9972 LookupDC = VD->getDeclContext();
9974 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
9975 ParameterLists.push_back(VTD->getTemplateParameters());
9976 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
9977 ParameterLists.push_back(PSD->getTemplateParameters());
9979 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9980 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
9981 ParameterLists.push_back(TD->getTemplateParameterList(i));
9983 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
9984 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
9985 ParameterLists.push_back(CTD->getTemplateParameters());
9986 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
9987 ParameterLists.push_back(PSD->getTemplateParameters());
9990 // FIXME: Alias declarations and concepts.
9993 Scope *InnermostTemplateScope = nullptr;
9994 for (TemplateParameterList *Params : ParameterLists) {
9995 // Ignore explicit specializations; they don't contribute to the template
9997 if (Params->size() == 0)
10000 InnermostTemplateScope = EnterScope();
10001 for (NamedDecl *Param : *Params) {
10002 if (Param->getDeclName()) {
10003 InnermostTemplateScope->AddDecl(Param);
10004 IdResolver.AddDecl(Param);
10010 // Associate the new template scopes with the corresponding entities.
10011 if (InnermostTemplateScope) {
10012 assert(LookupDC && "no enclosing DeclContext for template lookup");
10013 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10019 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10020 if (!RecordD) return;
10021 AdjustDeclIfTemplate(RecordD);
10022 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10023 PushDeclContext(S, Record);
10026 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10027 if (!RecordD) return;
10031 /// This is used to implement the constant expression evaluation part of the
10032 /// attribute enable_if extension. There is nothing in standard C++ which would
10033 /// require reentering parameters.
10034 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10039 if (Param->getDeclName())
10040 IdResolver.AddDecl(Param);
10043 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
10044 /// parsing a top-level (non-nested) C++ class, and we are now
10045 /// parsing those parts of the given Method declaration that could
10046 /// not be parsed earlier (C++ [class.mem]p2), such as default
10047 /// arguments. This action should enter the scope of the given
10048 /// Method declaration as if we had just parsed the qualified method
10049 /// name. However, it should not bring the parameters into scope;
10050 /// that will be performed by ActOnDelayedCXXMethodParameter.
10051 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10054 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
10055 /// C++ method declaration. We're (re-)introducing the given
10056 /// function parameter into scope for use in parsing later parts of
10057 /// the method declaration. For example, we could see an
10058 /// ActOnParamDefaultArgument event for this parameter.
10059 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10063 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10066 if (Param->getDeclName())
10067 IdResolver.AddDecl(Param);
10070 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10071 /// processing the delayed method declaration for Method. The method
10072 /// declaration is now considered finished. There may be a separate
10073 /// ActOnStartOfFunctionDef action later (not necessarily
10074 /// immediately!) for this method, if it was also defined inside the
10076 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10080 AdjustDeclIfTemplate(MethodD);
10082 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10084 // Now that we have our default arguments, check the constructor
10085 // again. It could produce additional diagnostics or affect whether
10086 // the class has implicitly-declared destructors, among other
10088 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10089 CheckConstructor(Constructor);
10091 // Check the default arguments, which we may have added.
10092 if (!Method->isInvalidDecl())
10093 CheckCXXDefaultArguments(Method);
10096 // Emit the given diagnostic for each non-address-space qualifier.
10097 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10098 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10099 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10100 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10101 bool DiagOccured = false;
10102 FTI.MethodQualifiers->forEachQualifier(
10103 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10104 SourceLocation SL) {
10105 // This diagnostic should be emitted on any qualifier except an addr
10106 // space qualifier. However, forEachQualifier currently doesn't visit
10107 // addr space qualifiers, so there's no way to write this condition
10108 // right now; we just diagnose on everything.
10109 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10110 DiagOccured = true;
10113 D.setInvalidType();
10117 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10118 /// the well-formedness of the constructor declarator @p D with type @p
10119 /// R. If there are any errors in the declarator, this routine will
10120 /// emit diagnostics and set the invalid bit to true. In any case, the type
10121 /// will be updated to reflect a well-formed type for the constructor and
10123 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10124 StorageClass &SC) {
10125 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10127 // C++ [class.ctor]p3:
10128 // A constructor shall not be virtual (10.3) or static (9.4). A
10129 // constructor can be invoked for a const, volatile or const
10130 // volatile object. A constructor shall not be declared const,
10131 // volatile, or const volatile (9.3.2).
10133 if (!D.isInvalidType())
10134 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10135 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10136 << SourceRange(D.getIdentifierLoc());
10137 D.setInvalidType();
10139 if (SC == SC_Static) {
10140 if (!D.isInvalidType())
10141 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10142 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10143 << SourceRange(D.getIdentifierLoc());
10144 D.setInvalidType();
10148 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10149 diagnoseIgnoredQualifiers(
10150 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10151 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10152 D.getDeclSpec().getRestrictSpecLoc(),
10153 D.getDeclSpec().getAtomicSpecLoc());
10154 D.setInvalidType();
10157 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10159 // C++0x [class.ctor]p4:
10160 // A constructor shall not be declared with a ref-qualifier.
10161 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10162 if (FTI.hasRefQualifier()) {
10163 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10164 << FTI.RefQualifierIsLValueRef
10165 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10166 D.setInvalidType();
10169 // Rebuild the function type "R" without any type qualifiers (in
10170 // case any of the errors above fired) and with "void" as the
10171 // return type, since constructors don't have return types.
10172 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10173 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10176 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10177 EPI.TypeQuals = Qualifiers();
10178 EPI.RefQualifier = RQ_None;
10180 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10183 /// CheckConstructor - Checks a fully-formed constructor for
10184 /// well-formedness, issuing any diagnostics required. Returns true if
10185 /// the constructor declarator is invalid.
10186 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10187 CXXRecordDecl *ClassDecl
10188 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10190 return Constructor->setInvalidDecl();
10192 // C++ [class.copy]p3:
10193 // A declaration of a constructor for a class X is ill-formed if
10194 // its first parameter is of type (optionally cv-qualified) X and
10195 // either there are no other parameters or else all other
10196 // parameters have default arguments.
10197 if (!Constructor->isInvalidDecl() &&
10198 Constructor->hasOneParamOrDefaultArgs() &&
10199 Constructor->getTemplateSpecializationKind() !=
10200 TSK_ImplicitInstantiation) {
10201 QualType ParamType = Constructor->getParamDecl(0)->getType();
10202 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10203 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10204 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10205 const char *ConstRef
10206 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10208 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10209 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10211 // FIXME: Rather that making the constructor invalid, we should endeavor
10212 // to fix the type.
10213 Constructor->setInvalidDecl();
10218 /// CheckDestructor - Checks a fully-formed destructor definition for
10219 /// well-formedness, issuing any diagnostics required. Returns true
10221 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10222 CXXRecordDecl *RD = Destructor->getParent();
10224 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10225 SourceLocation Loc;
10227 if (!Destructor->isImplicit())
10228 Loc = Destructor->getLocation();
10230 Loc = RD->getLocation();
10232 // If we have a virtual destructor, look up the deallocation function
10233 if (FunctionDecl *OperatorDelete =
10234 FindDeallocationFunctionForDestructor(Loc, RD)) {
10235 Expr *ThisArg = nullptr;
10237 // If the notional 'delete this' expression requires a non-trivial
10238 // conversion from 'this' to the type of a destroying operator delete's
10239 // first parameter, perform that conversion now.
10240 if (OperatorDelete->isDestroyingOperatorDelete()) {
10241 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10242 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10243 // C++ [class.dtor]p13:
10244 // ... as if for the expression 'delete this' appearing in a
10245 // non-virtual destructor of the destructor's class.
10246 ContextRAII SwitchContext(*this, Destructor);
10248 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10249 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
10250 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10251 if (This.isInvalid()) {
10252 // FIXME: Register this as a context note so that it comes out
10253 // in the right order.
10254 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10257 ThisArg = This.get();
10261 DiagnoseUseOfDecl(OperatorDelete, Loc);
10262 MarkFunctionReferenced(Loc, OperatorDelete);
10263 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10270 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10271 /// the well-formednes of the destructor declarator @p D with type @p
10272 /// R. If there are any errors in the declarator, this routine will
10273 /// emit diagnostics and set the declarator to invalid. Even if this happens,
10274 /// will be updated to reflect a well-formed type for the destructor and
10276 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10277 StorageClass& SC) {
10278 // C++ [class.dtor]p1:
10279 // [...] A typedef-name that names a class is a class-name
10280 // (7.1.3); however, a typedef-name that names a class shall not
10281 // be used as the identifier in the declarator for a destructor
10283 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10284 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10285 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10286 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10287 else if (const TemplateSpecializationType *TST =
10288 DeclaratorType->getAs<TemplateSpecializationType>())
10289 if (TST->isTypeAlias())
10290 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10291 << DeclaratorType << 1;
10293 // C++ [class.dtor]p2:
10294 // A destructor is used to destroy objects of its class type. A
10295 // destructor takes no parameters, and no return type can be
10296 // specified for it (not even void). The address of a destructor
10297 // shall not be taken. A destructor shall not be static. A
10298 // destructor can be invoked for a const, volatile or const
10299 // volatile object. A destructor shall not be declared const,
10300 // volatile or const volatile (9.3.2).
10301 if (SC == SC_Static) {
10302 if (!D.isInvalidType())
10303 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10304 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10305 << SourceRange(D.getIdentifierLoc())
10306 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10310 if (!D.isInvalidType()) {
10311 // Destructors don't have return types, but the parser will
10312 // happily parse something like:
10318 // The return type will be eliminated later.
10319 if (D.getDeclSpec().hasTypeSpecifier())
10320 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10321 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10322 << SourceRange(D.getIdentifierLoc());
10323 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10324 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10326 D.getDeclSpec().getConstSpecLoc(),
10327 D.getDeclSpec().getVolatileSpecLoc(),
10328 D.getDeclSpec().getRestrictSpecLoc(),
10329 D.getDeclSpec().getAtomicSpecLoc());
10330 D.setInvalidType();
10334 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10336 // C++0x [class.dtor]p2:
10337 // A destructor shall not be declared with a ref-qualifier.
10338 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10339 if (FTI.hasRefQualifier()) {
10340 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10341 << FTI.RefQualifierIsLValueRef
10342 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10343 D.setInvalidType();
10346 // Make sure we don't have any parameters.
10347 if (FTIHasNonVoidParameters(FTI)) {
10348 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10350 // Delete the parameters.
10352 D.setInvalidType();
10355 // Make sure the destructor isn't variadic.
10356 if (FTI.isVariadic) {
10357 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10358 D.setInvalidType();
10361 // Rebuild the function type "R" without any type qualifiers or
10362 // parameters (in case any of the errors above fired) and with
10363 // "void" as the return type, since destructors don't have return
10365 if (!D.isInvalidType())
10368 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10369 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10370 EPI.Variadic = false;
10371 EPI.TypeQuals = Qualifiers();
10372 EPI.RefQualifier = RQ_None;
10373 return Context.getFunctionType(Context.VoidTy, None, EPI);
10376 static void extendLeft(SourceRange &R, SourceRange Before) {
10377 if (Before.isInvalid())
10379 R.setBegin(Before.getBegin());
10380 if (R.getEnd().isInvalid())
10381 R.setEnd(Before.getEnd());
10384 static void extendRight(SourceRange &R, SourceRange After) {
10385 if (After.isInvalid())
10387 if (R.getBegin().isInvalid())
10388 R.setBegin(After.getBegin());
10389 R.setEnd(After.getEnd());
10392 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10393 /// well-formednes of the conversion function declarator @p D with
10394 /// type @p R. If there are any errors in the declarator, this routine
10395 /// will emit diagnostics and return true. Otherwise, it will return
10396 /// false. Either way, the type @p R will be updated to reflect a
10397 /// well-formed type for the conversion operator.
10398 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10399 StorageClass& SC) {
10400 // C++ [class.conv.fct]p1:
10401 // Neither parameter types nor return type can be specified. The
10402 // type of a conversion function (8.3.5) is "function taking no
10403 // parameter returning conversion-type-id."
10404 if (SC == SC_Static) {
10405 if (!D.isInvalidType())
10406 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10407 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10408 << D.getName().getSourceRange();
10409 D.setInvalidType();
10413 TypeSourceInfo *ConvTSI = nullptr;
10414 QualType ConvType =
10415 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10417 const DeclSpec &DS = D.getDeclSpec();
10418 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10419 // Conversion functions don't have return types, but the parser will
10420 // happily parse something like:
10423 // float operator bool();
10426 // The return type will be changed later anyway.
10427 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10428 << SourceRange(DS.getTypeSpecTypeLoc())
10429 << SourceRange(D.getIdentifierLoc());
10430 D.setInvalidType();
10431 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10432 // It's also plausible that the user writes type qualifiers in the wrong
10434 // struct S { const operator int(); };
10435 // FIXME: we could provide a fixit to move the qualifiers onto the
10436 // conversion type.
10437 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10438 << SourceRange(D.getIdentifierLoc()) << 0;
10439 D.setInvalidType();
10442 const auto *Proto = R->castAs<FunctionProtoType>();
10444 // Make sure we don't have any parameters.
10445 if (Proto->getNumParams() > 0) {
10446 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10448 // Delete the parameters.
10449 D.getFunctionTypeInfo().freeParams();
10450 D.setInvalidType();
10451 } else if (Proto->isVariadic()) {
10452 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10453 D.setInvalidType();
10456 // Diagnose "&operator bool()" and other such nonsense. This
10457 // is actually a gcc extension which we don't support.
10458 if (Proto->getReturnType() != ConvType) {
10459 bool NeedsTypedef = false;
10460 SourceRange Before, After;
10462 // Walk the chunks and extract information on them for our diagnostic.
10463 bool PastFunctionChunk = false;
10464 for (auto &Chunk : D.type_objects()) {
10465 switch (Chunk.Kind) {
10466 case DeclaratorChunk::Function:
10467 if (!PastFunctionChunk) {
10468 if (Chunk.Fun.HasTrailingReturnType) {
10469 TypeSourceInfo *TRT = nullptr;
10470 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10471 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10473 PastFunctionChunk = true;
10477 case DeclaratorChunk::Array:
10478 NeedsTypedef = true;
10479 extendRight(After, Chunk.getSourceRange());
10482 case DeclaratorChunk::Pointer:
10483 case DeclaratorChunk::BlockPointer:
10484 case DeclaratorChunk::Reference:
10485 case DeclaratorChunk::MemberPointer:
10486 case DeclaratorChunk::Pipe:
10487 extendLeft(Before, Chunk.getSourceRange());
10490 case DeclaratorChunk::Paren:
10491 extendLeft(Before, Chunk.Loc);
10492 extendRight(After, Chunk.EndLoc);
10497 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10498 After.isValid() ? After.getBegin() :
10499 D.getIdentifierLoc();
10500 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10501 DB << Before << After;
10503 if (!NeedsTypedef) {
10504 DB << /*don't need a typedef*/0;
10506 // If we can provide a correct fix-it hint, do so.
10507 if (After.isInvalid() && ConvTSI) {
10508 SourceLocation InsertLoc =
10509 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10510 DB << FixItHint::CreateInsertion(InsertLoc, " ")
10511 << FixItHint::CreateInsertionFromRange(
10512 InsertLoc, CharSourceRange::getTokenRange(Before))
10513 << FixItHint::CreateRemoval(Before);
10515 } else if (!Proto->getReturnType()->isDependentType()) {
10516 DB << /*typedef*/1 << Proto->getReturnType();
10517 } else if (getLangOpts().CPlusPlus11) {
10518 DB << /*alias template*/2 << Proto->getReturnType();
10520 DB << /*might not be fixable*/3;
10523 // Recover by incorporating the other type chunks into the result type.
10524 // Note, this does *not* change the name of the function. This is compatible
10525 // with the GCC extension:
10526 // struct S { &operator int(); } s;
10527 // int &r = s.operator int(); // ok in GCC
10528 // S::operator int&() {} // error in GCC, function name is 'operator int'.
10529 ConvType = Proto->getReturnType();
10532 // C++ [class.conv.fct]p4:
10533 // The conversion-type-id shall not represent a function type nor
10535 if (ConvType->isArrayType()) {
10536 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10537 ConvType = Context.getPointerType(ConvType);
10538 D.setInvalidType();
10539 } else if (ConvType->isFunctionType()) {
10540 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10541 ConvType = Context.getPointerType(ConvType);
10542 D.setInvalidType();
10545 // Rebuild the function type "R" without any parameters (in case any
10546 // of the errors above fired) and with the conversion type as the
10548 if (D.isInvalidType())
10549 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10551 // C++0x explicit conversion operators.
10552 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10553 Diag(DS.getExplicitSpecLoc(),
10554 getLangOpts().CPlusPlus11
10555 ? diag::warn_cxx98_compat_explicit_conversion_functions
10556 : diag::ext_explicit_conversion_functions)
10557 << SourceRange(DS.getExplicitSpecRange());
10560 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10561 /// the declaration of the given C++ conversion function. This routine
10562 /// is responsible for recording the conversion function in the C++
10563 /// class, if possible.
10564 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10565 assert(Conversion && "Expected to receive a conversion function declaration");
10567 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10569 // Make sure we aren't redeclaring the conversion function.
10570 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10571 // C++ [class.conv.fct]p1:
10572 // [...] A conversion function is never used to convert a
10573 // (possibly cv-qualified) object to the (possibly cv-qualified)
10574 // same object type (or a reference to it), to a (possibly
10575 // cv-qualified) base class of that type (or a reference to it),
10576 // or to (possibly cv-qualified) void.
10578 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10579 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10580 ConvType = ConvTypeRef->getPointeeType();
10581 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10582 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10583 /* Suppress diagnostics for instantiations. */;
10584 else if (Conversion->size_overridden_methods() != 0)
10585 /* Suppress diagnostics for overriding virtual function in a base class. */;
10586 else if (ConvType->isRecordType()) {
10587 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10588 if (ConvType == ClassType)
10589 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10591 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10592 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10593 << ClassType << ConvType;
10594 } else if (ConvType->isVoidType()) {
10595 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10596 << ClassType << ConvType;
10599 if (FunctionTemplateDecl *ConversionTemplate
10600 = Conversion->getDescribedFunctionTemplate())
10601 return ConversionTemplate;
10607 /// Utility class to accumulate and print a diagnostic listing the invalid
10608 /// specifier(s) on a declaration.
10609 struct BadSpecifierDiagnoser {
10610 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10611 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10612 ~BadSpecifierDiagnoser() {
10613 Diagnostic << Specifiers;
10616 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10617 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10619 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10620 return check(SpecLoc,
10621 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10623 void check(SourceLocation SpecLoc, const char *Spec) {
10624 if (SpecLoc.isInvalid()) return;
10625 Diagnostic << SourceRange(SpecLoc, SpecLoc);
10626 if (!Specifiers.empty()) Specifiers += " ";
10627 Specifiers += Spec;
10631 Sema::SemaDiagnosticBuilder Diagnostic;
10632 std::string Specifiers;
10636 /// Check the validity of a declarator that we parsed for a deduction-guide.
10637 /// These aren't actually declarators in the grammar, so we need to check that
10638 /// the user didn't specify any pieces that are not part of the deduction-guide
10640 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10641 StorageClass &SC) {
10642 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10643 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10644 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
10646 // C++ [temp.deduct.guide]p3:
10647 // A deduction-gide shall be declared in the same scope as the
10648 // corresponding class template.
10649 if (!CurContext->getRedeclContext()->Equals(
10650 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10651 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10652 << GuidedTemplateDecl;
10653 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10656 auto &DS = D.getMutableDeclSpec();
10657 // We leave 'friend' and 'virtual' to be rejected in the normal way.
10658 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10659 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10660 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10661 BadSpecifierDiagnoser Diagnoser(
10662 *this, D.getIdentifierLoc(),
10663 diag::err_deduction_guide_invalid_specifier);
10665 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10666 DS.ClearStorageClassSpecs();
10669 // 'explicit' is permitted.
10670 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10671 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10672 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10673 DS.ClearConstexprSpec();
10675 Diagnoser.check(DS.getConstSpecLoc(), "const");
10676 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10677 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10678 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10679 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10680 DS.ClearTypeQualifiers();
10682 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10683 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10684 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10685 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10686 DS.ClearTypeSpecType();
10689 if (D.isInvalidType())
10692 // Check the declarator is simple enough.
10693 bool FoundFunction = false;
10694 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10695 if (Chunk.Kind == DeclaratorChunk::Paren)
10697 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10698 Diag(D.getDeclSpec().getBeginLoc(),
10699 diag::err_deduction_guide_with_complex_decl)
10700 << D.getSourceRange();
10703 if (!Chunk.Fun.hasTrailingReturnType()) {
10704 Diag(D.getName().getBeginLoc(),
10705 diag::err_deduction_guide_no_trailing_return_type);
10709 // Check that the return type is written as a specialization of
10710 // the template specified as the deduction-guide's name.
10711 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10712 TypeSourceInfo *TSI = nullptr;
10713 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10714 assert(TSI && "deduction guide has valid type but invalid return type?");
10715 bool AcceptableReturnType = false;
10716 bool MightInstantiateToSpecialization = false;
10718 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10719 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10720 bool TemplateMatches =
10721 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10722 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10723 AcceptableReturnType = true;
10725 // This could still instantiate to the right type, unless we know it
10726 // names the wrong class template.
10727 auto *TD = SpecifiedName.getAsTemplateDecl();
10728 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10731 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10732 MightInstantiateToSpecialization = true;
10735 if (!AcceptableReturnType) {
10736 Diag(TSI->getTypeLoc().getBeginLoc(),
10737 diag::err_deduction_guide_bad_trailing_return_type)
10738 << GuidedTemplate << TSI->getType()
10739 << MightInstantiateToSpecialization
10740 << TSI->getTypeLoc().getSourceRange();
10743 // Keep going to check that we don't have any inner declarator pieces (we
10744 // could still have a function returning a pointer to a function).
10745 FoundFunction = true;
10748 if (D.isFunctionDefinition())
10749 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10752 //===----------------------------------------------------------------------===//
10753 // Namespace Handling
10754 //===----------------------------------------------------------------------===//
10756 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10758 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10759 SourceLocation Loc,
10760 IdentifierInfo *II, bool *IsInline,
10761 NamespaceDecl *PrevNS) {
10762 assert(*IsInline != PrevNS->isInline());
10764 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
10765 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
10766 // inline namespaces, with the intention of bringing names into namespace std.
10768 // We support this just well enough to get that case working; this is not
10769 // sufficient to support reopening namespaces as inline in general.
10770 if (*IsInline && II && II->getName().startswith("__atomic") &&
10771 S.getSourceManager().isInSystemHeader(Loc)) {
10772 // Mark all prior declarations of the namespace as inline.
10773 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
10774 NS = NS->getPreviousDecl())
10775 NS->setInline(*IsInline);
10776 // Patch up the lookup table for the containing namespace. This isn't really
10777 // correct, but it's good enough for this particular case.
10778 for (auto *I : PrevNS->decls())
10779 if (auto *ND = dyn_cast<NamedDecl>(I))
10780 PrevNS->getParent()->makeDeclVisibleInContext(ND);
10784 if (PrevNS->isInline())
10785 // The user probably just forgot the 'inline', so suggest that it
10787 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10788 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10790 S.Diag(Loc, diag::err_inline_namespace_mismatch);
10792 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10793 *IsInline = PrevNS->isInline();
10796 /// ActOnStartNamespaceDef - This is called at the start of a namespace
10798 Decl *Sema::ActOnStartNamespaceDef(
10799 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10800 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10801 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10802 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10803 // For anonymous namespace, take the location of the left brace.
10804 SourceLocation Loc = II ? IdentLoc : LBrace;
10805 bool IsInline = InlineLoc.isValid();
10806 bool IsInvalid = false;
10807 bool IsStd = false;
10808 bool AddToKnown = false;
10809 Scope *DeclRegionScope = NamespcScope->getParent();
10811 NamespaceDecl *PrevNS = nullptr;
10813 // C++ [namespace.def]p2:
10814 // The identifier in an original-namespace-definition shall not
10815 // have been previously defined in the declarative region in
10816 // which the original-namespace-definition appears. The
10817 // identifier in an original-namespace-definition is the name of
10818 // the namespace. Subsequently in that declarative region, it is
10819 // treated as an original-namespace-name.
10821 // Since namespace names are unique in their scope, and we don't
10822 // look through using directives, just look for any ordinary names
10823 // as if by qualified name lookup.
10824 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10825 ForExternalRedeclaration);
10826 LookupQualifiedName(R, CurContext->getRedeclContext());
10827 NamedDecl *PrevDecl =
10828 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10829 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10832 // This is an extended namespace definition.
10833 if (IsInline != PrevNS->isInline())
10834 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10835 &IsInline, PrevNS);
10836 } else if (PrevDecl) {
10837 // This is an invalid name redefinition.
10838 Diag(Loc, diag::err_redefinition_different_kind)
10840 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10842 // Continue on to push Namespc as current DeclContext and return it.
10843 } else if (II->isStr("std") &&
10844 CurContext->getRedeclContext()->isTranslationUnit()) {
10845 // This is the first "real" definition of the namespace "std", so update
10846 // our cache of the "std" namespace to point at this definition.
10847 PrevNS = getStdNamespace();
10849 AddToKnown = !IsInline;
10851 // We've seen this namespace for the first time.
10852 AddToKnown = !IsInline;
10855 // Anonymous namespaces.
10857 // Determine whether the parent already has an anonymous namespace.
10858 DeclContext *Parent = CurContext->getRedeclContext();
10859 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10860 PrevNS = TU->getAnonymousNamespace();
10862 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
10863 PrevNS = ND->getAnonymousNamespace();
10866 if (PrevNS && IsInline != PrevNS->isInline())
10867 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
10868 &IsInline, PrevNS);
10871 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
10872 StartLoc, Loc, II, PrevNS);
10874 Namespc->setInvalidDecl();
10876 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
10877 AddPragmaAttributes(DeclRegionScope, Namespc);
10879 // FIXME: Should we be merging attributes?
10880 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
10881 PushNamespaceVisibilityAttr(Attr, Loc);
10884 StdNamespace = Namespc;
10886 KnownNamespaces[Namespc] = false;
10889 PushOnScopeChains(Namespc, DeclRegionScope);
10891 // Link the anonymous namespace into its parent.
10892 DeclContext *Parent = CurContext->getRedeclContext();
10893 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
10894 TU->setAnonymousNamespace(Namespc);
10896 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
10899 CurContext->addDecl(Namespc);
10901 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
10902 // behaves as if it were replaced by
10903 // namespace unique { /* empty body */ }
10904 // using namespace unique;
10905 // namespace unique { namespace-body }
10906 // where all occurrences of 'unique' in a translation unit are
10907 // replaced by the same identifier and this identifier differs
10908 // from all other identifiers in the entire program.
10910 // We just create the namespace with an empty name and then add an
10911 // implicit using declaration, just like the standard suggests.
10913 // CodeGen enforces the "universally unique" aspect by giving all
10914 // declarations semantically contained within an anonymous
10915 // namespace internal linkage.
10918 UD = UsingDirectiveDecl::Create(Context, Parent,
10919 /* 'using' */ LBrace,
10920 /* 'namespace' */ SourceLocation(),
10921 /* qualifier */ NestedNameSpecifierLoc(),
10922 /* identifier */ SourceLocation(),
10924 /* Ancestor */ Parent);
10926 Parent->addDecl(UD);
10930 ActOnDocumentableDecl(Namespc);
10932 // Although we could have an invalid decl (i.e. the namespace name is a
10933 // redefinition), push it as current DeclContext and try to continue parsing.
10934 // FIXME: We should be able to push Namespc here, so that the each DeclContext
10935 // for the namespace has the declarations that showed up in that particular
10936 // namespace definition.
10937 PushDeclContext(NamespcScope, Namespc);
10941 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
10942 /// is a namespace alias, returns the namespace it points to.
10943 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
10944 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
10945 return AD->getNamespace();
10946 return dyn_cast_or_null<NamespaceDecl>(D);
10949 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
10950 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
10951 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
10952 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
10953 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
10954 Namespc->setRBraceLoc(RBrace);
10956 if (Namespc->hasAttr<VisibilityAttr>())
10957 PopPragmaVisibility(true, RBrace);
10958 // If this namespace contains an export-declaration, export it now.
10959 if (DeferredExportedNamespaces.erase(Namespc))
10960 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
10963 CXXRecordDecl *Sema::getStdBadAlloc() const {
10964 return cast_or_null<CXXRecordDecl>(
10965 StdBadAlloc.get(Context.getExternalSource()));
10968 EnumDecl *Sema::getStdAlignValT() const {
10969 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
10972 NamespaceDecl *Sema::getStdNamespace() const {
10973 return cast_or_null<NamespaceDecl>(
10974 StdNamespace.get(Context.getExternalSource()));
10977 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
10978 if (!StdExperimentalNamespaceCache) {
10979 if (auto Std = getStdNamespace()) {
10980 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
10981 SourceLocation(), LookupNamespaceName);
10982 if (!LookupQualifiedName(Result, Std) ||
10983 !(StdExperimentalNamespaceCache =
10984 Result.getAsSingle<NamespaceDecl>()))
10985 Result.suppressDiagnostics();
10988 return StdExperimentalNamespaceCache;
10993 enum UnsupportedSTLSelect {
11000 struct InvalidSTLDiagnoser {
11002 SourceLocation Loc;
11003 QualType TyForDiags;
11005 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11006 const VarDecl *VD = nullptr) {
11008 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11009 << TyForDiags << ((int)Sel);
11010 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11011 assert(!Name.empty());
11015 if (Sel == USS_InvalidMember) {
11016 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11017 << VD << VD->getSourceRange();
11024 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11025 SourceLocation Loc,
11026 ComparisonCategoryUsage Usage) {
11027 assert(getLangOpts().CPlusPlus &&
11028 "Looking for comparison category type outside of C++.");
11030 // Use an elaborated type for diagnostics which has a name containing the
11031 // prepended 'std' namespace but not any inline namespace names.
11032 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11034 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11035 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11038 // Check if we've already successfully checked the comparison category type
11039 // before. If so, skip checking it again.
11040 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11041 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11042 // The only thing we need to check is that the type has a reachable
11043 // definition in the current context.
11044 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11047 return Info->getType();
11050 // If lookup failed
11052 std::string NameForDiags = "std::";
11053 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11054 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11055 << NameForDiags << (int)Usage;
11059 assert(Info->Kind == Kind);
11060 assert(Info->Record);
11062 // Update the Record decl in case we encountered a forward declaration on our
11063 // first pass. FIXME: This is a bit of a hack.
11064 if (Info->Record->hasDefinition())
11065 Info->Record = Info->Record->getDefinition();
11067 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11070 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11072 if (!Info->Record->isTriviallyCopyable())
11073 return UnsupportedSTLError(USS_NonTrivial);
11075 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11076 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11077 // Tolerate empty base classes.
11078 if (Base->isEmpty())
11080 // Reject STL implementations which have at least one non-empty base.
11081 return UnsupportedSTLError();
11084 // Check that the STL has implemented the types using a single integer field.
11085 // This expectation allows better codegen for builtin operators. We require:
11086 // (1) The class has exactly one field.
11087 // (2) The field is an integral or enumeration type.
11088 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11089 if (std::distance(FIt, FEnd) != 1 ||
11090 !FIt->getType()->isIntegralOrEnumerationType()) {
11091 return UnsupportedSTLError();
11094 // Build each of the require values and store them in Info.
11095 for (ComparisonCategoryResult CCR :
11096 ComparisonCategories::getPossibleResultsForType(Kind)) {
11097 StringRef MemName = ComparisonCategories::getResultString(CCR);
11098 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11101 return UnsupportedSTLError(USS_MissingMember, MemName);
11103 VarDecl *VD = ValInfo->VD;
11104 assert(VD && "should not be null!");
11106 // Attempt to diagnose reasons why the STL definition of this type
11107 // might be foobar, including it failing to be a constant expression.
11108 // TODO Handle more ways the lookup or result can be invalid.
11109 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
11110 !VD->checkInitIsICE())
11111 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11113 // Attempt to evaluate the var decl as a constant expression and extract
11114 // the value of its first field as a ICE. If this fails, the STL
11115 // implementation is not supported.
11116 if (!ValInfo->hasValidIntValue())
11117 return UnsupportedSTLError();
11119 MarkVariableReferenced(Loc, VD);
11122 // We've successfully built the required types and expressions. Update
11123 // the cache and return the newly cached value.
11124 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11125 return Info->getType();
11128 /// Retrieve the special "std" namespace, which may require us to
11129 /// implicitly define the namespace.
11130 NamespaceDecl *Sema::getOrCreateStdNamespace() {
11131 if (!StdNamespace) {
11132 // The "std" namespace has not yet been defined, so build one implicitly.
11133 StdNamespace = NamespaceDecl::Create(Context,
11134 Context.getTranslationUnitDecl(),
11136 SourceLocation(), SourceLocation(),
11137 &PP.getIdentifierTable().get("std"),
11138 /*PrevDecl=*/nullptr);
11139 getStdNamespace()->setImplicit(true);
11142 return getStdNamespace();
11145 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11146 assert(getLangOpts().CPlusPlus &&
11147 "Looking for std::initializer_list outside of C++.");
11149 // We're looking for implicit instantiations of
11150 // template <typename E> class std::initializer_list.
11152 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11155 ClassTemplateDecl *Template = nullptr;
11156 const TemplateArgument *Arguments = nullptr;
11158 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11160 ClassTemplateSpecializationDecl *Specialization =
11161 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11162 if (!Specialization)
11165 Template = Specialization->getSpecializedTemplate();
11166 Arguments = Specialization->getTemplateArgs().data();
11167 } else if (const TemplateSpecializationType *TST =
11168 Ty->getAs<TemplateSpecializationType>()) {
11169 Template = dyn_cast_or_null<ClassTemplateDecl>(
11170 TST->getTemplateName().getAsTemplateDecl());
11171 Arguments = TST->getArgs();
11176 if (!StdInitializerList) {
11177 // Haven't recognized std::initializer_list yet, maybe this is it.
11178 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11179 if (TemplateClass->getIdentifier() !=
11180 &PP.getIdentifierTable().get("initializer_list") ||
11181 !getStdNamespace()->InEnclosingNamespaceSetOf(
11182 TemplateClass->getDeclContext()))
11184 // This is a template called std::initializer_list, but is it the right
11186 TemplateParameterList *Params = Template->getTemplateParameters();
11187 if (Params->getMinRequiredArguments() != 1)
11189 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11192 // It's the right template.
11193 StdInitializerList = Template;
11196 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11199 // This is an instance of std::initializer_list. Find the argument type.
11201 *Element = Arguments[0].getAsType();
11205 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11206 NamespaceDecl *Std = S.getStdNamespace();
11208 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11212 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11213 Loc, Sema::LookupOrdinaryName);
11214 if (!S.LookupQualifiedName(Result, Std)) {
11215 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11218 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11220 Result.suppressDiagnostics();
11221 // We found something weird. Complain about the first thing we found.
11222 NamedDecl *Found = *Result.begin();
11223 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11227 // We found some template called std::initializer_list. Now verify that it's
11229 TemplateParameterList *Params = Template->getTemplateParameters();
11230 if (Params->getMinRequiredArguments() != 1 ||
11231 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11232 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11239 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11240 if (!StdInitializerList) {
11241 StdInitializerList = LookupStdInitializerList(*this, Loc);
11242 if (!StdInitializerList)
11246 TemplateArgumentListInfo Args(Loc, Loc);
11247 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11248 Context.getTrivialTypeSourceInfo(Element,
11250 return Context.getCanonicalType(
11251 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11254 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11255 // C++ [dcl.init.list]p2:
11256 // A constructor is an initializer-list constructor if its first parameter
11257 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11258 // std::initializer_list<E> for some type E, and either there are no other
11259 // parameters or else all other parameters have default arguments.
11260 if (!Ctor->hasOneParamOrDefaultArgs())
11263 QualType ArgType = Ctor->getParamDecl(0)->getType();
11264 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11265 ArgType = RT->getPointeeType().getUnqualifiedType();
11267 return isStdInitializerList(ArgType, nullptr);
11270 /// Determine whether a using statement is in a context where it will be
11271 /// apply in all contexts.
11272 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11273 switch (CurContext->getDeclKind()) {
11274 case Decl::TranslationUnit:
11276 case Decl::LinkageSpec:
11277 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11285 // Callback to only accept typo corrections that are namespaces.
11286 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11288 bool ValidateCandidate(const TypoCorrection &candidate) override {
11289 if (NamedDecl *ND = candidate.getCorrectionDecl())
11290 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11294 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11295 return std::make_unique<NamespaceValidatorCCC>(*this);
11301 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11303 SourceLocation IdentLoc,
11304 IdentifierInfo *Ident) {
11306 NamespaceValidatorCCC CCC{};
11307 if (TypoCorrection Corrected =
11308 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11309 Sema::CTK_ErrorRecovery)) {
11310 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11311 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11312 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11313 Ident->getName().equals(CorrectedStr);
11314 S.diagnoseTypo(Corrected,
11315 S.PDiag(diag::err_using_directive_member_suggest)
11316 << Ident << DC << DroppedSpecifier << SS.getRange(),
11317 S.PDiag(diag::note_namespace_defined_here));
11319 S.diagnoseTypo(Corrected,
11320 S.PDiag(diag::err_using_directive_suggest) << Ident,
11321 S.PDiag(diag::note_namespace_defined_here));
11323 R.addDecl(Corrected.getFoundDecl());
11329 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11330 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11331 SourceLocation IdentLoc,
11332 IdentifierInfo *NamespcName,
11333 const ParsedAttributesView &AttrList) {
11334 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11335 assert(NamespcName && "Invalid NamespcName.");
11336 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
11338 // This can only happen along a recovery path.
11339 while (S->isTemplateParamScope())
11340 S = S->getParent();
11341 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11343 UsingDirectiveDecl *UDir = nullptr;
11344 NestedNameSpecifier *Qualifier = nullptr;
11346 Qualifier = SS.getScopeRep();
11348 // Lookup namespace name.
11349 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11350 LookupParsedName(R, S, &SS);
11351 if (R.isAmbiguous())
11356 // Allow "using namespace std;" or "using namespace ::std;" even if
11357 // "std" hasn't been defined yet, for GCC compatibility.
11358 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11359 NamespcName->isStr("std")) {
11360 Diag(IdentLoc, diag::ext_using_undefined_std);
11361 R.addDecl(getOrCreateStdNamespace());
11364 // Otherwise, attempt typo correction.
11365 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11369 NamedDecl *Named = R.getRepresentativeDecl();
11370 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11371 assert(NS && "expected namespace decl");
11373 // The use of a nested name specifier may trigger deprecation warnings.
11374 DiagnoseUseOfDecl(Named, IdentLoc);
11376 // C++ [namespace.udir]p1:
11377 // A using-directive specifies that the names in the nominated
11378 // namespace can be used in the scope in which the
11379 // using-directive appears after the using-directive. During
11380 // unqualified name lookup (3.4.1), the names appear as if they
11381 // were declared in the nearest enclosing namespace which
11382 // contains both the using-directive and the nominated
11383 // namespace. [Note: in this context, "contains" means "contains
11384 // directly or indirectly". ]
11386 // Find enclosing context containing both using-directive and
11387 // nominated namespace.
11388 DeclContext *CommonAncestor = NS;
11389 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11390 CommonAncestor = CommonAncestor->getParent();
11392 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11393 SS.getWithLocInContext(Context),
11394 IdentLoc, Named, CommonAncestor);
11396 if (IsUsingDirectiveInToplevelContext(CurContext) &&
11397 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11398 Diag(IdentLoc, diag::warn_using_directive_in_header);
11401 PushUsingDirective(S, UDir);
11403 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11407 ProcessDeclAttributeList(S, UDir, AttrList);
11412 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11413 // If the scope has an associated entity and the using directive is at
11414 // namespace or translation unit scope, add the UsingDirectiveDecl into
11415 // its lookup structure so qualified name lookup can find it.
11416 DeclContext *Ctx = S->getEntity();
11417 if (Ctx && !Ctx->isFunctionOrMethod())
11418 Ctx->addDecl(UDir);
11420 // Otherwise, it is at block scope. The using-directives will affect lookup
11421 // only to the end of the scope.
11422 S->PushUsingDirective(UDir);
11425 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11426 SourceLocation UsingLoc,
11427 SourceLocation TypenameLoc, CXXScopeSpec &SS,
11428 UnqualifiedId &Name,
11429 SourceLocation EllipsisLoc,
11430 const ParsedAttributesView &AttrList) {
11431 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
11433 if (SS.isEmpty()) {
11434 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11438 switch (Name.getKind()) {
11439 case UnqualifiedIdKind::IK_ImplicitSelfParam:
11440 case UnqualifiedIdKind::IK_Identifier:
11441 case UnqualifiedIdKind::IK_OperatorFunctionId:
11442 case UnqualifiedIdKind::IK_LiteralOperatorId:
11443 case UnqualifiedIdKind::IK_ConversionFunctionId:
11446 case UnqualifiedIdKind::IK_ConstructorName:
11447 case UnqualifiedIdKind::IK_ConstructorTemplateId:
11448 // C++11 inheriting constructors.
11449 Diag(Name.getBeginLoc(),
11450 getLangOpts().CPlusPlus11
11451 ? diag::warn_cxx98_compat_using_decl_constructor
11452 : diag::err_using_decl_constructor)
11455 if (getLangOpts().CPlusPlus11) break;
11459 case UnqualifiedIdKind::IK_DestructorName:
11460 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11463 case UnqualifiedIdKind::IK_TemplateId:
11464 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11465 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11468 case UnqualifiedIdKind::IK_DeductionGuideName:
11469 llvm_unreachable("cannot parse qualified deduction guide name");
11472 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11473 DeclarationName TargetName = TargetNameInfo.getName();
11477 // Warn about access declarations.
11478 if (UsingLoc.isInvalid()) {
11479 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11480 ? diag::err_access_decl
11481 : diag::warn_access_decl_deprecated)
11482 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11485 if (EllipsisLoc.isInvalid()) {
11486 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11487 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11490 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11491 !TargetNameInfo.containsUnexpandedParameterPack()) {
11492 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11493 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11494 EllipsisLoc = SourceLocation();
11499 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11500 SS, TargetNameInfo, EllipsisLoc, AttrList,
11501 /*IsInstantiation*/false);
11503 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11508 /// Determine whether a using declaration considers the given
11509 /// declarations as "equivalent", e.g., if they are redeclarations of
11510 /// the same entity or are both typedefs of the same type.
11512 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11513 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11516 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11517 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11518 return Context.hasSameType(TD1->getUnderlyingType(),
11519 TD2->getUnderlyingType());
11525 /// Determines whether to create a using shadow decl for a particular
11526 /// decl, given the set of decls existing prior to this using lookup.
11527 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
11528 const LookupResult &Previous,
11529 UsingShadowDecl *&PrevShadow) {
11530 // Diagnose finding a decl which is not from a base class of the
11531 // current class. We do this now because there are cases where this
11532 // function will silently decide not to build a shadow decl, which
11533 // will pre-empt further diagnostics.
11535 // We don't need to do this in C++11 because we do the check once on
11538 // FIXME: diagnose the following if we care enough:
11539 // struct A { int foo; };
11540 // struct B : A { using A::foo; };
11541 // template <class T> struct C : A {};
11542 // template <class T> struct D : C<T> { using B::foo; } // <---
11543 // This is invalid (during instantiation) in C++03 because B::foo
11544 // resolves to the using decl in B, which is not a base class of D<T>.
11545 // We can't diagnose it immediately because C<T> is an unknown
11546 // specialization. The UsingShadowDecl in D<T> then points directly
11547 // to A::foo, which will look well-formed when we instantiate.
11548 // The right solution is to not collapse the shadow-decl chain.
11549 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
11550 DeclContext *OrigDC = Orig->getDeclContext();
11552 // Handle enums and anonymous structs.
11553 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
11554 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11555 while (OrigRec->isAnonymousStructOrUnion())
11556 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11558 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11559 if (OrigDC == CurContext) {
11560 Diag(Using->getLocation(),
11561 diag::err_using_decl_nested_name_specifier_is_current_class)
11562 << Using->getQualifierLoc().getSourceRange();
11563 Diag(Orig->getLocation(), diag::note_using_decl_target);
11564 Using->setInvalidDecl();
11568 Diag(Using->getQualifierLoc().getBeginLoc(),
11569 diag::err_using_decl_nested_name_specifier_is_not_base_class)
11570 << Using->getQualifier()
11571 << cast<CXXRecordDecl>(CurContext)
11572 << Using->getQualifierLoc().getSourceRange();
11573 Diag(Orig->getLocation(), diag::note_using_decl_target);
11574 Using->setInvalidDecl();
11579 if (Previous.empty()) return false;
11581 NamedDecl *Target = Orig;
11582 if (isa<UsingShadowDecl>(Target))
11583 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11585 // If the target happens to be one of the previous declarations, we
11586 // don't have a conflict.
11588 // FIXME: but we might be increasing its access, in which case we
11589 // should redeclare it.
11590 NamedDecl *NonTag = nullptr, *Tag = nullptr;
11591 bool FoundEquivalentDecl = false;
11592 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11594 NamedDecl *D = (*I)->getUnderlyingDecl();
11595 // We can have UsingDecls in our Previous results because we use the same
11596 // LookupResult for checking whether the UsingDecl itself is a valid
11598 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
11601 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11602 // C++ [class.mem]p19:
11603 // If T is the name of a class, then [every named member other than
11604 // a non-static data member] shall have a name different from T
11605 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11606 !isa<IndirectFieldDecl>(Target) &&
11607 !isa<UnresolvedUsingValueDecl>(Target) &&
11608 DiagnoseClassNameShadow(
11610 DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
11614 if (IsEquivalentForUsingDecl(Context, D, Target)) {
11615 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11616 PrevShadow = Shadow;
11617 FoundEquivalentDecl = true;
11618 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11619 // We don't conflict with an existing using shadow decl of an equivalent
11620 // declaration, but we're not a redeclaration of it.
11621 FoundEquivalentDecl = true;
11625 (isa<TagDecl>(D) ? Tag : NonTag) = D;
11628 if (FoundEquivalentDecl)
11631 if (FunctionDecl *FD = Target->getAsFunction()) {
11632 NamedDecl *OldDecl = nullptr;
11633 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11634 /*IsForUsingDecl*/ true)) {
11638 case Ovl_NonFunction:
11639 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11642 // We found a decl with the exact signature.
11644 // If we're in a record, we want to hide the target, so we
11645 // return true (without a diagnostic) to tell the caller not to
11646 // build a shadow decl.
11647 if (CurContext->isRecord())
11650 // If we're not in a record, this is an error.
11651 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11655 Diag(Target->getLocation(), diag::note_using_decl_target);
11656 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11657 Using->setInvalidDecl();
11661 // Target is not a function.
11663 if (isa<TagDecl>(Target)) {
11664 // No conflict between a tag and a non-tag.
11665 if (!Tag) return false;
11667 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11668 Diag(Target->getLocation(), diag::note_using_decl_target);
11669 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11670 Using->setInvalidDecl();
11674 // No conflict between a tag and a non-tag.
11675 if (!NonTag) return false;
11677 Diag(Using->getLocation(), diag::err_using_decl_conflict);
11678 Diag(Target->getLocation(), diag::note_using_decl_target);
11679 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11680 Using->setInvalidDecl();
11684 /// Determine whether a direct base class is a virtual base class.
11685 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11686 if (!Derived->getNumVBases())
11688 for (auto &B : Derived->bases())
11689 if (B.getType()->getAsCXXRecordDecl() == Base)
11690 return B.isVirtual();
11691 llvm_unreachable("not a direct base class");
11694 /// Builds a shadow declaration corresponding to a 'using' declaration.
11695 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
11698 UsingShadowDecl *PrevDecl) {
11699 // If we resolved to another shadow declaration, just coalesce them.
11700 NamedDecl *Target = Orig;
11701 if (isa<UsingShadowDecl>(Target)) {
11702 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11703 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
11706 NamedDecl *NonTemplateTarget = Target;
11707 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11708 NonTemplateTarget = TargetTD->getTemplatedDecl();
11710 UsingShadowDecl *Shadow;
11711 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11712 bool IsVirtualBase =
11713 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11714 UD->getQualifier()->getAsRecordDecl());
11715 Shadow = ConstructorUsingShadowDecl::Create(
11716 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
11718 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
11721 UD->addShadowDecl(Shadow);
11723 Shadow->setAccess(UD->getAccess());
11724 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
11725 Shadow->setInvalidDecl();
11727 Shadow->setPreviousDecl(PrevDecl);
11730 PushOnScopeChains(Shadow, S);
11732 CurContext->addDecl(Shadow);
11738 /// Hides a using shadow declaration. This is required by the current
11739 /// using-decl implementation when a resolvable using declaration in a
11740 /// class is followed by a declaration which would hide or override
11741 /// one or more of the using decl's targets; for example:
11743 /// struct Base { void foo(int); };
11744 /// struct Derived : Base {
11745 /// using Base::foo;
11749 /// The governing language is C++03 [namespace.udecl]p12:
11751 /// When a using-declaration brings names from a base class into a
11752 /// derived class scope, member functions in the derived class
11753 /// override and/or hide member functions with the same name and
11754 /// parameter types in a base class (rather than conflicting).
11756 /// There are two ways to implement this:
11757 /// (1) optimistically create shadow decls when they're not hidden
11758 /// by existing declarations, or
11759 /// (2) don't create any shadow decls (or at least don't make them
11760 /// visible) until we've fully parsed/instantiated the class.
11761 /// The problem with (1) is that we might have to retroactively remove
11762 /// a shadow decl, which requires several O(n) operations because the
11763 /// decl structures are (very reasonably) not designed for removal.
11764 /// (2) avoids this but is very fiddly and phase-dependent.
11765 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11766 if (Shadow->getDeclName().getNameKind() ==
11767 DeclarationName::CXXConversionFunctionName)
11768 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11770 // Remove it from the DeclContext...
11771 Shadow->getDeclContext()->removeDecl(Shadow);
11773 // ...and the scope, if applicable...
11775 S->RemoveDecl(Shadow);
11776 IdResolver.RemoveDecl(Shadow);
11779 // ...and the using decl.
11780 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
11782 // TODO: complain somehow if Shadow was used. It shouldn't
11783 // be possible for this to happen, because...?
11786 /// Find the base specifier for a base class with the given type.
11787 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11788 QualType DesiredBase,
11789 bool &AnyDependentBases) {
11790 // Check whether the named type is a direct base class.
11791 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11792 .getUnqualifiedType();
11793 for (auto &Base : Derived->bases()) {
11794 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11795 if (CanonicalDesiredBase == BaseType)
11797 if (BaseType->isDependentType())
11798 AnyDependentBases = true;
11804 class UsingValidatorCCC final : public CorrectionCandidateCallback {
11806 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
11807 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
11808 : HasTypenameKeyword(HasTypenameKeyword),
11809 IsInstantiation(IsInstantiation), OldNNS(NNS),
11810 RequireMemberOf(RequireMemberOf) {}
11812 bool ValidateCandidate(const TypoCorrection &Candidate) override {
11813 NamedDecl *ND = Candidate.getCorrectionDecl();
11815 // Keywords are not valid here.
11816 if (!ND || isa<NamespaceDecl>(ND))
11819 // Completely unqualified names are invalid for a 'using' declaration.
11820 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
11823 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
11826 if (RequireMemberOf) {
11827 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11828 if (FoundRecord && FoundRecord->isInjectedClassName()) {
11829 // No-one ever wants a using-declaration to name an injected-class-name
11830 // of a base class, unless they're declaring an inheriting constructor.
11831 ASTContext &Ctx = ND->getASTContext();
11832 if (!Ctx.getLangOpts().CPlusPlus11)
11834 QualType FoundType = Ctx.getRecordType(FoundRecord);
11836 // Check that the injected-class-name is named as a member of its own
11837 // type; we don't want to suggest 'using Derived::Base;', since that
11838 // means something else.
11839 NestedNameSpecifier *Specifier =
11840 Candidate.WillReplaceSpecifier()
11841 ? Candidate.getCorrectionSpecifier()
11843 if (!Specifier->getAsType() ||
11844 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
11847 // Check that this inheriting constructor declaration actually names a
11848 // direct base class of the current class.
11849 bool AnyDependentBases = false;
11850 if (!findDirectBaseWithType(RequireMemberOf,
11851 Ctx.getRecordType(FoundRecord),
11852 AnyDependentBases) &&
11853 !AnyDependentBases)
11856 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
11857 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
11860 // FIXME: Check that the base class member is accessible?
11863 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
11864 if (FoundRecord && FoundRecord->isInjectedClassName())
11868 if (isa<TypeDecl>(ND))
11869 return HasTypenameKeyword || !IsInstantiation;
11871 return !HasTypenameKeyword;
11874 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11875 return std::make_unique<UsingValidatorCCC>(*this);
11879 bool HasTypenameKeyword;
11880 bool IsInstantiation;
11881 NestedNameSpecifier *OldNNS;
11882 CXXRecordDecl *RequireMemberOf;
11884 } // end anonymous namespace
11886 /// Builds a using declaration.
11888 /// \param IsInstantiation - Whether this call arises from an
11889 /// instantiation of an unresolved using declaration. We treat
11890 /// the lookup differently for these declarations.
11891 NamedDecl *Sema::BuildUsingDeclaration(
11892 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
11893 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
11894 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
11895 const ParsedAttributesView &AttrList, bool IsInstantiation) {
11896 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
11897 SourceLocation IdentLoc = NameInfo.getLoc();
11898 assert(IdentLoc.isValid() && "Invalid TargetName location.");
11900 // FIXME: We ignore attributes for now.
11902 // For an inheriting constructor declaration, the name of the using
11903 // declaration is the name of a constructor in this class, not in the
11905 DeclarationNameInfo UsingName = NameInfo;
11906 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
11907 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
11908 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
11909 Context.getCanonicalType(Context.getRecordType(RD))));
11911 // Do the redeclaration lookup in the current scope.
11912 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
11913 ForVisibleRedeclaration);
11914 Previous.setHideTags(false);
11916 LookupName(Previous, S);
11918 // It is really dumb that we have to do this.
11919 LookupResult::Filter F = Previous.makeFilter();
11920 while (F.hasNext()) {
11921 NamedDecl *D = F.next();
11922 if (!isDeclInScope(D, CurContext, S))
11924 // If we found a local extern declaration that's not ordinarily visible,
11925 // and this declaration is being added to a non-block scope, ignore it.
11926 // We're only checking for scope conflicts here, not also for violations
11927 // of the linkage rules.
11928 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
11929 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
11934 assert(IsInstantiation && "no scope in non-instantiation");
11935 if (CurContext->isRecord())
11936 LookupQualifiedName(Previous, CurContext);
11938 // No redeclaration check is needed here; in non-member contexts we
11939 // diagnosed all possible conflicts with other using-declarations when
11940 // building the template:
11942 // For a dependent non-type using declaration, the only valid case is
11943 // if we instantiate to a single enumerator. We check for conflicts
11944 // between shadow declarations we introduce, and we check in the template
11945 // definition for conflicts between a non-type using declaration and any
11946 // other declaration, which together covers all cases.
11948 // A dependent typename using declaration will never successfully
11949 // instantiate, since it will always name a class member, so we reject
11950 // that in the template definition.
11954 // Check for invalid redeclarations.
11955 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
11956 SS, IdentLoc, Previous))
11959 // Check for bad qualifiers.
11960 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
11964 DeclContext *LookupContext = computeDeclContext(SS);
11966 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11967 if (!LookupContext || EllipsisLoc.isValid()) {
11968 if (HasTypenameKeyword) {
11969 // FIXME: not all declaration name kinds are legal here
11970 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
11971 UsingLoc, TypenameLoc,
11973 IdentLoc, NameInfo.getName(),
11976 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
11977 QualifierLoc, NameInfo, EllipsisLoc);
11980 CurContext->addDecl(D);
11984 auto Build = [&](bool Invalid) {
11986 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
11987 UsingName, HasTypenameKeyword);
11989 CurContext->addDecl(UD);
11990 UD->setInvalidDecl(Invalid);
11993 auto BuildInvalid = [&]{ return Build(true); };
11994 auto BuildValid = [&]{ return Build(false); };
11996 if (RequireCompleteDeclContext(SS, LookupContext))
11997 return BuildInvalid();
11999 // Look up the target name.
12000 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12002 // Unlike most lookups, we don't always want to hide tag
12003 // declarations: tag names are visible through the using declaration
12004 // even if hidden by ordinary names, *except* in a dependent context
12005 // where it's important for the sanity of two-phase lookup.
12006 if (!IsInstantiation)
12007 R.setHideTags(false);
12009 // For the purposes of this lookup, we have a base object type
12010 // equal to that of the current context.
12011 if (CurContext->isRecord()) {
12012 R.setBaseObjectType(
12013 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12016 LookupQualifiedName(R, LookupContext);
12018 // Try to correct typos if possible. If constructor name lookup finds no
12019 // results, that means the named class has no explicit constructors, and we
12020 // suppressed declaring implicit ones (probably because it's dependent or
12023 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12024 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
12025 // it will believe that glibc provides a ::gets in cases where it does not,
12026 // and will try to pull it into namespace std with a using-declaration.
12027 // Just ignore the using-declaration in that case.
12028 auto *II = NameInfo.getName().getAsIdentifierInfo();
12029 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12030 CurContext->isStdNamespace() &&
12031 isa<TranslationUnitDecl>(LookupContext) &&
12032 getSourceManager().isInSystemHeader(UsingLoc))
12034 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12035 dyn_cast<CXXRecordDecl>(CurContext));
12036 if (TypoCorrection Corrected =
12037 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12038 CTK_ErrorRecovery)) {
12039 // We reject candidates where DroppedSpecifier == true, hence the
12040 // literal '0' below.
12041 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12042 << NameInfo.getName() << LookupContext << 0
12045 // If we picked a correction with no attached Decl we can't do anything
12046 // useful with it, bail out.
12047 NamedDecl *ND = Corrected.getCorrectionDecl();
12049 return BuildInvalid();
12051 // If we corrected to an inheriting constructor, handle it as one.
12052 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12053 if (RD && RD->isInjectedClassName()) {
12054 // The parent of the injected class name is the class itself.
12055 RD = cast<CXXRecordDecl>(RD->getParent());
12057 // Fix up the information we'll use to build the using declaration.
12058 if (Corrected.WillReplaceSpecifier()) {
12059 NestedNameSpecifierLocBuilder Builder;
12060 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12061 QualifierLoc.getSourceRange());
12062 QualifierLoc = Builder.getWithLocInContext(Context);
12065 // In this case, the name we introduce is the name of a derived class
12067 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12068 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12069 Context.getCanonicalType(Context.getRecordType(CurClass))));
12070 UsingName.setNamedTypeInfo(nullptr);
12071 for (auto *Ctor : LookupConstructors(RD))
12075 // FIXME: Pick up all the declarations if we found an overloaded
12077 UsingName.setName(ND->getDeclName());
12081 Diag(IdentLoc, diag::err_no_member)
12082 << NameInfo.getName() << LookupContext << SS.getRange();
12083 return BuildInvalid();
12087 if (R.isAmbiguous())
12088 return BuildInvalid();
12090 if (HasTypenameKeyword) {
12091 // If we asked for a typename and got a non-type decl, error out.
12092 if (!R.getAsSingle<TypeDecl>()) {
12093 Diag(IdentLoc, diag::err_using_typename_non_type);
12094 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12095 Diag((*I)->getUnderlyingDecl()->getLocation(),
12096 diag::note_using_decl_target);
12097 return BuildInvalid();
12100 // If we asked for a non-typename and we got a type, error out,
12101 // but only if this is an instantiation of an unresolved using
12102 // decl. Otherwise just silently find the type name.
12103 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12104 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12105 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12106 return BuildInvalid();
12110 // C++14 [namespace.udecl]p6:
12111 // A using-declaration shall not name a namespace.
12112 if (R.getAsSingle<NamespaceDecl>()) {
12113 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12115 return BuildInvalid();
12118 // C++14 [namespace.udecl]p7:
12119 // A using-declaration shall not name a scoped enumerator.
12120 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
12121 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
12122 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
12124 return BuildInvalid();
12128 UsingDecl *UD = BuildValid();
12130 // Some additional rules apply to inheriting constructors.
12131 if (UsingName.getName().getNameKind() ==
12132 DeclarationName::CXXConstructorName) {
12133 // Suppress access diagnostics; the access check is instead performed at the
12134 // point of use for an inheriting constructor.
12135 R.suppressDiagnostics();
12136 if (CheckInheritingConstructorUsingDecl(UD))
12140 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12141 UsingShadowDecl *PrevDecl = nullptr;
12142 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12143 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12149 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12150 ArrayRef<NamedDecl *> Expansions) {
12151 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
12152 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
12153 isa<UsingPackDecl>(InstantiatedFrom));
12156 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12157 UPD->setAccess(InstantiatedFrom->getAccess());
12158 CurContext->addDecl(UPD);
12162 /// Additional checks for a using declaration referring to a constructor name.
12163 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12164 assert(!UD->hasTypename() && "expecting a constructor name");
12166 const Type *SourceType = UD->getQualifier()->getAsType();
12167 assert(SourceType &&
12168 "Using decl naming constructor doesn't have type in scope spec.");
12169 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12171 // Check whether the named type is a direct base class.
12172 bool AnyDependentBases = false;
12173 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12174 AnyDependentBases);
12175 if (!Base && !AnyDependentBases) {
12176 Diag(UD->getUsingLoc(),
12177 diag::err_using_decl_constructor_not_in_direct_base)
12178 << UD->getNameInfo().getSourceRange()
12179 << QualType(SourceType, 0) << TargetClass;
12180 UD->setInvalidDecl();
12185 Base->setInheritConstructors();
12190 /// Checks that the given using declaration is not an invalid
12191 /// redeclaration. Note that this is checking only for the using decl
12192 /// itself, not for any ill-formedness among the UsingShadowDecls.
12193 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12194 bool HasTypenameKeyword,
12195 const CXXScopeSpec &SS,
12196 SourceLocation NameLoc,
12197 const LookupResult &Prev) {
12198 NestedNameSpecifier *Qual = SS.getScopeRep();
12200 // C++03 [namespace.udecl]p8:
12201 // C++0x [namespace.udecl]p10:
12202 // A using-declaration is a declaration and can therefore be used
12203 // repeatedly where (and only where) multiple declarations are
12206 // That's in non-member contexts.
12207 if (!CurContext->getRedeclContext()->isRecord()) {
12208 // A dependent qualifier outside a class can only ever resolve to an
12209 // enumeration type. Therefore it conflicts with any other non-type
12210 // declaration in the same scope.
12211 // FIXME: How should we check for dependent type-type conflicts at block
12213 if (Qual->isDependent() && !HasTypenameKeyword) {
12214 for (auto *D : Prev) {
12215 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12216 bool OldCouldBeEnumerator =
12217 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12219 OldCouldBeEnumerator ? diag::err_redefinition
12220 : diag::err_redefinition_different_kind)
12221 << Prev.getLookupName();
12222 Diag(D->getLocation(), diag::note_previous_definition);
12230 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12234 NestedNameSpecifier *DQual;
12235 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12236 DTypename = UD->hasTypename();
12237 DQual = UD->getQualifier();
12238 } else if (UnresolvedUsingValueDecl *UD
12239 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12241 DQual = UD->getQualifier();
12242 } else if (UnresolvedUsingTypenameDecl *UD
12243 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12245 DQual = UD->getQualifier();
12248 // using decls differ if one says 'typename' and the other doesn't.
12249 // FIXME: non-dependent using decls?
12250 if (HasTypenameKeyword != DTypename) continue;
12252 // using decls differ if they name different scopes (but note that
12253 // template instantiation can cause this check to trigger when it
12254 // didn't before instantiation).
12255 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
12256 Context.getCanonicalNestedNameSpecifier(DQual))
12259 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12260 Diag(D->getLocation(), diag::note_using_decl) << 1;
12268 /// Checks that the given nested-name qualifier used in a using decl
12269 /// in the current context is appropriately related to the current
12270 /// scope. If an error is found, diagnoses it and returns true.
12271 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
12273 const CXXScopeSpec &SS,
12274 const DeclarationNameInfo &NameInfo,
12275 SourceLocation NameLoc) {
12276 DeclContext *NamedContext = computeDeclContext(SS);
12278 if (!CurContext->isRecord()) {
12279 // C++03 [namespace.udecl]p3:
12280 // C++0x [namespace.udecl]p8:
12281 // A using-declaration for a class member shall be a member-declaration.
12283 // If we weren't able to compute a valid scope, it might validly be a
12284 // dependent class scope or a dependent enumeration unscoped scope. If
12285 // we have a 'typename' keyword, the scope must resolve to a class type.
12286 if ((HasTypename && !NamedContext) ||
12287 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
12288 auto *RD = NamedContext
12289 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12291 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
12294 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
12297 // If we have a complete, non-dependent source type, try to suggest a
12298 // way to get the same effect.
12302 // Find what this using-declaration was referring to.
12303 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12304 R.setHideTags(false);
12305 R.suppressDiagnostics();
12306 LookupQualifiedName(R, RD);
12308 if (R.getAsSingle<TypeDecl>()) {
12309 if (getLangOpts().CPlusPlus11) {
12310 // Convert 'using X::Y;' to 'using Y = X::Y;'.
12311 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12312 << 0 // alias declaration
12313 << FixItHint::CreateInsertion(SS.getBeginLoc(),
12314 NameInfo.getName().getAsString() +
12317 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12318 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12319 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12320 << 1 // typedef declaration
12321 << FixItHint::CreateReplacement(UsingLoc, "typedef")
12322 << FixItHint::CreateInsertion(
12323 InsertLoc, " " + NameInfo.getName().getAsString());
12325 } else if (R.getAsSingle<VarDecl>()) {
12326 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12327 // repeating the type of the static data member here.
12329 if (getLangOpts().CPlusPlus11) {
12330 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12331 FixIt = FixItHint::CreateReplacement(
12332 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12335 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12336 << 2 // reference declaration
12338 } else if (R.getAsSingle<EnumConstantDecl>()) {
12339 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12340 // repeating the type of the enumeration here, and we can't do so if
12341 // the type is anonymous.
12343 if (getLangOpts().CPlusPlus11) {
12344 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12345 FixIt = FixItHint::CreateReplacement(
12347 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12350 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12351 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12357 // Otherwise, this might be valid.
12361 // The current scope is a record.
12363 // If the named context is dependent, we can't decide much.
12364 if (!NamedContext) {
12365 // FIXME: in C++0x, we can diagnose if we can prove that the
12366 // nested-name-specifier does not refer to a base class, which is
12367 // still possible in some cases.
12369 // Otherwise we have to conservatively report that things might be
12374 if (!NamedContext->isRecord()) {
12375 // Ideally this would point at the last name in the specifier,
12376 // but we don't have that level of source info.
12377 Diag(SS.getRange().getBegin(),
12378 diag::err_using_decl_nested_name_specifier_is_not_class)
12379 << SS.getScopeRep() << SS.getRange();
12383 if (!NamedContext->isDependentContext() &&
12384 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12387 if (getLangOpts().CPlusPlus11) {
12388 // C++11 [namespace.udecl]p3:
12389 // In a using-declaration used as a member-declaration, the
12390 // nested-name-specifier shall name a base class of the class
12393 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12394 cast<CXXRecordDecl>(NamedContext))) {
12395 if (CurContext == NamedContext) {
12397 diag::err_using_decl_nested_name_specifier_is_current_class)
12402 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12403 Diag(SS.getRange().getBegin(),
12404 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12405 << SS.getScopeRep()
12406 << cast<CXXRecordDecl>(CurContext)
12415 // C++03 [namespace.udecl]p4:
12416 // A using-declaration used as a member-declaration shall refer
12417 // to a member of a base class of the class being defined [etc.].
12419 // Salient point: SS doesn't have to name a base class as long as
12420 // lookup only finds members from base classes. Therefore we can
12421 // diagnose here only if we can prove that that can't happen,
12422 // i.e. if the class hierarchies provably don't intersect.
12424 // TODO: it would be nice if "definitely valid" results were cached
12425 // in the UsingDecl and UsingShadowDecl so that these checks didn't
12426 // need to be repeated.
12428 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12429 auto Collect = [&Bases](const CXXRecordDecl *Base) {
12430 Bases.insert(Base);
12434 // Collect all bases. Return false if we find a dependent base.
12435 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12438 // Returns true if the base is dependent or is one of the accumulated base
12440 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12441 return !Bases.count(Base);
12444 // Return false if the class has a dependent base or if it or one
12445 // of its bases is present in the base set of the current context.
12446 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12447 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12450 Diag(SS.getRange().getBegin(),
12451 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12452 << SS.getScopeRep()
12453 << cast<CXXRecordDecl>(CurContext)
12459 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12460 MultiTemplateParamsArg TemplateParamLists,
12461 SourceLocation UsingLoc, UnqualifiedId &Name,
12462 const ParsedAttributesView &AttrList,
12463 TypeResult Type, Decl *DeclFromDeclSpec) {
12464 // Skip up to the relevant declaration scope.
12465 while (S->isTemplateParamScope())
12466 S = S->getParent();
12467 assert((S->getFlags() & Scope::DeclScope) &&
12468 "got alias-declaration outside of declaration scope");
12470 if (Type.isInvalid())
12473 bool Invalid = false;
12474 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12475 TypeSourceInfo *TInfo = nullptr;
12476 GetTypeFromParser(Type.get(), &TInfo);
12478 if (DiagnoseClassNameShadow(CurContext, NameInfo))
12481 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12482 UPPC_DeclarationType)) {
12484 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12485 TInfo->getTypeLoc().getBeginLoc());
12488 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12489 TemplateParamLists.size()
12490 ? forRedeclarationInCurContext()
12491 : ForVisibleRedeclaration);
12492 LookupName(Previous, S);
12494 // Warn about shadowing the name of a template parameter.
12495 if (Previous.isSingleResult() &&
12496 Previous.getFoundDecl()->isTemplateParameter()) {
12497 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12501 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
12502 "name in alias declaration must be an identifier");
12503 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12504 Name.StartLocation,
12505 Name.Identifier, TInfo);
12507 NewTD->setAccess(AS);
12510 NewTD->setInvalidDecl();
12512 ProcessDeclAttributeList(S, NewTD, AttrList);
12513 AddPragmaAttributes(S, NewTD);
12515 CheckTypedefForVariablyModifiedType(S, NewTD);
12516 Invalid |= NewTD->isInvalidDecl();
12518 bool Redeclaration = false;
12521 if (TemplateParamLists.size()) {
12522 TypeAliasTemplateDecl *OldDecl = nullptr;
12523 TemplateParameterList *OldTemplateParams = nullptr;
12525 if (TemplateParamLists.size() != 1) {
12526 Diag(UsingLoc, diag::err_alias_template_extra_headers)
12527 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12528 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12530 TemplateParameterList *TemplateParams = TemplateParamLists[0];
12532 // Check that we can declare a template here.
12533 if (CheckTemplateDeclScope(S, TemplateParams))
12536 // Only consider previous declarations in the same scope.
12537 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12538 /*ExplicitInstantiationOrSpecialization*/false);
12539 if (!Previous.empty()) {
12540 Redeclaration = true;
12542 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12543 if (!OldDecl && !Invalid) {
12544 Diag(UsingLoc, diag::err_redefinition_different_kind)
12545 << Name.Identifier;
12547 NamedDecl *OldD = Previous.getRepresentativeDecl();
12548 if (OldD->getLocation().isValid())
12549 Diag(OldD->getLocation(), diag::note_previous_definition);
12554 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12555 if (TemplateParameterListsAreEqual(TemplateParams,
12556 OldDecl->getTemplateParameters(),
12558 TPL_TemplateMatch))
12559 OldTemplateParams =
12560 OldDecl->getMostRecentDecl()->getTemplateParameters();
12564 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12566 !Context.hasSameType(OldTD->getUnderlyingType(),
12567 NewTD->getUnderlyingType())) {
12568 // FIXME: The C++0x standard does not clearly say this is ill-formed,
12569 // but we can't reasonably accept it.
12570 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12571 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12572 if (OldTD->getLocation().isValid())
12573 Diag(OldTD->getLocation(), diag::note_previous_definition);
12579 // Merge any previous default template arguments into our parameters,
12580 // and check the parameter list.
12581 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12582 TPC_TypeAliasTemplate))
12585 TypeAliasTemplateDecl *NewDecl =
12586 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12587 Name.Identifier, TemplateParams,
12589 NewTD->setDescribedAliasTemplate(NewDecl);
12591 NewDecl->setAccess(AS);
12594 NewDecl->setInvalidDecl();
12595 else if (OldDecl) {
12596 NewDecl->setPreviousDecl(OldDecl);
12597 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12602 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12603 setTagNameForLinkagePurposes(TD, NewTD);
12604 handleTagNumbering(TD, S);
12606 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12610 PushOnScopeChains(NewND, S);
12611 ActOnDocumentableDecl(NewND);
12615 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12616 SourceLocation AliasLoc,
12617 IdentifierInfo *Alias, CXXScopeSpec &SS,
12618 SourceLocation IdentLoc,
12619 IdentifierInfo *Ident) {
12621 // Lookup the namespace name.
12622 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12623 LookupParsedName(R, S, &SS);
12625 if (R.isAmbiguous())
12629 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12630 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12634 assert(!R.isAmbiguous() && !R.empty());
12635 NamedDecl *ND = R.getRepresentativeDecl();
12637 // Check if we have a previous declaration with the same name.
12638 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12639 ForVisibleRedeclaration);
12640 LookupName(PrevR, S);
12642 // Check we're not shadowing a template parameter.
12643 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12644 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12648 // Filter out any other lookup result from an enclosing scope.
12649 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12650 /*AllowInlineNamespace*/false);
12652 // Find the previous declaration and check that we can redeclare it.
12653 NamespaceAliasDecl *Prev = nullptr;
12654 if (PrevR.isSingleResult()) {
12655 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12656 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12657 // We already have an alias with the same name that points to the same
12658 // namespace; check that it matches.
12659 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12661 } else if (isVisible(PrevDecl)) {
12662 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12664 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12665 << AD->getNamespace();
12668 } else if (isVisible(PrevDecl)) {
12669 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12670 ? diag::err_redefinition
12671 : diag::err_redefinition_different_kind;
12672 Diag(AliasLoc, DiagID) << Alias;
12673 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12678 // The use of a nested name specifier may trigger deprecation warnings.
12679 DiagnoseUseOfDecl(ND, IdentLoc);
12681 NamespaceAliasDecl *AliasDecl =
12682 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
12683 Alias, SS.getWithLocInContext(Context),
12686 AliasDecl->setPreviousDecl(Prev);
12688 PushOnScopeChains(AliasDecl, S);
12693 struct SpecialMemberExceptionSpecInfo
12694 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
12695 SourceLocation Loc;
12696 Sema::ImplicitExceptionSpecification ExceptSpec;
12698 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
12699 Sema::CXXSpecialMember CSM,
12700 Sema::InheritedConstructorInfo *ICI,
12701 SourceLocation Loc)
12702 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
12704 bool visitBase(CXXBaseSpecifier *Base);
12705 bool visitField(FieldDecl *FD);
12707 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
12710 void visitSubobjectCall(Subobject Subobj,
12711 Sema::SpecialMemberOverloadResult SMOR);
12715 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
12716 auto *RT = Base->getType()->getAs<RecordType>();
12720 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
12721 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
12722 if (auto *BaseCtor = SMOR.getMethod()) {
12723 visitSubobjectCall(Base, BaseCtor);
12727 visitClassSubobject(BaseClass, Base, 0);
12731 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
12732 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
12733 Expr *E = FD->getInClassInitializer();
12735 // FIXME: It's a little wasteful to build and throw away a
12736 // CXXDefaultInitExpr here.
12737 // FIXME: We should have a single context note pointing at Loc, and
12738 // this location should be MD->getLocation() instead, since that's
12739 // the location where we actually use the default init expression.
12740 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
12742 ExceptSpec.CalledExpr(E);
12743 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
12744 ->getAs<RecordType>()) {
12745 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
12746 FD->getType().getCVRQualifiers());
12751 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
12754 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
12755 bool IsMutable = Field && Field->isMutable();
12756 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
12759 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
12760 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
12761 // Note, if lookup fails, it doesn't matter what exception specification we
12762 // choose because the special member will be deleted.
12763 if (CXXMethodDecl *MD = SMOR.getMethod())
12764 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
12767 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
12768 llvm::APSInt Result;
12769 ExprResult Converted = CheckConvertedConstantExpression(
12770 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
12771 ExplicitSpec.setExpr(Converted.get());
12772 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
12773 ExplicitSpec.setKind(Result.getBoolValue()
12774 ? ExplicitSpecKind::ResolvedTrue
12775 : ExplicitSpecKind::ResolvedFalse);
12778 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
12782 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
12783 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
12784 if (!ExplicitExpr->isTypeDependent())
12785 tryResolveExplicitSpecifier(ES);
12789 static Sema::ImplicitExceptionSpecification
12790 ComputeDefaultedSpecialMemberExceptionSpec(
12791 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
12792 Sema::InheritedConstructorInfo *ICI) {
12793 ComputingExceptionSpec CES(S, MD, Loc);
12795 CXXRecordDecl *ClassDecl = MD->getParent();
12797 // C++ [except.spec]p14:
12798 // An implicitly declared special member function (Clause 12) shall have an
12799 // exception-specification. [...]
12800 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
12801 if (ClassDecl->isInvalidDecl())
12802 return Info.ExceptSpec;
12804 // FIXME: If this diagnostic fires, we're probably missing a check for
12805 // attempting to resolve an exception specification before it's known
12806 // at a higher level.
12807 if (S.RequireCompleteType(MD->getLocation(),
12808 S.Context.getRecordType(ClassDecl),
12809 diag::err_exception_spec_incomplete_type))
12810 return Info.ExceptSpec;
12812 // C++1z [except.spec]p7:
12813 // [Look for exceptions thrown by] a constructor selected [...] to
12814 // initialize a potentially constructed subobject,
12815 // C++1z [except.spec]p8:
12816 // The exception specification for an implicitly-declared destructor, or a
12817 // destructor without a noexcept-specifier, is potentially-throwing if and
12818 // only if any of the destructors for any of its potentially constructed
12819 // subojects is potentially throwing.
12820 // FIXME: We respect the first rule but ignore the "potentially constructed"
12821 // in the second rule to resolve a core issue (no number yet) that would have
12823 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
12824 // struct B : A {};
12825 // struct C : B { void f(); };
12826 // ... due to giving B::~B() a non-throwing exception specification.
12827 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
12828 : Info.VisitAllBases);
12830 return Info.ExceptSpec;
12834 /// RAII object to register a special member as being currently declared.
12835 struct DeclaringSpecialMember {
12837 Sema::SpecialMemberDecl D;
12838 Sema::ContextRAII SavedContext;
12839 bool WasAlreadyBeingDeclared;
12841 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
12842 : S(S), D(RD, CSM), SavedContext(S, RD) {
12843 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
12844 if (WasAlreadyBeingDeclared)
12845 // This almost never happens, but if it does, ensure that our cache
12846 // doesn't contain a stale result.
12847 S.SpecialMemberCache.clear();
12849 // Register a note to be produced if we encounter an error while
12850 // declaring the special member.
12851 Sema::CodeSynthesisContext Ctx;
12852 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
12853 // FIXME: We don't have a location to use here. Using the class's
12854 // location maintains the fiction that we declare all special members
12855 // with the class, but (1) it's not clear that lying about that helps our
12856 // users understand what's going on, and (2) there may be outer contexts
12857 // on the stack (some of which are relevant) and printing them exposes
12859 Ctx.PointOfInstantiation = RD->getLocation();
12861 Ctx.SpecialMember = CSM;
12862 S.pushCodeSynthesisContext(Ctx);
12865 ~DeclaringSpecialMember() {
12866 if (!WasAlreadyBeingDeclared) {
12867 S.SpecialMembersBeingDeclared.erase(D);
12868 S.popCodeSynthesisContext();
12872 /// Are we already trying to declare this special member?
12873 bool isAlreadyBeingDeclared() const {
12874 return WasAlreadyBeingDeclared;
12879 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
12880 // Look up any existing declarations, but don't trigger declaration of all
12881 // implicit special members with this name.
12882 DeclarationName Name = FD->getDeclName();
12883 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
12884 ForExternalRedeclaration);
12885 for (auto *D : FD->getParent()->lookup(Name))
12886 if (auto *Acceptable = R.getAcceptableDecl(D))
12887 R.addDecl(Acceptable);
12889 R.suppressDiagnostics();
12891 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
12894 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
12896 ArrayRef<QualType> Args) {
12897 // Build an exception specification pointing back at this constructor.
12898 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
12900 LangAS AS = getDefaultCXXMethodAddrSpace();
12901 if (AS != LangAS::Default) {
12902 EPI.TypeQuals.addAddressSpace(AS);
12905 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
12906 SpecialMem->setType(QT);
12909 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
12910 CXXRecordDecl *ClassDecl) {
12911 // C++ [class.ctor]p5:
12912 // A default constructor for a class X is a constructor of class X
12913 // that can be called without an argument. If there is no
12914 // user-declared constructor for class X, a default constructor is
12915 // implicitly declared. An implicitly-declared default constructor
12916 // is an inline public member of its class.
12917 assert(ClassDecl->needsImplicitDefaultConstructor() &&
12918 "Should not build implicit default constructor!");
12920 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
12921 if (DSM.isAlreadyBeingDeclared())
12924 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12925 CXXDefaultConstructor,
12928 // Create the actual constructor declaration.
12929 CanQualType ClassType
12930 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
12931 SourceLocation ClassLoc = ClassDecl->getLocation();
12932 DeclarationName Name
12933 = Context.DeclarationNames.getCXXConstructorName(ClassType);
12934 DeclarationNameInfo NameInfo(Name, ClassLoc);
12935 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
12936 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
12937 /*TInfo=*/nullptr, ExplicitSpecifier(),
12938 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12939 Constexpr ? CSK_constexpr : CSK_unspecified);
12940 DefaultCon->setAccess(AS_public);
12941 DefaultCon->setDefaulted();
12943 if (getLangOpts().CUDA) {
12944 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
12946 /* ConstRHS */ false,
12947 /* Diagnose */ false);
12950 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
12952 // We don't need to use SpecialMemberIsTrivial here; triviality for default
12953 // constructors is easy to compute.
12954 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
12956 // Note that we have declared this constructor.
12957 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
12959 Scope *S = getScopeForContext(ClassDecl);
12960 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
12962 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
12963 SetDeclDeleted(DefaultCon, ClassLoc);
12966 PushOnScopeChains(DefaultCon, S, false);
12967 ClassDecl->addDecl(DefaultCon);
12972 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
12973 CXXConstructorDecl *Constructor) {
12974 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
12975 !Constructor->doesThisDeclarationHaveABody() &&
12976 !Constructor->isDeleted()) &&
12977 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
12978 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
12981 CXXRecordDecl *ClassDecl = Constructor->getParent();
12982 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
12984 SynthesizedFunctionScope Scope(*this, Constructor);
12986 // The exception specification is needed because we are defining the
12988 ResolveExceptionSpec(CurrentLocation,
12989 Constructor->getType()->castAs<FunctionProtoType>());
12990 MarkVTableUsed(CurrentLocation, ClassDecl);
12992 // Add a context note for diagnostics produced after this point.
12993 Scope.addContextNote(CurrentLocation);
12995 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
12996 Constructor->setInvalidDecl();
13000 SourceLocation Loc = Constructor->getEndLoc().isValid()
13001 ? Constructor->getEndLoc()
13002 : Constructor->getLocation();
13003 Constructor->setBody(new (Context) CompoundStmt(Loc));
13004 Constructor->markUsed(Context);
13006 if (ASTMutationListener *L = getASTMutationListener()) {
13007 L->CompletedImplicitDefinition(Constructor);
13010 DiagnoseUninitializedFields(*this, Constructor);
13013 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13014 // Perform any delayed checks on exception specifications.
13015 CheckDelayedMemberExceptionSpecs();
13018 /// Find or create the fake constructor we synthesize to model constructing an
13019 /// object of a derived class via a constructor of a base class.
13020 CXXConstructorDecl *
13021 Sema::findInheritingConstructor(SourceLocation Loc,
13022 CXXConstructorDecl *BaseCtor,
13023 ConstructorUsingShadowDecl *Shadow) {
13024 CXXRecordDecl *Derived = Shadow->getParent();
13025 SourceLocation UsingLoc = Shadow->getLocation();
13027 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13028 // For now we use the name of the base class constructor as a member of the
13029 // derived class to indicate a (fake) inherited constructor name.
13030 DeclarationName Name = BaseCtor->getDeclName();
13032 // Check to see if we already have a fake constructor for this inherited
13033 // constructor call.
13034 for (NamedDecl *Ctor : Derived->lookup(Name))
13035 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13036 ->getInheritedConstructor()
13039 return cast<CXXConstructorDecl>(Ctor);
13041 DeclarationNameInfo NameInfo(Name, UsingLoc);
13042 TypeSourceInfo *TInfo =
13043 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13044 FunctionProtoTypeLoc ProtoLoc =
13045 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13047 // Check the inherited constructor is valid and find the list of base classes
13048 // from which it was inherited.
13049 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13052 BaseCtor->isConstexpr() &&
13053 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13054 false, BaseCtor, &ICI);
13056 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13057 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13058 BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
13059 /*isImplicitlyDeclared=*/true,
13060 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
13061 InheritedConstructor(Shadow, BaseCtor),
13062 BaseCtor->getTrailingRequiresClause());
13063 if (Shadow->isInvalidDecl())
13064 DerivedCtor->setInvalidDecl();
13066 // Build an unevaluated exception specification for this fake constructor.
13067 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13068 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13069 EPI.ExceptionSpec.Type = EST_Unevaluated;
13070 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13071 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13072 FPT->getParamTypes(), EPI));
13074 // Build the parameter declarations.
13075 SmallVector<ParmVarDecl *, 16> ParamDecls;
13076 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13077 TypeSourceInfo *TInfo =
13078 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13079 ParmVarDecl *PD = ParmVarDecl::Create(
13080 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13081 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13082 PD->setScopeInfo(0, I);
13084 // Ensure attributes are propagated onto parameters (this matters for
13085 // format, pass_object_size, ...).
13086 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13087 ParamDecls.push_back(PD);
13088 ProtoLoc.setParam(I, PD);
13091 // Set up the new constructor.
13092 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
13093 DerivedCtor->setAccess(BaseCtor->getAccess());
13094 DerivedCtor->setParams(ParamDecls);
13095 Derived->addDecl(DerivedCtor);
13097 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13098 SetDeclDeleted(DerivedCtor, UsingLoc);
13100 return DerivedCtor;
13103 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13104 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13105 Ctor->getInheritedConstructor().getShadowDecl());
13106 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13110 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13111 CXXConstructorDecl *Constructor) {
13112 CXXRecordDecl *ClassDecl = Constructor->getParent();
13113 assert(Constructor->getInheritedConstructor() &&
13114 !Constructor->doesThisDeclarationHaveABody() &&
13115 !Constructor->isDeleted());
13116 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13119 // Initializations are performed "as if by a defaulted default constructor",
13120 // so enter the appropriate scope.
13121 SynthesizedFunctionScope Scope(*this, Constructor);
13123 // The exception specification is needed because we are defining the
13125 ResolveExceptionSpec(CurrentLocation,
13126 Constructor->getType()->castAs<FunctionProtoType>());
13127 MarkVTableUsed(CurrentLocation, ClassDecl);
13129 // Add a context note for diagnostics produced after this point.
13130 Scope.addContextNote(CurrentLocation);
13132 ConstructorUsingShadowDecl *Shadow =
13133 Constructor->getInheritedConstructor().getShadowDecl();
13134 CXXConstructorDecl *InheritedCtor =
13135 Constructor->getInheritedConstructor().getConstructor();
13137 // [class.inhctor.init]p1:
13138 // initialization proceeds as if a defaulted default constructor is used to
13139 // initialize the D object and each base class subobject from which the
13140 // constructor was inherited
13142 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13143 CXXRecordDecl *RD = Shadow->getParent();
13144 SourceLocation InitLoc = Shadow->getLocation();
13146 // Build explicit initializers for all base classes from which the
13147 // constructor was inherited.
13148 SmallVector<CXXCtorInitializer*, 8> Inits;
13149 for (bool VBase : {false, true}) {
13150 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13151 if (B.isVirtual() != VBase)
13154 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13158 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13159 if (!BaseCtor.first)
13162 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13163 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13164 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13166 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13167 Inits.push_back(new (Context) CXXCtorInitializer(
13168 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13169 SourceLocation()));
13173 // We now proceed as if for a defaulted default constructor, with the relevant
13174 // initializers replaced.
13176 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13177 Constructor->setInvalidDecl();
13181 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13182 Constructor->markUsed(Context);
13184 if (ASTMutationListener *L = getASTMutationListener()) {
13185 L->CompletedImplicitDefinition(Constructor);
13188 DiagnoseUninitializedFields(*this, Constructor);
13191 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13192 // C++ [class.dtor]p2:
13193 // If a class has no user-declared destructor, a destructor is
13194 // declared implicitly. An implicitly-declared destructor is an
13195 // inline public member of its class.
13196 assert(ClassDecl->needsImplicitDestructor());
13198 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13199 if (DSM.isAlreadyBeingDeclared())
13202 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13206 // Create the actual destructor declaration.
13207 CanQualType ClassType
13208 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13209 SourceLocation ClassLoc = ClassDecl->getLocation();
13210 DeclarationName Name
13211 = Context.DeclarationNames.getCXXDestructorName(ClassType);
13212 DeclarationNameInfo NameInfo(Name, ClassLoc);
13213 CXXDestructorDecl *Destructor =
13214 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
13215 QualType(), nullptr, /*isInline=*/true,
13216 /*isImplicitlyDeclared=*/true,
13217 Constexpr ? CSK_constexpr : CSK_unspecified);
13218 Destructor->setAccess(AS_public);
13219 Destructor->setDefaulted();
13221 if (getLangOpts().CUDA) {
13222 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13224 /* ConstRHS */ false,
13225 /* Diagnose */ false);
13228 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13230 // We don't need to use SpecialMemberIsTrivial here; triviality for
13231 // destructors is easy to compute.
13232 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13233 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13234 ClassDecl->hasTrivialDestructorForCall());
13236 // Note that we have declared this destructor.
13237 ++getASTContext().NumImplicitDestructorsDeclared;
13239 Scope *S = getScopeForContext(ClassDecl);
13240 CheckImplicitSpecialMemberDeclaration(S, Destructor);
13242 // We can't check whether an implicit destructor is deleted before we complete
13243 // the definition of the class, because its validity depends on the alignment
13244 // of the class. We'll check this from ActOnFields once the class is complete.
13245 if (ClassDecl->isCompleteDefinition() &&
13246 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13247 SetDeclDeleted(Destructor, ClassLoc);
13249 // Introduce this destructor into its scope.
13251 PushOnScopeChains(Destructor, S, false);
13252 ClassDecl->addDecl(Destructor);
13257 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13258 CXXDestructorDecl *Destructor) {
13259 assert((Destructor->isDefaulted() &&
13260 !Destructor->doesThisDeclarationHaveABody() &&
13261 !Destructor->isDeleted()) &&
13262 "DefineImplicitDestructor - call it for implicit default dtor");
13263 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13266 CXXRecordDecl *ClassDecl = Destructor->getParent();
13267 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
13269 SynthesizedFunctionScope Scope(*this, Destructor);
13271 // The exception specification is needed because we are defining the
13273 ResolveExceptionSpec(CurrentLocation,
13274 Destructor->getType()->castAs<FunctionProtoType>());
13275 MarkVTableUsed(CurrentLocation, ClassDecl);
13277 // Add a context note for diagnostics produced after this point.
13278 Scope.addContextNote(CurrentLocation);
13280 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13281 Destructor->getParent());
13283 if (CheckDestructor(Destructor)) {
13284 Destructor->setInvalidDecl();
13288 SourceLocation Loc = Destructor->getEndLoc().isValid()
13289 ? Destructor->getEndLoc()
13290 : Destructor->getLocation();
13291 Destructor->setBody(new (Context) CompoundStmt(Loc));
13292 Destructor->markUsed(Context);
13294 if (ASTMutationListener *L = getASTMutationListener()) {
13295 L->CompletedImplicitDefinition(Destructor);
13299 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13300 CXXDestructorDecl *Destructor) {
13301 if (Destructor->isInvalidDecl())
13304 CXXRecordDecl *ClassDecl = Destructor->getParent();
13305 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
13306 "implicit complete dtors unneeded outside MS ABI");
13307 assert(ClassDecl->getNumVBases() > 0 &&
13308 "complete dtor only exists for classes with vbases");
13310 SynthesizedFunctionScope Scope(*this, Destructor);
13312 // Add a context note for diagnostics produced after this point.
13313 Scope.addContextNote(CurrentLocation);
13315 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13318 /// Perform any semantic analysis which needs to be delayed until all
13319 /// pending class member declarations have been parsed.
13320 void Sema::ActOnFinishCXXMemberDecls() {
13321 // If the context is an invalid C++ class, just suppress these checks.
13322 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13323 if (Record->isInvalidDecl()) {
13324 DelayedOverridingExceptionSpecChecks.clear();
13325 DelayedEquivalentExceptionSpecChecks.clear();
13328 checkForMultipleExportedDefaultConstructors(*this, Record);
13332 void Sema::ActOnFinishCXXNonNestedClass() {
13333 referenceDLLExportedClassMethods();
13335 if (!DelayedDllExportMemberFunctions.empty()) {
13336 SmallVector<CXXMethodDecl*, 4> WorkList;
13337 std::swap(DelayedDllExportMemberFunctions, WorkList);
13338 for (CXXMethodDecl *M : WorkList) {
13339 DefineDefaultedFunction(*this, M, M->getLocation());
13341 // Pass the method to the consumer to get emitted. This is not necessary
13342 // for explicit instantiation definitions, as they will get emitted
13344 if (M->getParent()->getTemplateSpecializationKind() !=
13345 TSK_ExplicitInstantiationDefinition)
13346 ActOnFinishInlineFunctionDef(M);
13351 void Sema::referenceDLLExportedClassMethods() {
13352 if (!DelayedDllExportClasses.empty()) {
13353 // Calling ReferenceDllExportedMembers might cause the current function to
13354 // be called again, so use a local copy of DelayedDllExportClasses.
13355 SmallVector<CXXRecordDecl *, 4> WorkList;
13356 std::swap(DelayedDllExportClasses, WorkList);
13357 for (CXXRecordDecl *Class : WorkList)
13358 ReferenceDllExportedMembers(*this, Class);
13362 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13363 assert(getLangOpts().CPlusPlus11 &&
13364 "adjusting dtor exception specs was introduced in c++11");
13366 if (Destructor->isDependentContext())
13369 // C++11 [class.dtor]p3:
13370 // A declaration of a destructor that does not have an exception-
13371 // specification is implicitly considered to have the same exception-
13372 // specification as an implicit declaration.
13373 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13374 if (DtorType->hasExceptionSpec())
13377 // Replace the destructor's type, building off the existing one. Fortunately,
13378 // the only thing of interest in the destructor type is its extended info.
13379 // The return and arguments are fixed.
13380 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13381 EPI.ExceptionSpec.Type = EST_Unevaluated;
13382 EPI.ExceptionSpec.SourceDecl = Destructor;
13383 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13385 // FIXME: If the destructor has a body that could throw, and the newly created
13386 // spec doesn't allow exceptions, we should emit a warning, because this
13387 // change in behavior can break conforming C++03 programs at runtime.
13388 // However, we don't have a body or an exception specification yet, so it
13389 // needs to be done somewhere else.
13393 /// An abstract base class for all helper classes used in building the
13394 // copy/move operators. These classes serve as factory functions and help us
13395 // avoid using the same Expr* in the AST twice.
13396 class ExprBuilder {
13397 ExprBuilder(const ExprBuilder&) = delete;
13398 ExprBuilder &operator=(const ExprBuilder&) = delete;
13401 static Expr *assertNotNull(Expr *E) {
13402 assert(E && "Expression construction must not fail.");
13408 virtual ~ExprBuilder() {}
13410 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13413 class RefBuilder: public ExprBuilder {
13418 Expr *build(Sema &S, SourceLocation Loc) const override {
13419 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13422 RefBuilder(VarDecl *Var, QualType VarType)
13423 : Var(Var), VarType(VarType) {}
13426 class ThisBuilder: public ExprBuilder {
13428 Expr *build(Sema &S, SourceLocation Loc) const override {
13429 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13433 class CastBuilder: public ExprBuilder {
13434 const ExprBuilder &Builder;
13436 ExprValueKind Kind;
13437 const CXXCastPath &Path;
13440 Expr *build(Sema &S, SourceLocation Loc) const override {
13441 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13442 CK_UncheckedDerivedToBase, Kind,
13446 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13447 const CXXCastPath &Path)
13448 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13451 class DerefBuilder: public ExprBuilder {
13452 const ExprBuilder &Builder;
13455 Expr *build(Sema &S, SourceLocation Loc) const override {
13456 return assertNotNull(
13457 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13460 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13463 class MemberBuilder: public ExprBuilder {
13464 const ExprBuilder &Builder;
13468 LookupResult &MemberLookup;
13471 Expr *build(Sema &S, SourceLocation Loc) const override {
13472 return assertNotNull(S.BuildMemberReferenceExpr(
13473 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13474 nullptr, MemberLookup, nullptr, nullptr).get());
13477 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13478 LookupResult &MemberLookup)
13479 : Builder(Builder), Type(Type), IsArrow(IsArrow),
13480 MemberLookup(MemberLookup) {}
13483 class MoveCastBuilder: public ExprBuilder {
13484 const ExprBuilder &Builder;
13487 Expr *build(Sema &S, SourceLocation Loc) const override {
13488 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13491 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13494 class LvalueConvBuilder: public ExprBuilder {
13495 const ExprBuilder &Builder;
13498 Expr *build(Sema &S, SourceLocation Loc) const override {
13499 return assertNotNull(
13500 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13503 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13506 class SubscriptBuilder: public ExprBuilder {
13507 const ExprBuilder &Base;
13508 const ExprBuilder &Index;
13511 Expr *build(Sema &S, SourceLocation Loc) const override {
13512 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13513 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13516 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13517 : Base(Base), Index(Index) {}
13520 } // end anonymous namespace
13522 /// When generating a defaulted copy or move assignment operator, if a field
13523 /// should be copied with __builtin_memcpy rather than via explicit assignments,
13524 /// do so. This optimization only applies for arrays of scalars, and for arrays
13525 /// of class type where the selected copy/move-assignment operator is trivial.
13527 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13528 const ExprBuilder &ToB, const ExprBuilder &FromB) {
13529 // Compute the size of the memory buffer to be copied.
13530 QualType SizeType = S.Context.getSizeType();
13531 llvm::APInt Size(S.Context.getTypeSize(SizeType),
13532 S.Context.getTypeSizeInChars(T).getQuantity());
13534 // Take the address of the field references for "from" and "to". We
13535 // directly construct UnaryOperators here because semantic analysis
13536 // does not permit us to take the address of an xvalue.
13537 Expr *From = FromB.build(S, Loc);
13538 From = UnaryOperator::Create(
13539 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13540 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13541 Expr *To = ToB.build(S, Loc);
13542 To = UnaryOperator::Create(
13543 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13544 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13546 const Type *E = T->getBaseElementTypeUnsafe();
13547 bool NeedsCollectableMemCpy =
13548 E->isRecordType() &&
13549 E->castAs<RecordType>()->getDecl()->hasObjectMember();
13551 // Create a reference to the __builtin_objc_memmove_collectable function
13552 StringRef MemCpyName = NeedsCollectableMemCpy ?
13553 "__builtin_objc_memmove_collectable" :
13554 "__builtin_memcpy";
13555 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13556 Sema::LookupOrdinaryName);
13557 S.LookupName(R, S.TUScope, true);
13559 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13561 // Something went horribly wrong earlier, and we will have complained
13563 return StmtError();
13565 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13566 VK_RValue, Loc, nullptr);
13567 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
13569 Expr *CallArgs[] = {
13570 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13572 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13573 Loc, CallArgs, Loc);
13575 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
13576 return Call.getAs<Stmt>();
13579 /// Builds a statement that copies/moves the given entity from \p From to
13582 /// This routine is used to copy/move the members of a class with an
13583 /// implicitly-declared copy/move assignment operator. When the entities being
13584 /// copied are arrays, this routine builds for loops to copy them.
13586 /// \param S The Sema object used for type-checking.
13588 /// \param Loc The location where the implicit copy/move is being generated.
13590 /// \param T The type of the expressions being copied/moved. Both expressions
13591 /// must have this type.
13593 /// \param To The expression we are copying/moving to.
13595 /// \param From The expression we are copying/moving from.
13597 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13598 /// Otherwise, it's a non-static member subobject.
13600 /// \param Copying Whether we're copying or moving.
13602 /// \param Depth Internal parameter recording the depth of the recursion.
13604 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13605 /// if a memcpy should be used instead.
13607 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13608 const ExprBuilder &To, const ExprBuilder &From,
13609 bool CopyingBaseSubobject, bool Copying,
13610 unsigned Depth = 0) {
13611 // C++11 [class.copy]p28:
13612 // Each subobject is assigned in the manner appropriate to its type:
13614 // - if the subobject is of class type, as if by a call to operator= with
13615 // the subobject as the object expression and the corresponding
13616 // subobject of x as a single function argument (as if by explicit
13617 // qualification; that is, ignoring any possible virtual overriding
13618 // functions in more derived classes);
13620 // C++03 [class.copy]p13:
13621 // - if the subobject is of class type, the copy assignment operator for
13622 // the class is used (as if by explicit qualification; that is,
13623 // ignoring any possible virtual overriding functions in more derived
13625 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13626 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13628 // Look for operator=.
13629 DeclarationName Name
13630 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13631 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13632 S.LookupQualifiedName(OpLookup, ClassDecl, false);
13634 // Prior to C++11, filter out any result that isn't a copy/move-assignment
13636 if (!S.getLangOpts().CPlusPlus11) {
13637 LookupResult::Filter F = OpLookup.makeFilter();
13638 while (F.hasNext()) {
13639 NamedDecl *D = F.next();
13640 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13641 if (Method->isCopyAssignmentOperator() ||
13642 (!Copying && Method->isMoveAssignmentOperator()))
13650 // Suppress the protected check (C++ [class.protected]) for each of the
13651 // assignment operators we found. This strange dance is required when
13652 // we're assigning via a base classes's copy-assignment operator. To
13653 // ensure that we're getting the right base class subobject (without
13654 // ambiguities), we need to cast "this" to that subobject type; to
13655 // ensure that we don't go through the virtual call mechanism, we need
13656 // to qualify the operator= name with the base class (see below). However,
13657 // this means that if the base class has a protected copy assignment
13658 // operator, the protected member access check will fail. So, we
13659 // rewrite "protected" access to "public" access in this case, since we
13660 // know by construction that we're calling from a derived class.
13661 if (CopyingBaseSubobject) {
13662 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
13664 if (L.getAccess() == AS_protected)
13665 L.setAccess(AS_public);
13669 // Create the nested-name-specifier that will be used to qualify the
13670 // reference to operator=; this is required to suppress the virtual
13673 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
13674 SS.MakeTrivial(S.Context,
13675 NestedNameSpecifier::Create(S.Context, nullptr, false,
13679 // Create the reference to operator=.
13680 ExprResult OpEqualRef
13681 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
13682 SS, /*TemplateKWLoc=*/SourceLocation(),
13683 /*FirstQualifierInScope=*/nullptr,
13685 /*TemplateArgs=*/nullptr, /*S*/nullptr,
13686 /*SuppressQualifierCheck=*/true);
13687 if (OpEqualRef.isInvalid())
13688 return StmtError();
13690 // Build the call to the assignment operator.
13692 Expr *FromInst = From.build(S, Loc);
13693 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
13694 OpEqualRef.getAs<Expr>(),
13695 Loc, FromInst, Loc);
13696 if (Call.isInvalid())
13697 return StmtError();
13699 // If we built a call to a trivial 'operator=' while copying an array,
13700 // bail out. We'll replace the whole shebang with a memcpy.
13701 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
13702 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
13703 return StmtResult((Stmt*)nullptr);
13705 // Convert to an expression-statement, and clean up any produced
13707 return S.ActOnExprStmt(Call);
13710 // - if the subobject is of scalar type, the built-in assignment
13711 // operator is used.
13712 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
13714 ExprResult Assignment = S.CreateBuiltinBinOp(
13715 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
13716 if (Assignment.isInvalid())
13717 return StmtError();
13718 return S.ActOnExprStmt(Assignment);
13721 // - if the subobject is an array, each element is assigned, in the
13722 // manner appropriate to the element type;
13724 // Construct a loop over the array bounds, e.g.,
13726 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
13728 // that will copy each of the array elements.
13729 QualType SizeType = S.Context.getSizeType();
13731 // Create the iteration variable.
13732 IdentifierInfo *IterationVarName = nullptr;
13734 SmallString<8> Str;
13735 llvm::raw_svector_ostream OS(Str);
13736 OS << "__i" << Depth;
13737 IterationVarName = &S.Context.Idents.get(OS.str());
13739 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
13740 IterationVarName, SizeType,
13741 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
13744 // Initialize the iteration variable to zero.
13745 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
13746 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
13748 // Creates a reference to the iteration variable.
13749 RefBuilder IterationVarRef(IterationVar, SizeType);
13750 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
13752 // Create the DeclStmt that holds the iteration variable.
13753 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
13755 // Subscript the "from" and "to" expressions with the iteration variable.
13756 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
13757 MoveCastBuilder FromIndexMove(FromIndexCopy);
13758 const ExprBuilder *FromIndex;
13760 FromIndex = &FromIndexCopy;
13762 FromIndex = &FromIndexMove;
13764 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
13766 // Build the copy/move for an individual element of the array.
13768 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
13769 ToIndex, *FromIndex, CopyingBaseSubobject,
13770 Copying, Depth + 1);
13771 // Bail out if copying fails or if we determined that we should use memcpy.
13772 if (Copy.isInvalid() || !Copy.get())
13775 // Create the comparison against the array bound.
13777 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
13778 Expr *Comparison = BinaryOperator::Create(
13779 S.Context, IterationVarRefRVal.build(S, Loc),
13780 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
13781 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides());
13783 // Create the pre-increment of the iteration variable. We can determine
13784 // whether the increment will overflow based on the value of the array
13786 Expr *Increment = UnaryOperator::Create(
13787 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
13788 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
13790 // Construct the loop that copies all elements of this array.
13791 return S.ActOnForStmt(
13792 Loc, Loc, InitStmt,
13793 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
13794 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
13798 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
13799 const ExprBuilder &To, const ExprBuilder &From,
13800 bool CopyingBaseSubobject, bool Copying) {
13801 // Maybe we should use a memcpy?
13802 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
13803 T.isTriviallyCopyableType(S.Context))
13804 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13806 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
13807 CopyingBaseSubobject,
13810 // If we ended up picking a trivial assignment operator for an array of a
13811 // non-trivially-copyable class type, just emit a memcpy.
13812 if (!Result.isInvalid() && !Result.get())
13813 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
13818 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
13819 // Note: The following rules are largely analoguous to the copy
13820 // constructor rules. Note that virtual bases are not taken into account
13821 // for determining the argument type of the operator. Note also that
13822 // operators taking an object instead of a reference are allowed.
13823 assert(ClassDecl->needsImplicitCopyAssignment());
13825 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
13826 if (DSM.isAlreadyBeingDeclared())
13829 QualType ArgType = Context.getTypeDeclType(ClassDecl);
13830 LangAS AS = getDefaultCXXMethodAddrSpace();
13831 if (AS != LangAS::Default)
13832 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
13833 QualType RetType = Context.getLValueReferenceType(ArgType);
13834 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
13836 ArgType = ArgType.withConst();
13838 ArgType = Context.getLValueReferenceType(ArgType);
13840 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13844 // An implicitly-declared copy assignment operator is an inline public
13845 // member of its class.
13846 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13847 SourceLocation ClassLoc = ClassDecl->getLocation();
13848 DeclarationNameInfo NameInfo(Name, ClassLoc);
13849 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
13850 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
13851 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
13852 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
13854 CopyAssignment->setAccess(AS_public);
13855 CopyAssignment->setDefaulted();
13856 CopyAssignment->setImplicit();
13858 if (getLangOpts().CUDA) {
13859 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
13861 /* ConstRHS */ Const,
13862 /* Diagnose */ false);
13865 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
13867 // Add the parameter to the operator.
13868 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
13869 ClassLoc, ClassLoc,
13870 /*Id=*/nullptr, ArgType,
13871 /*TInfo=*/nullptr, SC_None,
13873 CopyAssignment->setParams(FromParam);
13875 CopyAssignment->setTrivial(
13876 ClassDecl->needsOverloadResolutionForCopyAssignment()
13877 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
13878 : ClassDecl->hasTrivialCopyAssignment());
13880 // Note that we have added this copy-assignment operator.
13881 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
13883 Scope *S = getScopeForContext(ClassDecl);
13884 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
13886 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
13887 ClassDecl->setImplicitCopyAssignmentIsDeleted();
13888 SetDeclDeleted(CopyAssignment, ClassLoc);
13892 PushOnScopeChains(CopyAssignment, S, false);
13893 ClassDecl->addDecl(CopyAssignment);
13895 return CopyAssignment;
13898 /// Diagnose an implicit copy operation for a class which is odr-used, but
13899 /// which is deprecated because the class has a user-declared copy constructor,
13900 /// copy assignment operator, or destructor.
13901 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
13902 assert(CopyOp->isImplicit());
13904 CXXRecordDecl *RD = CopyOp->getParent();
13905 CXXMethodDecl *UserDeclaredOperation = nullptr;
13907 // In Microsoft mode, assignment operations don't affect constructors and
13909 if (RD->hasUserDeclaredDestructor()) {
13910 UserDeclaredOperation = RD->getDestructor();
13911 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
13912 RD->hasUserDeclaredCopyConstructor() &&
13913 !S.getLangOpts().MSVCCompat) {
13914 // Find any user-declared copy constructor.
13915 for (auto *I : RD->ctors()) {
13916 if (I->isCopyConstructor()) {
13917 UserDeclaredOperation = I;
13921 assert(UserDeclaredOperation);
13922 } else if (isa<CXXConstructorDecl>(CopyOp) &&
13923 RD->hasUserDeclaredCopyAssignment() &&
13924 !S.getLangOpts().MSVCCompat) {
13925 // Find any user-declared move assignment operator.
13926 for (auto *I : RD->methods()) {
13927 if (I->isCopyAssignmentOperator()) {
13928 UserDeclaredOperation = I;
13932 assert(UserDeclaredOperation);
13935 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) {
13936 S.Diag(UserDeclaredOperation->getLocation(),
13937 isa<CXXDestructorDecl>(UserDeclaredOperation)
13938 ? diag::warn_deprecated_copy_dtor_operation
13939 : diag::warn_deprecated_copy_operation)
13940 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp);
13944 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
13945 CXXMethodDecl *CopyAssignOperator) {
13946 assert((CopyAssignOperator->isDefaulted() &&
13947 CopyAssignOperator->isOverloadedOperator() &&
13948 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
13949 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
13950 !CopyAssignOperator->isDeleted()) &&
13951 "DefineImplicitCopyAssignment called for wrong function");
13952 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
13955 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
13956 if (ClassDecl->isInvalidDecl()) {
13957 CopyAssignOperator->setInvalidDecl();
13961 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
13963 // The exception specification is needed because we are defining the
13965 ResolveExceptionSpec(CurrentLocation,
13966 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
13968 // Add a context note for diagnostics produced after this point.
13969 Scope.addContextNote(CurrentLocation);
13971 // C++11 [class.copy]p18:
13972 // The [definition of an implicitly declared copy assignment operator] is
13973 // deprecated if the class has a user-declared copy constructor or a
13974 // user-declared destructor.
13975 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
13976 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
13978 // C++0x [class.copy]p30:
13979 // The implicitly-defined or explicitly-defaulted copy assignment operator
13980 // for a non-union class X performs memberwise copy assignment of its
13981 // subobjects. The direct base classes of X are assigned first, in the
13982 // order of their declaration in the base-specifier-list, and then the
13983 // immediate non-static data members of X are assigned, in the order in
13984 // which they were declared in the class definition.
13986 // The statements that form the synthesized function body.
13987 SmallVector<Stmt*, 8> Statements;
13989 // The parameter for the "other" object, which we are copying from.
13990 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
13991 Qualifiers OtherQuals = Other->getType().getQualifiers();
13992 QualType OtherRefType = Other->getType();
13993 if (const LValueReferenceType *OtherRef
13994 = OtherRefType->getAs<LValueReferenceType>()) {
13995 OtherRefType = OtherRef->getPointeeType();
13996 OtherQuals = OtherRefType.getQualifiers();
13999 // Our location for everything implicitly-generated.
14000 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14001 ? CopyAssignOperator->getEndLoc()
14002 : CopyAssignOperator->getLocation();
14004 // Builds a DeclRefExpr for the "other" object.
14005 RefBuilder OtherRef(Other, OtherRefType);
14007 // Builds the "this" pointer.
14010 // Assign base classes.
14011 bool Invalid = false;
14012 for (auto &Base : ClassDecl->bases()) {
14013 // Form the assignment:
14014 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14015 QualType BaseType = Base.getType().getUnqualifiedType();
14016 if (!BaseType->isRecordType()) {
14021 CXXCastPath BasePath;
14022 BasePath.push_back(&Base);
14024 // Construct the "from" expression, which is an implicit cast to the
14025 // appropriately-qualified base type.
14026 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14027 VK_LValue, BasePath);
14029 // Dereference "this".
14030 DerefBuilder DerefThis(This);
14031 CastBuilder To(DerefThis,
14032 Context.getQualifiedType(
14033 BaseType, CopyAssignOperator->getMethodQualifiers()),
14034 VK_LValue, BasePath);
14037 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14039 /*CopyingBaseSubobject=*/true,
14041 if (Copy.isInvalid()) {
14042 CopyAssignOperator->setInvalidDecl();
14046 // Success! Record the copy.
14047 Statements.push_back(Copy.getAs<Expr>());
14050 // Assign non-static members.
14051 for (auto *Field : ClassDecl->fields()) {
14052 // FIXME: We should form some kind of AST representation for the implied
14053 // memcpy in a union copy operation.
14054 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14057 if (Field->isInvalidDecl()) {
14062 // Check for members of reference type; we can't copy those.
14063 if (Field->getType()->isReferenceType()) {
14064 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14065 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14066 Diag(Field->getLocation(), diag::note_declared_at);
14071 // Check for members of const-qualified, non-class type.
14072 QualType BaseType = Context.getBaseElementType(Field->getType());
14073 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14074 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14075 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14076 Diag(Field->getLocation(), diag::note_declared_at);
14081 // Suppress assigning zero-width bitfields.
14082 if (Field->isZeroLengthBitField(Context))
14085 QualType FieldType = Field->getType().getNonReferenceType();
14086 if (FieldType->isIncompleteArrayType()) {
14087 assert(ClassDecl->hasFlexibleArrayMember() &&
14088 "Incomplete array type is not valid");
14092 // Build references to the field in the object we're copying from and to.
14093 CXXScopeSpec SS; // Intentionally empty
14094 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14096 MemberLookup.addDecl(Field);
14097 MemberLookup.resolveKind();
14099 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14101 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14103 // Build the copy of this field.
14104 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14106 /*CopyingBaseSubobject=*/false,
14108 if (Copy.isInvalid()) {
14109 CopyAssignOperator->setInvalidDecl();
14113 // Success! Record the copy.
14114 Statements.push_back(Copy.getAs<Stmt>());
14118 // Add a "return *this;"
14119 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14121 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14122 if (Return.isInvalid())
14125 Statements.push_back(Return.getAs<Stmt>());
14129 CopyAssignOperator->setInvalidDecl();
14135 CompoundScopeRAII CompoundScope(*this);
14136 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14137 /*isStmtExpr=*/false);
14138 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14140 CopyAssignOperator->setBody(Body.getAs<Stmt>());
14141 CopyAssignOperator->markUsed(Context);
14143 if (ASTMutationListener *L = getASTMutationListener()) {
14144 L->CompletedImplicitDefinition(CopyAssignOperator);
14148 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14149 assert(ClassDecl->needsImplicitMoveAssignment());
14151 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14152 if (DSM.isAlreadyBeingDeclared())
14155 // Note: The following rules are largely analoguous to the move
14156 // constructor rules.
14158 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14159 LangAS AS = getDefaultCXXMethodAddrSpace();
14160 if (AS != LangAS::Default)
14161 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14162 QualType RetType = Context.getLValueReferenceType(ArgType);
14163 ArgType = Context.getRValueReferenceType(ArgType);
14165 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14169 // An implicitly-declared move assignment operator is an inline public
14170 // member of its class.
14171 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14172 SourceLocation ClassLoc = ClassDecl->getLocation();
14173 DeclarationNameInfo NameInfo(Name, ClassLoc);
14174 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14175 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14176 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14177 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
14179 MoveAssignment->setAccess(AS_public);
14180 MoveAssignment->setDefaulted();
14181 MoveAssignment->setImplicit();
14183 if (getLangOpts().CUDA) {
14184 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14186 /* ConstRHS */ false,
14187 /* Diagnose */ false);
14190 // Build an exception specification pointing back at this member.
14191 FunctionProtoType::ExtProtoInfo EPI =
14192 getImplicitMethodEPI(*this, MoveAssignment);
14193 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
14195 // Add the parameter to the operator.
14196 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14197 ClassLoc, ClassLoc,
14198 /*Id=*/nullptr, ArgType,
14199 /*TInfo=*/nullptr, SC_None,
14201 MoveAssignment->setParams(FromParam);
14203 MoveAssignment->setTrivial(
14204 ClassDecl->needsOverloadResolutionForMoveAssignment()
14205 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14206 : ClassDecl->hasTrivialMoveAssignment());
14208 // Note that we have added this copy-assignment operator.
14209 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14211 Scope *S = getScopeForContext(ClassDecl);
14212 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14214 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14215 ClassDecl->setImplicitMoveAssignmentIsDeleted();
14216 SetDeclDeleted(MoveAssignment, ClassLoc);
14220 PushOnScopeChains(MoveAssignment, S, false);
14221 ClassDecl->addDecl(MoveAssignment);
14223 return MoveAssignment;
14226 /// Check if we're implicitly defining a move assignment operator for a class
14227 /// with virtual bases. Such a move assignment might move-assign the virtual
14228 /// base multiple times.
14229 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14230 SourceLocation CurrentLocation) {
14231 assert(!Class->isDependentContext() && "should not define dependent move");
14233 // Only a virtual base could get implicitly move-assigned multiple times.
14234 // Only a non-trivial move assignment can observe this. We only want to
14235 // diagnose if we implicitly define an assignment operator that assigns
14236 // two base classes, both of which move-assign the same virtual base.
14237 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14238 Class->getNumBases() < 2)
14241 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14242 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14245 for (auto &BI : Class->bases()) {
14246 Worklist.push_back(&BI);
14247 while (!Worklist.empty()) {
14248 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14249 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14251 // If the base has no non-trivial move assignment operators,
14252 // we don't care about moves from it.
14253 if (!Base->hasNonTrivialMoveAssignment())
14256 // If there's nothing virtual here, skip it.
14257 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14260 // If we're not actually going to call a move assignment for this base,
14261 // or the selected move assignment is trivial, skip it.
14262 Sema::SpecialMemberOverloadResult SMOR =
14263 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14264 /*ConstArg*/false, /*VolatileArg*/false,
14265 /*RValueThis*/true, /*ConstThis*/false,
14266 /*VolatileThis*/false);
14267 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14268 !SMOR.getMethod()->isMoveAssignmentOperator())
14271 if (BaseSpec->isVirtual()) {
14272 // We're going to move-assign this virtual base, and its move
14273 // assignment operator is not trivial. If this can happen for
14274 // multiple distinct direct bases of Class, diagnose it. (If it
14275 // only happens in one base, we'll diagnose it when synthesizing
14276 // that base class's move assignment operator.)
14277 CXXBaseSpecifier *&Existing =
14278 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14280 if (Existing && Existing != &BI) {
14281 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14283 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14284 << (Base->getCanonicalDecl() ==
14285 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14286 << Base << Existing->getType() << Existing->getSourceRange();
14287 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14288 << (Base->getCanonicalDecl() ==
14289 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14290 << Base << BI.getType() << BaseSpec->getSourceRange();
14292 // Only diagnose each vbase once.
14293 Existing = nullptr;
14296 // Only walk over bases that have defaulted move assignment operators.
14297 // We assume that any user-provided move assignment operator handles
14298 // the multiple-moves-of-vbase case itself somehow.
14299 if (!SMOR.getMethod()->isDefaulted())
14302 // We're going to move the base classes of Base. Add them to the list.
14303 for (auto &BI : Base->bases())
14304 Worklist.push_back(&BI);
14310 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14311 CXXMethodDecl *MoveAssignOperator) {
14312 assert((MoveAssignOperator->isDefaulted() &&
14313 MoveAssignOperator->isOverloadedOperator() &&
14314 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
14315 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
14316 !MoveAssignOperator->isDeleted()) &&
14317 "DefineImplicitMoveAssignment called for wrong function");
14318 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14321 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14322 if (ClassDecl->isInvalidDecl()) {
14323 MoveAssignOperator->setInvalidDecl();
14327 // C++0x [class.copy]p28:
14328 // The implicitly-defined or move assignment operator for a non-union class
14329 // X performs memberwise move assignment of its subobjects. The direct base
14330 // classes of X are assigned first, in the order of their declaration in the
14331 // base-specifier-list, and then the immediate non-static data members of X
14332 // are assigned, in the order in which they were declared in the class
14335 // Issue a warning if our implicit move assignment operator will move
14336 // from a virtual base more than once.
14337 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14339 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14341 // The exception specification is needed because we are defining the
14343 ResolveExceptionSpec(CurrentLocation,
14344 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14346 // Add a context note for diagnostics produced after this point.
14347 Scope.addContextNote(CurrentLocation);
14349 // The statements that form the synthesized function body.
14350 SmallVector<Stmt*, 8> Statements;
14352 // The parameter for the "other" object, which we are move from.
14353 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14354 QualType OtherRefType =
14355 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14357 // Our location for everything implicitly-generated.
14358 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14359 ? MoveAssignOperator->getEndLoc()
14360 : MoveAssignOperator->getLocation();
14362 // Builds a reference to the "other" object.
14363 RefBuilder OtherRef(Other, OtherRefType);
14365 MoveCastBuilder MoveOther(OtherRef);
14367 // Builds the "this" pointer.
14370 // Assign base classes.
14371 bool Invalid = false;
14372 for (auto &Base : ClassDecl->bases()) {
14373 // C++11 [class.copy]p28:
14374 // It is unspecified whether subobjects representing virtual base classes
14375 // are assigned more than once by the implicitly-defined copy assignment
14377 // FIXME: Do not assign to a vbase that will be assigned by some other base
14378 // class. For a move-assignment, this can result in the vbase being moved
14381 // Form the assignment:
14382 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14383 QualType BaseType = Base.getType().getUnqualifiedType();
14384 if (!BaseType->isRecordType()) {
14389 CXXCastPath BasePath;
14390 BasePath.push_back(&Base);
14392 // Construct the "from" expression, which is an implicit cast to the
14393 // appropriately-qualified base type.
14394 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14396 // Dereference "this".
14397 DerefBuilder DerefThis(This);
14399 // Implicitly cast "this" to the appropriately-qualified base type.
14400 CastBuilder To(DerefThis,
14401 Context.getQualifiedType(
14402 BaseType, MoveAssignOperator->getMethodQualifiers()),
14403 VK_LValue, BasePath);
14406 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14408 /*CopyingBaseSubobject=*/true,
14409 /*Copying=*/false);
14410 if (Move.isInvalid()) {
14411 MoveAssignOperator->setInvalidDecl();
14415 // Success! Record the move.
14416 Statements.push_back(Move.getAs<Expr>());
14419 // Assign non-static members.
14420 for (auto *Field : ClassDecl->fields()) {
14421 // FIXME: We should form some kind of AST representation for the implied
14422 // memcpy in a union copy operation.
14423 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14426 if (Field->isInvalidDecl()) {
14431 // Check for members of reference type; we can't move those.
14432 if (Field->getType()->isReferenceType()) {
14433 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14434 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14435 Diag(Field->getLocation(), diag::note_declared_at);
14440 // Check for members of const-qualified, non-class type.
14441 QualType BaseType = Context.getBaseElementType(Field->getType());
14442 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14443 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14444 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14445 Diag(Field->getLocation(), diag::note_declared_at);
14450 // Suppress assigning zero-width bitfields.
14451 if (Field->isZeroLengthBitField(Context))
14454 QualType FieldType = Field->getType().getNonReferenceType();
14455 if (FieldType->isIncompleteArrayType()) {
14456 assert(ClassDecl->hasFlexibleArrayMember() &&
14457 "Incomplete array type is not valid");
14461 // Build references to the field in the object we're copying from and to.
14462 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14464 MemberLookup.addDecl(Field);
14465 MemberLookup.resolveKind();
14466 MemberBuilder From(MoveOther, OtherRefType,
14467 /*IsArrow=*/false, MemberLookup);
14468 MemberBuilder To(This, getCurrentThisType(),
14469 /*IsArrow=*/true, MemberLookup);
14471 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
14472 "Member reference with rvalue base must be rvalue except for reference "
14473 "members, which aren't allowed for move assignment.");
14475 // Build the move of this field.
14476 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14478 /*CopyingBaseSubobject=*/false,
14479 /*Copying=*/false);
14480 if (Move.isInvalid()) {
14481 MoveAssignOperator->setInvalidDecl();
14485 // Success! Record the copy.
14486 Statements.push_back(Move.getAs<Stmt>());
14490 // Add a "return *this;"
14491 ExprResult ThisObj =
14492 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14494 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14495 if (Return.isInvalid())
14498 Statements.push_back(Return.getAs<Stmt>());
14502 MoveAssignOperator->setInvalidDecl();
14508 CompoundScopeRAII CompoundScope(*this);
14509 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14510 /*isStmtExpr=*/false);
14511 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
14513 MoveAssignOperator->setBody(Body.getAs<Stmt>());
14514 MoveAssignOperator->markUsed(Context);
14516 if (ASTMutationListener *L = getASTMutationListener()) {
14517 L->CompletedImplicitDefinition(MoveAssignOperator);
14521 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14522 CXXRecordDecl *ClassDecl) {
14523 // C++ [class.copy]p4:
14524 // If the class definition does not explicitly declare a copy
14525 // constructor, one is declared implicitly.
14526 assert(ClassDecl->needsImplicitCopyConstructor());
14528 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14529 if (DSM.isAlreadyBeingDeclared())
14532 QualType ClassType = Context.getTypeDeclType(ClassDecl);
14533 QualType ArgType = ClassType;
14534 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14536 ArgType = ArgType.withConst();
14538 LangAS AS = getDefaultCXXMethodAddrSpace();
14539 if (AS != LangAS::Default)
14540 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14542 ArgType = Context.getLValueReferenceType(ArgType);
14544 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14545 CXXCopyConstructor,
14548 DeclarationName Name
14549 = Context.DeclarationNames.getCXXConstructorName(
14550 Context.getCanonicalType(ClassType));
14551 SourceLocation ClassLoc = ClassDecl->getLocation();
14552 DeclarationNameInfo NameInfo(Name, ClassLoc);
14554 // An implicitly-declared copy constructor is an inline public
14555 // member of its class.
14556 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14557 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14558 ExplicitSpecifier(),
14560 /*isImplicitlyDeclared=*/true,
14561 Constexpr ? CSK_constexpr : CSK_unspecified);
14562 CopyConstructor->setAccess(AS_public);
14563 CopyConstructor->setDefaulted();
14565 if (getLangOpts().CUDA) {
14566 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14568 /* ConstRHS */ Const,
14569 /* Diagnose */ false);
14572 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14574 // Add the parameter to the constructor.
14575 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
14576 ClassLoc, ClassLoc,
14577 /*IdentifierInfo=*/nullptr,
14578 ArgType, /*TInfo=*/nullptr,
14580 CopyConstructor->setParams(FromParam);
14582 CopyConstructor->setTrivial(
14583 ClassDecl->needsOverloadResolutionForCopyConstructor()
14584 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14585 : ClassDecl->hasTrivialCopyConstructor());
14587 CopyConstructor->setTrivialForCall(
14588 ClassDecl->hasAttr<TrivialABIAttr>() ||
14589 (ClassDecl->needsOverloadResolutionForCopyConstructor()
14590 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14591 TAH_ConsiderTrivialABI)
14592 : ClassDecl->hasTrivialCopyConstructorForCall()));
14594 // Note that we have declared this constructor.
14595 ++getASTContext().NumImplicitCopyConstructorsDeclared;
14597 Scope *S = getScopeForContext(ClassDecl);
14598 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14600 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14601 ClassDecl->setImplicitCopyConstructorIsDeleted();
14602 SetDeclDeleted(CopyConstructor, ClassLoc);
14606 PushOnScopeChains(CopyConstructor, S, false);
14607 ClassDecl->addDecl(CopyConstructor);
14609 return CopyConstructor;
14612 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14613 CXXConstructorDecl *CopyConstructor) {
14614 assert((CopyConstructor->isDefaulted() &&
14615 CopyConstructor->isCopyConstructor() &&
14616 !CopyConstructor->doesThisDeclarationHaveABody() &&
14617 !CopyConstructor->isDeleted()) &&
14618 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
14619 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14622 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14623 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
14625 SynthesizedFunctionScope Scope(*this, CopyConstructor);
14627 // The exception specification is needed because we are defining the
14629 ResolveExceptionSpec(CurrentLocation,
14630 CopyConstructor->getType()->castAs<FunctionProtoType>());
14631 MarkVTableUsed(CurrentLocation, ClassDecl);
14633 // Add a context note for diagnostics produced after this point.
14634 Scope.addContextNote(CurrentLocation);
14636 // C++11 [class.copy]p7:
14637 // The [definition of an implicitly declared copy constructor] is
14638 // deprecated if the class has a user-declared copy assignment operator
14639 // or a user-declared destructor.
14640 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14641 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14643 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14644 CopyConstructor->setInvalidDecl();
14646 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
14647 ? CopyConstructor->getEndLoc()
14648 : CopyConstructor->getLocation();
14649 Sema::CompoundScopeRAII CompoundScope(*this);
14650 CopyConstructor->setBody(
14651 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
14652 CopyConstructor->markUsed(Context);
14655 if (ASTMutationListener *L = getASTMutationListener()) {
14656 L->CompletedImplicitDefinition(CopyConstructor);
14660 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
14661 CXXRecordDecl *ClassDecl) {
14662 assert(ClassDecl->needsImplicitMoveConstructor());
14664 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
14665 if (DSM.isAlreadyBeingDeclared())
14668 QualType ClassType = Context.getTypeDeclType(ClassDecl);
14670 QualType ArgType = ClassType;
14671 LangAS AS = getDefaultCXXMethodAddrSpace();
14672 if (AS != LangAS::Default)
14673 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
14674 ArgType = Context.getRValueReferenceType(ArgType);
14676 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14677 CXXMoveConstructor,
14680 DeclarationName Name
14681 = Context.DeclarationNames.getCXXConstructorName(
14682 Context.getCanonicalType(ClassType));
14683 SourceLocation ClassLoc = ClassDecl->getLocation();
14684 DeclarationNameInfo NameInfo(Name, ClassLoc);
14686 // C++11 [class.copy]p11:
14687 // An implicitly-declared copy/move constructor is an inline public
14688 // member of its class.
14689 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
14690 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14691 ExplicitSpecifier(),
14693 /*isImplicitlyDeclared=*/true,
14694 Constexpr ? CSK_constexpr : CSK_unspecified);
14695 MoveConstructor->setAccess(AS_public);
14696 MoveConstructor->setDefaulted();
14698 if (getLangOpts().CUDA) {
14699 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
14701 /* ConstRHS */ false,
14702 /* Diagnose */ false);
14705 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
14707 // Add the parameter to the constructor.
14708 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
14709 ClassLoc, ClassLoc,
14710 /*IdentifierInfo=*/nullptr,
14711 ArgType, /*TInfo=*/nullptr,
14713 MoveConstructor->setParams(FromParam);
14715 MoveConstructor->setTrivial(
14716 ClassDecl->needsOverloadResolutionForMoveConstructor()
14717 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
14718 : ClassDecl->hasTrivialMoveConstructor());
14720 MoveConstructor->setTrivialForCall(
14721 ClassDecl->hasAttr<TrivialABIAttr>() ||
14722 (ClassDecl->needsOverloadResolutionForMoveConstructor()
14723 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
14724 TAH_ConsiderTrivialABI)
14725 : ClassDecl->hasTrivialMoveConstructorForCall()));
14727 // Note that we have declared this constructor.
14728 ++getASTContext().NumImplicitMoveConstructorsDeclared;
14730 Scope *S = getScopeForContext(ClassDecl);
14731 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
14733 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
14734 ClassDecl->setImplicitMoveConstructorIsDeleted();
14735 SetDeclDeleted(MoveConstructor, ClassLoc);
14739 PushOnScopeChains(MoveConstructor, S, false);
14740 ClassDecl->addDecl(MoveConstructor);
14742 return MoveConstructor;
14745 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
14746 CXXConstructorDecl *MoveConstructor) {
14747 assert((MoveConstructor->isDefaulted() &&
14748 MoveConstructor->isMoveConstructor() &&
14749 !MoveConstructor->doesThisDeclarationHaveABody() &&
14750 !MoveConstructor->isDeleted()) &&
14751 "DefineImplicitMoveConstructor - call it for implicit move ctor");
14752 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
14755 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
14756 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
14758 SynthesizedFunctionScope Scope(*this, MoveConstructor);
14760 // The exception specification is needed because we are defining the
14762 ResolveExceptionSpec(CurrentLocation,
14763 MoveConstructor->getType()->castAs<FunctionProtoType>());
14764 MarkVTableUsed(CurrentLocation, ClassDecl);
14766 // Add a context note for diagnostics produced after this point.
14767 Scope.addContextNote(CurrentLocation);
14769 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
14770 MoveConstructor->setInvalidDecl();
14772 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
14773 ? MoveConstructor->getEndLoc()
14774 : MoveConstructor->getLocation();
14775 Sema::CompoundScopeRAII CompoundScope(*this);
14776 MoveConstructor->setBody(ActOnCompoundStmt(
14777 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
14778 MoveConstructor->markUsed(Context);
14781 if (ASTMutationListener *L = getASTMutationListener()) {
14782 L->CompletedImplicitDefinition(MoveConstructor);
14786 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
14787 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
14790 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
14791 SourceLocation CurrentLocation,
14792 CXXConversionDecl *Conv) {
14793 SynthesizedFunctionScope Scope(*this, Conv);
14794 assert(!Conv->getReturnType()->isUndeducedType());
14796 CXXRecordDecl *Lambda = Conv->getParent();
14797 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
14798 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
14800 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
14801 CallOp = InstantiateFunctionDeclaration(
14802 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14806 Invoker = InstantiateFunctionDeclaration(
14807 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
14812 if (CallOp->isInvalidDecl())
14815 // Mark the call operator referenced (and add to pending instantiations
14817 // For both the conversion and static-invoker template specializations
14818 // we construct their body's in this function, so no need to add them
14819 // to the PendingInstantiations.
14820 MarkFunctionReferenced(CurrentLocation, CallOp);
14822 // Fill in the __invoke function with a dummy implementation. IR generation
14823 // will fill in the actual details. Update its type in case it contained
14825 Invoker->markUsed(Context);
14826 Invoker->setReferenced();
14827 Invoker->setType(Conv->getReturnType()->getPointeeType());
14828 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
14830 // Construct the body of the conversion function { return __invoke; }.
14831 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
14832 VK_LValue, Conv->getLocation());
14833 assert(FunctionRef && "Can't refer to __invoke function?");
14834 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
14835 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
14836 Conv->getLocation()));
14837 Conv->markUsed(Context);
14838 Conv->setReferenced();
14840 if (ASTMutationListener *L = getASTMutationListener()) {
14841 L->CompletedImplicitDefinition(Conv);
14842 L->CompletedImplicitDefinition(Invoker);
14848 void Sema::DefineImplicitLambdaToBlockPointerConversion(
14849 SourceLocation CurrentLocation,
14850 CXXConversionDecl *Conv)
14852 assert(!Conv->getParent()->isGenericLambda());
14854 SynthesizedFunctionScope Scope(*this, Conv);
14856 // Copy-initialize the lambda object as needed to capture it.
14857 Expr *This = ActOnCXXThis(CurrentLocation).get();
14858 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
14860 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
14861 Conv->getLocation(),
14864 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
14865 // behavior. Note that only the general conversion function does this
14866 // (since it's unusable otherwise); in the case where we inline the
14867 // block literal, it has block literal lifetime semantics.
14868 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
14869 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
14870 CK_CopyAndAutoreleaseBlockObject,
14871 BuildBlock.get(), nullptr, VK_RValue);
14873 if (BuildBlock.isInvalid()) {
14874 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14875 Conv->setInvalidDecl();
14879 // Create the return statement that returns the block from the conversion
14881 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
14882 if (Return.isInvalid()) {
14883 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
14884 Conv->setInvalidDecl();
14888 // Set the body of the conversion function.
14889 Stmt *ReturnS = Return.get();
14890 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
14891 Conv->getLocation()));
14892 Conv->markUsed(Context);
14894 // We're done; notify the mutation listener, if any.
14895 if (ASTMutationListener *L = getASTMutationListener()) {
14896 L->CompletedImplicitDefinition(Conv);
14900 /// Determine whether the given list arguments contains exactly one
14901 /// "real" (non-default) argument.
14902 static bool hasOneRealArgument(MultiExprArg Args) {
14903 switch (Args.size()) {
14908 if (!Args[1]->isDefaultArgument())
14913 return !Args[0]->isDefaultArgument();
14920 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14921 NamedDecl *FoundDecl,
14922 CXXConstructorDecl *Constructor,
14923 MultiExprArg ExprArgs,
14924 bool HadMultipleCandidates,
14925 bool IsListInitialization,
14926 bool IsStdInitListInitialization,
14927 bool RequiresZeroInit,
14928 unsigned ConstructKind,
14929 SourceRange ParenRange) {
14930 bool Elidable = false;
14932 // C++0x [class.copy]p34:
14933 // When certain criteria are met, an implementation is allowed to
14934 // omit the copy/move construction of a class object, even if the
14935 // copy/move constructor and/or destructor for the object have
14936 // side effects. [...]
14937 // - when a temporary class object that has not been bound to a
14938 // reference (12.2) would be copied/moved to a class object
14939 // with the same cv-unqualified type, the copy/move operation
14940 // can be omitted by constructing the temporary object
14941 // directly into the target of the omitted copy/move
14942 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
14943 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
14944 Expr *SubExpr = ExprArgs[0];
14945 Elidable = SubExpr->isTemporaryObject(
14946 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
14949 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
14950 FoundDecl, Constructor,
14951 Elidable, ExprArgs, HadMultipleCandidates,
14952 IsListInitialization,
14953 IsStdInitListInitialization, RequiresZeroInit,
14954 ConstructKind, ParenRange);
14958 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14959 NamedDecl *FoundDecl,
14960 CXXConstructorDecl *Constructor,
14962 MultiExprArg ExprArgs,
14963 bool HadMultipleCandidates,
14964 bool IsListInitialization,
14965 bool IsStdInitListInitialization,
14966 bool RequiresZeroInit,
14967 unsigned ConstructKind,
14968 SourceRange ParenRange) {
14969 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
14970 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
14971 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
14972 return ExprError();
14975 return BuildCXXConstructExpr(
14976 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
14977 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
14978 RequiresZeroInit, ConstructKind, ParenRange);
14981 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
14982 /// including handling of its default argument expressions.
14984 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
14985 CXXConstructorDecl *Constructor,
14987 MultiExprArg ExprArgs,
14988 bool HadMultipleCandidates,
14989 bool IsListInitialization,
14990 bool IsStdInitListInitialization,
14991 bool RequiresZeroInit,
14992 unsigned ConstructKind,
14993 SourceRange ParenRange) {
14994 assert(declaresSameEntity(
14995 Constructor->getParent(),
14996 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
14997 "given constructor for wrong type");
14998 MarkFunctionReferenced(ConstructLoc, Constructor);
14999 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15000 return ExprError();
15001 if (getLangOpts().SYCLIsDevice &&
15002 !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15003 return ExprError();
15005 return CheckForImmediateInvocation(
15006 CXXConstructExpr::Create(
15007 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15008 HadMultipleCandidates, IsListInitialization,
15009 IsStdInitListInitialization, RequiresZeroInit,
15010 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15015 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15016 assert(Field->hasInClassInitializer());
15018 // If we already have the in-class initializer nothing needs to be done.
15019 if (Field->getInClassInitializer())
15020 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15022 // If we might have already tried and failed to instantiate, don't try again.
15023 if (Field->isInvalidDecl())
15024 return ExprError();
15026 // Maybe we haven't instantiated the in-class initializer. Go check the
15027 // pattern FieldDecl to see if it has one.
15028 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15030 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15031 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15032 DeclContext::lookup_result Lookup =
15033 ClassPattern->lookup(Field->getDeclName());
15035 // Lookup can return at most two results: the pattern for the field, or the
15036 // injected class name of the parent record. No other member can have the
15037 // same name as the field.
15038 // In modules mode, lookup can return multiple results (coming from
15039 // different modules).
15040 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
15041 "more than two lookup results for field name");
15042 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
15044 assert(isa<CXXRecordDecl>(Lookup[0]) &&
15045 "cannot have other non-field member with same name");
15046 for (auto L : Lookup)
15047 if (isa<FieldDecl>(L)) {
15048 Pattern = cast<FieldDecl>(L);
15051 assert(Pattern && "We must have set the Pattern!");
15054 if (!Pattern->hasInClassInitializer() ||
15055 InstantiateInClassInitializer(Loc, Field, Pattern,
15056 getTemplateInstantiationArgs(Field))) {
15057 // Don't diagnose this again.
15058 Field->setInvalidDecl();
15059 return ExprError();
15061 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15065 // If the brace-or-equal-initializer of a non-static data member
15066 // invokes a defaulted default constructor of its class or of an
15067 // enclosing class in a potentially evaluated subexpression, the
15068 // program is ill-formed.
15070 // This resolution is unworkable: the exception specification of the
15071 // default constructor can be needed in an unevaluated context, in
15072 // particular, in the operand of a noexcept-expression, and we can be
15073 // unable to compute an exception specification for an enclosed class.
15075 // Any attempt to resolve the exception specification of a defaulted default
15076 // constructor before the initializer is lexically complete will ultimately
15077 // come here at which point we can diagnose it.
15078 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15079 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
15080 << OutermostClass << Field;
15081 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
15082 // Recover by marking the field invalid, unless we're in a SFINAE context.
15083 if (!isSFINAEContext())
15084 Field->setInvalidDecl();
15085 return ExprError();
15088 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15089 if (VD->isInvalidDecl()) return;
15090 // If initializing the variable failed, don't also diagnose problems with
15091 // the desctructor, they're likely related.
15092 if (VD->getInit() && VD->getInit()->containsErrors())
15095 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15096 if (ClassDecl->isInvalidDecl()) return;
15097 if (ClassDecl->hasIrrelevantDestructor()) return;
15098 if (ClassDecl->isDependentContext()) return;
15100 if (VD->isNoDestroy(getASTContext()))
15103 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15105 // If this is an array, we'll require the destructor during initialization, so
15106 // we can skip over this. We still want to emit exit-time destructor warnings
15108 if (!VD->getType()->isArrayType()) {
15109 MarkFunctionReferenced(VD->getLocation(), Destructor);
15110 CheckDestructorAccess(VD->getLocation(), Destructor,
15111 PDiag(diag::err_access_dtor_var)
15112 << VD->getDeclName() << VD->getType());
15113 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15116 if (Destructor->isTrivial()) return;
15118 // If the destructor is constexpr, check whether the variable has constant
15119 // destruction now.
15120 if (Destructor->isConstexpr()) {
15121 bool HasConstantInit = false;
15122 if (VD->getInit() && !VD->getInit()->isValueDependent())
15123 HasConstantInit = VD->evaluateValue();
15124 SmallVector<PartialDiagnosticAt, 8> Notes;
15125 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15127 Diag(VD->getLocation(),
15128 diag::err_constexpr_var_requires_const_destruction) << VD;
15129 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15130 Diag(Notes[I].first, Notes[I].second);
15134 if (!VD->hasGlobalStorage()) return;
15136 // Emit warning for non-trivial dtor in global scope (a real global,
15137 // class-static, function-static).
15138 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15140 // TODO: this should be re-enabled for static locals by !CXAAtExit
15141 if (!VD->isStaticLocal())
15142 Diag(VD->getLocation(), diag::warn_global_destructor);
15145 /// Given a constructor and the set of arguments provided for the
15146 /// constructor, convert the arguments and add any required default arguments
15147 /// to form a proper call to this constructor.
15149 /// \returns true if an error occurred, false otherwise.
15151 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15152 MultiExprArg ArgsPtr,
15153 SourceLocation Loc,
15154 SmallVectorImpl<Expr*> &ConvertedArgs,
15155 bool AllowExplicit,
15156 bool IsListInitialization) {
15157 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15158 unsigned NumArgs = ArgsPtr.size();
15159 Expr **Args = ArgsPtr.data();
15161 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15162 unsigned NumParams = Proto->getNumParams();
15164 // If too few arguments are available, we'll fill in the rest with defaults.
15165 if (NumArgs < NumParams)
15166 ConvertedArgs.reserve(NumParams);
15168 ConvertedArgs.reserve(NumArgs);
15170 VariadicCallType CallType =
15171 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15172 SmallVector<Expr *, 8> AllArgs;
15173 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15175 llvm::makeArrayRef(Args, NumArgs),
15177 CallType, AllowExplicit,
15178 IsListInitialization);
15179 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15181 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15183 CheckConstructorCall(Constructor,
15184 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15191 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15192 const FunctionDecl *FnDecl) {
15193 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15194 if (isa<NamespaceDecl>(DC)) {
15195 return SemaRef.Diag(FnDecl->getLocation(),
15196 diag::err_operator_new_delete_declared_in_namespace)
15197 << FnDecl->getDeclName();
15200 if (isa<TranslationUnitDecl>(DC) &&
15201 FnDecl->getStorageClass() == SC_Static) {
15202 return SemaRef.Diag(FnDecl->getLocation(),
15203 diag::err_operator_new_delete_declared_static)
15204 << FnDecl->getDeclName();
15211 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
15212 QualType QTy = PtrTy->getPointeeType();
15213 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
15214 return SemaRef.Context.getPointerType(QTy);
15218 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15219 CanQualType ExpectedResultType,
15220 CanQualType ExpectedFirstParamType,
15221 unsigned DependentParamTypeDiag,
15222 unsigned InvalidParamTypeDiag) {
15223 QualType ResultType =
15224 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15226 // The operator is valid on any address space for OpenCL.
15227 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15228 if (auto *PtrTy = ResultType->getAs<PointerType>()) {
15229 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15233 // Check that the result type is what we expect.
15234 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15235 // Reject even if the type is dependent; an operator delete function is
15236 // required to have a non-dependent result type.
15237 return SemaRef.Diag(
15238 FnDecl->getLocation(),
15239 ResultType->isDependentType()
15240 ? diag::err_operator_new_delete_dependent_result_type
15241 : diag::err_operator_new_delete_invalid_result_type)
15242 << FnDecl->getDeclName() << ExpectedResultType;
15245 // A function template must have at least 2 parameters.
15246 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15247 return SemaRef.Diag(FnDecl->getLocation(),
15248 diag::err_operator_new_delete_template_too_few_parameters)
15249 << FnDecl->getDeclName();
15251 // The function decl must have at least 1 parameter.
15252 if (FnDecl->getNumParams() == 0)
15253 return SemaRef.Diag(FnDecl->getLocation(),
15254 diag::err_operator_new_delete_too_few_parameters)
15255 << FnDecl->getDeclName();
15257 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15258 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15259 // The operator is valid on any address space for OpenCL.
15261 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
15262 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15266 // Check that the first parameter type is what we expect.
15267 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15268 ExpectedFirstParamType) {
15269 // The first parameter type is not allowed to be dependent. As a tentative
15270 // DR resolution, we allow a dependent parameter type if it is the right
15271 // type anyway, to allow destroying operator delete in class templates.
15272 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15273 ? DependentParamTypeDiag
15274 : InvalidParamTypeDiag)
15275 << FnDecl->getDeclName() << ExpectedFirstParamType;
15282 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15283 // C++ [basic.stc.dynamic.allocation]p1:
15284 // A program is ill-formed if an allocation function is declared in a
15285 // namespace scope other than global scope or declared static in global
15287 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15290 CanQualType SizeTy =
15291 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15293 // C++ [basic.stc.dynamic.allocation]p1:
15294 // The return type shall be void*. The first parameter shall have type
15296 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15298 diag::err_operator_new_dependent_param_type,
15299 diag::err_operator_new_param_type))
15302 // C++ [basic.stc.dynamic.allocation]p1:
15303 // The first parameter shall not have an associated default argument.
15304 if (FnDecl->getParamDecl(0)->hasDefaultArg())
15305 return SemaRef.Diag(FnDecl->getLocation(),
15306 diag::err_operator_new_default_arg)
15307 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15313 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15314 // C++ [basic.stc.dynamic.deallocation]p1:
15315 // A program is ill-formed if deallocation functions are declared in a
15316 // namespace scope other than global scope or declared static in global
15318 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15321 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15324 // Within a class C, the first parameter of a destroying operator delete
15325 // shall be of type C *. The first parameter of any other deallocation
15326 // function shall be of type void *.
15327 CanQualType ExpectedFirstParamType =
15328 MD && MD->isDestroyingOperatorDelete()
15329 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15330 SemaRef.Context.getRecordType(MD->getParent())))
15331 : SemaRef.Context.VoidPtrTy;
15333 // C++ [basic.stc.dynamic.deallocation]p2:
15334 // Each deallocation function shall return void
15335 if (CheckOperatorNewDeleteTypes(
15336 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15337 diag::err_operator_delete_dependent_param_type,
15338 diag::err_operator_delete_param_type))
15342 // A destroying operator delete shall be a usual deallocation function.
15343 if (MD && !MD->getParent()->isDependentContext() &&
15344 MD->isDestroyingOperatorDelete() &&
15345 !SemaRef.isUsualDeallocationFunction(MD)) {
15346 SemaRef.Diag(MD->getLocation(),
15347 diag::err_destroying_operator_delete_not_usual);
15354 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
15355 /// of this overloaded operator is well-formed. If so, returns false;
15356 /// otherwise, emits appropriate diagnostics and returns true.
15357 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15358 assert(FnDecl && FnDecl->isOverloadedOperator() &&
15359 "Expected an overloaded operator declaration");
15361 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15363 // C++ [over.oper]p5:
15364 // The allocation and deallocation functions, operator new,
15365 // operator new[], operator delete and operator delete[], are
15366 // described completely in 3.7.3. The attributes and restrictions
15367 // found in the rest of this subclause do not apply to them unless
15368 // explicitly stated in 3.7.3.
15369 if (Op == OO_Delete || Op == OO_Array_Delete)
15370 return CheckOperatorDeleteDeclaration(*this, FnDecl);
15372 if (Op == OO_New || Op == OO_Array_New)
15373 return CheckOperatorNewDeclaration(*this, FnDecl);
15375 // C++ [over.oper]p6:
15376 // An operator function shall either be a non-static member
15377 // function or be a non-member function and have at least one
15378 // parameter whose type is a class, a reference to a class, an
15379 // enumeration, or a reference to an enumeration.
15380 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15381 if (MethodDecl->isStatic())
15382 return Diag(FnDecl->getLocation(),
15383 diag::err_operator_overload_static) << FnDecl->getDeclName();
15385 bool ClassOrEnumParam = false;
15386 for (auto Param : FnDecl->parameters()) {
15387 QualType ParamType = Param->getType().getNonReferenceType();
15388 if (ParamType->isDependentType() || ParamType->isRecordType() ||
15389 ParamType->isEnumeralType()) {
15390 ClassOrEnumParam = true;
15395 if (!ClassOrEnumParam)
15396 return Diag(FnDecl->getLocation(),
15397 diag::err_operator_overload_needs_class_or_enum)
15398 << FnDecl->getDeclName();
15401 // C++ [over.oper]p8:
15402 // An operator function cannot have default arguments (8.3.6),
15403 // except where explicitly stated below.
15405 // Only the function-call operator allows default arguments
15406 // (C++ [over.call]p1).
15407 if (Op != OO_Call) {
15408 for (auto Param : FnDecl->parameters()) {
15409 if (Param->hasDefaultArg())
15410 return Diag(Param->getLocation(),
15411 diag::err_operator_overload_default_arg)
15412 << FnDecl->getDeclName() << Param->getDefaultArgRange();
15416 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15417 { false, false, false }
15418 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15419 , { Unary, Binary, MemberOnly }
15420 #include "clang/Basic/OperatorKinds.def"
15423 bool CanBeUnaryOperator = OperatorUses[Op][0];
15424 bool CanBeBinaryOperator = OperatorUses[Op][1];
15425 bool MustBeMemberOperator = OperatorUses[Op][2];
15427 // C++ [over.oper]p8:
15428 // [...] Operator functions cannot have more or fewer parameters
15429 // than the number required for the corresponding operator, as
15430 // described in the rest of this subclause.
15431 unsigned NumParams = FnDecl->getNumParams()
15432 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15433 if (Op != OO_Call &&
15434 ((NumParams == 1 && !CanBeUnaryOperator) ||
15435 (NumParams == 2 && !CanBeBinaryOperator) ||
15436 (NumParams < 1) || (NumParams > 2))) {
15437 // We have the wrong number of parameters.
15438 unsigned ErrorKind;
15439 if (CanBeUnaryOperator && CanBeBinaryOperator) {
15440 ErrorKind = 2; // 2 -> unary or binary.
15441 } else if (CanBeUnaryOperator) {
15442 ErrorKind = 0; // 0 -> unary
15444 assert(CanBeBinaryOperator &&
15445 "All non-call overloaded operators are unary or binary!");
15446 ErrorKind = 1; // 1 -> binary
15449 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15450 << FnDecl->getDeclName() << NumParams << ErrorKind;
15453 // Overloaded operators other than operator() cannot be variadic.
15454 if (Op != OO_Call &&
15455 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15456 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15457 << FnDecl->getDeclName();
15460 // Some operators must be non-static member functions.
15461 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15462 return Diag(FnDecl->getLocation(),
15463 diag::err_operator_overload_must_be_member)
15464 << FnDecl->getDeclName();
15467 // C++ [over.inc]p1:
15468 // The user-defined function called operator++ implements the
15469 // prefix and postfix ++ operator. If this function is a member
15470 // function with no parameters, or a non-member function with one
15471 // parameter of class or enumeration type, it defines the prefix
15472 // increment operator ++ for objects of that type. If the function
15473 // is a member function with one parameter (which shall be of type
15474 // int) or a non-member function with two parameters (the second
15475 // of which shall be of type int), it defines the postfix
15476 // increment operator ++ for objects of that type.
15477 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15478 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15479 QualType ParamType = LastParam->getType();
15481 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15482 !ParamType->isDependentType())
15483 return Diag(LastParam->getLocation(),
15484 diag::err_operator_overload_post_incdec_must_be_int)
15485 << LastParam->getType() << (Op == OO_MinusMinus);
15492 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15493 FunctionTemplateDecl *TpDecl) {
15494 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15496 // Must have one or two template parameters.
15497 if (TemplateParams->size() == 1) {
15498 NonTypeTemplateParmDecl *PmDecl =
15499 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15501 // The template parameter must be a char parameter pack.
15502 if (PmDecl && PmDecl->isTemplateParameterPack() &&
15503 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15506 } else if (TemplateParams->size() == 2) {
15507 TemplateTypeParmDecl *PmType =
15508 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15509 NonTypeTemplateParmDecl *PmArgs =
15510 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15512 // The second template parameter must be a parameter pack with the
15513 // first template parameter as its type.
15514 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15515 PmArgs->isTemplateParameterPack()) {
15516 const TemplateTypeParmType *TArgs =
15517 PmArgs->getType()->getAs<TemplateTypeParmType>();
15518 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15519 TArgs->getIndex() == PmType->getIndex()) {
15520 if (!SemaRef.inTemplateInstantiation())
15521 SemaRef.Diag(TpDecl->getLocation(),
15522 diag::ext_string_literal_operator_template);
15528 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15529 diag::err_literal_operator_template)
15530 << TpDecl->getTemplateParameters()->getSourceRange();
15534 /// CheckLiteralOperatorDeclaration - Check whether the declaration
15535 /// of this literal operator function is well-formed. If so, returns
15536 /// false; otherwise, emits appropriate diagnostics and returns true.
15537 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15538 if (isa<CXXMethodDecl>(FnDecl)) {
15539 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15540 << FnDecl->getDeclName();
15544 if (FnDecl->isExternC()) {
15545 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15546 if (const LinkageSpecDecl *LSD =
15547 FnDecl->getDeclContext()->getExternCContext())
15548 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15552 // This might be the definition of a literal operator template.
15553 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15555 // This might be a specialization of a literal operator template.
15557 TpDecl = FnDecl->getPrimaryTemplate();
15559 // template <char...> type operator "" name() and
15560 // template <class T, T...> type operator "" name() are the only valid
15561 // template signatures, and the only valid signatures with no parameters.
15563 if (FnDecl->param_size() != 0) {
15564 Diag(FnDecl->getLocation(),
15565 diag::err_literal_operator_template_with_params);
15569 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15572 } else if (FnDecl->param_size() == 1) {
15573 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15575 QualType ParamType = Param->getType().getUnqualifiedType();
15577 // Only unsigned long long int, long double, any character type, and const
15578 // char * are allowed as the only parameters.
15579 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15580 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15581 Context.hasSameType(ParamType, Context.CharTy) ||
15582 Context.hasSameType(ParamType, Context.WideCharTy) ||
15583 Context.hasSameType(ParamType, Context.Char8Ty) ||
15584 Context.hasSameType(ParamType, Context.Char16Ty) ||
15585 Context.hasSameType(ParamType, Context.Char32Ty)) {
15586 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15587 QualType InnerType = Ptr->getPointeeType();
15589 // Pointer parameter must be a const char *.
15590 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15592 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15593 Diag(Param->getSourceRange().getBegin(),
15594 diag::err_literal_operator_param)
15595 << ParamType << "'const char *'" << Param->getSourceRange();
15599 } else if (ParamType->isRealFloatingType()) {
15600 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15601 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15604 } else if (ParamType->isIntegerType()) {
15605 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15606 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15610 Diag(Param->getSourceRange().getBegin(),
15611 diag::err_literal_operator_invalid_param)
15612 << ParamType << Param->getSourceRange();
15616 } else if (FnDecl->param_size() == 2) {
15617 FunctionDecl::param_iterator Param = FnDecl->param_begin();
15619 // First, verify that the first parameter is correct.
15621 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15623 // Two parameter function must have a pointer to const as a
15624 // first parameter; let's strip those qualifiers.
15625 const PointerType *PT = FirstParamType->getAs<PointerType>();
15628 Diag((*Param)->getSourceRange().getBegin(),
15629 diag::err_literal_operator_param)
15630 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15634 QualType PointeeType = PT->getPointeeType();
15635 // First parameter must be const
15636 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
15637 Diag((*Param)->getSourceRange().getBegin(),
15638 diag::err_literal_operator_param)
15639 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15643 QualType InnerType = PointeeType.getUnqualifiedType();
15644 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
15645 // const char32_t* are allowed as the first parameter to a two-parameter
15647 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
15648 Context.hasSameType(InnerType, Context.WideCharTy) ||
15649 Context.hasSameType(InnerType, Context.Char8Ty) ||
15650 Context.hasSameType(InnerType, Context.Char16Ty) ||
15651 Context.hasSameType(InnerType, Context.Char32Ty))) {
15652 Diag((*Param)->getSourceRange().getBegin(),
15653 diag::err_literal_operator_param)
15654 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
15658 // Move on to the second and final parameter.
15661 // The second parameter must be a std::size_t.
15662 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
15663 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
15664 Diag((*Param)->getSourceRange().getBegin(),
15665 diag::err_literal_operator_param)
15666 << SecondParamType << Context.getSizeType()
15667 << (*Param)->getSourceRange();
15671 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
15675 // Parameters are good.
15677 // A parameter-declaration-clause containing a default argument is not
15678 // equivalent to any of the permitted forms.
15679 for (auto Param : FnDecl->parameters()) {
15680 if (Param->hasDefaultArg()) {
15681 Diag(Param->getDefaultArgRange().getBegin(),
15682 diag::err_literal_operator_default_argument)
15683 << Param->getDefaultArgRange();
15688 StringRef LiteralName
15689 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
15690 if (LiteralName[0] != '_' &&
15691 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
15692 // C++11 [usrlit.suffix]p1:
15693 // Literal suffix identifiers that do not start with an underscore
15694 // are reserved for future standardization.
15695 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
15696 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
15702 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
15703 /// linkage specification, including the language and (if present)
15704 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
15705 /// language string literal. LBraceLoc, if valid, provides the location of
15706 /// the '{' brace. Otherwise, this linkage specification does not
15707 /// have any braces.
15708 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
15710 SourceLocation LBraceLoc) {
15711 StringLiteral *Lit = cast<StringLiteral>(LangStr);
15712 if (!Lit->isAscii()) {
15713 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
15714 << LangStr->getSourceRange();
15718 StringRef Lang = Lit->getString();
15719 LinkageSpecDecl::LanguageIDs Language;
15721 Language = LinkageSpecDecl::lang_c;
15722 else if (Lang == "C++")
15723 Language = LinkageSpecDecl::lang_cxx;
15725 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
15726 << LangStr->getSourceRange();
15730 // FIXME: Add all the various semantics of linkage specifications
15732 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
15733 LangStr->getExprLoc(), Language,
15734 LBraceLoc.isValid());
15735 CurContext->addDecl(D);
15736 PushDeclContext(S, D);
15740 /// ActOnFinishLinkageSpecification - Complete the definition of
15741 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
15742 /// valid, it's the position of the closing '}' brace in a linkage
15743 /// specification that uses braces.
15744 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
15746 SourceLocation RBraceLoc) {
15747 if (RBraceLoc.isValid()) {
15748 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
15749 LSDecl->setRBraceLoc(RBraceLoc);
15752 return LinkageSpec;
15755 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
15756 const ParsedAttributesView &AttrList,
15757 SourceLocation SemiLoc) {
15758 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
15759 // Attribute declarations appertain to empty declaration so we handle
15761 ProcessDeclAttributeList(S, ED, AttrList);
15763 CurContext->addDecl(ED);
15767 /// Perform semantic analysis for the variable declaration that
15768 /// occurs within a C++ catch clause, returning the newly-created
15770 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
15771 TypeSourceInfo *TInfo,
15772 SourceLocation StartLoc,
15773 SourceLocation Loc,
15774 IdentifierInfo *Name) {
15775 bool Invalid = false;
15776 QualType ExDeclType = TInfo->getType();
15778 // Arrays and functions decay.
15779 if (ExDeclType->isArrayType())
15780 ExDeclType = Context.getArrayDecayedType(ExDeclType);
15781 else if (ExDeclType->isFunctionType())
15782 ExDeclType = Context.getPointerType(ExDeclType);
15784 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
15785 // The exception-declaration shall not denote a pointer or reference to an
15786 // incomplete type, other than [cv] void*.
15787 // N2844 forbids rvalue references.
15788 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
15789 Diag(Loc, diag::err_catch_rvalue_ref);
15793 if (ExDeclType->isVariablyModifiedType()) {
15794 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
15798 QualType BaseType = ExDeclType;
15799 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
15800 unsigned DK = diag::err_catch_incomplete;
15801 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
15802 BaseType = Ptr->getPointeeType();
15804 DK = diag::err_catch_incomplete_ptr;
15805 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
15806 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
15807 BaseType = Ref->getPointeeType();
15809 DK = diag::err_catch_incomplete_ref;
15811 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
15812 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
15815 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
15816 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
15820 if (!Invalid && !ExDeclType->isDependentType() &&
15821 RequireNonAbstractType(Loc, ExDeclType,
15822 diag::err_abstract_type_in_decl,
15823 AbstractVariableType))
15826 // Only the non-fragile NeXT runtime currently supports C++ catches
15827 // of ObjC types, and no runtime supports catching ObjC types by value.
15828 if (!Invalid && getLangOpts().ObjC) {
15829 QualType T = ExDeclType;
15830 if (const ReferenceType *RT = T->getAs<ReferenceType>())
15831 T = RT->getPointeeType();
15833 if (T->isObjCObjectType()) {
15834 Diag(Loc, diag::err_objc_object_catch);
15836 } else if (T->isObjCObjectPointerType()) {
15837 // FIXME: should this be a test for macosx-fragile specifically?
15838 if (getLangOpts().ObjCRuntime.isFragile())
15839 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
15843 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
15844 ExDeclType, TInfo, SC_None);
15845 ExDecl->setExceptionVariable(true);
15847 // In ARC, infer 'retaining' for variables of retainable type.
15848 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
15851 if (!Invalid && !ExDeclType->isDependentType()) {
15852 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
15853 // Insulate this from anything else we might currently be parsing.
15854 EnterExpressionEvaluationContext scope(
15855 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15857 // C++ [except.handle]p16:
15858 // The object declared in an exception-declaration or, if the
15859 // exception-declaration does not specify a name, a temporary (12.2) is
15860 // copy-initialized (8.5) from the exception object. [...]
15861 // The object is destroyed when the handler exits, after the destruction
15862 // of any automatic objects initialized within the handler.
15864 // We just pretend to initialize the object with itself, then make sure
15865 // it can be destroyed later.
15866 QualType initType = Context.getExceptionObjectType(ExDeclType);
15868 InitializedEntity entity =
15869 InitializedEntity::InitializeVariable(ExDecl);
15870 InitializationKind initKind =
15871 InitializationKind::CreateCopy(Loc, SourceLocation());
15873 Expr *opaqueValue =
15874 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
15875 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
15876 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
15877 if (result.isInvalid())
15880 // If the constructor used was non-trivial, set this as the
15882 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
15883 if (!construct->getConstructor()->isTrivial()) {
15884 Expr *init = MaybeCreateExprWithCleanups(construct);
15885 ExDecl->setInit(init);
15888 // And make sure it's destructable.
15889 FinalizeVarWithDestructor(ExDecl, recordType);
15895 ExDecl->setInvalidDecl();
15900 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
15902 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
15903 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15904 bool Invalid = D.isInvalidType();
15906 // Check for unexpanded parameter packs.
15907 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15908 UPPC_ExceptionType)) {
15909 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
15910 D.getIdentifierLoc());
15914 IdentifierInfo *II = D.getIdentifier();
15915 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
15916 LookupOrdinaryName,
15917 ForVisibleRedeclaration)) {
15918 // The scope should be freshly made just for us. There is just no way
15919 // it contains any previous declaration, except for function parameters in
15920 // a function-try-block's catch statement.
15921 assert(!S->isDeclScope(PrevDecl));
15922 if (isDeclInScope(PrevDecl, CurContext, S)) {
15923 Diag(D.getIdentifierLoc(), diag::err_redefinition)
15924 << D.getIdentifier();
15925 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15927 } else if (PrevDecl->isTemplateParameter())
15928 // Maybe we will complain about the shadowed template parameter.
15929 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15932 if (D.getCXXScopeSpec().isSet() && !Invalid) {
15933 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
15934 << D.getCXXScopeSpec().getRange();
15938 VarDecl *ExDecl = BuildExceptionDeclaration(
15939 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
15941 ExDecl->setInvalidDecl();
15943 // Add the exception declaration into this scope.
15945 PushOnScopeChains(ExDecl, S);
15947 CurContext->addDecl(ExDecl);
15949 ProcessDeclAttributes(S, ExDecl, D);
15953 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15955 Expr *AssertMessageExpr,
15956 SourceLocation RParenLoc) {
15957 StringLiteral *AssertMessage =
15958 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
15960 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
15963 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
15964 AssertMessage, RParenLoc, false);
15967 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
15969 StringLiteral *AssertMessage,
15970 SourceLocation RParenLoc,
15972 assert(AssertExpr != nullptr && "Expected non-null condition");
15973 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
15975 // In a static_assert-declaration, the constant-expression shall be a
15976 // constant expression that can be contextually converted to bool.
15977 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
15978 if (Converted.isInvalid())
15981 ExprResult FullAssertExpr =
15982 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
15983 /*DiscardedValue*/ false,
15984 /*IsConstexpr*/ true);
15985 if (FullAssertExpr.isInvalid())
15988 AssertExpr = FullAssertExpr.get();
15991 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond,
15992 diag::err_static_assert_expression_is_not_constant,
15993 /*AllowFold=*/false).isInvalid())
15996 if (!Failed && !Cond) {
15997 SmallString<256> MsgBuffer;
15998 llvm::raw_svector_ostream Msg(MsgBuffer);
16000 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16002 Expr *InnerCond = nullptr;
16003 std::string InnerCondDescription;
16004 std::tie(InnerCond, InnerCondDescription) =
16005 findFailedBooleanCondition(Converted.get());
16006 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16007 // Drill down into concept specialization expressions to see why they
16008 // weren't satisfied.
16009 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16010 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16011 ConstraintSatisfaction Satisfaction;
16012 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16013 DiagnoseUnsatisfiedConstraint(Satisfaction);
16014 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16015 && !isa<IntegerLiteral>(InnerCond)) {
16016 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16017 << InnerCondDescription << !AssertMessage
16018 << Msg.str() << InnerCond->getSourceRange();
16020 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16021 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16026 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16027 /*DiscardedValue*/false,
16028 /*IsConstexpr*/true);
16029 if (FullAssertExpr.isInvalid())
16032 AssertExpr = FullAssertExpr.get();
16035 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16036 AssertExpr, AssertMessage, RParenLoc,
16039 CurContext->addDecl(Decl);
16043 /// Perform semantic analysis of the given friend type declaration.
16045 /// \returns A friend declaration that.
16046 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16047 SourceLocation FriendLoc,
16048 TypeSourceInfo *TSInfo) {
16049 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
16051 QualType T = TSInfo->getType();
16052 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16054 // C++03 [class.friend]p2:
16055 // An elaborated-type-specifier shall be used in a friend declaration
16058 // * The class-key of the elaborated-type-specifier is required.
16059 if (!CodeSynthesisContexts.empty()) {
16060 // Do not complain about the form of friend template types during any kind
16061 // of code synthesis. For template instantiation, we will have complained
16062 // when the template was defined.
16064 if (!T->isElaboratedTypeSpecifier()) {
16065 // If we evaluated the type to a record type, suggest putting
16067 if (const RecordType *RT = T->getAs<RecordType>()) {
16068 RecordDecl *RD = RT->getDecl();
16070 SmallString<16> InsertionText(" ");
16071 InsertionText += RD->getKindName();
16073 Diag(TypeRange.getBegin(),
16074 getLangOpts().CPlusPlus11 ?
16075 diag::warn_cxx98_compat_unelaborated_friend_type :
16076 diag::ext_unelaborated_friend_type)
16077 << (unsigned) RD->getTagKind()
16079 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16083 getLangOpts().CPlusPlus11 ?
16084 diag::warn_cxx98_compat_nonclass_type_friend :
16085 diag::ext_nonclass_type_friend)
16089 } else if (T->getAs<EnumType>()) {
16091 getLangOpts().CPlusPlus11 ?
16092 diag::warn_cxx98_compat_enum_friend :
16093 diag::ext_enum_friend)
16098 // C++11 [class.friend]p3:
16099 // A friend declaration that does not declare a function shall have one
16100 // of the following forms:
16101 // friend elaborated-type-specifier ;
16102 // friend simple-type-specifier ;
16103 // friend typename-specifier ;
16104 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16105 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16108 // If the type specifier in a friend declaration designates a (possibly
16109 // cv-qualified) class type, that class is declared as a friend; otherwise,
16110 // the friend declaration is ignored.
16111 return FriendDecl::Create(Context, CurContext,
16112 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16116 /// Handle a friend tag declaration where the scope specifier was
16118 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16119 unsigned TagSpec, SourceLocation TagLoc,
16120 CXXScopeSpec &SS, IdentifierInfo *Name,
16121 SourceLocation NameLoc,
16122 const ParsedAttributesView &Attr,
16123 MultiTemplateParamsArg TempParamLists) {
16124 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16126 bool IsMemberSpecialization = false;
16127 bool Invalid = false;
16129 if (TemplateParameterList *TemplateParams =
16130 MatchTemplateParametersToScopeSpecifier(
16131 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16132 IsMemberSpecialization, Invalid)) {
16133 if (TemplateParams->size() > 0) {
16134 // This is a declaration of a class template.
16138 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16139 NameLoc, Attr, TemplateParams, AS_public,
16140 /*ModulePrivateLoc=*/SourceLocation(),
16141 FriendLoc, TempParamLists.size() - 1,
16142 TempParamLists.data()).get();
16144 // The "template<>" header is extraneous.
16145 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16146 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16147 IsMemberSpecialization = true;
16151 if (Invalid) return nullptr;
16153 bool isAllExplicitSpecializations = true;
16154 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16155 if (TempParamLists[I]->size()) {
16156 isAllExplicitSpecializations = false;
16161 // FIXME: don't ignore attributes.
16163 // If it's explicit specializations all the way down, just forget
16164 // about the template header and build an appropriate non-templated
16165 // friend. TODO: for source fidelity, remember the headers.
16166 if (isAllExplicitSpecializations) {
16167 if (SS.isEmpty()) {
16168 bool Owned = false;
16169 bool IsDependent = false;
16170 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16172 /*ModulePrivateLoc=*/SourceLocation(),
16173 MultiTemplateParamsArg(), Owned, IsDependent,
16174 /*ScopedEnumKWLoc=*/SourceLocation(),
16175 /*ScopedEnumUsesClassTag=*/false,
16176 /*UnderlyingType=*/TypeResult(),
16177 /*IsTypeSpecifier=*/false,
16178 /*IsTemplateParamOrArg=*/false);
16181 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16182 ElaboratedTypeKeyword Keyword
16183 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16184 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16189 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16190 if (isa<DependentNameType>(T)) {
16191 DependentNameTypeLoc TL =
16192 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16193 TL.setElaboratedKeywordLoc(TagLoc);
16194 TL.setQualifierLoc(QualifierLoc);
16195 TL.setNameLoc(NameLoc);
16197 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16198 TL.setElaboratedKeywordLoc(TagLoc);
16199 TL.setQualifierLoc(QualifierLoc);
16200 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16203 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16204 TSI, FriendLoc, TempParamLists);
16205 Friend->setAccess(AS_public);
16206 CurContext->addDecl(Friend);
16210 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
16214 // Handle the case of a templated-scope friend class. e.g.
16215 // template <class T> class A<T>::B;
16216 // FIXME: we don't support these right now.
16217 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16218 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16219 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16220 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16221 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16222 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16223 TL.setElaboratedKeywordLoc(TagLoc);
16224 TL.setQualifierLoc(SS.getWithLocInContext(Context));
16225 TL.setNameLoc(NameLoc);
16227 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16228 TSI, FriendLoc, TempParamLists);
16229 Friend->setAccess(AS_public);
16230 Friend->setUnsupportedFriend(true);
16231 CurContext->addDecl(Friend);
16235 /// Handle a friend type declaration. This works in tandem with
16238 /// Notes on friend class templates:
16240 /// We generally treat friend class declarations as if they were
16241 /// declaring a class. So, for example, the elaborated type specifier
16242 /// in a friend declaration is required to obey the restrictions of a
16243 /// class-head (i.e. no typedefs in the scope chain), template
16244 /// parameters are required to match up with simple template-ids, &c.
16245 /// However, unlike when declaring a template specialization, it's
16246 /// okay to refer to a template specialization without an empty
16247 /// template parameter declaration, e.g.
16248 /// friend class A<T>::B<unsigned>;
16249 /// We permit this as a special case; if there are any template
16250 /// parameters present at all, require proper matching, i.e.
16251 /// template <> template \<class T> friend class A<int>::B;
16252 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16253 MultiTemplateParamsArg TempParams) {
16254 SourceLocation Loc = DS.getBeginLoc();
16256 assert(DS.isFriendSpecified());
16257 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16259 // C++ [class.friend]p3:
16260 // A friend declaration that does not declare a function shall have one of
16261 // the following forms:
16262 // friend elaborated-type-specifier ;
16263 // friend simple-type-specifier ;
16264 // friend typename-specifier ;
16266 // Any declaration with a type qualifier does not have that form. (It's
16267 // legal to specify a qualified type as a friend, you just can't write the
16269 if (DS.getTypeQualifiers()) {
16270 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16271 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16272 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16273 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16274 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16275 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16276 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16277 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16278 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16279 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16282 // Try to convert the decl specifier to a type. This works for
16283 // friend templates because ActOnTag never produces a ClassTemplateDecl
16284 // for a TUK_Friend.
16285 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
16286 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16287 QualType T = TSI->getType();
16288 if (TheDeclarator.isInvalidType())
16291 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16294 // This is definitely an error in C++98. It's probably meant to
16295 // be forbidden in C++0x, too, but the specification is just
16298 // The problem is with declarations like the following:
16299 // template <T> friend A<T>::foo;
16300 // where deciding whether a class C is a friend or not now hinges
16301 // on whether there exists an instantiation of A that causes
16302 // 'foo' to equal C. There are restrictions on class-heads
16303 // (which we declare (by fiat) elaborated friend declarations to
16304 // be) that makes this tractable.
16306 // FIXME: handle "template <> friend class A<T>;", which
16307 // is possibly well-formed? Who even knows?
16308 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16309 Diag(Loc, diag::err_tagless_friend_type_template)
16310 << DS.getSourceRange();
16314 // C++98 [class.friend]p1: A friend of a class is a function
16315 // or class that is not a member of the class . . .
16316 // This is fixed in DR77, which just barely didn't make the C++03
16317 // deadline. It's also a very silly restriction that seriously
16318 // affects inner classes and which nobody else seems to implement;
16319 // thus we never diagnose it, not even in -pedantic.
16321 // But note that we could warn about it: it's always useless to
16322 // friend one of your own members (it's not, however, worthless to
16323 // friend a member of an arbitrary specialization of your template).
16326 if (!TempParams.empty())
16327 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16330 DS.getFriendSpecLoc());
16332 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16337 D->setAccess(AS_public);
16338 CurContext->addDecl(D);
16343 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16344 MultiTemplateParamsArg TemplateParams) {
16345 const DeclSpec &DS = D.getDeclSpec();
16347 assert(DS.isFriendSpecified());
16348 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
16350 SourceLocation Loc = D.getIdentifierLoc();
16351 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16353 // C++ [class.friend]p1
16354 // A friend of a class is a function or class....
16355 // Note that this sees through typedefs, which is intended.
16356 // It *doesn't* see through dependent types, which is correct
16357 // according to [temp.arg.type]p3:
16358 // If a declaration acquires a function type through a
16359 // type dependent on a template-parameter and this causes
16360 // a declaration that does not use the syntactic form of a
16361 // function declarator to have a function type, the program
16363 if (!TInfo->getType()->isFunctionType()) {
16364 Diag(Loc, diag::err_unexpected_friend);
16366 // It might be worthwhile to try to recover by creating an
16367 // appropriate declaration.
16371 // C++ [namespace.memdef]p3
16372 // - If a friend declaration in a non-local class first declares a
16373 // class or function, the friend class or function is a member
16374 // of the innermost enclosing namespace.
16375 // - The name of the friend is not found by simple name lookup
16376 // until a matching declaration is provided in that namespace
16377 // scope (either before or after the class declaration granting
16379 // - If a friend function is called, its name may be found by the
16380 // name lookup that considers functions from namespaces and
16381 // classes associated with the types of the function arguments.
16382 // - When looking for a prior declaration of a class or a function
16383 // declared as a friend, scopes outside the innermost enclosing
16384 // namespace scope are not considered.
16386 CXXScopeSpec &SS = D.getCXXScopeSpec();
16387 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16388 assert(NameInfo.getName());
16390 // Check for unexpanded parameter packs.
16391 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16392 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16393 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16396 // The context we found the declaration in, or in which we should
16397 // create the declaration.
16399 Scope *DCScope = S;
16400 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16401 ForExternalRedeclaration);
16403 // There are five cases here.
16404 // - There's no scope specifier and we're in a local class. Only look
16405 // for functions declared in the immediately-enclosing block scope.
16406 // We recover from invalid scope qualifiers as if they just weren't there.
16407 FunctionDecl *FunctionContainingLocalClass = nullptr;
16408 if ((SS.isInvalid() || !SS.isSet()) &&
16409 (FunctionContainingLocalClass =
16410 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16411 // C++11 [class.friend]p11:
16412 // If a friend declaration appears in a local class and the name
16413 // specified is an unqualified name, a prior declaration is
16414 // looked up without considering scopes that are outside the
16415 // innermost enclosing non-class scope. For a friend function
16416 // declaration, if there is no prior declaration, the program is
16419 // Find the innermost enclosing non-class scope. This is the block
16420 // scope containing the local class definition (or for a nested class,
16421 // the outer local class).
16422 DCScope = S->getFnParent();
16424 // Look up the function name in the scope.
16425 Previous.clear(LookupLocalFriendName);
16426 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16428 if (!Previous.empty()) {
16429 // All possible previous declarations must have the same context:
16430 // either they were declared at block scope or they are members of
16431 // one of the enclosing local classes.
16432 DC = Previous.getRepresentativeDecl()->getDeclContext();
16434 // This is ill-formed, but provide the context that we would have
16435 // declared the function in, if we were permitted to, for error recovery.
16436 DC = FunctionContainingLocalClass;
16438 adjustContextForLocalExternDecl(DC);
16440 // C++ [class.friend]p6:
16441 // A function can be defined in a friend declaration of a class if and
16442 // only if the class is a non-local class (9.8), the function name is
16443 // unqualified, and the function has namespace scope.
16444 if (D.isFunctionDefinition()) {
16445 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16448 // - There's no scope specifier, in which case we just go to the
16449 // appropriate scope and look for a function or function template
16450 // there as appropriate.
16451 } else if (SS.isInvalid() || !SS.isSet()) {
16452 // C++11 [namespace.memdef]p3:
16453 // If the name in a friend declaration is neither qualified nor
16454 // a template-id and the declaration is a function or an
16455 // elaborated-type-specifier, the lookup to determine whether
16456 // the entity has been previously declared shall not consider
16457 // any scopes outside the innermost enclosing namespace.
16458 bool isTemplateId =
16459 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16461 // Find the appropriate context according to the above.
16464 // Skip class contexts. If someone can cite chapter and verse
16465 // for this behavior, that would be nice --- it's what GCC and
16466 // EDG do, and it seems like a reasonable intent, but the spec
16467 // really only says that checks for unqualified existing
16468 // declarations should stop at the nearest enclosing namespace,
16469 // not that they should only consider the nearest enclosing
16471 while (DC->isRecord())
16472 DC = DC->getParent();
16474 DeclContext *LookupDC = DC;
16475 while (LookupDC->isTransparentContext())
16476 LookupDC = LookupDC->getParent();
16479 LookupQualifiedName(Previous, LookupDC);
16481 if (!Previous.empty()) {
16486 if (isTemplateId) {
16487 if (isa<TranslationUnitDecl>(LookupDC)) break;
16489 if (LookupDC->isFileContext()) break;
16491 LookupDC = LookupDC->getParent();
16494 DCScope = getScopeForDeclContext(S, DC);
16496 // - There's a non-dependent scope specifier, in which case we
16497 // compute it and do a previous lookup there for a function
16498 // or function template.
16499 } else if (!SS.getScopeRep()->isDependent()) {
16500 DC = computeDeclContext(SS);
16501 if (!DC) return nullptr;
16503 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16505 LookupQualifiedName(Previous, DC);
16507 // C++ [class.friend]p1: A friend of a class is a function or
16508 // class that is not a member of the class . . .
16509 if (DC->Equals(CurContext))
16510 Diag(DS.getFriendSpecLoc(),
16511 getLangOpts().CPlusPlus11 ?
16512 diag::warn_cxx98_compat_friend_is_member :
16513 diag::err_friend_is_member);
16515 if (D.isFunctionDefinition()) {
16516 // C++ [class.friend]p6:
16517 // A function can be defined in a friend declaration of a class if and
16518 // only if the class is a non-local class (9.8), the function name is
16519 // unqualified, and the function has namespace scope.
16521 // FIXME: We should only do this if the scope specifier names the
16522 // innermost enclosing namespace; otherwise the fixit changes the
16523 // meaning of the code.
16524 SemaDiagnosticBuilder DB
16525 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16527 DB << SS.getScopeRep();
16528 if (DC->isFileContext())
16529 DB << FixItHint::CreateRemoval(SS.getRange());
16533 // - There's a scope specifier that does not match any template
16534 // parameter lists, in which case we use some arbitrary context,
16535 // create a method or method template, and wait for instantiation.
16536 // - There's a scope specifier that does match some template
16537 // parameter lists, which we don't handle right now.
16539 if (D.isFunctionDefinition()) {
16540 // C++ [class.friend]p6:
16541 // A function can be defined in a friend declaration of a class if and
16542 // only if the class is a non-local class (9.8), the function name is
16543 // unqualified, and the function has namespace scope.
16544 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16545 << SS.getScopeRep();
16549 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
16552 if (!DC->isRecord()) {
16554 switch (D.getName().getKind()) {
16555 case UnqualifiedIdKind::IK_ConstructorTemplateId:
16556 case UnqualifiedIdKind::IK_ConstructorName:
16559 case UnqualifiedIdKind::IK_DestructorName:
16562 case UnqualifiedIdKind::IK_ConversionFunctionId:
16565 case UnqualifiedIdKind::IK_DeductionGuideName:
16568 case UnqualifiedIdKind::IK_Identifier:
16569 case UnqualifiedIdKind::IK_ImplicitSelfParam:
16570 case UnqualifiedIdKind::IK_LiteralOperatorId:
16571 case UnqualifiedIdKind::IK_OperatorFunctionId:
16572 case UnqualifiedIdKind::IK_TemplateId:
16575 // This implies that it has to be an operator or function.
16576 if (DiagArg >= 0) {
16577 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16582 // FIXME: This is an egregious hack to cope with cases where the scope stack
16583 // does not contain the declaration context, i.e., in an out-of-line
16584 // definition of a class.
16585 Scope FakeDCScope(S, Scope::DeclScope, Diags);
16587 FakeDCScope.setEntity(DC);
16588 DCScope = &FakeDCScope;
16591 bool AddToScope = true;
16592 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16593 TemplateParams, AddToScope);
16594 if (!ND) return nullptr;
16596 assert(ND->getLexicalDeclContext() == CurContext);
16598 // If we performed typo correction, we might have added a scope specifier
16599 // and changed the decl context.
16600 DC = ND->getDeclContext();
16602 // Add the function declaration to the appropriate lookup tables,
16603 // adjusting the redeclarations list as necessary. We don't
16604 // want to do this yet if the friending class is dependent.
16606 // Also update the scope-based lookup if the target context's
16607 // lookup context is in lexical scope.
16608 if (!CurContext->isDependentContext()) {
16609 DC = DC->getRedeclContext();
16610 DC->makeDeclVisibleInContext(ND);
16611 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16612 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16615 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16616 D.getIdentifierLoc(), ND,
16617 DS.getFriendSpecLoc());
16618 FrD->setAccess(AS_public);
16619 CurContext->addDecl(FrD);
16621 if (ND->isInvalidDecl()) {
16622 FrD->setInvalidDecl();
16624 if (DC->isRecord()) CheckFriendAccess(ND);
16627 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16628 FD = FTD->getTemplatedDecl();
16630 FD = cast<FunctionDecl>(ND);
16632 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
16633 // default argument expression, that declaration shall be a definition
16634 // and shall be the only declaration of the function or function
16635 // template in the translation unit.
16636 if (functionDeclHasDefaultArgument(FD)) {
16637 // We can't look at FD->getPreviousDecl() because it may not have been set
16638 // if we're in a dependent context. If the function is known to be a
16639 // redeclaration, we will have narrowed Previous down to the right decl.
16640 if (D.isRedeclaration()) {
16641 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
16642 Diag(Previous.getRepresentativeDecl()->getLocation(),
16643 diag::note_previous_declaration);
16644 } else if (!D.isFunctionDefinition())
16645 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
16648 // Mark templated-scope function declarations as unsupported.
16649 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
16650 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
16651 << SS.getScopeRep() << SS.getRange()
16652 << cast<CXXRecordDecl>(CurContext);
16653 FrD->setUnsupportedFriend(true);
16660 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
16661 AdjustDeclIfTemplate(Dcl);
16663 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
16665 Diag(DelLoc, diag::err_deleted_non_function);
16669 // Deleted function does not have a body.
16670 Fn->setWillHaveBody(false);
16672 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
16673 // Don't consider the implicit declaration we generate for explicit
16674 // specializations. FIXME: Do not generate these implicit declarations.
16675 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
16676 Prev->getPreviousDecl()) &&
16677 !Prev->isDefined()) {
16678 Diag(DelLoc, diag::err_deleted_decl_not_first);
16679 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
16680 Prev->isImplicit() ? diag::note_previous_implicit_declaration
16681 : diag::note_previous_declaration);
16682 // We can't recover from this; the declaration might have already
16684 Fn->setInvalidDecl();
16688 // To maintain the invariant that functions are only deleted on their first
16689 // declaration, mark the implicitly-instantiated declaration of the
16690 // explicitly-specialized function as deleted instead of marking the
16691 // instantiated redeclaration.
16692 Fn = Fn->getCanonicalDecl();
16695 // dllimport/dllexport cannot be deleted.
16696 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
16697 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
16698 Fn->setInvalidDecl();
16701 // C++11 [basic.start.main]p3:
16702 // A program that defines main as deleted [...] is ill-formed.
16704 Diag(DelLoc, diag::err_deleted_main);
16706 // C++11 [dcl.fct.def.delete]p4:
16707 // A deleted function is implicitly inline.
16708 Fn->setImplicitlyInline();
16709 Fn->setDeletedAsWritten();
16712 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
16713 if (!Dcl || Dcl->isInvalidDecl())
16716 auto *FD = dyn_cast<FunctionDecl>(Dcl);
16718 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
16719 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
16720 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
16725 Diag(DefaultLoc, diag::err_default_special_members)
16726 << getLangOpts().CPlusPlus20;
16730 // Reject if this can't possibly be a defaultable function.
16731 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
16733 // A dependent function that doesn't locally look defaultable can
16734 // still instantiate to a defaultable function if it's a constructor
16735 // or assignment operator.
16736 (!FD->isDependentContext() ||
16737 (!isa<CXXConstructorDecl>(FD) &&
16738 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
16739 Diag(DefaultLoc, diag::err_default_special_members)
16740 << getLangOpts().CPlusPlus20;
16744 if (DefKind.isComparison() &&
16745 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
16746 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
16747 << (int)DefKind.asComparison();
16751 // Issue compatibility warning. We already warned if the operator is
16752 // 'operator<=>' when parsing the '<=>' token.
16753 if (DefKind.isComparison() &&
16754 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
16755 Diag(DefaultLoc, getLangOpts().CPlusPlus20
16756 ? diag::warn_cxx17_compat_defaulted_comparison
16757 : diag::ext_defaulted_comparison);
16760 FD->setDefaulted();
16761 FD->setExplicitlyDefaulted();
16763 // Defer checking functions that are defaulted in a dependent context.
16764 if (FD->isDependentContext())
16767 // Unset that we will have a body for this function. We might not,
16768 // if it turns out to be trivial, and we don't need this marking now
16769 // that we've marked it as defaulted.
16770 FD->setWillHaveBody(false);
16772 // If this definition appears within the record, do the checking when
16773 // the record is complete. This is always the case for a defaulted
16775 if (DefKind.isComparison())
16777 auto *MD = cast<CXXMethodDecl>(FD);
16779 const FunctionDecl *Primary = FD;
16780 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
16781 // Ask the template instantiation pattern that actually had the
16782 // '= default' on it.
16785 // If the method was defaulted on its first declaration, we will have
16786 // already performed the checking in CheckCompletedCXXClass. Such a
16787 // declaration doesn't trigger an implicit definition.
16788 if (Primary->getCanonicalDecl()->isDefaulted())
16791 // FIXME: Once we support defining comparisons out of class, check for a
16792 // defaulted comparison here.
16793 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
16794 MD->setInvalidDecl();
16796 DefineDefaultedFunction(*this, MD, DefaultLoc);
16799 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
16800 for (Stmt *SubStmt : S->children()) {
16803 if (isa<ReturnStmt>(SubStmt))
16804 Self.Diag(SubStmt->getBeginLoc(),
16805 diag::err_return_in_constructor_handler);
16806 if (!isa<Expr>(SubStmt))
16807 SearchForReturnInStmt(Self, SubStmt);
16811 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
16812 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
16813 CXXCatchStmt *Handler = TryBlock->getHandler(I);
16814 SearchForReturnInStmt(*this, Handler);
16818 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
16819 const CXXMethodDecl *Old) {
16820 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
16821 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
16823 if (OldFT->hasExtParameterInfos()) {
16824 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
16825 // A parameter of the overriding method should be annotated with noescape
16826 // if the corresponding parameter of the overridden method is annotated.
16827 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
16828 !NewFT->getExtParameterInfo(I).isNoEscape()) {
16829 Diag(New->getParamDecl(I)->getLocation(),
16830 diag::warn_overriding_method_missing_noescape);
16831 Diag(Old->getParamDecl(I)->getLocation(),
16832 diag::note_overridden_marked_noescape);
16836 // Virtual overrides must have the same code_seg.
16837 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
16838 const auto *NewCSA = New->getAttr<CodeSegAttr>();
16839 if ((NewCSA || OldCSA) &&
16840 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
16841 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
16842 Diag(Old->getLocation(), diag::note_previous_declaration);
16846 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
16848 // If the calling conventions match, everything is fine
16849 if (NewCC == OldCC)
16852 // If the calling conventions mismatch because the new function is static,
16853 // suppress the calling convention mismatch error; the error about static
16854 // function override (err_static_overrides_virtual from
16855 // Sema::CheckFunctionDeclaration) is more clear.
16856 if (New->getStorageClass() == SC_Static)
16859 Diag(New->getLocation(),
16860 diag::err_conflicting_overriding_cc_attributes)
16861 << New->getDeclName() << New->getType() << Old->getType();
16862 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
16866 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
16867 const CXXMethodDecl *Old) {
16868 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
16869 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
16871 if (Context.hasSameType(NewTy, OldTy) ||
16872 NewTy->isDependentType() || OldTy->isDependentType())
16875 // Check if the return types are covariant
16876 QualType NewClassTy, OldClassTy;
16878 /// Both types must be pointers or references to classes.
16879 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
16880 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
16881 NewClassTy = NewPT->getPointeeType();
16882 OldClassTy = OldPT->getPointeeType();
16884 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
16885 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
16886 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
16887 NewClassTy = NewRT->getPointeeType();
16888 OldClassTy = OldRT->getPointeeType();
16893 // The return types aren't either both pointers or references to a class type.
16894 if (NewClassTy.isNull()) {
16895 Diag(New->getLocation(),
16896 diag::err_different_return_type_for_overriding_virtual_function)
16897 << New->getDeclName() << NewTy << OldTy
16898 << New->getReturnTypeSourceRange();
16899 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16900 << Old->getReturnTypeSourceRange();
16905 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
16906 // C++14 [class.virtual]p8:
16907 // If the class type in the covariant return type of D::f differs from
16908 // that of B::f, the class type in the return type of D::f shall be
16909 // complete at the point of declaration of D::f or shall be the class
16911 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
16912 if (!RT->isBeingDefined() &&
16913 RequireCompleteType(New->getLocation(), NewClassTy,
16914 diag::err_covariant_return_incomplete,
16915 New->getDeclName()))
16919 // Check if the new class derives from the old class.
16920 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
16921 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
16922 << New->getDeclName() << NewTy << OldTy
16923 << New->getReturnTypeSourceRange();
16924 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16925 << Old->getReturnTypeSourceRange();
16929 // Check if we the conversion from derived to base is valid.
16930 if (CheckDerivedToBaseConversion(
16931 NewClassTy, OldClassTy,
16932 diag::err_covariant_return_inaccessible_base,
16933 diag::err_covariant_return_ambiguous_derived_to_base_conv,
16934 New->getLocation(), New->getReturnTypeSourceRange(),
16935 New->getDeclName(), nullptr)) {
16936 // FIXME: this note won't trigger for delayed access control
16937 // diagnostics, and it's impossible to get an undelayed error
16938 // here from access control during the original parse because
16939 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
16940 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16941 << Old->getReturnTypeSourceRange();
16946 // The qualifiers of the return types must be the same.
16947 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
16948 Diag(New->getLocation(),
16949 diag::err_covariant_return_type_different_qualifications)
16950 << New->getDeclName() << NewTy << OldTy
16951 << New->getReturnTypeSourceRange();
16952 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16953 << Old->getReturnTypeSourceRange();
16958 // The new class type must have the same or less qualifiers as the old type.
16959 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
16960 Diag(New->getLocation(),
16961 diag::err_covariant_return_type_class_type_more_qualified)
16962 << New->getDeclName() << NewTy << OldTy
16963 << New->getReturnTypeSourceRange();
16964 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
16965 << Old->getReturnTypeSourceRange();
16972 /// Mark the given method pure.
16974 /// \param Method the method to be marked pure.
16976 /// \param InitRange the source range that covers the "0" initializer.
16977 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
16978 SourceLocation EndLoc = InitRange.getEnd();
16979 if (EndLoc.isValid())
16980 Method->setRangeEnd(EndLoc);
16982 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
16987 if (!Method->isInvalidDecl())
16988 Diag(Method->getLocation(), diag::err_non_virtual_pure)
16989 << Method->getDeclName() << InitRange;
16993 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
16994 if (D->getFriendObjectKind())
16995 Diag(D->getLocation(), diag::err_pure_friend);
16996 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
16997 CheckPureMethod(M, ZeroLoc);
16999 Diag(D->getLocation(), diag::err_illegal_initializer);
17002 /// Determine whether the given declaration is a global variable or
17003 /// static data member.
17004 static bool isNonlocalVariable(const Decl *D) {
17005 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17006 return Var->hasGlobalStorage();
17011 /// Invoked when we are about to parse an initializer for the declaration
17014 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17015 /// static data member of class X, names should be looked up in the scope of
17016 /// class X. If the declaration had a scope specifier, a scope will have
17017 /// been created and passed in for this purpose. Otherwise, S will be null.
17018 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17019 // If there is no declaration, there was an error parsing it.
17020 if (!D || D->isInvalidDecl())
17023 // We will always have a nested name specifier here, but this declaration
17024 // might not be out of line if the specifier names the current namespace:
17027 if (S && D->isOutOfLine())
17028 EnterDeclaratorContext(S, D->getDeclContext());
17030 // If we are parsing the initializer for a static data member, push a
17031 // new expression evaluation context that is associated with this static
17033 if (isNonlocalVariable(D))
17034 PushExpressionEvaluationContext(
17035 ExpressionEvaluationContext::PotentiallyEvaluated, D);
17038 /// Invoked after we are finished parsing an initializer for the declaration D.
17039 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17040 // If there is no declaration, there was an error parsing it.
17041 if (!D || D->isInvalidDecl())
17044 if (isNonlocalVariable(D))
17045 PopExpressionEvaluationContext();
17047 if (S && D->isOutOfLine())
17048 ExitDeclaratorContext(S);
17051 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17052 /// C++ if/switch/while/for statement.
17053 /// e.g: "if (int x = f()) {...}"
17054 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17056 // The declarator shall not specify a function or an array.
17057 // The type-specifier-seq shall not contain typedef and shall not declare a
17058 // new class or enumeration.
17059 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
17060 "Parser allowed 'typedef' as storage class of condition decl.");
17062 Decl *Dcl = ActOnDeclarator(S, D);
17066 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17067 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17068 << D.getSourceRange();
17075 void Sema::LoadExternalVTableUses() {
17076 if (!ExternalSource)
17079 SmallVector<ExternalVTableUse, 4> VTables;
17080 ExternalSource->ReadUsedVTables(VTables);
17081 SmallVector<VTableUse, 4> NewUses;
17082 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17083 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17084 = VTablesUsed.find(VTables[I].Record);
17085 // Even if a definition wasn't required before, it may be required now.
17086 if (Pos != VTablesUsed.end()) {
17087 if (!Pos->second && VTables[I].DefinitionRequired)
17088 Pos->second = true;
17092 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17093 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17096 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17099 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17100 bool DefinitionRequired) {
17101 // Ignore any vtable uses in unevaluated operands or for classes that do
17102 // not have a vtable.
17103 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17104 CurContext->isDependentContext() || isUnevaluatedContext())
17106 // Do not mark as used if compiling for the device outside of the target
17108 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17109 !isInOpenMPDeclareTargetContext() &&
17110 !isInOpenMPTargetExecutionDirective()) {
17111 if (!DefinitionRequired)
17112 MarkVirtualMembersReferenced(Loc, Class);
17116 // Try to insert this class into the map.
17117 LoadExternalVTableUses();
17118 Class = Class->getCanonicalDecl();
17119 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17120 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17122 // If we already had an entry, check to see if we are promoting this vtable
17123 // to require a definition. If so, we need to reappend to the VTableUses
17124 // list, since we may have already processed the first entry.
17125 if (DefinitionRequired && !Pos.first->second) {
17126 Pos.first->second = true;
17128 // Otherwise, we can early exit.
17132 // The Microsoft ABI requires that we perform the destructor body
17133 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17134 // the deleting destructor is emitted with the vtable, not with the
17135 // destructor definition as in the Itanium ABI.
17136 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17137 CXXDestructorDecl *DD = Class->getDestructor();
17138 if (DD && DD->isVirtual() && !DD->isDeleted()) {
17139 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17140 // If this is an out-of-line declaration, marking it referenced will
17141 // not do anything. Manually call CheckDestructor to look up operator
17143 ContextRAII SavedContext(*this, DD);
17144 CheckDestructor(DD);
17146 MarkFunctionReferenced(Loc, Class->getDestructor());
17152 // Local classes need to have their virtual members marked
17153 // immediately. For all other classes, we mark their virtual members
17154 // at the end of the translation unit.
17155 if (Class->isLocalClass())
17156 MarkVirtualMembersReferenced(Loc, Class);
17158 VTableUses.push_back(std::make_pair(Class, Loc));
17161 bool Sema::DefineUsedVTables() {
17162 LoadExternalVTableUses();
17163 if (VTableUses.empty())
17166 // Note: The VTableUses vector could grow as a result of marking
17167 // the members of a class as "used", so we check the size each
17168 // time through the loop and prefer indices (which are stable) to
17169 // iterators (which are not).
17170 bool DefinedAnything = false;
17171 for (unsigned I = 0; I != VTableUses.size(); ++I) {
17172 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17175 TemplateSpecializationKind ClassTSK =
17176 Class->getTemplateSpecializationKind();
17178 SourceLocation Loc = VTableUses[I].second;
17180 bool DefineVTable = true;
17182 // If this class has a key function, but that key function is
17183 // defined in another translation unit, we don't need to emit the
17184 // vtable even though we're using it.
17185 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17186 if (KeyFunction && !KeyFunction->hasBody()) {
17187 // The key function is in another translation unit.
17188 DefineVTable = false;
17189 TemplateSpecializationKind TSK =
17190 KeyFunction->getTemplateSpecializationKind();
17191 assert(TSK != TSK_ExplicitInstantiationDefinition &&
17192 TSK != TSK_ImplicitInstantiation &&
17193 "Instantiations don't have key functions");
17195 } else if (!KeyFunction) {
17196 // If we have a class with no key function that is the subject
17197 // of an explicit instantiation declaration, suppress the
17198 // vtable; it will live with the explicit instantiation
17200 bool IsExplicitInstantiationDeclaration =
17201 ClassTSK == TSK_ExplicitInstantiationDeclaration;
17202 for (auto R : Class->redecls()) {
17203 TemplateSpecializationKind TSK
17204 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17205 if (TSK == TSK_ExplicitInstantiationDeclaration)
17206 IsExplicitInstantiationDeclaration = true;
17207 else if (TSK == TSK_ExplicitInstantiationDefinition) {
17208 IsExplicitInstantiationDeclaration = false;
17213 if (IsExplicitInstantiationDeclaration)
17214 DefineVTable = false;
17217 // The exception specifications for all virtual members may be needed even
17218 // if we are not providing an authoritative form of the vtable in this TU.
17219 // We may choose to emit it available_externally anyway.
17220 if (!DefineVTable) {
17221 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17225 // Mark all of the virtual members of this class as referenced, so
17226 // that we can build a vtable. Then, tell the AST consumer that a
17227 // vtable for this class is required.
17228 DefinedAnything = true;
17229 MarkVirtualMembersReferenced(Loc, Class);
17230 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17231 if (VTablesUsed[Canonical])
17232 Consumer.HandleVTable(Class);
17234 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17235 // no key function or the key function is inlined. Don't warn in C++ ABIs
17236 // that lack key functions, since the user won't be able to make one.
17237 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17238 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17239 const FunctionDecl *KeyFunctionDef = nullptr;
17240 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17241 KeyFunctionDef->isInlined())) {
17242 Diag(Class->getLocation(),
17243 ClassTSK == TSK_ExplicitInstantiationDefinition
17244 ? diag::warn_weak_template_vtable
17245 : diag::warn_weak_vtable)
17250 VTableUses.clear();
17252 return DefinedAnything;
17255 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17256 const CXXRecordDecl *RD) {
17257 for (const auto *I : RD->methods())
17258 if (I->isVirtual() && !I->isPure())
17259 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17262 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17263 const CXXRecordDecl *RD,
17264 bool ConstexprOnly) {
17265 // Mark all functions which will appear in RD's vtable as used.
17266 CXXFinalOverriderMap FinalOverriders;
17267 RD->getFinalOverriders(FinalOverriders);
17268 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17269 E = FinalOverriders.end();
17271 for (OverridingMethods::const_iterator OI = I->second.begin(),
17272 OE = I->second.end();
17274 assert(OI->second.size() > 0 && "no final overrider");
17275 CXXMethodDecl *Overrider = OI->second.front().Method;
17277 // C++ [basic.def.odr]p2:
17278 // [...] A virtual member function is used if it is not pure. [...]
17279 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17280 MarkFunctionReferenced(Loc, Overrider);
17284 // Only classes that have virtual bases need a VTT.
17285 if (RD->getNumVBases() == 0)
17288 for (const auto &I : RD->bases()) {
17290 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17291 if (Base->getNumVBases() == 0)
17293 MarkVirtualMembersReferenced(Loc, Base);
17297 /// SetIvarInitializers - This routine builds initialization ASTs for the
17298 /// Objective-C implementation whose ivars need be initialized.
17299 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17300 if (!getLangOpts().CPlusPlus)
17302 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17303 SmallVector<ObjCIvarDecl*, 8> ivars;
17304 CollectIvarsToConstructOrDestruct(OID, ivars);
17307 SmallVector<CXXCtorInitializer*, 32> AllToInit;
17308 for (unsigned i = 0; i < ivars.size(); i++) {
17309 FieldDecl *Field = ivars[i];
17310 if (Field->isInvalidDecl())
17313 CXXCtorInitializer *Member;
17314 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17315 InitializationKind InitKind =
17316 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17318 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17319 ExprResult MemberInit =
17320 InitSeq.Perform(*this, InitEntity, InitKind, None);
17321 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17322 // Note, MemberInit could actually come back empty if no initialization
17323 // is required (e.g., because it would call a trivial default constructor)
17324 if (!MemberInit.get() || MemberInit.isInvalid())
17328 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17330 MemberInit.getAs<Expr>(),
17332 AllToInit.push_back(Member);
17334 // Be sure that the destructor is accessible and is marked as referenced.
17335 if (const RecordType *RecordTy =
17336 Context.getBaseElementType(Field->getType())
17337 ->getAs<RecordType>()) {
17338 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17339 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17340 MarkFunctionReferenced(Field->getLocation(), Destructor);
17341 CheckDestructorAccess(Field->getLocation(), Destructor,
17342 PDiag(diag::err_access_dtor_ivar)
17343 << Context.getBaseElementType(Field->getType()));
17347 ObjCImplementation->setIvarInitializers(Context,
17348 AllToInit.data(), AllToInit.size());
17353 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17354 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17355 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17356 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17358 if (Ctor->isInvalidDecl())
17361 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17363 // Target may not be determinable yet, for instance if this is a dependent
17364 // call in an uninstantiated template.
17366 const FunctionDecl *FNTarget = nullptr;
17367 (void)Target->hasBody(FNTarget);
17368 Target = const_cast<CXXConstructorDecl*>(
17369 cast_or_null<CXXConstructorDecl>(FNTarget));
17372 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17373 // Avoid dereferencing a null pointer here.
17374 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17376 if (!Current.insert(Canonical).second)
17379 // We know that beyond here, we aren't chaining into a cycle.
17380 if (!Target || !Target->isDelegatingConstructor() ||
17381 Target->isInvalidDecl() || Valid.count(TCanonical)) {
17382 Valid.insert(Current.begin(), Current.end());
17384 // We've hit a cycle.
17385 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17386 Current.count(TCanonical)) {
17387 // If we haven't diagnosed this cycle yet, do so now.
17388 if (!Invalid.count(TCanonical)) {
17389 S.Diag((*Ctor->init_begin())->getSourceLocation(),
17390 diag::warn_delegating_ctor_cycle)
17393 // Don't add a note for a function delegating directly to itself.
17394 if (TCanonical != Canonical)
17395 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17397 CXXConstructorDecl *C = Target;
17398 while (C->getCanonicalDecl() != Canonical) {
17399 const FunctionDecl *FNTarget = nullptr;
17400 (void)C->getTargetConstructor()->hasBody(FNTarget);
17401 assert(FNTarget && "Ctor cycle through bodiless function");
17403 C = const_cast<CXXConstructorDecl*>(
17404 cast<CXXConstructorDecl>(FNTarget));
17405 S.Diag(C->getLocation(), diag::note_which_delegates_to);
17409 Invalid.insert(Current.begin(), Current.end());
17412 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17417 void Sema::CheckDelegatingCtorCycles() {
17418 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17420 for (DelegatingCtorDeclsType::iterator
17421 I = DelegatingCtorDecls.begin(ExternalSource),
17422 E = DelegatingCtorDecls.end();
17424 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17426 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17427 (*CI)->setInvalidDecl();
17431 /// AST visitor that finds references to the 'this' expression.
17432 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17436 explicit FindCXXThisExpr(Sema &S) : S(S) { }
17438 bool VisitCXXThisExpr(CXXThisExpr *E) {
17439 S.Diag(E->getLocation(), diag::err_this_static_member_func)
17440 << E->isImplicit();
17446 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17447 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17451 TypeLoc TL = TSInfo->getTypeLoc();
17452 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17456 // C++11 [expr.prim.general]p3:
17457 // [The expression this] shall not appear before the optional
17458 // cv-qualifier-seq and it shall not appear within the declaration of a
17459 // static member function (although its type and value category are defined
17460 // within a static member function as they are within a non-static member
17461 // function). [ Note: this is because declaration matching does not occur
17462 // until the complete declarator is known. - end note ]
17463 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17464 FindCXXThisExpr Finder(*this);
17466 // If the return type came after the cv-qualifier-seq, check it now.
17467 if (Proto->hasTrailingReturn() &&
17468 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17471 // Check the exception specification.
17472 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17475 // Check the trailing requires clause
17476 if (Expr *E = Method->getTrailingRequiresClause())
17477 if (!Finder.TraverseStmt(E))
17480 return checkThisInStaticMemberFunctionAttributes(Method);
17483 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17484 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17488 TypeLoc TL = TSInfo->getTypeLoc();
17489 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17493 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17494 FindCXXThisExpr Finder(*this);
17496 switch (Proto->getExceptionSpecType()) {
17498 case EST_Uninstantiated:
17499 case EST_Unevaluated:
17500 case EST_BasicNoexcept:
17502 case EST_DynamicNone:
17507 case EST_DependentNoexcept:
17508 case EST_NoexceptFalse:
17509 case EST_NoexceptTrue:
17510 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17515 for (const auto &E : Proto->exceptions()) {
17516 if (!Finder.TraverseType(E))
17525 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17526 FindCXXThisExpr Finder(*this);
17528 // Check attributes.
17529 for (const auto *A : Method->attrs()) {
17530 // FIXME: This should be emitted by tblgen.
17531 Expr *Arg = nullptr;
17532 ArrayRef<Expr *> Args;
17533 if (const auto *G = dyn_cast<GuardedByAttr>(A))
17535 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17537 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17538 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17539 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17540 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17541 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17542 Arg = ETLF->getSuccessValue();
17543 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17544 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17545 Arg = STLF->getSuccessValue();
17546 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17547 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17548 Arg = LR->getArg();
17549 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17550 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17551 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17552 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17553 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17554 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17555 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17556 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17557 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17558 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17560 if (Arg && !Finder.TraverseStmt(Arg))
17563 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17564 if (!Finder.TraverseStmt(Args[I]))
17572 void Sema::checkExceptionSpecification(
17573 bool IsTopLevel, ExceptionSpecificationType EST,
17574 ArrayRef<ParsedType> DynamicExceptions,
17575 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17576 SmallVectorImpl<QualType> &Exceptions,
17577 FunctionProtoType::ExceptionSpecInfo &ESI) {
17578 Exceptions.clear();
17580 if (EST == EST_Dynamic) {
17581 Exceptions.reserve(DynamicExceptions.size());
17582 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17583 // FIXME: Preserve type source info.
17584 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17587 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17588 collectUnexpandedParameterPacks(ET, Unexpanded);
17589 if (!Unexpanded.empty()) {
17590 DiagnoseUnexpandedParameterPacks(
17591 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17597 // Check that the type is valid for an exception spec, and
17599 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17600 Exceptions.push_back(ET);
17602 ESI.Exceptions = Exceptions;
17606 if (isComputedNoexcept(EST)) {
17607 assert((NoexceptExpr->isTypeDependent() ||
17608 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
17610 "Parser should have made sure that the expression is boolean");
17611 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17612 ESI.Type = EST_BasicNoexcept;
17616 ESI.NoexceptExpr = NoexceptExpr;
17621 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17622 ExceptionSpecificationType EST,
17623 SourceRange SpecificationRange,
17624 ArrayRef<ParsedType> DynamicExceptions,
17625 ArrayRef<SourceRange> DynamicExceptionRanges,
17626 Expr *NoexceptExpr) {
17630 // Dig out the method we're referring to.
17631 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
17632 MethodD = FunTmpl->getTemplatedDecl();
17634 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
17638 // Check the exception specification.
17639 llvm::SmallVector<QualType, 4> Exceptions;
17640 FunctionProtoType::ExceptionSpecInfo ESI;
17641 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
17642 DynamicExceptionRanges, NoexceptExpr, Exceptions,
17645 // Update the exception specification on the function type.
17646 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
17648 if (Method->isStatic())
17649 checkThisInStaticMemberFunctionExceptionSpec(Method);
17651 if (Method->isVirtual()) {
17652 // Check overrides, which we previously had to delay.
17653 for (const CXXMethodDecl *O : Method->overridden_methods())
17654 CheckOverridingFunctionExceptionSpec(Method, O);
17658 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
17660 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
17661 SourceLocation DeclStart, Declarator &D,
17663 InClassInitStyle InitStyle,
17664 AccessSpecifier AS,
17665 const ParsedAttr &MSPropertyAttr) {
17666 IdentifierInfo *II = D.getIdentifier();
17668 Diag(DeclStart, diag::err_anonymous_property);
17671 SourceLocation Loc = D.getIdentifierLoc();
17673 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17674 QualType T = TInfo->getType();
17675 if (getLangOpts().CPlusPlus) {
17676 CheckExtraCXXDefaultArguments(D);
17678 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17679 UPPC_DataMemberType)) {
17680 D.setInvalidType();
17682 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17686 DiagnoseFunctionSpecifiers(D.getDeclSpec());
17688 if (D.getDeclSpec().isInlineSpecified())
17689 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17690 << getLangOpts().CPlusPlus17;
17691 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
17692 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
17693 diag::err_invalid_thread)
17694 << DeclSpec::getSpecifierName(TSCS);
17696 // Check to see if this name was declared as a member previously
17697 NamedDecl *PrevDecl = nullptr;
17698 LookupResult Previous(*this, II, Loc, LookupMemberName,
17699 ForVisibleRedeclaration);
17700 LookupName(Previous, S);
17701 switch (Previous.getResultKind()) {
17702 case LookupResult::Found:
17703 case LookupResult::FoundUnresolvedValue:
17704 PrevDecl = Previous.getAsSingle<NamedDecl>();
17707 case LookupResult::FoundOverloaded:
17708 PrevDecl = Previous.getRepresentativeDecl();
17711 case LookupResult::NotFound:
17712 case LookupResult::NotFoundInCurrentInstantiation:
17713 case LookupResult::Ambiguous:
17717 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17718 // Maybe we will complain about the shadowed template parameter.
17719 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17720 // Just pretend that we didn't see the previous declaration.
17721 PrevDecl = nullptr;
17724 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17725 PrevDecl = nullptr;
17727 SourceLocation TSSL = D.getBeginLoc();
17728 MSPropertyDecl *NewPD =
17729 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
17730 MSPropertyAttr.getPropertyDataGetter(),
17731 MSPropertyAttr.getPropertyDataSetter());
17732 ProcessDeclAttributes(TUScope, NewPD, D);
17733 NewPD->setAccess(AS);
17735 if (NewPD->isInvalidDecl())
17736 Record->setInvalidDecl();
17738 if (D.getDeclSpec().isModulePrivateSpecified())
17739 NewPD->setModulePrivate();
17741 if (NewPD->isInvalidDecl() && PrevDecl) {
17742 // Don't introduce NewFD into scope; there's already something
17743 // with the same name in the same scope.
17745 PushOnScopeChains(NewPD, S);
17747 Record->addDecl(NewPD);
17752 void Sema::ActOnStartFunctionDeclarationDeclarator(
17753 Declarator &Declarator, unsigned TemplateParameterDepth) {
17754 auto &Info = InventedParameterInfos.emplace_back();
17755 TemplateParameterList *ExplicitParams = nullptr;
17756 ArrayRef<TemplateParameterList *> ExplicitLists =
17757 Declarator.getTemplateParameterLists();
17758 if (!ExplicitLists.empty()) {
17759 bool IsMemberSpecialization, IsInvalid;
17760 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
17761 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
17762 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
17763 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
17764 /*SuppressDiagnostic=*/true);
17766 if (ExplicitParams) {
17767 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
17768 for (NamedDecl *Param : *ExplicitParams)
17769 Info.TemplateParams.push_back(Param);
17770 Info.NumExplicitTemplateParams = ExplicitParams->size();
17772 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
17773 Info.NumExplicitTemplateParams = 0;
17777 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
17778 auto &FSI = InventedParameterInfos.back();
17779 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
17780 if (FSI.NumExplicitTemplateParams != 0) {
17781 TemplateParameterList *ExplicitParams =
17782 Declarator.getTemplateParameterLists().back();
17783 Declarator.setInventedTemplateParameterList(
17784 TemplateParameterList::Create(
17785 Context, ExplicitParams->getTemplateLoc(),
17786 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
17787 ExplicitParams->getRAngleLoc(),
17788 ExplicitParams->getRequiresClause()));
17790 Declarator.setInventedTemplateParameterList(
17791 TemplateParameterList::Create(
17792 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
17793 SourceLocation(), /*RequiresClause=*/nullptr));
17796 InventedParameterInfos.pop_back();