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/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/LiteralSupport.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Initialization.h"
34 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/ParsedTemplate.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/Template.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
46 using namespace clang;
48 //===----------------------------------------------------------------------===//
49 // CheckDefaultArgumentVisitor
50 //===----------------------------------------------------------------------===//
53 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
54 /// the default argument of a parameter to determine whether it
55 /// contains any ill-formed subexpressions. For example, this will
56 /// diagnose the use of local variables or parameters within the
57 /// default argument expression.
58 class CheckDefaultArgumentVisitor
59 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
64 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
65 : DefaultArg(defarg), S(s) {}
67 bool VisitExpr(Expr *Node);
68 bool VisitDeclRefExpr(DeclRefExpr *DRE);
69 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
70 bool VisitLambdaExpr(LambdaExpr *Lambda);
71 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE);
74 /// VisitExpr - Visit all of the children of this expression.
75 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
76 bool IsInvalid = false;
77 for (Stmt *SubStmt : Node->children())
78 IsInvalid |= Visit(SubStmt);
82 /// VisitDeclRefExpr - Visit a reference to a declaration, to
83 /// determine whether this declaration can be used in the default
84 /// argument expression.
85 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
86 NamedDecl *Decl = DRE->getDecl();
87 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
88 // C++ [dcl.fct.default]p9
89 // Default arguments are evaluated each time the function is
90 // called. The order of evaluation of function arguments is
91 // unspecified. Consequently, parameters of a function shall not
92 // be used in default argument expressions, even if they are not
93 // evaluated. Parameters of a function declared before a default
94 // argument expression are in scope and can hide namespace and
95 // class member names.
96 return S->Diag(DRE->getBeginLoc(),
97 diag::err_param_default_argument_references_param)
98 << Param->getDeclName() << DefaultArg->getSourceRange();
99 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
100 // C++ [dcl.fct.default]p7
101 // Local variables shall not be used in default argument
103 if (VDecl->isLocalVarDecl())
104 return S->Diag(DRE->getBeginLoc(),
105 diag::err_param_default_argument_references_local)
106 << VDecl->getDeclName() << DefaultArg->getSourceRange();
112 /// VisitCXXThisExpr - Visit a C++ "this" expression.
113 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
114 // C++ [dcl.fct.default]p8:
115 // The keyword this shall not be used in a default argument of a
117 return S->Diag(ThisE->getBeginLoc(),
118 diag::err_param_default_argument_references_this)
119 << ThisE->getSourceRange();
122 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
123 bool Invalid = false;
124 for (PseudoObjectExpr::semantics_iterator
125 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) {
128 // Look through bindings.
129 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
130 E = OVE->getSourceExpr();
131 assert(E && "pseudo-object binding without source expression?");
139 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) {
140 // C++11 [expr.lambda.prim]p13:
141 // A lambda-expression appearing in a default argument shall not
142 // implicitly or explicitly capture any entity.
143 if (Lambda->capture_begin() == Lambda->capture_end())
146 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
151 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
152 const CXXMethodDecl *Method) {
153 // If we have an MSAny spec already, don't bother.
154 if (!Method || ComputedEST == EST_MSAny)
157 const FunctionProtoType *Proto
158 = Method->getType()->getAs<FunctionProtoType>();
159 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
163 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
165 // If we have a throw-all spec at this point, ignore the function.
166 if (ComputedEST == EST_None)
169 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
170 EST = EST_BasicNoexcept;
174 case EST_Uninstantiated:
175 case EST_Unevaluated:
176 llvm_unreachable("should not see unresolved exception specs here");
178 // If this function can throw any exceptions, make a note of that.
181 // FIXME: Whichever we see last of MSAny and None determines our result.
182 // We should make a consistent, order-independent choice here.
186 case EST_NoexceptFalse:
188 ComputedEST = EST_None;
190 // FIXME: If the call to this decl is using any of its default arguments, we
191 // need to search them for potentially-throwing calls.
192 // If this function has a basic noexcept, it doesn't affect the outcome.
193 case EST_BasicNoexcept:
194 case EST_NoexceptTrue:
197 // If we're still at noexcept(true) and there's a throw() callee,
198 // change to that specification.
199 case EST_DynamicNone:
200 if (ComputedEST == EST_BasicNoexcept)
201 ComputedEST = EST_DynamicNone;
203 case EST_DependentNoexcept:
205 "should not generate implicit declarations for dependent cases");
209 assert(EST == EST_Dynamic && "EST case not considered earlier.");
210 assert(ComputedEST != EST_None &&
211 "Shouldn't collect exceptions when throw-all is guaranteed.");
212 ComputedEST = EST_Dynamic;
213 // Record the exceptions in this function's exception specification.
214 for (const auto &E : Proto->exceptions())
215 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
216 Exceptions.push_back(E);
219 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
220 if (!E || ComputedEST == EST_MSAny)
225 // C++0x [except.spec]p14:
226 // [An] implicit exception-specification specifies the type-id T if and
227 // only if T is allowed by the exception-specification of a function directly
228 // invoked by f's implicit definition; f shall allow all exceptions if any
229 // function it directly invokes allows all exceptions, and f shall allow no
230 // exceptions if every function it directly invokes allows no exceptions.
232 // Note in particular that if an implicit exception-specification is generated
233 // for a function containing a throw-expression, that specification can still
234 // be noexcept(true).
236 // Note also that 'directly invoked' is not defined in the standard, and there
237 // is no indication that we should only consider potentially-evaluated calls.
239 // Ultimately we should implement the intent of the standard: the exception
240 // specification should be the set of exceptions which can be thrown by the
241 // implicit definition. For now, we assume that any non-nothrow expression can
242 // throw any exception.
244 if (Self->canThrow(E))
245 ComputedEST = EST_None;
249 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
250 SourceLocation EqualLoc) {
251 if (RequireCompleteType(Param->getLocation(), Param->getType(),
252 diag::err_typecheck_decl_incomplete_type)) {
253 Param->setInvalidDecl();
257 // C++ [dcl.fct.default]p5
258 // A default argument expression is implicitly converted (clause
259 // 4) to the parameter type. The default argument expression has
260 // the same semantic constraints as the initializer expression in
261 // a declaration of a variable of the parameter type, using the
262 // copy-initialization semantics (8.5).
263 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
265 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
267 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
268 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
269 if (Result.isInvalid())
271 Arg = Result.getAs<Expr>();
273 CheckCompletedExpr(Arg, EqualLoc);
274 Arg = MaybeCreateExprWithCleanups(Arg);
276 // Okay: add the default argument to the parameter
277 Param->setDefaultArg(Arg);
279 // We have already instantiated this parameter; provide each of the
280 // instantiations with the uninstantiated default argument.
281 UnparsedDefaultArgInstantiationsMap::iterator InstPos
282 = UnparsedDefaultArgInstantiations.find(Param);
283 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
284 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
285 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
287 // We're done tracking this parameter's instantiations.
288 UnparsedDefaultArgInstantiations.erase(InstPos);
294 /// ActOnParamDefaultArgument - Check whether the default argument
295 /// provided for a function parameter is well-formed. If so, attach it
296 /// to the parameter declaration.
298 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
300 if (!param || !DefaultArg)
303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
304 UnparsedDefaultArgLocs.erase(Param);
306 // Default arguments are only permitted in C++
307 if (!getLangOpts().CPlusPlus) {
308 Diag(EqualLoc, diag::err_param_default_argument)
309 << DefaultArg->getSourceRange();
310 Param->setInvalidDecl();
314 // Check for unexpanded parameter packs.
315 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
316 Param->setInvalidDecl();
320 // C++11 [dcl.fct.default]p3
321 // A default argument expression [...] shall not be specified for a
323 if (Param->isParameterPack()) {
324 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
325 << DefaultArg->getSourceRange();
329 // Check that the default argument is well-formed
330 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
331 if (DefaultArgChecker.Visit(DefaultArg)) {
332 Param->setInvalidDecl();
336 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
339 /// ActOnParamUnparsedDefaultArgument - We've seen a default
340 /// argument for a function parameter, but we can't parse it yet
341 /// because we're inside a class definition. Note that this default
342 /// argument will be parsed later.
343 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
344 SourceLocation EqualLoc,
345 SourceLocation ArgLoc) {
349 ParmVarDecl *Param = cast<ParmVarDecl>(param);
350 Param->setUnparsedDefaultArg();
351 UnparsedDefaultArgLocs[Param] = ArgLoc;
354 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
355 /// the default argument for the parameter param failed.
356 void Sema::ActOnParamDefaultArgumentError(Decl *param,
357 SourceLocation EqualLoc) {
361 ParmVarDecl *Param = cast<ParmVarDecl>(param);
362 Param->setInvalidDecl();
363 UnparsedDefaultArgLocs.erase(Param);
364 Param->setDefaultArg(new(Context)
365 OpaqueValueExpr(EqualLoc,
366 Param->getType().getNonReferenceType(),
370 /// CheckExtraCXXDefaultArguments - Check for any extra default
371 /// arguments in the declarator, which is not a function declaration
372 /// or definition and therefore is not permitted to have default
373 /// arguments. This routine should be invoked for every declarator
374 /// that is not a function declaration or definition.
375 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
376 // C++ [dcl.fct.default]p3
377 // A default argument expression shall be specified only in the
378 // parameter-declaration-clause of a function declaration or in a
379 // template-parameter (14.1). It shall not be specified for a
380 // parameter pack. If it is specified in a
381 // parameter-declaration-clause, it shall not occur within a
382 // declarator or abstract-declarator of a parameter-declaration.
383 bool MightBeFunction = D.isFunctionDeclarationContext();
384 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
385 DeclaratorChunk &chunk = D.getTypeObject(i);
386 if (chunk.Kind == DeclaratorChunk::Function) {
387 if (MightBeFunction) {
388 // This is a function declaration. It can have default arguments, but
389 // keep looking in case its return type is a function type with default
391 MightBeFunction = false;
394 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
396 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
397 if (Param->hasUnparsedDefaultArg()) {
398 std::unique_ptr<CachedTokens> Toks =
399 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
401 if (Toks->size() > 1)
402 SR = SourceRange((*Toks)[1].getLocation(),
403 Toks->back().getLocation());
405 SR = UnparsedDefaultArgLocs[Param];
406 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
408 } else if (Param->getDefaultArg()) {
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
410 << Param->getDefaultArg()->getSourceRange();
411 Param->setDefaultArg(nullptr);
414 } else if (chunk.Kind != DeclaratorChunk::Paren) {
415 MightBeFunction = false;
420 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
421 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
422 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
423 if (!PVD->hasDefaultArg())
425 if (!PVD->hasInheritedDefaultArg())
431 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
432 /// function, once we already know that they have the same
433 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
434 /// error, false otherwise.
435 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
437 bool Invalid = false;
439 // The declaration context corresponding to the scope is the semantic
440 // parent, unless this is a local function declaration, in which case
441 // it is that surrounding function.
442 DeclContext *ScopeDC = New->isLocalExternDecl()
443 ? New->getLexicalDeclContext()
444 : New->getDeclContext();
446 // Find the previous declaration for the purpose of default arguments.
447 FunctionDecl *PrevForDefaultArgs = Old;
448 for (/**/; PrevForDefaultArgs;
449 // Don't bother looking back past the latest decl if this is a local
450 // extern declaration; nothing else could work.
451 PrevForDefaultArgs = New->isLocalExternDecl()
453 : PrevForDefaultArgs->getPreviousDecl()) {
454 // Ignore hidden declarations.
455 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
458 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
459 !New->isCXXClassMember()) {
460 // Ignore default arguments of old decl if they are not in
461 // the same scope and this is not an out-of-line definition of
462 // a member function.
466 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
467 // If only one of these is a local function declaration, then they are
468 // declared in different scopes, even though isDeclInScope may think
469 // they're in the same scope. (If both are local, the scope check is
470 // sufficient, and if neither is local, then they are in the same scope.)
474 // We found the right previous declaration.
478 // C++ [dcl.fct.default]p4:
479 // For non-template functions, default arguments can be added in
480 // later declarations of a function in the same
481 // scope. Declarations in different scopes have completely
482 // distinct sets of default arguments. That is, declarations in
483 // inner scopes do not acquire default arguments from
484 // declarations in outer scopes, and vice versa. In a given
485 // function declaration, all parameters subsequent to a
486 // parameter with a default argument shall have default
487 // arguments supplied in this or previous declarations. A
488 // default argument shall not be redefined by a later
489 // declaration (not even to the same value).
491 // C++ [dcl.fct.default]p6:
492 // Except for member functions of class templates, the default arguments
493 // in a member function definition that appears outside of the class
494 // definition are added to the set of default arguments provided by the
495 // member function declaration in the class definition.
496 for (unsigned p = 0, NumParams = PrevForDefaultArgs
497 ? PrevForDefaultArgs->getNumParams()
499 p < NumParams; ++p) {
500 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
501 ParmVarDecl *NewParam = New->getParamDecl(p);
503 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
504 bool NewParamHasDfl = NewParam->hasDefaultArg();
506 if (OldParamHasDfl && NewParamHasDfl) {
507 unsigned DiagDefaultParamID =
508 diag::err_param_default_argument_redefinition;
510 // MSVC accepts that default parameters be redefined for member functions
511 // of template class. The new default parameter's value is ignored.
513 if (getLangOpts().MicrosoftExt) {
514 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
515 if (MD && MD->getParent()->getDescribedClassTemplate()) {
516 // Merge the old default argument into the new parameter.
517 NewParam->setHasInheritedDefaultArg();
518 if (OldParam->hasUninstantiatedDefaultArg())
519 NewParam->setUninstantiatedDefaultArg(
520 OldParam->getUninstantiatedDefaultArg());
522 NewParam->setDefaultArg(OldParam->getInit());
523 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
528 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
529 // hint here. Alternatively, we could walk the type-source information
530 // for NewParam to find the last source location in the type... but it
531 // isn't worth the effort right now. This is the kind of test case that
532 // is hard to get right:
534 // void g(int (*fp)(int) = f);
535 // void g(int (*fp)(int) = &f);
536 Diag(NewParam->getLocation(), DiagDefaultParamID)
537 << NewParam->getDefaultArgRange();
539 // Look for the function declaration where the default argument was
540 // actually written, which may be a declaration prior to Old.
541 for (auto Older = PrevForDefaultArgs;
542 OldParam->hasInheritedDefaultArg(); /**/) {
543 Older = Older->getPreviousDecl();
544 OldParam = Older->getParamDecl(p);
547 Diag(OldParam->getLocation(), diag::note_previous_definition)
548 << OldParam->getDefaultArgRange();
549 } else if (OldParamHasDfl) {
550 // Merge the old default argument into the new parameter unless the new
551 // function is a friend declaration in a template class. In the latter
552 // case the default arguments will be inherited when the friend
553 // declaration will be instantiated.
554 if (New->getFriendObjectKind() == Decl::FOK_None ||
555 !New->getLexicalDeclContext()->isDependentContext()) {
556 // It's important to use getInit() here; getDefaultArg()
557 // strips off any top-level ExprWithCleanups.
558 NewParam->setHasInheritedDefaultArg();
559 if (OldParam->hasUnparsedDefaultArg())
560 NewParam->setUnparsedDefaultArg();
561 else if (OldParam->hasUninstantiatedDefaultArg())
562 NewParam->setUninstantiatedDefaultArg(
563 OldParam->getUninstantiatedDefaultArg());
565 NewParam->setDefaultArg(OldParam->getInit());
567 } else if (NewParamHasDfl) {
568 if (New->getDescribedFunctionTemplate()) {
569 // Paragraph 4, quoted above, only applies to non-template functions.
570 Diag(NewParam->getLocation(),
571 diag::err_param_default_argument_template_redecl)
572 << NewParam->getDefaultArgRange();
573 Diag(PrevForDefaultArgs->getLocation(),
574 diag::note_template_prev_declaration)
576 } else if (New->getTemplateSpecializationKind()
577 != TSK_ImplicitInstantiation &&
578 New->getTemplateSpecializationKind() != TSK_Undeclared) {
579 // C++ [temp.expr.spec]p21:
580 // Default function arguments shall not be specified in a declaration
581 // or a definition for one of the following explicit specializations:
582 // - the explicit specialization of a function template;
583 // - the explicit specialization of a member function template;
584 // - the explicit specialization of a member function of a class
585 // template where the class template specialization to which the
586 // member function specialization belongs is implicitly
588 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
589 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
590 << New->getDeclName()
591 << NewParam->getDefaultArgRange();
592 } else if (New->getDeclContext()->isDependentContext()) {
593 // C++ [dcl.fct.default]p6 (DR217):
594 // Default arguments for a member function of a class template shall
595 // be specified on the initial declaration of the member function
596 // within the class template.
598 // Reading the tea leaves a bit in DR217 and its reference to DR205
599 // leads me to the conclusion that one cannot add default function
600 // arguments for an out-of-line definition of a member function of a
603 if (CXXRecordDecl *Record
604 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
605 if (Record->getDescribedClassTemplate())
607 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
613 Diag(NewParam->getLocation(),
614 diag::err_param_default_argument_member_template_redecl)
616 << NewParam->getDefaultArgRange();
621 // DR1344: If a default argument is added outside a class definition and that
622 // default argument makes the function a special member function, the program
623 // is ill-formed. This can only happen for constructors.
624 if (isa<CXXConstructorDecl>(New) &&
625 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
626 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
627 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
628 if (NewSM != OldSM) {
629 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
630 assert(NewParam->hasDefaultArg());
631 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
632 << NewParam->getDefaultArgRange() << NewSM;
633 Diag(Old->getLocation(), diag::note_previous_declaration);
637 const FunctionDecl *Def;
638 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
639 // template has a constexpr specifier then all its declarations shall
640 // contain the constexpr specifier.
641 if (New->getConstexprKind() != Old->getConstexprKind()) {
642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643 << New << New->getConstexprKind() << Old->getConstexprKind();
644 Diag(Old->getLocation(), diag::note_previous_declaration);
646 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
647 Old->isDefined(Def) &&
648 // If a friend function is inlined but does not have 'inline'
649 // specifier, it is a definition. Do not report attribute conflict
650 // in this case, redefinition will be diagnosed later.
651 (New->isInlineSpecified() ||
652 New->getFriendObjectKind() == Decl::FOK_None)) {
653 // C++11 [dcl.fcn.spec]p4:
654 // If the definition of a function appears in a translation unit before its
655 // first declaration as inline, the program is ill-formed.
656 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
657 Diag(Def->getLocation(), diag::note_previous_definition);
661 // C++17 [temp.deduct.guide]p3:
662 // Two deduction guide declarations in the same translation unit
663 // for the same class template shall not have equivalent
664 // parameter-declaration-clauses.
665 if (isa<CXXDeductionGuideDecl>(New) &&
666 !New->isFunctionTemplateSpecialization()) {
667 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
668 Diag(Old->getLocation(), diag::note_previous_declaration);
671 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
672 // argument expression, that declaration shall be a definition and shall be
673 // the only declaration of the function or function template in the
675 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
676 functionDeclHasDefaultArgument(Old)) {
677 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
678 Diag(Old->getLocation(), diag::note_previous_declaration);
686 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
687 MultiTemplateParamsArg TemplateParamLists) {
688 assert(D.isDecompositionDeclarator());
689 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
691 // The syntax only allows a decomposition declarator as a simple-declaration,
692 // a for-range-declaration, or a condition in Clang, but we parse it in more
694 if (!D.mayHaveDecompositionDeclarator()) {
695 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
696 << Decomp.getSourceRange();
700 if (!TemplateParamLists.empty()) {
701 // FIXME: There's no rule against this, but there are also no rules that
702 // would actually make it usable, so we reject it for now.
703 Diag(TemplateParamLists.front()->getTemplateLoc(),
704 diag::err_decomp_decl_template);
708 Diag(Decomp.getLSquareLoc(),
709 !getLangOpts().CPlusPlus17
710 ? diag::ext_decomp_decl
711 : D.getContext() == DeclaratorContext::ConditionContext
712 ? diag::ext_decomp_decl_cond
713 : diag::warn_cxx14_compat_decomp_decl)
714 << Decomp.getSourceRange();
716 // The semantic context is always just the current context.
717 DeclContext *const DC = CurContext;
719 // C++17 [dcl.dcl]/8:
720 // The decl-specifier-seq shall contain only the type-specifier auto
721 // and cv-qualifiers.
722 // C++2a [dcl.dcl]/8:
723 // If decl-specifier-seq contains any decl-specifier other than static,
724 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
725 auto &DS = D.getDeclSpec();
727 SmallVector<StringRef, 8> BadSpecifiers;
728 SmallVector<SourceLocation, 8> BadSpecifierLocs;
729 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
730 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
731 if (auto SCS = DS.getStorageClassSpec()) {
732 if (SCS == DeclSpec::SCS_static) {
733 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
734 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
736 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
737 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
740 if (auto TSCS = DS.getThreadStorageClassSpec()) {
741 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
742 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
744 if (DS.hasConstexprSpecifier()) {
745 BadSpecifiers.push_back(
746 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
747 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
749 if (DS.isInlineSpecified()) {
750 BadSpecifiers.push_back("inline");
751 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
753 if (!BadSpecifiers.empty()) {
754 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
755 Err << (int)BadSpecifiers.size()
756 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
757 // Don't add FixItHints to remove the specifiers; we do still respect
758 // them when building the underlying variable.
759 for (auto Loc : BadSpecifierLocs)
760 Err << SourceRange(Loc, Loc);
761 } else if (!CPlusPlus20Specifiers.empty()) {
762 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
763 getLangOpts().CPlusPlus2a
764 ? diag::warn_cxx17_compat_decomp_decl_spec
765 : diag::ext_decomp_decl_spec);
766 Warn << (int)CPlusPlus20Specifiers.size()
767 << llvm::join(CPlusPlus20Specifiers.begin(),
768 CPlusPlus20Specifiers.end(), " ");
769 for (auto Loc : CPlusPlus20SpecifierLocs)
770 Warn << SourceRange(Loc, Loc);
772 // We can't recover from it being declared as a typedef.
773 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
777 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
778 QualType R = TInfo->getType();
780 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
781 UPPC_DeclarationType))
784 // The syntax only allows a single ref-qualifier prior to the decomposition
785 // declarator. No other declarator chunks are permitted. Also check the type
787 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
788 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
789 (D.getNumTypeObjects() == 1 &&
790 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
791 Diag(Decomp.getLSquareLoc(),
792 (D.hasGroupingParens() ||
793 (D.getNumTypeObjects() &&
794 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
795 ? diag::err_decomp_decl_parens
796 : diag::err_decomp_decl_type)
799 // In most cases, there's no actual problem with an explicitly-specified
800 // type, but a function type won't work here, and ActOnVariableDeclarator
801 // shouldn't be called for such a type.
802 if (R->isFunctionType())
806 // Build the BindingDecls.
807 SmallVector<BindingDecl*, 8> Bindings;
809 // Build the BindingDecls.
810 for (auto &B : D.getDecompositionDeclarator().bindings()) {
811 // Check for name conflicts.
812 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
813 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
814 ForVisibleRedeclaration);
815 LookupName(Previous, S,
816 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
818 // It's not permitted to shadow a template parameter name.
819 if (Previous.isSingleResult() &&
820 Previous.getFoundDecl()->isTemplateParameter()) {
821 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
822 Previous.getFoundDecl());
826 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
827 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
828 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
829 /*AllowInlineNamespace*/false);
830 if (!Previous.empty()) {
831 auto *Old = Previous.getRepresentativeDecl();
832 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
833 Diag(Old->getLocation(), diag::note_previous_definition);
836 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
837 PushOnScopeChains(BD, S, true);
838 Bindings.push_back(BD);
839 ParsingInitForAutoVars.insert(BD);
842 // There are no prior lookup results for the variable itself, because it
844 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
845 Decomp.getLSquareLoc());
846 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
847 ForVisibleRedeclaration);
849 // Build the variable that holds the non-decomposed object.
850 bool AddToScope = true;
852 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
853 MultiTemplateParamsArg(), AddToScope, Bindings);
856 CurContext->addHiddenDecl(New);
859 if (isInOpenMPDeclareTargetContext())
860 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
865 static bool checkSimpleDecomposition(
866 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
867 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
868 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
869 if ((int64_t)Bindings.size() != NumElems) {
870 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
871 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
872 << (NumElems < Bindings.size());
877 for (auto *B : Bindings) {
878 SourceLocation Loc = B->getLocation();
879 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
882 E = GetInit(Loc, E.get(), I++);
885 B->setBinding(ElemType, E.get());
891 static bool checkArrayLikeDecomposition(Sema &S,
892 ArrayRef<BindingDecl *> Bindings,
893 ValueDecl *Src, QualType DecompType,
894 const llvm::APSInt &NumElems,
896 return checkSimpleDecomposition(
897 S, Bindings, Src, DecompType, NumElems, ElemType,
898 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
899 ExprResult E = S.ActOnIntegerConstant(Loc, I);
902 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
906 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
907 ValueDecl *Src, QualType DecompType,
908 const ConstantArrayType *CAT) {
909 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
910 llvm::APSInt(CAT->getSize()),
911 CAT->getElementType());
914 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
915 ValueDecl *Src, QualType DecompType,
916 const VectorType *VT) {
917 return checkArrayLikeDecomposition(
918 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
919 S.Context.getQualifiedType(VT->getElementType(),
920 DecompType.getQualifiers()));
923 static bool checkComplexDecomposition(Sema &S,
924 ArrayRef<BindingDecl *> Bindings,
925 ValueDecl *Src, QualType DecompType,
926 const ComplexType *CT) {
927 return checkSimpleDecomposition(
928 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
929 S.Context.getQualifiedType(CT->getElementType(),
930 DecompType.getQualifiers()),
931 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
932 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
936 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
937 TemplateArgumentListInfo &Args) {
939 llvm::raw_svector_ostream OS(SS);
941 for (auto &Arg : Args.arguments()) {
944 Arg.getArgument().print(PrintingPolicy, OS);
950 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
951 SourceLocation Loc, StringRef Trait,
952 TemplateArgumentListInfo &Args,
954 auto DiagnoseMissing = [&] {
956 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
961 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
962 NamespaceDecl *Std = S.getStdNamespace();
964 return DiagnoseMissing();
966 // Look up the trait itself, within namespace std. We can diagnose various
967 // problems with this lookup even if we've been asked to not diagnose a
968 // missing specialization, because this can only fail if the user has been
969 // declaring their own names in namespace std or we don't support the
970 // standard library implementation in use.
971 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
972 Loc, Sema::LookupOrdinaryName);
973 if (!S.LookupQualifiedName(Result, Std))
974 return DiagnoseMissing();
975 if (Result.isAmbiguous())
978 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
980 Result.suppressDiagnostics();
981 NamedDecl *Found = *Result.begin();
982 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
983 S.Diag(Found->getLocation(), diag::note_declared_at);
987 // Build the template-id.
988 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
989 if (TraitTy.isNull())
991 if (!S.isCompleteType(Loc, TraitTy)) {
993 S.RequireCompleteType(
994 Loc, TraitTy, DiagID,
995 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
999 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1000 assert(RD && "specialization of class template is not a class?");
1002 // Look up the member of the trait type.
1003 S.LookupQualifiedName(TraitMemberLookup, RD);
1004 return TraitMemberLookup.isAmbiguous();
1007 static TemplateArgumentLoc
1008 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1010 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1011 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1014 static TemplateArgumentLoc
1015 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1016 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1019 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1021 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1022 llvm::APSInt &Size) {
1023 EnterExpressionEvaluationContext ContextRAII(
1024 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1026 DeclarationName Value = S.PP.getIdentifierInfo("value");
1027 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1029 // Form template argument list for tuple_size<T>.
1030 TemplateArgumentListInfo Args(Loc, Loc);
1031 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1033 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1034 // it's not tuple-like.
1035 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1037 return IsTupleLike::NotTupleLike;
1039 // If we get this far, we've committed to the tuple interpretation, but
1040 // we can still fail if there actually isn't a usable ::value.
1042 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1044 TemplateArgumentListInfo &Args;
1045 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1046 : R(R), Args(Args) {}
1047 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1048 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1049 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1051 } Diagnoser(R, Args);
1054 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1056 return IsTupleLike::Error;
1058 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1060 return IsTupleLike::Error;
1062 return IsTupleLike::TupleLike;
1065 /// \return std::tuple_element<I, T>::type.
1066 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1067 unsigned I, QualType T) {
1068 // Form template argument list for tuple_element<I, T>.
1069 TemplateArgumentListInfo Args(Loc, Loc);
1071 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1072 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1074 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1075 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1076 if (lookupStdTypeTraitMember(
1077 S, R, Loc, "tuple_element", Args,
1078 diag::err_decomp_decl_std_tuple_element_not_specialized))
1081 auto *TD = R.getAsSingle<TypeDecl>();
1083 R.suppressDiagnostics();
1084 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1085 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1087 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1091 return S.Context.getTypeDeclType(TD);
1095 struct BindingDiagnosticTrap {
1097 DiagnosticErrorTrap Trap;
1100 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1101 : S(S), Trap(S.Diags), BD(BD) {}
1102 ~BindingDiagnosticTrap() {
1103 if (Trap.hasErrorOccurred())
1104 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1109 static bool checkTupleLikeDecomposition(Sema &S,
1110 ArrayRef<BindingDecl *> Bindings,
1111 VarDecl *Src, QualType DecompType,
1112 const llvm::APSInt &TupleSize) {
1113 if ((int64_t)Bindings.size() != TupleSize) {
1114 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1115 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1116 << (TupleSize < Bindings.size());
1120 if (Bindings.empty())
1123 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1126 // The unqualified-id get is looked up in the scope of E by class member
1127 // access lookup ...
1128 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1129 bool UseMemberGet = false;
1130 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1131 if (auto *RD = DecompType->getAsCXXRecordDecl())
1132 S.LookupQualifiedName(MemberGet, RD);
1133 if (MemberGet.isAmbiguous())
1135 // ... and if that finds at least one declaration that is a function
1136 // template whose first template parameter is a non-type parameter ...
1137 for (NamedDecl *D : MemberGet) {
1138 if (FunctionTemplateDecl *FTD =
1139 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1140 TemplateParameterList *TPL = FTD->getTemplateParameters();
1141 if (TPL->size() != 0 &&
1142 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1143 // ... the initializer is e.get<i>().
1144 UseMemberGet = true;
1152 for (auto *B : Bindings) {
1153 BindingDiagnosticTrap Trap(S, B);
1154 SourceLocation Loc = B->getLocation();
1156 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1160 // e is an lvalue if the type of the entity is an lvalue reference and
1161 // an xvalue otherwise
1162 if (!Src->getType()->isLValueReferenceType())
1163 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1164 E.get(), nullptr, VK_XValue);
1166 TemplateArgumentListInfo Args(Loc, Loc);
1168 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1171 // if [lookup of member get] finds at least one declaration, the
1172 // initializer is e.get<i-1>().
1173 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1174 CXXScopeSpec(), SourceLocation(), nullptr,
1175 MemberGet, &Args, nullptr);
1179 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1181 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1182 // in the associated namespaces.
1183 Expr *Get = UnresolvedLookupExpr::Create(
1184 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1185 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1186 UnresolvedSetIterator(), UnresolvedSetIterator());
1188 Expr *Arg = E.get();
1189 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1193 Expr *Init = E.get();
1195 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1196 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1200 // each vi is a variable of type "reference to T" initialized with the
1201 // initializer, where the reference is an lvalue reference if the
1202 // initializer is an lvalue and an rvalue reference otherwise
1204 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1205 if (RefType.isNull())
1207 auto *RefVD = VarDecl::Create(
1208 S.Context, Src->getDeclContext(), Loc, Loc,
1209 B->getDeclName().getAsIdentifierInfo(), RefType,
1210 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1211 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1212 RefVD->setTSCSpec(Src->getTSCSpec());
1213 RefVD->setImplicit();
1214 if (Src->isInlineSpecified())
1215 RefVD->setInlineSpecified();
1216 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1218 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1219 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1220 InitializationSequence Seq(S, Entity, Kind, Init);
1221 E = Seq.Perform(S, Entity, Kind, Init);
1224 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1227 RefVD->setInit(E.get());
1228 if (!E.get()->isValueDependent())
1229 RefVD->checkInitIsICE();
1231 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1232 DeclarationNameInfo(B->getDeclName(), Loc),
1237 B->setBinding(T, E.get());
1244 /// Find the base class to decompose in a built-in decomposition of a class type.
1245 /// This base class search is, unfortunately, not quite like any other that we
1246 /// perform anywhere else in C++.
1247 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1248 const CXXRecordDecl *RD,
1249 CXXCastPath &BasePath) {
1250 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1251 CXXBasePath &Path) {
1252 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1255 const CXXRecordDecl *ClassWithFields = nullptr;
1256 AccessSpecifier AS = AS_public;
1257 if (RD->hasDirectFields())
1259 // Otherwise, all of E's non-static data members shall be public direct
1261 ClassWithFields = RD;
1265 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1266 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1267 // If no classes have fields, just decompose RD itself. (This will work
1268 // if and only if zero bindings were provided.)
1269 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1272 CXXBasePath *BestPath = nullptr;
1273 for (auto &P : Paths) {
1276 else if (!S.Context.hasSameType(P.back().Base->getType(),
1277 BestPath->back().Base->getType())) {
1279 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1280 << false << RD << BestPath->back().Base->getType()
1281 << P.back().Base->getType();
1282 return DeclAccessPair();
1283 } else if (P.Access < BestPath->Access) {
1288 // ... unambiguous ...
1289 QualType BaseType = BestPath->back().Base->getType();
1290 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1291 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1292 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1293 return DeclAccessPair();
1296 // ... [accessible, implied by other rules] base class of E.
1297 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1298 *BestPath, diag::err_decomp_decl_inaccessible_base);
1299 AS = BestPath->Access;
1301 ClassWithFields = BaseType->getAsCXXRecordDecl();
1302 S.BuildBasePathArray(Paths, BasePath);
1305 // The above search did not check whether the selected class itself has base
1306 // classes with fields, so check that now.
1308 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1309 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1310 << (ClassWithFields == RD) << RD << ClassWithFields
1311 << Paths.front().back().Base->getType();
1312 return DeclAccessPair();
1315 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1318 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1319 ValueDecl *Src, QualType DecompType,
1320 const CXXRecordDecl *OrigRD) {
1321 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1322 diag::err_incomplete_type))
1325 CXXCastPath BasePath;
1326 DeclAccessPair BasePair =
1327 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1328 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1331 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1332 DecompType.getQualifiers());
1334 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1335 unsigned NumFields =
1336 std::count_if(RD->field_begin(), RD->field_end(),
1337 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1338 assert(Bindings.size() != NumFields);
1339 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1340 << DecompType << (unsigned)Bindings.size() << NumFields
1341 << (NumFields < Bindings.size());
1345 // all of E's non-static data members shall be [...] well-formed
1346 // when named as e.name in the context of the structured binding,
1347 // E shall not have an anonymous union member, ...
1349 for (auto *FD : RD->fields()) {
1350 if (FD->isUnnamedBitfield())
1353 if (FD->isAnonymousStructOrUnion()) {
1354 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1355 << DecompType << FD->getType()->isUnionType();
1356 S.Diag(FD->getLocation(), diag::note_declared_at);
1360 // We have a real field to bind.
1361 if (I >= Bindings.size())
1362 return DiagnoseBadNumberOfBindings();
1363 auto *B = Bindings[I++];
1364 SourceLocation Loc = B->getLocation();
1366 // The field must be accessible in the context of the structured binding.
1367 // We already checked that the base class is accessible.
1368 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1370 S.CheckStructuredBindingMemberAccess(
1371 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1372 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1373 BasePair.getAccess(), FD->getAccess())));
1375 // Initialize the binding to Src.FD.
1376 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1379 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1380 VK_LValue, &BasePath);
1383 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1385 DeclAccessPair::make(FD, FD->getAccess()),
1386 DeclarationNameInfo(FD->getDeclName(), Loc));
1390 // If the type of the member is T, the referenced type is cv T, where cv is
1391 // the cv-qualification of the decomposition expression.
1393 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1394 // 'const' to the type of the field.
1395 Qualifiers Q = DecompType.getQualifiers();
1396 if (FD->isMutable())
1398 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1401 if (I != Bindings.size())
1402 return DiagnoseBadNumberOfBindings();
1407 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1408 QualType DecompType = DD->getType();
1410 // If the type of the decomposition is dependent, then so is the type of
1412 if (DecompType->isDependentType()) {
1413 for (auto *B : DD->bindings())
1414 B->setType(Context.DependentTy);
1418 DecompType = DecompType.getNonReferenceType();
1419 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1421 // C++1z [dcl.decomp]/2:
1422 // If E is an array type [...]
1423 // As an extension, we also support decomposition of built-in complex and
1425 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1426 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1427 DD->setInvalidDecl();
1430 if (auto *VT = DecompType->getAs<VectorType>()) {
1431 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1432 DD->setInvalidDecl();
1435 if (auto *CT = DecompType->getAs<ComplexType>()) {
1436 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1437 DD->setInvalidDecl();
1441 // C++1z [dcl.decomp]/3:
1442 // if the expression std::tuple_size<E>::value is a well-formed integral
1443 // constant expression, [...]
1444 llvm::APSInt TupleSize(32);
1445 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1446 case IsTupleLike::Error:
1447 DD->setInvalidDecl();
1450 case IsTupleLike::TupleLike:
1451 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1452 DD->setInvalidDecl();
1455 case IsTupleLike::NotTupleLike:
1459 // C++1z [dcl.dcl]/8:
1460 // [E shall be of array or non-union class type]
1461 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1462 if (!RD || RD->isUnion()) {
1463 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1464 << DD << !RD << DecompType;
1465 DD->setInvalidDecl();
1469 // C++1z [dcl.decomp]/4:
1470 // all of E's non-static data members shall be [...] direct members of
1471 // E or of the same unambiguous public base class of E, ...
1472 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1473 DD->setInvalidDecl();
1476 /// Merge the exception specifications of two variable declarations.
1478 /// This is called when there's a redeclaration of a VarDecl. The function
1479 /// checks if the redeclaration might have an exception specification and
1480 /// validates compatibility and merges the specs if necessary.
1481 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1482 // Shortcut if exceptions are disabled.
1483 if (!getLangOpts().CXXExceptions)
1486 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1487 "Should only be called if types are otherwise the same.");
1489 QualType NewType = New->getType();
1490 QualType OldType = Old->getType();
1492 // We're only interested in pointers and references to functions, as well
1493 // as pointers to member functions.
1494 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1495 NewType = R->getPointeeType();
1496 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1497 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1498 NewType = P->getPointeeType();
1499 OldType = OldType->getAs<PointerType>()->getPointeeType();
1500 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1501 NewType = M->getPointeeType();
1502 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1505 if (!NewType->isFunctionProtoType())
1508 // There's lots of special cases for functions. For function pointers, system
1509 // libraries are hopefully not as broken so that we don't need these
1511 if (CheckEquivalentExceptionSpec(
1512 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1513 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1514 New->setInvalidDecl();
1518 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1519 /// function declaration are well-formed according to C++
1520 /// [dcl.fct.default].
1521 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1522 unsigned NumParams = FD->getNumParams();
1525 // Find first parameter with a default argument
1526 for (p = 0; p < NumParams; ++p) {
1527 ParmVarDecl *Param = FD->getParamDecl(p);
1528 if (Param->hasDefaultArg())
1532 // C++11 [dcl.fct.default]p4:
1533 // In a given function declaration, each parameter subsequent to a parameter
1534 // with a default argument shall have a default argument supplied in this or
1535 // a previous declaration or shall be a function parameter pack. A default
1536 // argument shall not be redefined by a later declaration (not even to the
1538 unsigned LastMissingDefaultArg = 0;
1539 for (; p < NumParams; ++p) {
1540 ParmVarDecl *Param = FD->getParamDecl(p);
1541 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1542 if (Param->isInvalidDecl())
1543 /* We already complained about this parameter. */;
1544 else if (Param->getIdentifier())
1545 Diag(Param->getLocation(),
1546 diag::err_param_default_argument_missing_name)
1547 << Param->getIdentifier();
1549 Diag(Param->getLocation(),
1550 diag::err_param_default_argument_missing);
1552 LastMissingDefaultArg = p;
1556 if (LastMissingDefaultArg > 0) {
1557 // Some default arguments were missing. Clear out all of the
1558 // default arguments up to (and including) the last missing
1559 // default argument, so that we leave the function parameters
1560 // in a semantically valid state.
1561 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1562 ParmVarDecl *Param = FD->getParamDecl(p);
1563 if (Param->hasDefaultArg()) {
1564 Param->setDefaultArg(nullptr);
1570 // CheckConstexprParameterTypes - Check whether a function's parameter types
1571 // are all literal types. If so, return true. If not, produce a suitable
1572 // diagnostic and return false.
1573 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1574 const FunctionDecl *FD) {
1575 unsigned ArgIndex = 0;
1576 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1577 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1578 e = FT->param_type_end();
1579 i != e; ++i, ++ArgIndex) {
1580 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1581 SourceLocation ParamLoc = PD->getLocation();
1582 if (!(*i)->isDependentType() &&
1583 SemaRef.RequireLiteralType(
1584 ParamLoc, *i, diag::err_constexpr_non_literal_param, ArgIndex + 1,
1585 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1592 /// Get diagnostic %select index for tag kind for
1593 /// record diagnostic message.
1594 /// WARNING: Indexes apply to particular diagnostics only!
1596 /// \returns diagnostic %select index.
1597 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1599 case TTK_Struct: return 0;
1600 case TTK_Interface: return 1;
1601 case TTK_Class: return 2;
1602 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1606 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1607 // the requirements of a constexpr function definition or a constexpr
1608 // constructor definition. If so, return true. If not, produce appropriate
1609 // diagnostics and return false.
1611 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1612 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1613 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1614 if (MD && MD->isInstance()) {
1615 // C++11 [dcl.constexpr]p4:
1616 // The definition of a constexpr constructor shall satisfy the following
1618 // - the class shall not have any virtual base classes;
1620 // FIXME: This only applies to constructors, not arbitrary member
1622 const CXXRecordDecl *RD = MD->getParent();
1623 if (RD->getNumVBases()) {
1624 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1625 << isa<CXXConstructorDecl>(NewFD)
1626 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1627 for (const auto &I : RD->vbases())
1628 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1629 << I.getSourceRange();
1634 if (!isa<CXXConstructorDecl>(NewFD)) {
1635 // C++11 [dcl.constexpr]p3:
1636 // The definition of a constexpr function shall satisfy the following
1638 // - it shall not be virtual; (removed in C++20)
1639 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1640 if (Method && Method->isVirtual()) {
1641 if (getLangOpts().CPlusPlus2a) {
1642 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1644 Method = Method->getCanonicalDecl();
1645 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1647 // If it's not obvious why this function is virtual, find an overridden
1648 // function which uses the 'virtual' keyword.
1649 const CXXMethodDecl *WrittenVirtual = Method;
1650 while (!WrittenVirtual->isVirtualAsWritten())
1651 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1652 if (WrittenVirtual != Method)
1653 Diag(WrittenVirtual->getLocation(),
1654 diag::note_overridden_virtual_function);
1659 // - its return type shall be a literal type;
1660 QualType RT = NewFD->getReturnType();
1661 if (!RT->isDependentType() &&
1662 RequireLiteralType(NewFD->getLocation(), RT,
1663 diag::err_constexpr_non_literal_return,
1664 NewFD->isConsteval()))
1668 // - each of its parameter types shall be a literal type;
1669 if (!CheckConstexprParameterTypes(*this, NewFD))
1675 /// Check the given declaration statement is legal within a constexpr function
1676 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1678 /// \return true if the body is OK (maybe only as an extension), false if we
1679 /// have diagnosed a problem.
1680 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1681 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1682 // C++11 [dcl.constexpr]p3 and p4:
1683 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1685 for (const auto *DclIt : DS->decls()) {
1686 switch (DclIt->getKind()) {
1687 case Decl::StaticAssert:
1689 case Decl::UsingShadow:
1690 case Decl::UsingDirective:
1691 case Decl::UnresolvedUsingTypename:
1692 case Decl::UnresolvedUsingValue:
1693 // - static_assert-declarations
1694 // - using-declarations,
1695 // - using-directives,
1699 case Decl::TypeAlias: {
1700 // - typedef declarations and alias-declarations that do not define
1701 // classes or enumerations,
1702 const auto *TN = cast<TypedefNameDecl>(DclIt);
1703 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1704 // Don't allow variably-modified types in constexpr functions.
1705 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1706 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1707 << TL.getSourceRange() << TL.getType()
1708 << isa<CXXConstructorDecl>(Dcl);
1715 case Decl::CXXRecord:
1716 // C++1y allows types to be defined, not just declared.
1717 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1718 SemaRef.Diag(DS->getBeginLoc(),
1719 SemaRef.getLangOpts().CPlusPlus14
1720 ? diag::warn_cxx11_compat_constexpr_type_definition
1721 : diag::ext_constexpr_type_definition)
1722 << isa<CXXConstructorDecl>(Dcl);
1725 case Decl::EnumConstant:
1726 case Decl::IndirectField:
1728 // These can only appear with other declarations which are banned in
1729 // C++11 and permitted in C++1y, so ignore them.
1733 case Decl::Decomposition: {
1734 // C++1y [dcl.constexpr]p3 allows anything except:
1735 // a definition of a variable of non-literal type or of static or
1736 // thread storage duration or for which no initialization is performed.
1737 const auto *VD = cast<VarDecl>(DclIt);
1738 if (VD->isThisDeclarationADefinition()) {
1739 if (VD->isStaticLocal()) {
1740 SemaRef.Diag(VD->getLocation(),
1741 diag::err_constexpr_local_var_static)
1742 << isa<CXXConstructorDecl>(Dcl)
1743 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1746 if (!VD->getType()->isDependentType() &&
1747 SemaRef.RequireLiteralType(
1748 VD->getLocation(), VD->getType(),
1749 diag::err_constexpr_local_var_non_literal_type,
1750 isa<CXXConstructorDecl>(Dcl)))
1752 if (!VD->getType()->isDependentType() &&
1753 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1754 SemaRef.Diag(VD->getLocation(),
1755 diag::err_constexpr_local_var_no_init)
1756 << isa<CXXConstructorDecl>(Dcl);
1760 SemaRef.Diag(VD->getLocation(),
1761 SemaRef.getLangOpts().CPlusPlus14
1762 ? diag::warn_cxx11_compat_constexpr_local_var
1763 : diag::ext_constexpr_local_var)
1764 << isa<CXXConstructorDecl>(Dcl);
1768 case Decl::NamespaceAlias:
1769 case Decl::Function:
1770 // These are disallowed in C++11 and permitted in C++1y. Allow them
1771 // everywhere as an extension.
1772 if (!Cxx1yLoc.isValid())
1773 Cxx1yLoc = DS->getBeginLoc();
1777 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1778 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1786 /// Check that the given field is initialized within a constexpr constructor.
1788 /// \param Dcl The constexpr constructor being checked.
1789 /// \param Field The field being checked. This may be a member of an anonymous
1790 /// struct or union nested within the class being checked.
1791 /// \param Inits All declarations, including anonymous struct/union members and
1792 /// indirect members, for which any initialization was provided.
1793 /// \param Diagnosed Set to true if an error is produced.
1794 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1795 const FunctionDecl *Dcl,
1797 llvm::SmallSet<Decl*, 16> &Inits,
1799 if (Field->isInvalidDecl())
1802 if (Field->isUnnamedBitfield())
1805 // Anonymous unions with no variant members and empty anonymous structs do not
1806 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1807 // indirect fields don't need initializing.
1808 if (Field->isAnonymousStructOrUnion() &&
1809 (Field->getType()->isUnionType()
1810 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1811 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1814 if (!Inits.count(Field)) {
1816 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1819 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1820 } else if (Field->isAnonymousStructOrUnion()) {
1821 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1822 for (auto *I : RD->fields())
1823 // If an anonymous union contains an anonymous struct of which any member
1824 // is initialized, all members must be initialized.
1825 if (!RD->isUnion() || Inits.count(I))
1826 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1830 /// Check the provided statement is allowed in a constexpr function
1833 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1834 SmallVectorImpl<SourceLocation> &ReturnStmts,
1835 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc) {
1836 // - its function-body shall be [...] a compound-statement that contains only
1837 switch (S->getStmtClass()) {
1838 case Stmt::NullStmtClass:
1839 // - null statements,
1842 case Stmt::DeclStmtClass:
1843 // - static_assert-declarations
1844 // - using-declarations,
1845 // - using-directives,
1846 // - typedef declarations and alias-declarations that do not define
1847 // classes or enumerations,
1848 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1852 case Stmt::ReturnStmtClass:
1853 // - and exactly one return statement;
1854 if (isa<CXXConstructorDecl>(Dcl)) {
1855 // C++1y allows return statements in constexpr constructors.
1856 if (!Cxx1yLoc.isValid())
1857 Cxx1yLoc = S->getBeginLoc();
1861 ReturnStmts.push_back(S->getBeginLoc());
1864 case Stmt::CompoundStmtClass: {
1865 // C++1y allows compound-statements.
1866 if (!Cxx1yLoc.isValid())
1867 Cxx1yLoc = S->getBeginLoc();
1869 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1870 for (auto *BodyIt : CompStmt->body()) {
1871 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1872 Cxx1yLoc, Cxx2aLoc))
1878 case Stmt::AttributedStmtClass:
1879 if (!Cxx1yLoc.isValid())
1880 Cxx1yLoc = S->getBeginLoc();
1883 case Stmt::IfStmtClass: {
1884 // C++1y allows if-statements.
1885 if (!Cxx1yLoc.isValid())
1886 Cxx1yLoc = S->getBeginLoc();
1888 IfStmt *If = cast<IfStmt>(S);
1889 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1890 Cxx1yLoc, Cxx2aLoc))
1892 if (If->getElse() &&
1893 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1894 Cxx1yLoc, Cxx2aLoc))
1899 case Stmt::WhileStmtClass:
1900 case Stmt::DoStmtClass:
1901 case Stmt::ForStmtClass:
1902 case Stmt::CXXForRangeStmtClass:
1903 case Stmt::ContinueStmtClass:
1904 // C++1y allows all of these. We don't allow them as extensions in C++11,
1905 // because they don't make sense without variable mutation.
1906 if (!SemaRef.getLangOpts().CPlusPlus14)
1908 if (!Cxx1yLoc.isValid())
1909 Cxx1yLoc = S->getBeginLoc();
1910 for (Stmt *SubStmt : S->children())
1912 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1913 Cxx1yLoc, Cxx2aLoc))
1917 case Stmt::SwitchStmtClass:
1918 case Stmt::CaseStmtClass:
1919 case Stmt::DefaultStmtClass:
1920 case Stmt::BreakStmtClass:
1921 // C++1y allows switch-statements, and since they don't need variable
1922 // mutation, we can reasonably allow them in C++11 as an extension.
1923 if (!Cxx1yLoc.isValid())
1924 Cxx1yLoc = S->getBeginLoc();
1925 for (Stmt *SubStmt : S->children())
1927 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1928 Cxx1yLoc, Cxx2aLoc))
1932 case Stmt::CXXTryStmtClass:
1933 if (Cxx2aLoc.isInvalid())
1934 Cxx2aLoc = S->getBeginLoc();
1935 for (Stmt *SubStmt : S->children()) {
1937 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1938 Cxx1yLoc, Cxx2aLoc))
1943 case Stmt::CXXCatchStmtClass:
1944 // Do not bother checking the language mode (already covered by the
1945 // try block check).
1946 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
1947 cast<CXXCatchStmt>(S)->getHandlerBlock(),
1948 ReturnStmts, Cxx1yLoc, Cxx2aLoc))
1956 // C++1y allows expression-statements.
1957 if (!Cxx1yLoc.isValid())
1958 Cxx1yLoc = S->getBeginLoc();
1962 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1963 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1967 /// Check the body for the given constexpr function declaration only contains
1968 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1970 /// \return true if the body is OK, false if we have diagnosed a problem.
1971 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1972 SmallVector<SourceLocation, 4> ReturnStmts;
1974 if (isa<CXXTryStmt>(Body)) {
1975 // C++11 [dcl.constexpr]p3:
1976 // The definition of a constexpr function shall satisfy the following
1977 // constraints: [...]
1978 // - its function-body shall be = delete, = default, or a
1979 // compound-statement
1981 // C++11 [dcl.constexpr]p4:
1982 // In the definition of a constexpr constructor, [...]
1983 // - its function-body shall not be a function-try-block;
1985 // This restriction is lifted in C++2a, as long as inner statements also
1986 // apply the general constexpr rules.
1987 Diag(Body->getBeginLoc(),
1988 !getLangOpts().CPlusPlus2a
1989 ? diag::ext_constexpr_function_try_block_cxx2a
1990 : diag::warn_cxx17_compat_constexpr_function_try_block)
1991 << isa<CXXConstructorDecl>(Dcl);
1994 // - its function-body shall be [...] a compound-statement that contains only
1995 // [... list of cases ...]
1997 // Note that walking the children here is enough to properly check for
1998 // CompoundStmt and CXXTryStmt body.
1999 SourceLocation Cxx1yLoc, Cxx2aLoc;
2000 for (Stmt *SubStmt : Body->children()) {
2002 !CheckConstexprFunctionStmt(*this, Dcl, SubStmt, ReturnStmts,
2003 Cxx1yLoc, Cxx2aLoc))
2007 if (Cxx2aLoc.isValid())
2009 getLangOpts().CPlusPlus2a
2010 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2011 : diag::ext_constexpr_body_invalid_stmt_cxx2a)
2012 << isa<CXXConstructorDecl>(Dcl);
2013 if (Cxx1yLoc.isValid())
2015 getLangOpts().CPlusPlus14
2016 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2017 : diag::ext_constexpr_body_invalid_stmt)
2018 << isa<CXXConstructorDecl>(Dcl);
2020 if (const CXXConstructorDecl *Constructor
2021 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2022 const CXXRecordDecl *RD = Constructor->getParent();
2024 // - every non-variant non-static data member and base class sub-object
2025 // shall be initialized;
2027 // - if the class is a union having variant members, exactly one of them
2028 // shall be initialized;
2029 if (RD->isUnion()) {
2030 if (Constructor->getNumCtorInitializers() == 0 &&
2031 RD->hasVariantMembers()) {
2032 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
2035 } else if (!Constructor->isDependentContext() &&
2036 !Constructor->isDelegatingConstructor()) {
2037 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2039 // Skip detailed checking if we have enough initializers, and we would
2040 // allow at most one initializer per member.
2041 bool AnyAnonStructUnionMembers = false;
2042 unsigned Fields = 0;
2043 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2044 E = RD->field_end(); I != E; ++I, ++Fields) {
2045 if (I->isAnonymousStructOrUnion()) {
2046 AnyAnonStructUnionMembers = true;
2051 // - if the class is a union-like class, but is not a union, for each of
2052 // its anonymous union members having variant members, exactly one of
2053 // them shall be initialized;
2054 if (AnyAnonStructUnionMembers ||
2055 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2056 // Check initialization of non-static data members. Base classes are
2057 // always initialized so do not need to be checked. Dependent bases
2058 // might not have initializers in the member initializer list.
2059 llvm::SmallSet<Decl*, 16> Inits;
2060 for (const auto *I: Constructor->inits()) {
2061 if (FieldDecl *FD = I->getMember())
2063 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2064 Inits.insert(ID->chain_begin(), ID->chain_end());
2067 bool Diagnosed = false;
2068 for (auto *I : RD->fields())
2069 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2075 if (ReturnStmts.empty()) {
2076 // C++1y doesn't require constexpr functions to contain a 'return'
2077 // statement. We still do, unless the return type might be void, because
2078 // otherwise if there's no return statement, the function cannot
2079 // be used in a core constant expression.
2080 bool OK = getLangOpts().CPlusPlus14 &&
2081 (Dcl->getReturnType()->isVoidType() ||
2082 Dcl->getReturnType()->isDependentType());
2083 Diag(Dcl->getLocation(),
2084 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2085 : diag::err_constexpr_body_no_return)
2086 << Dcl->isConsteval();
2089 } else if (ReturnStmts.size() > 1) {
2090 Diag(ReturnStmts.back(),
2091 getLangOpts().CPlusPlus14
2092 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2093 : diag::ext_constexpr_body_multiple_return);
2094 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2095 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2099 // C++11 [dcl.constexpr]p5:
2100 // if no function argument values exist such that the function invocation
2101 // substitution would produce a constant expression, the program is
2102 // ill-formed; no diagnostic required.
2103 // C++11 [dcl.constexpr]p3:
2104 // - every constructor call and implicit conversion used in initializing the
2105 // return value shall be one of those allowed in a constant expression.
2106 // C++11 [dcl.constexpr]p4:
2107 // - every constructor involved in initializing non-static data members and
2108 // base class sub-objects shall be a constexpr constructor.
2109 SmallVector<PartialDiagnosticAt, 8> Diags;
2110 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2111 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2112 << isa<CXXConstructorDecl>(Dcl);
2113 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2114 Diag(Diags[I].first, Diags[I].second);
2115 // Don't return false here: we allow this for compatibility in
2122 /// Get the class that is directly named by the current context. This is the
2123 /// class for which an unqualified-id in this scope could name a constructor
2126 /// If the scope specifier denotes a class, this will be that class.
2127 /// If the scope specifier is empty, this will be the class whose
2128 /// member-specification we are currently within. Otherwise, there
2129 /// is no such class.
2130 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2131 assert(getLangOpts().CPlusPlus && "No class names in C!");
2133 if (SS && SS->isInvalid())
2136 if (SS && SS->isNotEmpty()) {
2137 DeclContext *DC = computeDeclContext(*SS, true);
2138 return dyn_cast_or_null<CXXRecordDecl>(DC);
2141 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2144 /// isCurrentClassName - Determine whether the identifier II is the
2145 /// name of the class type currently being defined. In the case of
2146 /// nested classes, this will only return true if II is the name of
2147 /// the innermost class.
2148 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2149 const CXXScopeSpec *SS) {
2150 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2151 return CurDecl && &II == CurDecl->getIdentifier();
2154 /// Determine whether the identifier II is a typo for the name of
2155 /// the class type currently being defined. If so, update it to the identifier
2156 /// that should have been used.
2157 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2158 assert(getLangOpts().CPlusPlus && "No class names in C!");
2160 if (!getLangOpts().SpellChecking)
2163 CXXRecordDecl *CurDecl;
2164 if (SS && SS->isSet() && !SS->isInvalid()) {
2165 DeclContext *DC = computeDeclContext(*SS, true);
2166 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2168 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2170 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2171 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2172 < II->getLength()) {
2173 II = CurDecl->getIdentifier();
2180 /// Determine whether the given class is a base class of the given
2181 /// class, including looking at dependent bases.
2182 static bool findCircularInheritance(const CXXRecordDecl *Class,
2183 const CXXRecordDecl *Current) {
2184 SmallVector<const CXXRecordDecl*, 8> Queue;
2186 Class = Class->getCanonicalDecl();
2188 for (const auto &I : Current->bases()) {
2189 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2193 Base = Base->getDefinition();
2197 if (Base->getCanonicalDecl() == Class)
2200 Queue.push_back(Base);
2206 Current = Queue.pop_back_val();
2212 /// Check the validity of a C++ base class specifier.
2214 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2215 /// and returns NULL otherwise.
2217 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2218 SourceRange SpecifierRange,
2219 bool Virtual, AccessSpecifier Access,
2220 TypeSourceInfo *TInfo,
2221 SourceLocation EllipsisLoc) {
2222 QualType BaseType = TInfo->getType();
2224 // C++ [class.union]p1:
2225 // A union shall not have base classes.
2226 if (Class->isUnion()) {
2227 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2232 if (EllipsisLoc.isValid() &&
2233 !TInfo->getType()->containsUnexpandedParameterPack()) {
2234 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2235 << TInfo->getTypeLoc().getSourceRange();
2236 EllipsisLoc = SourceLocation();
2239 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2241 if (BaseType->isDependentType()) {
2242 // Make sure that we don't have circular inheritance among our dependent
2243 // bases. For non-dependent bases, the check for completeness below handles
2245 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2246 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2247 ((BaseDecl = BaseDecl->getDefinition()) &&
2248 findCircularInheritance(Class, BaseDecl))) {
2249 Diag(BaseLoc, diag::err_circular_inheritance)
2250 << BaseType << Context.getTypeDeclType(Class);
2252 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2253 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2260 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2261 Class->getTagKind() == TTK_Class,
2262 Access, TInfo, EllipsisLoc);
2265 // Base specifiers must be record types.
2266 if (!BaseType->isRecordType()) {
2267 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2271 // C++ [class.union]p1:
2272 // A union shall not be used as a base class.
2273 if (BaseType->isUnionType()) {
2274 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2278 // For the MS ABI, propagate DLL attributes to base class templates.
2279 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2280 if (Attr *ClassAttr = getDLLAttr(Class)) {
2281 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2282 BaseType->getAsCXXRecordDecl())) {
2283 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2289 // C++ [class.derived]p2:
2290 // The class-name in a base-specifier shall not be an incompletely
2292 if (RequireCompleteType(BaseLoc, BaseType,
2293 diag::err_incomplete_base_class, SpecifierRange)) {
2294 Class->setInvalidDecl();
2298 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2299 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2300 assert(BaseDecl && "Record type has no declaration");
2301 BaseDecl = BaseDecl->getDefinition();
2302 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2303 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2304 assert(CXXBaseDecl && "Base type is not a C++ type");
2306 // Microsoft docs say:
2307 // "If a base-class has a code_seg attribute, derived classes must have the
2309 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2310 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2311 if ((DerivedCSA || BaseCSA) &&
2312 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2313 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2314 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2319 // A class which contains a flexible array member is not suitable for use as a
2321 // - If the layout determines that a base comes before another base,
2322 // the flexible array member would index into the subsequent base.
2323 // - If the layout determines that base comes before the derived class,
2324 // the flexible array member would index into the derived class.
2325 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2326 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2327 << CXXBaseDecl->getDeclName();
2332 // If a class is marked final and it appears as a base-type-specifier in
2333 // base-clause, the program is ill-formed.
2334 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2335 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2336 << CXXBaseDecl->getDeclName()
2337 << FA->isSpelledAsSealed();
2338 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2339 << CXXBaseDecl->getDeclName() << FA->getRange();
2343 if (BaseDecl->isInvalidDecl())
2344 Class->setInvalidDecl();
2346 // Create the base specifier.
2347 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2348 Class->getTagKind() == TTK_Class,
2349 Access, TInfo, EllipsisLoc);
2352 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2353 /// one entry in the base class list of a class specifier, for
2355 /// class foo : public bar, virtual private baz {
2356 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2358 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2359 ParsedAttributes &Attributes,
2360 bool Virtual, AccessSpecifier Access,
2361 ParsedType basetype, SourceLocation BaseLoc,
2362 SourceLocation EllipsisLoc) {
2366 AdjustDeclIfTemplate(classdecl);
2367 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2371 // We haven't yet attached the base specifiers.
2372 Class->setIsParsingBaseSpecifiers();
2374 // We do not support any C++11 attributes on base-specifiers yet.
2375 // Diagnose any attributes we see.
2376 for (const ParsedAttr &AL : Attributes) {
2377 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2379 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2380 ? (unsigned)diag::warn_unknown_attribute_ignored
2381 : (unsigned)diag::err_base_specifier_attribute)
2385 TypeSourceInfo *TInfo = nullptr;
2386 GetTypeFromParser(basetype, &TInfo);
2388 if (EllipsisLoc.isInvalid() &&
2389 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2393 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2394 Virtual, Access, TInfo,
2398 Class->setInvalidDecl();
2403 /// Use small set to collect indirect bases. As this is only used
2404 /// locally, there's no need to abstract the small size parameter.
2405 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2407 /// Recursively add the bases of Type. Don't add Type itself.
2409 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2410 const QualType &Type)
2412 // Even though the incoming type is a base, it might not be
2413 // a class -- it could be a template parm, for instance.
2414 if (auto Rec = Type->getAs<RecordType>()) {
2415 auto Decl = Rec->getAsCXXRecordDecl();
2417 // Iterate over its bases.
2418 for (const auto &BaseSpec : Decl->bases()) {
2419 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2420 .getUnqualifiedType();
2421 if (Set.insert(Base).second)
2422 // If we've not already seen it, recurse.
2423 NoteIndirectBases(Context, Set, Base);
2428 /// Performs the actual work of attaching the given base class
2429 /// specifiers to a C++ class.
2430 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2431 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2435 // Used to keep track of which base types we have already seen, so
2436 // that we can properly diagnose redundant direct base types. Note
2437 // that the key is always the unqualified canonical type of the base
2439 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2441 // Used to track indirect bases so we can see if a direct base is
2443 IndirectBaseSet IndirectBaseTypes;
2445 // Copy non-redundant base specifiers into permanent storage.
2446 unsigned NumGoodBases = 0;
2447 bool Invalid = false;
2448 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2449 QualType NewBaseType
2450 = Context.getCanonicalType(Bases[idx]->getType());
2451 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2453 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2455 // C++ [class.mi]p3:
2456 // A class shall not be specified as a direct base class of a
2457 // derived class more than once.
2458 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2459 << KnownBase->getType() << Bases[idx]->getSourceRange();
2461 // Delete the duplicate base class specifier; we're going to
2462 // overwrite its pointer later.
2463 Context.Deallocate(Bases[idx]);
2467 // Okay, add this new base class.
2468 KnownBase = Bases[idx];
2469 Bases[NumGoodBases++] = Bases[idx];
2471 // Note this base's direct & indirect bases, if there could be ambiguity.
2472 if (Bases.size() > 1)
2473 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2475 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2476 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2477 if (Class->isInterface() &&
2478 (!RD->isInterfaceLike() ||
2479 KnownBase->getAccessSpecifier() != AS_public)) {
2480 // The Microsoft extension __interface does not permit bases that
2481 // are not themselves public interfaces.
2482 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2483 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2484 << RD->getSourceRange();
2487 if (RD->hasAttr<WeakAttr>())
2488 Class->addAttr(WeakAttr::CreateImplicit(Context));
2493 // Attach the remaining base class specifiers to the derived class.
2494 Class->setBases(Bases.data(), NumGoodBases);
2496 // Check that the only base classes that are duplicate are virtual.
2497 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2498 // Check whether this direct base is inaccessible due to ambiguity.
2499 QualType BaseType = Bases[idx]->getType();
2501 // Skip all dependent types in templates being used as base specifiers.
2502 // Checks below assume that the base specifier is a CXXRecord.
2503 if (BaseType->isDependentType())
2506 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2507 .getUnqualifiedType();
2509 if (IndirectBaseTypes.count(CanonicalBase)) {
2510 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2511 /*DetectVirtual=*/true);
2513 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2517 if (Paths.isAmbiguous(CanonicalBase))
2518 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2519 << BaseType << getAmbiguousPathsDisplayString(Paths)
2520 << Bases[idx]->getSourceRange();
2522 assert(Bases[idx]->isVirtual());
2525 // Delete the base class specifier, since its data has been copied
2526 // into the CXXRecordDecl.
2527 Context.Deallocate(Bases[idx]);
2533 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2534 /// class, after checking whether there are any duplicate base
2536 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2537 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2538 if (!ClassDecl || Bases.empty())
2541 AdjustDeclIfTemplate(ClassDecl);
2542 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2545 /// Determine whether the type \p Derived is a C++ class that is
2546 /// derived from the type \p Base.
2547 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2548 if (!getLangOpts().CPlusPlus)
2551 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2555 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2559 // If either the base or the derived type is invalid, don't try to
2560 // check whether one is derived from the other.
2561 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2564 // FIXME: In a modules build, do we need the entire path to be visible for us
2565 // to be able to use the inheritance relationship?
2566 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2569 return DerivedRD->isDerivedFrom(BaseRD);
2572 /// Determine whether the type \p Derived is a C++ class that is
2573 /// derived from the type \p Base.
2574 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2575 CXXBasePaths &Paths) {
2576 if (!getLangOpts().CPlusPlus)
2579 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2583 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2587 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2590 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2593 static void BuildBasePathArray(const CXXBasePath &Path,
2594 CXXCastPath &BasePathArray) {
2595 // We first go backward and check if we have a virtual base.
2596 // FIXME: It would be better if CXXBasePath had the base specifier for
2597 // the nearest virtual base.
2599 for (unsigned I = Path.size(); I != 0; --I) {
2600 if (Path[I - 1].Base->isVirtual()) {
2606 // Now add all bases.
2607 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2608 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2612 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2613 CXXCastPath &BasePathArray) {
2614 assert(BasePathArray.empty() && "Base path array must be empty!");
2615 assert(Paths.isRecordingPaths() && "Must record paths!");
2616 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2618 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2619 /// conversion (where Derived and Base are class types) is
2620 /// well-formed, meaning that the conversion is unambiguous (and
2621 /// that all of the base classes are accessible). Returns true
2622 /// and emits a diagnostic if the code is ill-formed, returns false
2623 /// otherwise. Loc is the location where this routine should point to
2624 /// if there is an error, and Range is the source range to highlight
2625 /// if there is an error.
2627 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2628 /// diagnostic for the respective type of error will be suppressed, but the
2629 /// check for ill-formed code will still be performed.
2631 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2632 unsigned InaccessibleBaseID,
2633 unsigned AmbigiousBaseConvID,
2634 SourceLocation Loc, SourceRange Range,
2635 DeclarationName Name,
2636 CXXCastPath *BasePath,
2637 bool IgnoreAccess) {
2638 // First, determine whether the path from Derived to Base is
2639 // ambiguous. This is slightly more expensive than checking whether
2640 // the Derived to Base conversion exists, because here we need to
2641 // explore multiple paths to determine if there is an ambiguity.
2642 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2643 /*DetectVirtual=*/false);
2644 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2645 if (!DerivationOkay)
2648 const CXXBasePath *Path = nullptr;
2649 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2650 Path = &Paths.front();
2652 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2653 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2654 // user to access such bases.
2655 if (!Path && getLangOpts().MSVCCompat) {
2656 for (const CXXBasePath &PossiblePath : Paths) {
2657 if (PossiblePath.size() == 1) {
2658 Path = &PossiblePath;
2659 if (AmbigiousBaseConvID)
2660 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2661 << Base << Derived << Range;
2668 if (!IgnoreAccess) {
2669 // Check that the base class can be accessed.
2671 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2672 case AR_inaccessible:
2681 // Build a base path if necessary.
2683 ::BuildBasePathArray(*Path, *BasePath);
2687 if (AmbigiousBaseConvID) {
2688 // We know that the derived-to-base conversion is ambiguous, and
2689 // we're going to produce a diagnostic. Perform the derived-to-base
2690 // search just one more time to compute all of the possible paths so
2691 // that we can print them out. This is more expensive than any of
2692 // the previous derived-to-base checks we've done, but at this point
2693 // performance isn't as much of an issue.
2695 Paths.setRecordingPaths(true);
2696 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2697 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2700 // Build up a textual representation of the ambiguous paths, e.g.,
2701 // D -> B -> A, that will be used to illustrate the ambiguous
2702 // conversions in the diagnostic. We only print one of the paths
2703 // to each base class subobject.
2704 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2706 Diag(Loc, AmbigiousBaseConvID)
2707 << Derived << Base << PathDisplayStr << Range << Name;
2713 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2714 SourceLocation Loc, SourceRange Range,
2715 CXXCastPath *BasePath,
2716 bool IgnoreAccess) {
2717 return CheckDerivedToBaseConversion(
2718 Derived, Base, diag::err_upcast_to_inaccessible_base,
2719 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2720 BasePath, IgnoreAccess);
2724 /// Builds a string representing ambiguous paths from a
2725 /// specific derived class to different subobjects of the same base
2728 /// This function builds a string that can be used in error messages
2729 /// to show the different paths that one can take through the
2730 /// inheritance hierarchy to go from the derived class to different
2731 /// subobjects of a base class. The result looks something like this:
2733 /// struct D -> struct B -> struct A
2734 /// struct D -> struct C -> struct A
2736 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2737 std::string PathDisplayStr;
2738 std::set<unsigned> DisplayedPaths;
2739 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2740 Path != Paths.end(); ++Path) {
2741 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2742 // We haven't displayed a path to this particular base
2743 // class subobject yet.
2744 PathDisplayStr += "\n ";
2745 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2746 for (CXXBasePath::const_iterator Element = Path->begin();
2747 Element != Path->end(); ++Element)
2748 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2752 return PathDisplayStr;
2755 //===----------------------------------------------------------------------===//
2756 // C++ class member Handling
2757 //===----------------------------------------------------------------------===//
2759 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2760 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
2761 SourceLocation ColonLoc,
2762 const ParsedAttributesView &Attrs) {
2763 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2764 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2766 CurContext->addHiddenDecl(ASDecl);
2767 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2770 /// CheckOverrideControl - Check C++11 override control semantics.
2771 void Sema::CheckOverrideControl(NamedDecl *D) {
2772 if (D->isInvalidDecl())
2775 // We only care about "override" and "final" declarations.
2776 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2779 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2781 // We can't check dependent instance methods.
2782 if (MD && MD->isInstance() &&
2783 (MD->getParent()->hasAnyDependentBases() ||
2784 MD->getType()->isDependentType()))
2787 if (MD && !MD->isVirtual()) {
2788 // If we have a non-virtual method, check if if hides a virtual method.
2789 // (In that case, it's most likely the method has the wrong type.)
2790 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2791 FindHiddenVirtualMethods(MD, OverloadedMethods);
2793 if (!OverloadedMethods.empty()) {
2794 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2795 Diag(OA->getLocation(),
2796 diag::override_keyword_hides_virtual_member_function)
2797 << "override" << (OverloadedMethods.size() > 1);
2798 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2799 Diag(FA->getLocation(),
2800 diag::override_keyword_hides_virtual_member_function)
2801 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2802 << (OverloadedMethods.size() > 1);
2804 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2805 MD->setInvalidDecl();
2808 // Fall through into the general case diagnostic.
2809 // FIXME: We might want to attempt typo correction here.
2812 if (!MD || !MD->isVirtual()) {
2813 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2814 Diag(OA->getLocation(),
2815 diag::override_keyword_only_allowed_on_virtual_member_functions)
2816 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2817 D->dropAttr<OverrideAttr>();
2819 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2820 Diag(FA->getLocation(),
2821 diag::override_keyword_only_allowed_on_virtual_member_functions)
2822 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2823 << FixItHint::CreateRemoval(FA->getLocation());
2824 D->dropAttr<FinalAttr>();
2829 // C++11 [class.virtual]p5:
2830 // If a function is marked with the virt-specifier override and
2831 // does not override a member function of a base class, the program is
2833 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2834 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2835 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2836 << MD->getDeclName();
2839 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2840 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2842 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2843 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2846 SourceLocation Loc = MD->getLocation();
2847 SourceLocation SpellingLoc = Loc;
2848 if (getSourceManager().isMacroArgExpansion(Loc))
2849 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
2850 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2851 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2854 if (MD->size_overridden_methods() > 0) {
2855 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2856 ? diag::warn_destructor_marked_not_override_overriding
2857 : diag::warn_function_marked_not_override_overriding;
2858 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2859 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2860 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2864 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2865 /// function overrides a virtual member function marked 'final', according to
2866 /// C++11 [class.virtual]p4.
2867 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2868 const CXXMethodDecl *Old) {
2869 FinalAttr *FA = Old->getAttr<FinalAttr>();
2873 Diag(New->getLocation(), diag::err_final_function_overridden)
2874 << New->getDeclName()
2875 << FA->isSpelledAsSealed();
2876 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2880 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2881 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2882 // FIXME: Destruction of ObjC lifetime types has side-effects.
2883 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2884 return !RD->isCompleteDefinition() ||
2885 !RD->hasTrivialDefaultConstructor() ||
2886 !RD->hasTrivialDestructor();
2890 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
2891 ParsedAttributesView::const_iterator Itr =
2892 llvm::find_if(list, [](const ParsedAttr &AL) {
2893 return AL.isDeclspecPropertyAttribute();
2895 if (Itr != list.end())
2900 // Check if there is a field shadowing.
2901 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2902 DeclarationName FieldName,
2903 const CXXRecordDecl *RD,
2905 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2908 // To record a shadowed field in a base
2909 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2910 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2911 CXXBasePath &Path) {
2912 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2913 // Record an ambiguous path directly
2914 if (Bases.find(Base) != Bases.end())
2916 for (const auto Field : Base->lookup(FieldName)) {
2917 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2918 Field->getAccess() != AS_private) {
2919 assert(Field->getAccess() != AS_none);
2920 assert(Bases.find(Base) == Bases.end());
2921 Bases[Base] = Field;
2928 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2929 /*DetectVirtual=*/true);
2930 if (!RD->lookupInBases(FieldShadowed, Paths))
2933 for (const auto &P : Paths) {
2934 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2935 auto It = Bases.find(Base);
2936 // Skip duplicated bases
2937 if (It == Bases.end())
2939 auto BaseField = It->second;
2940 assert(BaseField->getAccess() != AS_private);
2942 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2943 Diag(Loc, diag::warn_shadow_field)
2944 << FieldName << RD << Base << DeclIsField;
2945 Diag(BaseField->getLocation(), diag::note_shadow_field);
2951 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2952 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2953 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2954 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2955 /// present (but parsing it has been deferred).
2957 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2958 MultiTemplateParamsArg TemplateParameterLists,
2959 Expr *BW, const VirtSpecifiers &VS,
2960 InClassInitStyle InitStyle) {
2961 const DeclSpec &DS = D.getDeclSpec();
2962 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2963 DeclarationName Name = NameInfo.getName();
2964 SourceLocation Loc = NameInfo.getLoc();
2966 // For anonymous bitfields, the location should point to the type.
2967 if (Loc.isInvalid())
2968 Loc = D.getBeginLoc();
2970 Expr *BitWidth = static_cast<Expr*>(BW);
2972 assert(isa<CXXRecordDecl>(CurContext));
2973 assert(!DS.isFriendSpecified());
2975 bool isFunc = D.isDeclarationOfFunction();
2976 const ParsedAttr *MSPropertyAttr =
2977 getMSPropertyAttr(D.getDeclSpec().getAttributes());
2979 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2980 // The Microsoft extension __interface only permits public member functions
2981 // and prohibits constructors, destructors, operators, non-public member
2982 // functions, static methods and data members.
2983 unsigned InvalidDecl;
2984 bool ShowDeclName = true;
2986 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2990 else if (AS != AS_public)
2992 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2994 else switch (Name.getNameKind()) {
2995 case DeclarationName::CXXConstructorName:
2997 ShowDeclName = false;
3000 case DeclarationName::CXXDestructorName:
3002 ShowDeclName = false;
3005 case DeclarationName::CXXOperatorName:
3006 case DeclarationName::CXXConversionFunctionName:
3017 Diag(Loc, diag::err_invalid_member_in_interface)
3018 << (InvalidDecl-1) << Name;
3020 Diag(Loc, diag::err_invalid_member_in_interface)
3021 << (InvalidDecl-1) << "";
3026 // C++ 9.2p6: A member shall not be declared to have automatic storage
3027 // duration (auto, register) or with the extern storage-class-specifier.
3028 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3029 // data members and cannot be applied to names declared const or static,
3030 // and cannot be applied to reference members.
3031 switch (DS.getStorageClassSpec()) {
3032 case DeclSpec::SCS_unspecified:
3033 case DeclSpec::SCS_typedef:
3034 case DeclSpec::SCS_static:
3036 case DeclSpec::SCS_mutable:
3038 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3040 // FIXME: It would be nicer if the keyword was ignored only for this
3041 // declarator. Otherwise we could get follow-up errors.
3042 D.getMutableDeclSpec().ClearStorageClassSpecs();
3046 Diag(DS.getStorageClassSpecLoc(),
3047 diag::err_storageclass_invalid_for_member);
3048 D.getMutableDeclSpec().ClearStorageClassSpecs();
3052 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3053 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3056 if (DS.hasConstexprSpecifier() && isInstField) {
3057 SemaDiagnosticBuilder B =
3058 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3059 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3060 if (InitStyle == ICIS_NoInit) {
3062 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3063 B << FixItHint::CreateRemoval(ConstexprLoc);
3065 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3066 D.getMutableDeclSpec().ClearConstexprSpec();
3067 const char *PrevSpec;
3069 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3070 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3072 assert(!Failed && "Making a constexpr member const shouldn't fail");
3076 const char *PrevSpec;
3078 if (D.getMutableDeclSpec().SetStorageClassSpec(
3079 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3080 Context.getPrintingPolicy())) {
3081 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3082 "This is the only DeclSpec that should fail to be applied");
3085 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3086 isInstField = false;
3093 CXXScopeSpec &SS = D.getCXXScopeSpec();
3095 // Data members must have identifiers for names.
3096 if (!Name.isIdentifier()) {
3097 Diag(Loc, diag::err_bad_variable_name)
3102 IdentifierInfo *II = Name.getAsIdentifierInfo();
3104 // Member field could not be with "template" keyword.
3105 // So TemplateParameterLists should be empty in this case.
3106 if (TemplateParameterLists.size()) {
3107 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3108 if (TemplateParams->size()) {
3109 // There is no such thing as a member field template.
3110 Diag(D.getIdentifierLoc(), diag::err_template_member)
3112 << SourceRange(TemplateParams->getTemplateLoc(),
3113 TemplateParams->getRAngleLoc());
3115 // There is an extraneous 'template<>' for this member.
3116 Diag(TemplateParams->getTemplateLoc(),
3117 diag::err_template_member_noparams)
3119 << SourceRange(TemplateParams->getTemplateLoc(),
3120 TemplateParams->getRAngleLoc());
3125 if (SS.isSet() && !SS.isInvalid()) {
3126 // The user provided a superfluous scope specifier inside a class
3132 if (DeclContext *DC = computeDeclContext(SS, false))
3133 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3134 D.getName().getKind() ==
3135 UnqualifiedIdKind::IK_TemplateId);
3137 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3138 << Name << SS.getRange();
3143 if (MSPropertyAttr) {
3144 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3145 BitWidth, InitStyle, AS, *MSPropertyAttr);
3148 isInstField = false;
3150 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3151 BitWidth, InitStyle, AS);
3156 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3158 Member = HandleDeclarator(S, D, TemplateParameterLists);
3162 // Non-instance-fields can't have a bitfield.
3164 if (Member->isInvalidDecl()) {
3165 // don't emit another diagnostic.
3166 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3167 // C++ 9.6p3: A bit-field shall not be a static member.
3168 // "static member 'A' cannot be a bit-field"
3169 Diag(Loc, diag::err_static_not_bitfield)
3170 << Name << BitWidth->getSourceRange();
3171 } else if (isa<TypedefDecl>(Member)) {
3172 // "typedef member 'x' cannot be a bit-field"
3173 Diag(Loc, diag::err_typedef_not_bitfield)
3174 << Name << BitWidth->getSourceRange();
3176 // A function typedef ("typedef int f(); f a;").
3177 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3178 Diag(Loc, diag::err_not_integral_type_bitfield)
3179 << Name << cast<ValueDecl>(Member)->getType()
3180 << BitWidth->getSourceRange();
3184 Member->setInvalidDecl();
3187 NamedDecl *NonTemplateMember = Member;
3188 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3189 NonTemplateMember = FunTmpl->getTemplatedDecl();
3190 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3191 NonTemplateMember = VarTmpl->getTemplatedDecl();
3193 Member->setAccess(AS);
3195 // If we have declared a member function template or static data member
3196 // template, set the access of the templated declaration as well.
3197 if (NonTemplateMember != Member)
3198 NonTemplateMember->setAccess(AS);
3200 // C++ [temp.deduct.guide]p3:
3201 // A deduction guide [...] for a member class template [shall be
3202 // declared] with the same access [as the template].
3203 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3204 auto *TD = DG->getDeducedTemplate();
3205 // Access specifiers are only meaningful if both the template and the
3206 // deduction guide are from the same scope.
3207 if (AS != TD->getAccess() &&
3208 TD->getDeclContext()->getRedeclContext()->Equals(
3209 DG->getDeclContext()->getRedeclContext())) {
3210 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3211 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3213 const AccessSpecDecl *LastAccessSpec = nullptr;
3214 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3215 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3216 LastAccessSpec = AccessSpec;
3218 assert(LastAccessSpec && "differing access with no access specifier");
3219 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3225 if (VS.isOverrideSpecified())
3226 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3227 if (VS.isFinalSpecified())
3228 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3229 VS.isFinalSpelledSealed()));
3231 if (VS.getLastLocation().isValid()) {
3232 // Update the end location of a method that has a virt-specifiers.
3233 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3234 MD->setRangeEnd(VS.getLastLocation());
3237 CheckOverrideControl(Member);
3239 assert((Name || isInstField) && "No identifier for non-field ?");
3242 FieldDecl *FD = cast<FieldDecl>(Member);
3243 FieldCollector->Add(FD);
3245 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3246 // Remember all explicit private FieldDecls that have a name, no side
3247 // effects and are not part of a dependent type declaration.
3248 if (!FD->isImplicit() && FD->getDeclName() &&
3249 FD->getAccess() == AS_private &&
3250 !FD->hasAttr<UnusedAttr>() &&
3251 !FD->getParent()->isDependentContext() &&
3252 !InitializationHasSideEffects(*FD))
3253 UnusedPrivateFields.insert(FD);
3261 class UninitializedFieldVisitor
3262 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3264 // List of Decls to generate a warning on. Also remove Decls that become
3266 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3267 // List of base classes of the record. Classes are removed after their
3269 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3270 // Vector of decls to be removed from the Decl set prior to visiting the
3271 // nodes. These Decls may have been initialized in the prior initializer.
3272 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3273 // If non-null, add a note to the warning pointing back to the constructor.
3274 const CXXConstructorDecl *Constructor;
3275 // Variables to hold state when processing an initializer list. When
3276 // InitList is true, special case initialization of FieldDecls matching
3277 // InitListFieldDecl.
3279 FieldDecl *InitListFieldDecl;
3280 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3283 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3284 UninitializedFieldVisitor(Sema &S,
3285 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3286 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3287 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3288 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3290 // Returns true if the use of ME is not an uninitialized use.
3291 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3292 bool CheckReferenceOnly) {
3293 llvm::SmallVector<FieldDecl*, 4> Fields;
3294 bool ReferenceField = false;
3296 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3299 Fields.push_back(FD);
3300 if (FD->getType()->isReferenceType())
3301 ReferenceField = true;
3302 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3305 // Binding a reference to an uninitialized field is not an
3306 // uninitialized use.
3307 if (CheckReferenceOnly && !ReferenceField)
3310 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3311 // Discard the first field since it is the field decl that is being
3313 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3314 UsedFieldIndex.push_back((*I)->getFieldIndex());
3317 for (auto UsedIter = UsedFieldIndex.begin(),
3318 UsedEnd = UsedFieldIndex.end(),
3319 OrigIter = InitFieldIndex.begin(),
3320 OrigEnd = InitFieldIndex.end();
3321 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3322 if (*UsedIter < *OrigIter)
3324 if (*UsedIter > *OrigIter)
3331 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3333 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3336 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3338 MemberExpr *FieldME = ME;
3340 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3343 while (MemberExpr *SubME =
3344 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3346 if (isa<VarDecl>(SubME->getMemberDecl()))
3349 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3350 if (!FD->isAnonymousStructOrUnion())
3353 if (!FieldME->getType().isPODType(S.Context))
3354 AllPODFields = false;
3356 Base = SubME->getBase();
3359 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3362 if (AddressOf && AllPODFields)
3365 ValueDecl* FoundVD = FieldME->getMemberDecl();
3367 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3368 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3369 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3372 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3373 QualType T = BaseCast->getType();
3374 if (T->isPointerType() &&
3375 BaseClasses.count(T->getPointeeType())) {
3376 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3377 << T->getPointeeType() << FoundVD;
3382 if (!Decls.count(FoundVD))
3385 const bool IsReference = FoundVD->getType()->isReferenceType();
3387 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3388 // Special checking for initializer lists.
3389 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3393 // Prevent double warnings on use of unbounded references.
3394 if (CheckReferenceOnly && !IsReference)
3398 unsigned diag = IsReference
3399 ? diag::warn_reference_field_is_uninit
3400 : diag::warn_field_is_uninit;
3401 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3403 S.Diag(Constructor->getLocation(),
3404 diag::note_uninit_in_this_constructor)
3405 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3409 void HandleValue(Expr *E, bool AddressOf) {
3410 E = E->IgnoreParens();
3412 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3413 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3414 AddressOf /*AddressOf*/);
3418 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3419 Visit(CO->getCond());
3420 HandleValue(CO->getTrueExpr(), AddressOf);
3421 HandleValue(CO->getFalseExpr(), AddressOf);
3425 if (BinaryConditionalOperator *BCO =
3426 dyn_cast<BinaryConditionalOperator>(E)) {
3427 Visit(BCO->getCond());
3428 HandleValue(BCO->getFalseExpr(), AddressOf);
3432 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3433 HandleValue(OVE->getSourceExpr(), AddressOf);
3437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3438 switch (BO->getOpcode()) {
3443 HandleValue(BO->getLHS(), AddressOf);
3444 Visit(BO->getRHS());
3447 Visit(BO->getLHS());
3448 HandleValue(BO->getRHS(), AddressOf);
3456 void CheckInitListExpr(InitListExpr *ILE) {
3457 InitFieldIndex.push_back(0);
3458 for (auto Child : ILE->children()) {
3459 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3460 CheckInitListExpr(SubList);
3464 ++InitFieldIndex.back();
3466 InitFieldIndex.pop_back();
3469 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3470 FieldDecl *Field, const Type *BaseClass) {
3471 // Remove Decls that may have been initialized in the previous
3473 for (ValueDecl* VD : DeclsToRemove)
3475 DeclsToRemove.clear();
3477 Constructor = FieldConstructor;
3478 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3482 InitListFieldDecl = Field;
3483 InitFieldIndex.clear();
3484 CheckInitListExpr(ILE);
3493 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3496 void VisitMemberExpr(MemberExpr *ME) {
3497 // All uses of unbounded reference fields will warn.
3498 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3501 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3502 if (E->getCastKind() == CK_LValueToRValue) {
3503 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3507 Inherited::VisitImplicitCastExpr(E);
3510 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3511 if (E->getConstructor()->isCopyConstructor()) {
3512 Expr *ArgExpr = E->getArg(0);
3513 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3514 if (ILE->getNumInits() == 1)
3515 ArgExpr = ILE->getInit(0);
3516 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3517 if (ICE->getCastKind() == CK_NoOp)
3518 ArgExpr = ICE->getSubExpr();
3519 HandleValue(ArgExpr, false /*AddressOf*/);
3522 Inherited::VisitCXXConstructExpr(E);
3525 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3526 Expr *Callee = E->getCallee();
3527 if (isa<MemberExpr>(Callee)) {
3528 HandleValue(Callee, false /*AddressOf*/);
3529 for (auto Arg : E->arguments())
3534 Inherited::VisitCXXMemberCallExpr(E);
3537 void VisitCallExpr(CallExpr *E) {
3538 // Treat std::move as a use.
3539 if (E->isCallToStdMove()) {
3540 HandleValue(E->getArg(0), /*AddressOf=*/false);
3544 Inherited::VisitCallExpr(E);
3547 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3548 Expr *Callee = E->getCallee();
3550 if (isa<UnresolvedLookupExpr>(Callee))
3551 return Inherited::VisitCXXOperatorCallExpr(E);
3554 for (auto Arg : E->arguments())
3555 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3558 void VisitBinaryOperator(BinaryOperator *E) {
3559 // If a field assignment is detected, remove the field from the
3560 // uninitiailized field set.
3561 if (E->getOpcode() == BO_Assign)
3562 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3563 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3564 if (!FD->getType()->isReferenceType())
3565 DeclsToRemove.push_back(FD);
3567 if (E->isCompoundAssignmentOp()) {
3568 HandleValue(E->getLHS(), false /*AddressOf*/);
3573 Inherited::VisitBinaryOperator(E);
3576 void VisitUnaryOperator(UnaryOperator *E) {
3577 if (E->isIncrementDecrementOp()) {
3578 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3581 if (E->getOpcode() == UO_AddrOf) {
3582 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3583 HandleValue(ME->getBase(), true /*AddressOf*/);
3588 Inherited::VisitUnaryOperator(E);
3592 // Diagnose value-uses of fields to initialize themselves, e.g.
3594 // where foo is not also a parameter to the constructor.
3595 // Also diagnose across field uninitialized use such as
3597 // TODO: implement -Wuninitialized and fold this into that framework.
3598 static void DiagnoseUninitializedFields(
3599 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3601 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3602 Constructor->getLocation())) {
3606 if (Constructor->isInvalidDecl())
3609 const CXXRecordDecl *RD = Constructor->getParent();
3611 if (RD->getDescribedClassTemplate())
3614 // Holds fields that are uninitialized.
3615 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3617 // At the beginning, all fields are uninitialized.
3618 for (auto *I : RD->decls()) {
3619 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3620 UninitializedFields.insert(FD);
3621 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3622 UninitializedFields.insert(IFD->getAnonField());
3626 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3627 for (auto I : RD->bases())
3628 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3630 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3633 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3634 UninitializedFields,
3635 UninitializedBaseClasses);
3637 for (const auto *FieldInit : Constructor->inits()) {
3638 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3641 Expr *InitExpr = FieldInit->getInit();
3645 if (CXXDefaultInitExpr *Default =
3646 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3647 InitExpr = Default->getExpr();
3650 // In class initializers will point to the constructor.
3651 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3652 FieldInit->getAnyMember(),
3653 FieldInit->getBaseClass());
3655 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3656 FieldInit->getAnyMember(),
3657 FieldInit->getBaseClass());
3663 /// Enter a new C++ default initializer scope. After calling this, the
3664 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3665 /// parsing or instantiating the initializer failed.
3666 void Sema::ActOnStartCXXInClassMemberInitializer() {
3667 // Create a synthetic function scope to represent the call to the constructor
3668 // that notionally surrounds a use of this initializer.
3669 PushFunctionScope();
3672 /// This is invoked after parsing an in-class initializer for a
3673 /// non-static C++ class member, and after instantiating an in-class initializer
3674 /// in a class template. Such actions are deferred until the class is complete.
3675 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3676 SourceLocation InitLoc,
3678 // Pop the notional constructor scope we created earlier.
3679 PopFunctionScopeInfo(nullptr, D);
3681 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3682 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3683 "must set init style when field is created");
3686 D->setInvalidDecl();
3688 FD->removeInClassInitializer();
3692 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3693 FD->setInvalidDecl();
3694 FD->removeInClassInitializer();
3698 ExprResult Init = InitExpr;
3699 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3700 InitializedEntity Entity =
3701 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
3702 InitializationKind Kind =
3703 FD->getInClassInitStyle() == ICIS_ListInit
3704 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
3705 InitExpr->getBeginLoc(),
3706 InitExpr->getEndLoc())
3707 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
3708 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3709 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3710 if (Init.isInvalid()) {
3711 FD->setInvalidDecl();
3716 // C++11 [class.base.init]p7:
3717 // The initialization of each base and member constitutes a
3719 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
3720 if (Init.isInvalid()) {
3721 FD->setInvalidDecl();
3725 InitExpr = Init.get();
3727 FD->setInClassInitializer(InitExpr);
3730 /// Find the direct and/or virtual base specifiers that
3731 /// correspond to the given base type, for use in base initialization
3732 /// within a constructor.
3733 static bool FindBaseInitializer(Sema &SemaRef,
3734 CXXRecordDecl *ClassDecl,
3736 const CXXBaseSpecifier *&DirectBaseSpec,
3737 const CXXBaseSpecifier *&VirtualBaseSpec) {
3738 // First, check for a direct base class.
3739 DirectBaseSpec = nullptr;
3740 for (const auto &Base : ClassDecl->bases()) {
3741 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3742 // We found a direct base of this type. That's what we're
3744 DirectBaseSpec = &Base;
3749 // Check for a virtual base class.
3750 // FIXME: We might be able to short-circuit this if we know in advance that
3751 // there are no virtual bases.
3752 VirtualBaseSpec = nullptr;
3753 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3754 // We haven't found a base yet; search the class hierarchy for a
3755 // virtual base class.
3756 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3757 /*DetectVirtual=*/false);
3758 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3759 SemaRef.Context.getTypeDeclType(ClassDecl),
3761 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3762 Path != Paths.end(); ++Path) {
3763 if (Path->back().Base->isVirtual()) {
3764 VirtualBaseSpec = Path->back().Base;
3771 return DirectBaseSpec || VirtualBaseSpec;
3774 /// Handle a C++ member initializer using braced-init-list syntax.
3776 Sema::ActOnMemInitializer(Decl *ConstructorD,
3779 IdentifierInfo *MemberOrBase,
3780 ParsedType TemplateTypeTy,
3782 SourceLocation IdLoc,
3784 SourceLocation EllipsisLoc) {
3785 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3786 DS, IdLoc, InitList,
3790 /// Handle a C++ member initializer using parentheses syntax.
3792 Sema::ActOnMemInitializer(Decl *ConstructorD,
3795 IdentifierInfo *MemberOrBase,
3796 ParsedType TemplateTypeTy,
3798 SourceLocation IdLoc,
3799 SourceLocation LParenLoc,
3800 ArrayRef<Expr *> Args,
3801 SourceLocation RParenLoc,
3802 SourceLocation EllipsisLoc) {
3803 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
3804 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3805 DS, IdLoc, List, EllipsisLoc);
3810 // Callback to only accept typo corrections that can be a valid C++ member
3811 // intializer: either a non-static field member or a base class.
3812 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
3814 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3815 : ClassDecl(ClassDecl) {}
3817 bool ValidateCandidate(const TypoCorrection &candidate) override {
3818 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3819 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3820 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3821 return isa<TypeDecl>(ND);
3826 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3827 return llvm::make_unique<MemInitializerValidatorCCC>(*this);
3831 CXXRecordDecl *ClassDecl;
3836 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
3838 ParsedType TemplateTypeTy,
3839 IdentifierInfo *MemberOrBase) {
3840 if (SS.getScopeRep() || TemplateTypeTy)
3842 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3846 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3847 (Member = dyn_cast<IndirectFieldDecl>(Result.front())))
3852 /// Handle a C++ member initializer.
3854 Sema::BuildMemInitializer(Decl *ConstructorD,
3857 IdentifierInfo *MemberOrBase,
3858 ParsedType TemplateTypeTy,
3860 SourceLocation IdLoc,
3862 SourceLocation EllipsisLoc) {
3863 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3864 if (!Res.isUsable())
3871 AdjustDeclIfTemplate(ConstructorD);
3873 CXXConstructorDecl *Constructor
3874 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3876 // The user wrote a constructor initializer on a function that is
3877 // not a C++ constructor. Ignore the error for now, because we may
3878 // have more member initializers coming; we'll diagnose it just
3879 // once in ActOnMemInitializers.
3883 CXXRecordDecl *ClassDecl = Constructor->getParent();
3885 // C++ [class.base.init]p2:
3886 // Names in a mem-initializer-id are looked up in the scope of the
3887 // constructor's class and, if not found in that scope, are looked
3888 // up in the scope containing the constructor's definition.
3889 // [Note: if the constructor's class contains a member with the
3890 // same name as a direct or virtual base class of the class, a
3891 // mem-initializer-id naming the member or base class and composed
3892 // of a single identifier refers to the class member. A
3893 // mem-initializer-id for the hidden base class may be specified
3894 // using a qualified name. ]
3896 // Look for a member, first.
3897 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
3898 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
3899 if (EllipsisLoc.isValid())
3900 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3902 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3904 return BuildMemberInitializer(Member, Init, IdLoc);
3906 // It didn't name a member, so see if it names a class.
3908 TypeSourceInfo *TInfo = nullptr;
3910 if (TemplateTypeTy) {
3911 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3912 if (BaseType.isNull())
3914 } else if (DS.getTypeSpecType() == TST_decltype) {
3915 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3916 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3917 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3920 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3921 LookupParsedName(R, S, &SS);
3923 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3925 if (R.isAmbiguous()) return true;
3927 // We don't want access-control diagnostics here.
3928 R.suppressDiagnostics();
3930 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3931 bool NotUnknownSpecialization = false;
3932 DeclContext *DC = computeDeclContext(SS, false);
3933 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3934 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3936 if (!NotUnknownSpecialization) {
3937 // When the scope specifier can refer to a member of an unknown
3938 // specialization, we take it as a type name.
3939 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3940 SS.getWithLocInContext(Context),
3941 *MemberOrBase, IdLoc);
3942 if (BaseType.isNull())
3945 TInfo = Context.CreateTypeSourceInfo(BaseType);
3946 DependentNameTypeLoc TL =
3947 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3949 TL.setNameLoc(IdLoc);
3950 TL.setElaboratedKeywordLoc(SourceLocation());
3951 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3955 R.setLookupName(MemberOrBase);
3959 // If no results were found, try to correct typos.
3960 TypoCorrection Corr;
3961 MemInitializerValidatorCCC CCC(ClassDecl);
3962 if (R.empty() && BaseType.isNull() &&
3963 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3964 CCC, CTK_ErrorRecovery, ClassDecl))) {
3965 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3966 // We have found a non-static data member with a similar
3967 // name to what was typed; complain and initialize that
3970 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3971 << MemberOrBase << true);
3972 return BuildMemberInitializer(Member, Init, IdLoc);
3973 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3974 const CXXBaseSpecifier *DirectBaseSpec;
3975 const CXXBaseSpecifier *VirtualBaseSpec;
3976 if (FindBaseInitializer(*this, ClassDecl,
3977 Context.getTypeDeclType(Type),
3978 DirectBaseSpec, VirtualBaseSpec)) {
3979 // We have found a direct or virtual base class with a
3980 // similar name to what was typed; complain and initialize
3983 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3984 << MemberOrBase << false,
3985 PDiag() /*Suppress note, we provide our own.*/);
3987 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3989 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
3990 << BaseSpec->getType() << BaseSpec->getSourceRange();
3997 if (!TyD && BaseType.isNull()) {
3998 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3999 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4004 if (BaseType.isNull()) {
4005 BaseType = Context.getTypeDeclType(TyD);
4006 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4008 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4010 TInfo = Context.CreateTypeSourceInfo(BaseType);
4011 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4012 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4013 TL.setElaboratedKeywordLoc(SourceLocation());
4014 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4020 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4022 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4026 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4027 SourceLocation IdLoc) {
4028 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4029 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4030 assert((DirectMember || IndirectMember) &&
4031 "Member must be a FieldDecl or IndirectFieldDecl");
4033 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4036 if (Member->isInvalidDecl())
4040 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4041 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4042 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4043 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4045 // Template instantiation doesn't reconstruct ParenListExprs for us.
4049 SourceRange InitRange = Init->getSourceRange();
4051 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4052 // Can't check initialization for a member of dependent type or when
4053 // any of the arguments are type-dependent expressions.
4054 DiscardCleanupsInEvaluationContext();
4056 bool InitList = false;
4057 if (isa<InitListExpr>(Init)) {
4062 // Initialize the member.
4063 InitializedEntity MemberEntity =
4064 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4065 : InitializedEntity::InitializeMember(IndirectMember,
4067 InitializationKind Kind =
4068 InitList ? InitializationKind::CreateDirectList(
4069 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4070 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4071 InitRange.getEnd());
4073 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4074 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4076 if (MemberInit.isInvalid())
4079 // C++11 [class.base.init]p7:
4080 // The initialization of each base and member constitutes a
4082 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4083 /*DiscardedValue*/ false);
4084 if (MemberInit.isInvalid())
4087 Init = MemberInit.get();
4091 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4092 InitRange.getBegin(), Init,
4093 InitRange.getEnd());
4095 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4096 InitRange.getBegin(), Init,
4097 InitRange.getEnd());
4102 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4103 CXXRecordDecl *ClassDecl) {
4104 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4105 if (!LangOpts.CPlusPlus11)
4106 return Diag(NameLoc, diag::err_delegating_ctor)
4107 << TInfo->getTypeLoc().getLocalSourceRange();
4108 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4110 bool InitList = true;
4111 MultiExprArg Args = Init;
4112 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4114 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4117 SourceRange InitRange = Init->getSourceRange();
4118 // Initialize the object.
4119 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4120 QualType(ClassDecl->getTypeForDecl(), 0));
4121 InitializationKind Kind =
4122 InitList ? InitializationKind::CreateDirectList(
4123 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4124 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4125 InitRange.getEnd());
4126 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4127 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4129 if (DelegationInit.isInvalid())
4132 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4133 "Delegating constructor with no target?");
4135 // C++11 [class.base.init]p7:
4136 // The initialization of each base and member constitutes a
4138 DelegationInit = ActOnFinishFullExpr(
4139 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4140 if (DelegationInit.isInvalid())
4143 // If we are in a dependent context, template instantiation will
4144 // perform this type-checking again. Just save the arguments that we
4145 // received in a ParenListExpr.
4146 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4147 // of the information that we have about the base
4148 // initializer. However, deconstructing the ASTs is a dicey process,
4149 // and this approach is far more likely to get the corner cases right.
4150 if (CurContext->isDependentContext())
4151 DelegationInit = Init;
4153 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4154 DelegationInit.getAs<Expr>(),
4155 InitRange.getEnd());
4159 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4160 Expr *Init, CXXRecordDecl *ClassDecl,
4161 SourceLocation EllipsisLoc) {
4162 SourceLocation BaseLoc
4163 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4165 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4166 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4167 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4169 // C++ [class.base.init]p2:
4170 // [...] Unless the mem-initializer-id names a nonstatic data
4171 // member of the constructor's class or a direct or virtual base
4172 // of that class, the mem-initializer is ill-formed. A
4173 // mem-initializer-list can initialize a base class using any
4174 // name that denotes that base class type.
4175 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4177 SourceRange InitRange = Init->getSourceRange();
4178 if (EllipsisLoc.isValid()) {
4179 // This is a pack expansion.
4180 if (!BaseType->containsUnexpandedParameterPack()) {
4181 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4182 << SourceRange(BaseLoc, InitRange.getEnd());
4184 EllipsisLoc = SourceLocation();
4187 // Check for any unexpanded parameter packs.
4188 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4191 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4195 // Check for direct and virtual base classes.
4196 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4197 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4199 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4201 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4203 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4206 // C++ [base.class.init]p2:
4207 // Unless the mem-initializer-id names a nonstatic data member of the
4208 // constructor's class or a direct or virtual base of that class, the
4209 // mem-initializer is ill-formed.
4210 if (!DirectBaseSpec && !VirtualBaseSpec) {
4211 // If the class has any dependent bases, then it's possible that
4212 // one of those types will resolve to the same type as
4213 // BaseType. Therefore, just treat this as a dependent base
4214 // class initialization. FIXME: Should we try to check the
4215 // initialization anyway? It seems odd.
4216 if (ClassDecl->hasAnyDependentBases())
4219 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4220 << BaseType << Context.getTypeDeclType(ClassDecl)
4221 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4226 DiscardCleanupsInEvaluationContext();
4228 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4229 /*IsVirtual=*/false,
4230 InitRange.getBegin(), Init,
4231 InitRange.getEnd(), EllipsisLoc);
4234 // C++ [base.class.init]p2:
4235 // If a mem-initializer-id is ambiguous because it designates both
4236 // a direct non-virtual base class and an inherited virtual base
4237 // class, the mem-initializer is ill-formed.
4238 if (DirectBaseSpec && VirtualBaseSpec)
4239 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4240 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4242 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4244 BaseSpec = VirtualBaseSpec;
4246 // Initialize the base.
4247 bool InitList = true;
4248 MultiExprArg Args = Init;
4249 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4251 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4254 InitializedEntity BaseEntity =
4255 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4256 InitializationKind Kind =
4257 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4258 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4259 InitRange.getEnd());
4260 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4261 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4262 if (BaseInit.isInvalid())
4265 // C++11 [class.base.init]p7:
4266 // The initialization of each base and member constitutes a
4268 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4269 /*DiscardedValue*/ false);
4270 if (BaseInit.isInvalid())
4273 // If we are in a dependent context, template instantiation will
4274 // perform this type-checking again. Just save the arguments that we
4275 // received in a ParenListExpr.
4276 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4277 // of the information that we have about the base
4278 // initializer. However, deconstructing the ASTs is a dicey process,
4279 // and this approach is far more likely to get the corner cases right.
4280 if (CurContext->isDependentContext())
4283 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4284 BaseSpec->isVirtual(),
4285 InitRange.getBegin(),
4286 BaseInit.getAs<Expr>(),
4287 InitRange.getEnd(), EllipsisLoc);
4290 // Create a static_cast\<T&&>(expr).
4291 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4292 if (T.isNull()) T = E->getType();
4293 QualType TargetType = SemaRef.BuildReferenceType(
4294 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4295 SourceLocation ExprLoc = E->getBeginLoc();
4296 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4297 TargetType, ExprLoc);
4299 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4300 SourceRange(ExprLoc, ExprLoc),
4301 E->getSourceRange()).get();
4304 /// ImplicitInitializerKind - How an implicit base or member initializer should
4305 /// initialize its base or member.
4306 enum ImplicitInitializerKind {
4314 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4315 ImplicitInitializerKind ImplicitInitKind,
4316 CXXBaseSpecifier *BaseSpec,
4317 bool IsInheritedVirtualBase,
4318 CXXCtorInitializer *&CXXBaseInit) {
4319 InitializedEntity InitEntity
4320 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4321 IsInheritedVirtualBase);
4323 ExprResult BaseInit;
4325 switch (ImplicitInitKind) {
4328 InitializationKind InitKind
4329 = InitializationKind::CreateDefault(Constructor->getLocation());
4330 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4331 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4337 bool Moving = ImplicitInitKind == IIK_Move;
4338 ParmVarDecl *Param = Constructor->getParamDecl(0);
4339 QualType ParamType = Param->getType().getNonReferenceType();
4342 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4343 SourceLocation(), Param, false,
4344 Constructor->getLocation(), ParamType,
4345 VK_LValue, nullptr);
4347 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4349 // Cast to the base class to avoid ambiguities.
4351 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4352 ParamType.getQualifiers());
4355 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4358 CXXCastPath BasePath;
4359 BasePath.push_back(BaseSpec);
4360 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4361 CK_UncheckedDerivedToBase,
4362 Moving ? VK_XValue : VK_LValue,
4365 InitializationKind InitKind
4366 = InitializationKind::CreateDirect(Constructor->getLocation(),
4367 SourceLocation(), SourceLocation());
4368 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4369 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4374 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4375 if (BaseInit.isInvalid())
4379 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4380 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4382 BaseSpec->isVirtual(),
4384 BaseInit.getAs<Expr>(),
4391 static bool RefersToRValueRef(Expr *MemRef) {
4392 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4393 return Referenced->getType()->isRValueReferenceType();
4397 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4398 ImplicitInitializerKind ImplicitInitKind,
4399 FieldDecl *Field, IndirectFieldDecl *Indirect,
4400 CXXCtorInitializer *&CXXMemberInit) {
4401 if (Field->isInvalidDecl())
4404 SourceLocation Loc = Constructor->getLocation();
4406 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4407 bool Moving = ImplicitInitKind == IIK_Move;
4408 ParmVarDecl *Param = Constructor->getParamDecl(0);
4409 QualType ParamType = Param->getType().getNonReferenceType();
4411 // Suppress copying zero-width bitfields.
4412 if (Field->isZeroLengthBitField(SemaRef.Context))
4415 Expr *MemberExprBase =
4416 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4417 SourceLocation(), Param, false,
4418 Loc, ParamType, VK_LValue, nullptr);
4420 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4423 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4426 // Build a reference to this field within the parameter.
4428 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4429 Sema::LookupMemberName);
4430 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4431 : cast<ValueDecl>(Field), AS_public);
4432 MemberLookup.resolveKind();
4434 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4438 /*TemplateKWLoc=*/SourceLocation(),
4439 /*FirstQualifierInScope=*/nullptr,
4441 /*TemplateArgs=*/nullptr,
4443 if (CtorArg.isInvalid())
4446 // C++11 [class.copy]p15:
4447 // - if a member m has rvalue reference type T&&, it is direct-initialized
4448 // with static_cast<T&&>(x.m);
4449 if (RefersToRValueRef(CtorArg.get())) {
4450 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4453 InitializedEntity Entity =
4454 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4456 : InitializedEntity::InitializeMember(Field, nullptr,
4459 // Direct-initialize to use the copy constructor.
4460 InitializationKind InitKind =
4461 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4463 Expr *CtorArgE = CtorArg.getAs<Expr>();
4464 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4465 ExprResult MemberInit =
4466 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4467 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4468 if (MemberInit.isInvalid())
4472 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4473 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4475 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4476 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4480 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4481 "Unhandled implicit init kind!");
4483 QualType FieldBaseElementType =
4484 SemaRef.Context.getBaseElementType(Field->getType());
4486 if (FieldBaseElementType->isRecordType()) {
4487 InitializedEntity InitEntity =
4488 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4490 : InitializedEntity::InitializeMember(Field, nullptr,
4492 InitializationKind InitKind =
4493 InitializationKind::CreateDefault(Loc);
4495 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4496 ExprResult MemberInit =
4497 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4499 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4500 if (MemberInit.isInvalid())
4504 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4510 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4517 if (!Field->getParent()->isUnion()) {
4518 if (FieldBaseElementType->isReferenceType()) {
4519 SemaRef.Diag(Constructor->getLocation(),
4520 diag::err_uninitialized_member_in_ctor)
4521 << (int)Constructor->isImplicit()
4522 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4523 << 0 << Field->getDeclName();
4524 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4528 if (FieldBaseElementType.isConstQualified()) {
4529 SemaRef.Diag(Constructor->getLocation(),
4530 diag::err_uninitialized_member_in_ctor)
4531 << (int)Constructor->isImplicit()
4532 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4533 << 1 << Field->getDeclName();
4534 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4539 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4541 // Default-initialize Objective-C pointers to NULL.
4543 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4545 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4550 // Nothing to initialize.
4551 CXXMemberInit = nullptr;
4556 struct BaseAndFieldInfo {
4558 CXXConstructorDecl *Ctor;
4559 bool AnyErrorsInInits;
4560 ImplicitInitializerKind IIK;
4561 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4562 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4563 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4565 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4566 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4567 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4568 if (Ctor->getInheritedConstructor())
4570 else if (Generated && Ctor->isCopyConstructor())
4572 else if (Generated && Ctor->isMoveConstructor())
4578 bool isImplicitCopyOrMove() const {
4589 llvm_unreachable("Invalid ImplicitInitializerKind!");
4592 bool addFieldInitializer(CXXCtorInitializer *Init) {
4593 AllToInit.push_back(Init);
4595 // Check whether this initializer makes the field "used".
4596 if (Init->getInit()->HasSideEffects(S.Context))
4597 S.UnusedPrivateFields.remove(Init->getAnyMember());
4602 bool isInactiveUnionMember(FieldDecl *Field) {
4603 RecordDecl *Record = Field->getParent();
4604 if (!Record->isUnion())
4607 if (FieldDecl *Active =
4608 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4609 return Active != Field->getCanonicalDecl();
4611 // In an implicit copy or move constructor, ignore any in-class initializer.
4612 if (isImplicitCopyOrMove())
4615 // If there's no explicit initialization, the field is active only if it
4616 // has an in-class initializer...
4617 if (Field->hasInClassInitializer())
4619 // ... or it's an anonymous struct or union whose class has an in-class
4621 if (!Field->isAnonymousStructOrUnion())
4623 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4624 return !FieldRD->hasInClassInitializer();
4627 /// Determine whether the given field is, or is within, a union member
4628 /// that is inactive (because there was an initializer given for a different
4629 /// member of the union, or because the union was not initialized at all).
4630 bool isWithinInactiveUnionMember(FieldDecl *Field,
4631 IndirectFieldDecl *Indirect) {
4633 return isInactiveUnionMember(Field);
4635 for (auto *C : Indirect->chain()) {
4636 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4637 if (Field && isInactiveUnionMember(Field))
4645 /// Determine whether the given type is an incomplete or zero-lenfgth
4647 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4648 if (T->isIncompleteArrayType())
4651 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4652 if (!ArrayT->getSize())
4655 T = ArrayT->getElementType();
4661 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4663 IndirectFieldDecl *Indirect = nullptr) {
4664 if (Field->isInvalidDecl())
4667 // Overwhelmingly common case: we have a direct initializer for this field.
4668 if (CXXCtorInitializer *Init =
4669 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4670 return Info.addFieldInitializer(Init);
4672 // C++11 [class.base.init]p8:
4673 // if the entity is a non-static data member that has a
4674 // brace-or-equal-initializer and either
4675 // -- the constructor's class is a union and no other variant member of that
4676 // union is designated by a mem-initializer-id or
4677 // -- the constructor's class is not a union, and, if the entity is a member
4678 // of an anonymous union, no other member of that union is designated by
4679 // a mem-initializer-id,
4680 // the entity is initialized as specified in [dcl.init].
4682 // We also apply the same rules to handle anonymous structs within anonymous
4684 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4687 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4689 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4690 if (DIE.isInvalid())
4693 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
4694 SemaRef.checkInitializerLifetime(Entity, DIE.get());
4696 CXXCtorInitializer *Init;
4698 Init = new (SemaRef.Context)
4699 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4700 SourceLocation(), DIE.get(), SourceLocation());
4702 Init = new (SemaRef.Context)
4703 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4704 SourceLocation(), DIE.get(), SourceLocation());
4705 return Info.addFieldInitializer(Init);
4708 // Don't initialize incomplete or zero-length arrays.
4709 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4712 // Don't try to build an implicit initializer if there were semantic
4713 // errors in any of the initializers (and therefore we might be
4714 // missing some that the user actually wrote).
4715 if (Info.AnyErrorsInInits)
4718 CXXCtorInitializer *Init = nullptr;
4719 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4726 return Info.addFieldInitializer(Init);
4730 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4731 CXXCtorInitializer *Initializer) {
4732 assert(Initializer->isDelegatingInitializer());
4733 Constructor->setNumCtorInitializers(1);
4734 CXXCtorInitializer **initializer =
4735 new (Context) CXXCtorInitializer*[1];
4736 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4737 Constructor->setCtorInitializers(initializer);
4739 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4740 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4741 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4744 DelegatingCtorDecls.push_back(Constructor);
4746 DiagnoseUninitializedFields(*this, Constructor);
4751 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4752 ArrayRef<CXXCtorInitializer *> Initializers) {
4753 if (Constructor->isDependentContext()) {
4754 // Just store the initializers as written, they will be checked during
4756 if (!Initializers.empty()) {
4757 Constructor->setNumCtorInitializers(Initializers.size());
4758 CXXCtorInitializer **baseOrMemberInitializers =
4759 new (Context) CXXCtorInitializer*[Initializers.size()];
4760 memcpy(baseOrMemberInitializers, Initializers.data(),
4761 Initializers.size() * sizeof(CXXCtorInitializer*));
4762 Constructor->setCtorInitializers(baseOrMemberInitializers);
4765 // Let template instantiation know whether we had errors.
4767 Constructor->setInvalidDecl();
4772 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4774 // We need to build the initializer AST according to order of construction
4775 // and not what user specified in the Initializers list.
4776 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4780 bool HadError = false;
4782 for (unsigned i = 0; i < Initializers.size(); i++) {
4783 CXXCtorInitializer *Member = Initializers[i];
4785 if (Member->isBaseInitializer())
4786 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4788 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4790 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4791 for (auto *C : F->chain()) {
4792 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4793 if (FD && FD->getParent()->isUnion())
4794 Info.ActiveUnionMember.insert(std::make_pair(
4795 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4797 } else if (FieldDecl *FD = Member->getMember()) {
4798 if (FD->getParent()->isUnion())
4799 Info.ActiveUnionMember.insert(std::make_pair(
4800 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4805 // Keep track of the direct virtual bases.
4806 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4807 for (auto &I : ClassDecl->bases()) {
4809 DirectVBases.insert(&I);
4812 // Push virtual bases before others.
4813 for (auto &VBase : ClassDecl->vbases()) {
4814 if (CXXCtorInitializer *Value
4815 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4816 // [class.base.init]p7, per DR257:
4817 // A mem-initializer where the mem-initializer-id names a virtual base
4818 // class is ignored during execution of a constructor of any class that
4819 // is not the most derived class.
4820 if (ClassDecl->isAbstract()) {
4821 // FIXME: Provide a fixit to remove the base specifier. This requires
4822 // tracking the location of the associated comma for a base specifier.
4823 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4824 << VBase.getType() << ClassDecl;
4825 DiagnoseAbstractType(ClassDecl);
4828 Info.AllToInit.push_back(Value);
4829 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4830 // [class.base.init]p8, per DR257:
4831 // If a given [...] base class is not named by a mem-initializer-id
4832 // [...] and the entity is not a virtual base class of an abstract
4833 // class, then [...] the entity is default-initialized.
4834 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4835 CXXCtorInitializer *CXXBaseInit;
4836 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4837 &VBase, IsInheritedVirtualBase,
4843 Info.AllToInit.push_back(CXXBaseInit);
4847 // Non-virtual bases.
4848 for (auto &Base : ClassDecl->bases()) {
4849 // Virtuals are in the virtual base list and already constructed.
4850 if (Base.isVirtual())
4853 if (CXXCtorInitializer *Value
4854 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4855 Info.AllToInit.push_back(Value);
4856 } else if (!AnyErrors) {
4857 CXXCtorInitializer *CXXBaseInit;
4858 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4859 &Base, /*IsInheritedVirtualBase=*/false,
4865 Info.AllToInit.push_back(CXXBaseInit);
4870 for (auto *Mem : ClassDecl->decls()) {
4871 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4872 // C++ [class.bit]p2:
4873 // A declaration for a bit-field that omits the identifier declares an
4874 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4876 if (F->isUnnamedBitfield())
4879 // If we're not generating the implicit copy/move constructor, then we'll
4880 // handle anonymous struct/union fields based on their individual
4882 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4885 if (CollectFieldInitializer(*this, Info, F))
4890 // Beyond this point, we only consider default initialization.
4891 if (Info.isImplicitCopyOrMove())
4894 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4895 if (F->getType()->isIncompleteArrayType()) {
4896 assert(ClassDecl->hasFlexibleArrayMember() &&
4897 "Incomplete array type is not valid");
4901 // Initialize each field of an anonymous struct individually.
4902 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4909 unsigned NumInitializers = Info.AllToInit.size();
4910 if (NumInitializers > 0) {
4911 Constructor->setNumCtorInitializers(NumInitializers);
4912 CXXCtorInitializer **baseOrMemberInitializers =
4913 new (Context) CXXCtorInitializer*[NumInitializers];
4914 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4915 NumInitializers * sizeof(CXXCtorInitializer*));
4916 Constructor->setCtorInitializers(baseOrMemberInitializers);
4918 // Constructors implicitly reference the base and member
4920 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4921 Constructor->getParent());
4927 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4928 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4929 const RecordDecl *RD = RT->getDecl();
4930 if (RD->isAnonymousStructOrUnion()) {
4931 for (auto *Field : RD->fields())
4932 PopulateKeysForFields(Field, IdealInits);
4936 IdealInits.push_back(Field->getCanonicalDecl());
4939 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4940 return Context.getCanonicalType(BaseType).getTypePtr();
4943 static const void *GetKeyForMember(ASTContext &Context,
4944 CXXCtorInitializer *Member) {
4945 if (!Member->isAnyMemberInitializer())
4946 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4948 return Member->getAnyMember()->getCanonicalDecl();
4951 static void DiagnoseBaseOrMemInitializerOrder(
4952 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4953 ArrayRef<CXXCtorInitializer *> Inits) {
4954 if (Constructor->getDeclContext()->isDependentContext())
4957 // Don't check initializers order unless the warning is enabled at the
4958 // location of at least one initializer.
4959 bool ShouldCheckOrder = false;
4960 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4961 CXXCtorInitializer *Init = Inits[InitIndex];
4962 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4963 Init->getSourceLocation())) {
4964 ShouldCheckOrder = true;
4968 if (!ShouldCheckOrder)
4971 // Build the list of bases and members in the order that they'll
4972 // actually be initialized. The explicit initializers should be in
4973 // this same order but may be missing things.
4974 SmallVector<const void*, 32> IdealInitKeys;
4976 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4978 // 1. Virtual bases.
4979 for (const auto &VBase : ClassDecl->vbases())
4980 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4982 // 2. Non-virtual bases.
4983 for (const auto &Base : ClassDecl->bases()) {
4984 if (Base.isVirtual())
4986 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4989 // 3. Direct fields.
4990 for (auto *Field : ClassDecl->fields()) {
4991 if (Field->isUnnamedBitfield())
4994 PopulateKeysForFields(Field, IdealInitKeys);
4997 unsigned NumIdealInits = IdealInitKeys.size();
4998 unsigned IdealIndex = 0;
5000 CXXCtorInitializer *PrevInit = nullptr;
5001 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5002 CXXCtorInitializer *Init = Inits[InitIndex];
5003 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
5005 // Scan forward to try to find this initializer in the idealized
5006 // initializers list.
5007 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5008 if (InitKey == IdealInitKeys[IdealIndex])
5011 // If we didn't find this initializer, it must be because we
5012 // scanned past it on a previous iteration. That can only
5013 // happen if we're out of order; emit a warning.
5014 if (IdealIndex == NumIdealInits && PrevInit) {
5015 Sema::SemaDiagnosticBuilder D =
5016 SemaRef.Diag(PrevInit->getSourceLocation(),
5017 diag::warn_initializer_out_of_order);
5019 if (PrevInit->isAnyMemberInitializer())
5020 D << 0 << PrevInit->getAnyMember()->getDeclName();
5022 D << 1 << PrevInit->getTypeSourceInfo()->getType();
5024 if (Init->isAnyMemberInitializer())
5025 D << 0 << Init->getAnyMember()->getDeclName();
5027 D << 1 << Init->getTypeSourceInfo()->getType();
5029 // Move back to the initializer's location in the ideal list.
5030 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5031 if (InitKey == IdealInitKeys[IdealIndex])
5034 assert(IdealIndex < NumIdealInits &&
5035 "initializer not found in initializer list");
5043 bool CheckRedundantInit(Sema &S,
5044 CXXCtorInitializer *Init,
5045 CXXCtorInitializer *&PrevInit) {
5051 if (FieldDecl *Field = Init->getAnyMember())
5052 S.Diag(Init->getSourceLocation(),
5053 diag::err_multiple_mem_initialization)
5054 << Field->getDeclName()
5055 << Init->getSourceRange();
5057 const Type *BaseClass = Init->getBaseClass();
5058 assert(BaseClass && "neither field nor base");
5059 S.Diag(Init->getSourceLocation(),
5060 diag::err_multiple_base_initialization)
5061 << QualType(BaseClass, 0)
5062 << Init->getSourceRange();
5064 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5065 << 0 << PrevInit->getSourceRange();
5070 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5071 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5073 bool CheckRedundantUnionInit(Sema &S,
5074 CXXCtorInitializer *Init,
5075 RedundantUnionMap &Unions) {
5076 FieldDecl *Field = Init->getAnyMember();
5077 RecordDecl *Parent = Field->getParent();
5078 NamedDecl *Child = Field;
5080 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5081 if (Parent->isUnion()) {
5082 UnionEntry &En = Unions[Parent];
5083 if (En.first && En.first != Child) {
5084 S.Diag(Init->getSourceLocation(),
5085 diag::err_multiple_mem_union_initialization)
5086 << Field->getDeclName()
5087 << Init->getSourceRange();
5088 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5089 << 0 << En.second->getSourceRange();
5096 if (!Parent->isAnonymousStructOrUnion())
5101 Parent = cast<RecordDecl>(Parent->getDeclContext());
5108 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5109 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5110 SourceLocation ColonLoc,
5111 ArrayRef<CXXCtorInitializer*> MemInits,
5113 if (!ConstructorDecl)
5116 AdjustDeclIfTemplate(ConstructorDecl);
5118 CXXConstructorDecl *Constructor
5119 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5122 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5126 // Mapping for the duplicate initializers check.
5127 // For member initializers, this is keyed with a FieldDecl*.
5128 // For base initializers, this is keyed with a Type*.
5129 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5131 // Mapping for the inconsistent anonymous-union initializers check.
5132 RedundantUnionMap MemberUnions;
5134 bool HadError = false;
5135 for (unsigned i = 0; i < MemInits.size(); i++) {
5136 CXXCtorInitializer *Init = MemInits[i];
5138 // Set the source order index.
5139 Init->setSourceOrder(i);
5141 if (Init->isAnyMemberInitializer()) {
5142 const void *Key = GetKeyForMember(Context, Init);
5143 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5144 CheckRedundantUnionInit(*this, Init, MemberUnions))
5146 } else if (Init->isBaseInitializer()) {
5147 const void *Key = GetKeyForMember(Context, Init);
5148 if (CheckRedundantInit(*this, Init, Members[Key]))
5151 assert(Init->isDelegatingInitializer());
5152 // This must be the only initializer
5153 if (MemInits.size() != 1) {
5154 Diag(Init->getSourceLocation(),
5155 diag::err_delegating_initializer_alone)
5156 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5157 // We will treat this as being the only initializer.
5159 SetDelegatingInitializer(Constructor, MemInits[i]);
5160 // Return immediately as the initializer is set.
5168 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5170 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5172 DiagnoseUninitializedFields(*this, Constructor);
5176 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5177 CXXRecordDecl *ClassDecl) {
5178 // Ignore dependent contexts. Also ignore unions, since their members never
5179 // have destructors implicitly called.
5180 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5183 // FIXME: all the access-control diagnostics are positioned on the
5184 // field/base declaration. That's probably good; that said, the
5185 // user might reasonably want to know why the destructor is being
5186 // emitted, and we currently don't say.
5188 // Non-static data members.
5189 for (auto *Field : ClassDecl->fields()) {
5190 if (Field->isInvalidDecl())
5193 // Don't destroy incomplete or zero-length arrays.
5194 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5197 QualType FieldType = Context.getBaseElementType(Field->getType());
5199 const RecordType* RT = FieldType->getAs<RecordType>();
5203 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5204 if (FieldClassDecl->isInvalidDecl())
5206 if (FieldClassDecl->hasIrrelevantDestructor())
5208 // The destructor for an implicit anonymous union member is never invoked.
5209 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5212 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5213 assert(Dtor && "No dtor found for FieldClassDecl!");
5214 CheckDestructorAccess(Field->getLocation(), Dtor,
5215 PDiag(diag::err_access_dtor_field)
5216 << Field->getDeclName()
5219 MarkFunctionReferenced(Location, Dtor);
5220 DiagnoseUseOfDecl(Dtor, Location);
5223 // We only potentially invoke the destructors of potentially constructed
5225 bool VisitVirtualBases = !ClassDecl->isAbstract();
5227 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5230 for (const auto &Base : ClassDecl->bases()) {
5231 // Bases are always records in a well-formed non-dependent class.
5232 const RecordType *RT = Base.getType()->getAs<RecordType>();
5234 // Remember direct virtual bases.
5235 if (Base.isVirtual()) {
5236 if (!VisitVirtualBases)
5238 DirectVirtualBases.insert(RT);
5241 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5242 // If our base class is invalid, we probably can't get its dtor anyway.
5243 if (BaseClassDecl->isInvalidDecl())
5245 if (BaseClassDecl->hasIrrelevantDestructor())
5248 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5249 assert(Dtor && "No dtor found for BaseClassDecl!");
5251 // FIXME: caret should be on the start of the class name
5252 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5253 PDiag(diag::err_access_dtor_base)
5254 << Base.getType() << Base.getSourceRange(),
5255 Context.getTypeDeclType(ClassDecl));
5257 MarkFunctionReferenced(Location, Dtor);
5258 DiagnoseUseOfDecl(Dtor, Location);
5261 if (!VisitVirtualBases)
5265 for (const auto &VBase : ClassDecl->vbases()) {
5266 // Bases are always records in a well-formed non-dependent class.
5267 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5269 // Ignore direct virtual bases.
5270 if (DirectVirtualBases.count(RT))
5273 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5274 // If our base class is invalid, we probably can't get its dtor anyway.
5275 if (BaseClassDecl->isInvalidDecl())
5277 if (BaseClassDecl->hasIrrelevantDestructor())
5280 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5281 assert(Dtor && "No dtor found for BaseClassDecl!");
5282 if (CheckDestructorAccess(
5283 ClassDecl->getLocation(), Dtor,
5284 PDiag(diag::err_access_dtor_vbase)
5285 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5286 Context.getTypeDeclType(ClassDecl)) ==
5288 CheckDerivedToBaseConversion(
5289 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5290 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5291 SourceRange(), DeclarationName(), nullptr);
5294 MarkFunctionReferenced(Location, Dtor);
5295 DiagnoseUseOfDecl(Dtor, Location);
5299 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5303 if (CXXConstructorDecl *Constructor
5304 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5305 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5306 DiagnoseUninitializedFields(*this, Constructor);
5310 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5311 if (!getLangOpts().CPlusPlus)
5314 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5318 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5319 // class template specialization here, but doing so breaks a lot of code.
5321 // We can't answer whether something is abstract until it has a
5322 // definition. If it's currently being defined, we'll walk back
5323 // over all the declarations when we have a full definition.
5324 const CXXRecordDecl *Def = RD->getDefinition();
5325 if (!Def || Def->isBeingDefined())
5328 return RD->isAbstract();
5331 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5332 TypeDiagnoser &Diagnoser) {
5333 if (!isAbstractType(Loc, T))
5336 T = Context.getBaseElementType(T);
5337 Diagnoser.diagnose(*this, Loc, T);
5338 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5342 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5343 // Check if we've already emitted the list of pure virtual functions
5345 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5348 // If the diagnostic is suppressed, don't emit the notes. We're only
5349 // going to emit them once, so try to attach them to a diagnostic we're
5350 // actually going to show.
5351 if (Diags.isLastDiagnosticIgnored())
5354 CXXFinalOverriderMap FinalOverriders;
5355 RD->getFinalOverriders(FinalOverriders);
5357 // Keep a set of seen pure methods so we won't diagnose the same method
5359 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5361 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5362 MEnd = FinalOverriders.end();
5365 for (OverridingMethods::iterator SO = M->second.begin(),
5366 SOEnd = M->second.end();
5367 SO != SOEnd; ++SO) {
5368 // C++ [class.abstract]p4:
5369 // A class is abstract if it contains or inherits at least one
5370 // pure virtual function for which the final overrider is pure
5374 if (SO->second.size() != 1)
5377 if (!SO->second.front().Method->isPure())
5380 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5383 Diag(SO->second.front().Method->getLocation(),
5384 diag::note_pure_virtual_function)
5385 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5389 if (!PureVirtualClassDiagSet)
5390 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5391 PureVirtualClassDiagSet->insert(RD);
5395 struct AbstractUsageInfo {
5397 CXXRecordDecl *Record;
5398 CanQualType AbstractType;
5401 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5402 : S(S), Record(Record),
5403 AbstractType(S.Context.getCanonicalType(
5404 S.Context.getTypeDeclType(Record))),
5407 void DiagnoseAbstractType() {
5408 if (Invalid) return;
5409 S.DiagnoseAbstractType(Record);
5413 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5416 struct CheckAbstractUsage {
5417 AbstractUsageInfo &Info;
5418 const NamedDecl *Ctx;
5420 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5421 : Info(Info), Ctx(Ctx) {}
5423 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5424 switch (TL.getTypeLocClass()) {
5425 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5426 #define TYPELOC(CLASS, PARENT) \
5427 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5428 #include "clang/AST/TypeLocNodes.def"
5432 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5433 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5434 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5435 if (!TL.getParam(I))
5438 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5439 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5443 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5444 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5447 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5448 // Visit the type parameters from a permissive context.
5449 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5450 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5451 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5452 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5453 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5454 // TODO: other template argument types?
5458 // Visit pointee types from a permissive context.
5459 #define CheckPolymorphic(Type) \
5460 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5461 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5463 CheckPolymorphic(PointerTypeLoc)
5464 CheckPolymorphic(ReferenceTypeLoc)
5465 CheckPolymorphic(MemberPointerTypeLoc)
5466 CheckPolymorphic(BlockPointerTypeLoc)
5467 CheckPolymorphic(AtomicTypeLoc)
5469 /// Handle all the types we haven't given a more specific
5470 /// implementation for above.
5471 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5472 // Every other kind of type that we haven't called out already
5473 // that has an inner type is either (1) sugar or (2) contains that
5474 // inner type in some way as a subobject.
5475 if (TypeLoc Next = TL.getNextTypeLoc())
5476 return Visit(Next, Sel);
5478 // If there's no inner type and we're in a permissive context,
5480 if (Sel == Sema::AbstractNone) return;
5482 // Check whether the type matches the abstract type.
5483 QualType T = TL.getType();
5484 if (T->isArrayType()) {
5485 Sel = Sema::AbstractArrayType;
5486 T = Info.S.Context.getBaseElementType(T);
5488 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5489 if (CT != Info.AbstractType) return;
5491 // It matched; do some magic.
5492 if (Sel == Sema::AbstractArrayType) {
5493 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5494 << T << TL.getSourceRange();
5496 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5497 << Sel << T << TL.getSourceRange();
5499 Info.DiagnoseAbstractType();
5503 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5504 Sema::AbstractDiagSelID Sel) {
5505 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5510 /// Check for invalid uses of an abstract type in a method declaration.
5511 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5512 CXXMethodDecl *MD) {
5513 // No need to do the check on definitions, which require that
5514 // the return/param types be complete.
5515 if (MD->doesThisDeclarationHaveABody())
5518 // For safety's sake, just ignore it if we don't have type source
5519 // information. This should never happen for non-implicit methods,
5521 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5522 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5525 /// Check for invalid uses of an abstract type within a class definition.
5526 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5527 CXXRecordDecl *RD) {
5528 for (auto *D : RD->decls()) {
5529 if (D->isImplicit()) continue;
5531 // Methods and method templates.
5532 if (isa<CXXMethodDecl>(D)) {
5533 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5534 } else if (isa<FunctionTemplateDecl>(D)) {
5535 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5536 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5538 // Fields and static variables.
5539 } else if (isa<FieldDecl>(D)) {
5540 FieldDecl *FD = cast<FieldDecl>(D);
5541 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5542 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5543 } else if (isa<VarDecl>(D)) {
5544 VarDecl *VD = cast<VarDecl>(D);
5545 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5546 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5548 // Nested classes and class templates.
5549 } else if (isa<CXXRecordDecl>(D)) {
5550 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5551 } else if (isa<ClassTemplateDecl>(D)) {
5552 CheckAbstractClassUsage(Info,
5553 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5558 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5559 Attr *ClassAttr = getDLLAttr(Class);
5563 assert(ClassAttr->getKind() == attr::DLLExport);
5565 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5567 if (TSK == TSK_ExplicitInstantiationDeclaration)
5568 // Don't go any further if this is just an explicit instantiation
5572 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5573 S.MarkVTableUsed(Class->getLocation(), Class, true);
5575 for (Decl *Member : Class->decls()) {
5576 // Defined static variables that are members of an exported base
5577 // class must be marked export too.
5578 auto *VD = dyn_cast<VarDecl>(Member);
5579 if (VD && Member->getAttr<DLLExportAttr>() &&
5580 VD->getStorageClass() == SC_Static &&
5581 TSK == TSK_ImplicitInstantiation)
5582 S.MarkVariableReferenced(VD->getLocation(), VD);
5584 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5588 if (Member->getAttr<DLLExportAttr>()) {
5589 if (MD->isUserProvided()) {
5590 // Instantiate non-default class member functions ...
5592 // .. except for certain kinds of template specializations.
5593 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5596 S.MarkFunctionReferenced(Class->getLocation(), MD);
5598 // The function will be passed to the consumer when its definition is
5600 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5601 MD->isCopyAssignmentOperator() ||
5602 MD->isMoveAssignmentOperator()) {
5603 // Synthesize and instantiate non-trivial implicit methods, explicitly
5604 // defaulted methods, and the copy and move assignment operators. The
5605 // latter are exported even if they are trivial, because the address of
5606 // an operator can be taken and should compare equal across libraries.
5607 DiagnosticErrorTrap Trap(S.Diags);
5608 S.MarkFunctionReferenced(Class->getLocation(), MD);
5609 if (Trap.hasErrorOccurred()) {
5610 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5611 << Class << !S.getLangOpts().CPlusPlus11;
5615 // There is no later point when we will see the definition of this
5616 // function, so pass it to the consumer now.
5617 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5623 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5624 CXXRecordDecl *Class) {
5625 // Only the MS ABI has default constructor closures, so we don't need to do
5626 // this semantic checking anywhere else.
5627 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5630 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5631 for (Decl *Member : Class->decls()) {
5632 // Look for exported default constructors.
5633 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5634 if (!CD || !CD->isDefaultConstructor())
5636 auto *Attr = CD->getAttr<DLLExportAttr>();
5640 // If the class is non-dependent, mark the default arguments as ODR-used so
5641 // that we can properly codegen the constructor closure.
5642 if (!Class->isDependentContext()) {
5643 for (ParmVarDecl *PD : CD->parameters()) {
5644 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5645 S.DiscardCleanupsInEvaluationContext();
5649 if (LastExportedDefaultCtor) {
5650 S.Diag(LastExportedDefaultCtor->getLocation(),
5651 diag::err_attribute_dll_ambiguous_default_ctor)
5653 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5654 << CD->getDeclName();
5657 LastExportedDefaultCtor = CD;
5661 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
5662 // Mark any compiler-generated routines with the implicit code_seg attribute.
5663 for (auto *Method : Class->methods()) {
5664 if (Method->isUserProvided())
5666 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
5671 /// Check class-level dllimport/dllexport attribute.
5672 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5673 Attr *ClassAttr = getDLLAttr(Class);
5675 // MSVC inherits DLL attributes to partial class template specializations.
5676 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5677 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5678 if (Attr *TemplateAttr =
5679 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5680 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5681 A->setInherited(true);
5690 if (!Class->isExternallyVisible()) {
5691 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5692 << Class << ClassAttr;
5696 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5697 !ClassAttr->isInherited()) {
5698 // Diagnose dll attributes on members of class with dll attribute.
5699 for (Decl *Member : Class->decls()) {
5700 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5702 InheritableAttr *MemberAttr = getDLLAttr(Member);
5703 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5706 Diag(MemberAttr->getLocation(),
5707 diag::err_attribute_dll_member_of_dll_class)
5708 << MemberAttr << ClassAttr;
5709 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5710 Member->setInvalidDecl();
5714 if (Class->getDescribedClassTemplate())
5715 // Don't inherit dll attribute until the template is instantiated.
5718 // The class is either imported or exported.
5719 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5721 // Check if this was a dllimport attribute propagated from a derived class to
5722 // a base class template specialization. We don't apply these attributes to
5723 // static data members.
5724 const bool PropagatedImport =
5726 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
5728 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5730 // Ignore explicit dllexport on explicit class template instantiation
5731 // declarations, except in MinGW mode.
5732 if (ClassExported && !ClassAttr->isInherited() &&
5733 TSK == TSK_ExplicitInstantiationDeclaration &&
5734 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
5735 Class->dropAttr<DLLExportAttr>();
5739 // Force declaration of implicit members so they can inherit the attribute.
5740 ForceDeclarationOfImplicitMembers(Class);
5742 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5743 // seem to be true in practice?
5745 for (Decl *Member : Class->decls()) {
5746 VarDecl *VD = dyn_cast<VarDecl>(Member);
5747 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5749 // Only methods and static fields inherit the attributes.
5754 // Don't process deleted methods.
5755 if (MD->isDeleted())
5758 if (MD->isInlined()) {
5759 // MinGW does not import or export inline methods. But do it for
5760 // template instantiations.
5761 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5762 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() &&
5763 TSK != TSK_ExplicitInstantiationDeclaration &&
5764 TSK != TSK_ExplicitInstantiationDefinition)
5767 // MSVC versions before 2015 don't export the move assignment operators
5768 // and move constructor, so don't attempt to import/export them if
5769 // we have a definition.
5770 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5771 if ((MD->isMoveAssignmentOperator() ||
5772 (Ctor && Ctor->isMoveConstructor())) &&
5773 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5776 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5777 // operator is exported anyway.
5778 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5779 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5784 // Don't apply dllimport attributes to static data members of class template
5785 // instantiations when the attribute is propagated from a derived class.
5786 if (VD && PropagatedImport)
5789 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5792 if (!getDLLAttr(Member)) {
5793 InheritableAttr *NewAttr = nullptr;
5795 // Do not export/import inline function when -fno-dllexport-inlines is
5796 // passed. But add attribute for later local static var check.
5797 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
5798 TSK != TSK_ExplicitInstantiationDeclaration &&
5799 TSK != TSK_ExplicitInstantiationDefinition) {
5800 if (ClassExported) {
5801 NewAttr = ::new (getASTContext())
5802 DLLExportStaticLocalAttr(ClassAttr->getRange(),
5804 ClassAttr->getSpellingListIndex());
5806 NewAttr = ::new (getASTContext())
5807 DLLImportStaticLocalAttr(ClassAttr->getRange(),
5809 ClassAttr->getSpellingListIndex());
5812 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5815 NewAttr->setInherited(true);
5816 Member->addAttr(NewAttr);
5819 // Propagate DLLAttr to friend re-declarations of MD that have already
5820 // been constructed.
5821 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
5822 FD = FD->getPreviousDecl()) {
5823 if (FD->getFriendObjectKind() == Decl::FOK_None)
5825 assert(!getDLLAttr(FD) &&
5826 "friend re-decl should not already have a DLLAttr");
5827 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5828 NewAttr->setInherited(true);
5829 FD->addAttr(NewAttr);
5836 DelayedDllExportClasses.push_back(Class);
5839 /// Perform propagation of DLL attributes from a derived class to a
5840 /// templated base class for MS compatibility.
5841 void Sema::propagateDLLAttrToBaseClassTemplate(
5842 CXXRecordDecl *Class, Attr *ClassAttr,
5843 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5845 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5846 // If the base class template has a DLL attribute, don't try to change it.
5850 auto TSK = BaseTemplateSpec->getSpecializationKind();
5851 if (!getDLLAttr(BaseTemplateSpec) &&
5852 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5853 TSK == TSK_ImplicitInstantiation)) {
5854 // The template hasn't been instantiated yet (or it has, but only as an
5855 // explicit instantiation declaration or implicit instantiation, which means
5856 // we haven't codegenned any members yet), so propagate the attribute.
5857 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5858 NewAttr->setInherited(true);
5859 BaseTemplateSpec->addAttr(NewAttr);
5861 // If this was an import, mark that we propagated it from a derived class to
5862 // a base class template specialization.
5863 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
5864 ImportAttr->setPropagatedToBaseTemplate();
5866 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5867 // needs to be run again to work see the new attribute. Otherwise this will
5868 // get run whenever the template is instantiated.
5869 if (TSK != TSK_Undeclared)
5870 checkClassLevelDLLAttribute(BaseTemplateSpec);
5875 if (getDLLAttr(BaseTemplateSpec)) {
5876 // The template has already been specialized or instantiated with an
5877 // attribute, explicitly or through propagation. We should not try to change
5882 // The template was previously instantiated or explicitly specialized without
5883 // a dll attribute, It's too late for us to add an attribute, so warn that
5884 // this is unsupported.
5885 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5886 << BaseTemplateSpec->isExplicitSpecialization();
5887 Diag(ClassAttr->getLocation(), diag::note_attribute);
5888 if (BaseTemplateSpec->isExplicitSpecialization()) {
5889 Diag(BaseTemplateSpec->getLocation(),
5890 diag::note_template_class_explicit_specialization_was_here)
5891 << BaseTemplateSpec;
5893 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5894 diag::note_template_class_instantiation_was_here)
5895 << BaseTemplateSpec;
5899 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5900 SourceLocation DefaultLoc) {
5901 switch (S.getSpecialMember(MD)) {
5902 case Sema::CXXDefaultConstructor:
5903 S.DefineImplicitDefaultConstructor(DefaultLoc,
5904 cast<CXXConstructorDecl>(MD));
5906 case Sema::CXXCopyConstructor:
5907 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5909 case Sema::CXXCopyAssignment:
5910 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5912 case Sema::CXXDestructor:
5913 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5915 case Sema::CXXMoveConstructor:
5916 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5918 case Sema::CXXMoveAssignment:
5919 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5921 case Sema::CXXInvalid:
5922 llvm_unreachable("Invalid special member.");
5926 /// Determine whether a type is permitted to be passed or returned in
5927 /// registers, per C++ [class.temporary]p3.
5928 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
5929 TargetInfo::CallingConvKind CCK) {
5930 if (D->isDependentType() || D->isInvalidDecl())
5933 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
5934 // The PS4 platform ABI follows the behavior of Clang 3.2.
5935 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
5936 return !D->hasNonTrivialDestructorForCall() &&
5937 !D->hasNonTrivialCopyConstructorForCall();
5939 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
5940 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
5941 bool DtorIsTrivialForCall = false;
5943 // If a class has at least one non-deleted, trivial copy constructor, it
5944 // is passed according to the C ABI. Otherwise, it is passed indirectly.
5946 // Note: This permits classes with non-trivial copy or move ctors to be
5947 // passed in registers, so long as they *also* have a trivial copy ctor,
5948 // which is non-conforming.
5949 if (D->needsImplicitCopyConstructor()) {
5950 if (!D->defaultedCopyConstructorIsDeleted()) {
5951 if (D->hasTrivialCopyConstructor())
5952 CopyCtorIsTrivial = true;
5953 if (D->hasTrivialCopyConstructorForCall())
5954 CopyCtorIsTrivialForCall = true;
5957 for (const CXXConstructorDecl *CD : D->ctors()) {
5958 if (CD->isCopyConstructor() && !CD->isDeleted()) {
5959 if (CD->isTrivial())
5960 CopyCtorIsTrivial = true;
5961 if (CD->isTrivialForCall())
5962 CopyCtorIsTrivialForCall = true;
5967 if (D->needsImplicitDestructor()) {
5968 if (!D->defaultedDestructorIsDeleted() &&
5969 D->hasTrivialDestructorForCall())
5970 DtorIsTrivialForCall = true;
5971 } else if (const auto *DD = D->getDestructor()) {
5972 if (!DD->isDeleted() && DD->isTrivialForCall())
5973 DtorIsTrivialForCall = true;
5976 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
5977 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
5980 // If a class has a destructor, we'd really like to pass it indirectly
5981 // because it allows us to elide copies. Unfortunately, MSVC makes that
5982 // impossible for small types, which it will pass in a single register or
5983 // stack slot. Most objects with dtors are large-ish, so handle that early.
5984 // We can't call out all large objects as being indirect because there are
5985 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
5986 // how we pass large POD types.
5988 // Note: This permits small classes with nontrivial destructors to be
5989 // passed in registers, which is non-conforming.
5990 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
5991 uint64_t TypeSize = isAArch64 ? 128 : 64;
5993 if (CopyCtorIsTrivial &&
5994 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
5999 // Per C++ [class.temporary]p3, the relevant condition is:
6000 // each copy constructor, move constructor, and destructor of X is
6001 // either trivial or deleted, and X has at least one non-deleted copy
6002 // or move constructor
6003 bool HasNonDeletedCopyOrMove = false;
6005 if (D->needsImplicitCopyConstructor() &&
6006 !D->defaultedCopyConstructorIsDeleted()) {
6007 if (!D->hasTrivialCopyConstructorForCall())
6009 HasNonDeletedCopyOrMove = true;
6012 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6013 !D->defaultedMoveConstructorIsDeleted()) {
6014 if (!D->hasTrivialMoveConstructorForCall())
6016 HasNonDeletedCopyOrMove = true;
6019 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6020 !D->hasTrivialDestructorForCall())
6023 for (const CXXMethodDecl *MD : D->methods()) {
6024 if (MD->isDeleted())
6027 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6028 if (CD && CD->isCopyOrMoveConstructor())
6029 HasNonDeletedCopyOrMove = true;
6030 else if (!isa<CXXDestructorDecl>(MD))
6033 if (!MD->isTrivialForCall())
6037 return HasNonDeletedCopyOrMove;
6040 /// Perform semantic checks on a class definition that has been
6041 /// completing, introducing implicitly-declared members, checking for
6042 /// abstract types, etc.
6043 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
6047 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6048 AbstractUsageInfo Info(*this, Record);
6049 CheckAbstractClassUsage(Info, Record);
6052 // If this is not an aggregate type and has no user-declared constructor,
6053 // complain about any non-static data members of reference or const scalar
6054 // type, since they will never get initializers.
6055 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6056 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6057 !Record->isLambda()) {
6058 bool Complained = false;
6059 for (const auto *F : Record->fields()) {
6060 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6063 if (F->getType()->isReferenceType() ||
6064 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6066 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6067 << Record->getTagKind() << Record;
6071 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6072 << F->getType()->isReferenceType()
6073 << F->getDeclName();
6078 if (Record->getIdentifier()) {
6079 // C++ [class.mem]p13:
6080 // If T is the name of a class, then each of the following shall have a
6081 // name different from T:
6082 // - every member of every anonymous union that is a member of class T.
6084 // C++ [class.mem]p14:
6085 // In addition, if class T has a user-declared constructor (12.1), every
6086 // non-static data member of class T shall have a name different from T.
6087 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6088 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6090 NamedDecl *D = (*I)->getUnderlyingDecl();
6091 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6092 Record->hasUserDeclaredConstructor()) ||
6093 isa<IndirectFieldDecl>(D)) {
6094 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6095 << D->getDeclName();
6101 // Warn if the class has virtual methods but non-virtual public destructor.
6102 if (Record->isPolymorphic() && !Record->isDependentType()) {
6103 CXXDestructorDecl *dtor = Record->getDestructor();
6104 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6105 !Record->hasAttr<FinalAttr>())
6106 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6107 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6110 if (Record->isAbstract()) {
6111 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6112 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6113 << FA->isSpelledAsSealed();
6114 DiagnoseAbstractType(Record);
6118 // See if trivial_abi has to be dropped.
6119 if (Record->hasAttr<TrivialABIAttr>())
6120 checkIllFormedTrivialABIStruct(*Record);
6122 // Set HasTrivialSpecialMemberForCall if the record has attribute
6124 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6127 Record->setHasTrivialSpecialMemberForCall();
6129 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6130 // Check whether the explicitly-defaulted special members are valid.
6131 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
6132 CheckExplicitlyDefaultedSpecialMember(M);
6134 // For an explicitly defaulted or deleted special member, we defer
6135 // determining triviality until the class is complete. That time is now!
6136 CXXSpecialMember CSM = getSpecialMember(M);
6137 if (!M->isImplicit() && !M->isUserProvided()) {
6138 if (CSM != CXXInvalid) {
6139 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6140 // Inform the class that we've finished declaring this member.
6141 Record->finishedDefaultedOrDeletedMember(M);
6142 M->setTrivialForCall(
6144 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6145 Record->setTrivialForCallFlags(M);
6149 // Set triviality for the purpose of calls if this is a user-provided
6150 // copy/move constructor or destructor.
6151 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6152 CSM == CXXDestructor) && M->isUserProvided()) {
6153 M->setTrivialForCall(HasTrivialABI);
6154 Record->setTrivialForCallFlags(M);
6157 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6158 M->hasAttr<DLLExportAttr>()) {
6159 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6161 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6162 CSM == CXXDestructor))
6163 M->dropAttr<DLLExportAttr>();
6165 if (M->hasAttr<DLLExportAttr>()) {
6166 // Define after any fields with in-class initializers have been parsed.
6167 DelayedDllExportMemberFunctions.push_back(M);
6172 bool HasMethodWithOverrideControl = false,
6173 HasOverridingMethodWithoutOverrideControl = false;
6174 if (!Record->isDependentType()) {
6175 // Check the destructor before any other member function. We need to
6176 // determine whether it's trivial in order to determine whether the claas
6177 // type is a literal type, which is a prerequisite for determining whether
6178 // other special member functions are valid and whether they're implicitly
6180 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6181 CompleteMemberFunction(Dtor);
6183 for (auto *M : Record->methods()) {
6184 // See if a method overloads virtual methods in a base
6185 // class without overriding any.
6187 DiagnoseHiddenVirtualMethods(M);
6188 if (M->hasAttr<OverrideAttr>())
6189 HasMethodWithOverrideControl = true;
6190 else if (M->size_overridden_methods() > 0)
6191 HasOverridingMethodWithoutOverrideControl = true;
6193 if (!isa<CXXDestructorDecl>(M))
6194 CompleteMemberFunction(M);
6198 if (HasMethodWithOverrideControl &&
6199 HasOverridingMethodWithoutOverrideControl) {
6200 // At least one method has the 'override' control declared.
6201 // Diagnose all other overridden methods which do not have 'override' specified on them.
6202 for (auto *M : Record->methods())
6203 DiagnoseAbsenceOfOverrideControl(M);
6206 // ms_struct is a request to use the same ABI rules as MSVC. Check
6207 // whether this class uses any C++ features that are implemented
6208 // completely differently in MSVC, and if so, emit a diagnostic.
6209 // That diagnostic defaults to an error, but we allow projects to
6210 // map it down to a warning (or ignore it). It's a fairly common
6211 // practice among users of the ms_struct pragma to mass-annotate
6212 // headers, sweeping up a bunch of types that the project doesn't
6213 // really rely on MSVC-compatible layout for. We must therefore
6214 // support "ms_struct except for C++ stuff" as a secondary ABI.
6215 if (Record->isMsStruct(Context) &&
6216 (Record->isPolymorphic() || Record->getNumBases())) {
6217 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6220 checkClassLevelDLLAttribute(Record);
6221 checkClassLevelCodeSegAttribute(Record);
6223 bool ClangABICompat4 =
6224 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6225 TargetInfo::CallingConvKind CCK =
6226 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6227 bool CanPass = canPassInRegisters(*this, Record, CCK);
6229 // Do not change ArgPassingRestrictions if it has already been set to
6230 // APK_CanNeverPassInRegs.
6231 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6232 Record->setArgPassingRestrictions(CanPass
6233 ? RecordDecl::APK_CanPassInRegs
6234 : RecordDecl::APK_CannotPassInRegs);
6236 // If canPassInRegisters returns true despite the record having a non-trivial
6237 // destructor, the record is destructed in the callee. This happens only when
6238 // the record or one of its subobjects has a field annotated with trivial_abi
6239 // or a field qualified with ObjC __strong/__weak.
6240 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6241 Record->setParamDestroyedInCallee(true);
6242 else if (Record->hasNonTrivialDestructor())
6243 Record->setParamDestroyedInCallee(CanPass);
6245 if (getLangOpts().ForceEmitVTables) {
6246 // If we want to emit all the vtables, we need to mark it as used. This
6247 // is especially required for cases like vtable assumption loads.
6248 MarkVTableUsed(Record->getInnerLocStart(), Record);
6252 /// Look up the special member function that would be called by a special
6253 /// member function for a subobject of class type.
6255 /// \param Class The class type of the subobject.
6256 /// \param CSM The kind of special member function.
6257 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6258 /// \param ConstRHS True if this is a copy operation with a const object
6259 /// on its RHS, that is, if the argument to the outer special member
6260 /// function is 'const' and this is not a field marked 'mutable'.
6261 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
6262 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
6263 unsigned FieldQuals, bool ConstRHS) {
6264 unsigned LHSQuals = 0;
6265 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
6266 LHSQuals = FieldQuals;
6268 unsigned RHSQuals = FieldQuals;
6269 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
6272 RHSQuals |= Qualifiers::Const;
6274 return S.LookupSpecialMember(Class, CSM,
6275 RHSQuals & Qualifiers::Const,
6276 RHSQuals & Qualifiers::Volatile,
6278 LHSQuals & Qualifiers::Const,
6279 LHSQuals & Qualifiers::Volatile);
6282 class Sema::InheritedConstructorInfo {
6284 SourceLocation UseLoc;
6286 /// A mapping from the base classes through which the constructor was
6287 /// inherited to the using shadow declaration in that base class (or a null
6288 /// pointer if the constructor was declared in that base class).
6289 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
6293 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
6294 ConstructorUsingShadowDecl *Shadow)
6295 : S(S), UseLoc(UseLoc) {
6296 bool DiagnosedMultipleConstructedBases = false;
6297 CXXRecordDecl *ConstructedBase = nullptr;
6298 UsingDecl *ConstructedBaseUsing = nullptr;
6300 // Find the set of such base class subobjects and check that there's a
6301 // unique constructed subobject.
6302 for (auto *D : Shadow->redecls()) {
6303 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6304 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6305 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6307 InheritedFromBases.insert(
6308 std::make_pair(DNominatedBase->getCanonicalDecl(),
6309 DShadow->getNominatedBaseClassShadowDecl()));
6310 if (DShadow->constructsVirtualBase())
6311 InheritedFromBases.insert(
6312 std::make_pair(DConstructedBase->getCanonicalDecl(),
6313 DShadow->getConstructedBaseClassShadowDecl()));
6315 assert(DNominatedBase == DConstructedBase);
6317 // [class.inhctor.init]p2:
6318 // If the constructor was inherited from multiple base class subobjects
6319 // of type B, the program is ill-formed.
6320 if (!ConstructedBase) {
6321 ConstructedBase = DConstructedBase;
6322 ConstructedBaseUsing = D->getUsingDecl();
6323 } else if (ConstructedBase != DConstructedBase &&
6324 !Shadow->isInvalidDecl()) {
6325 if (!DiagnosedMultipleConstructedBases) {
6326 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6327 << Shadow->getTargetDecl();
6328 S.Diag(ConstructedBaseUsing->getLocation(),
6329 diag::note_ambiguous_inherited_constructor_using)
6331 DiagnosedMultipleConstructedBases = true;
6333 S.Diag(D->getUsingDecl()->getLocation(),
6334 diag::note_ambiguous_inherited_constructor_using)
6335 << DConstructedBase;
6339 if (DiagnosedMultipleConstructedBases)
6340 Shadow->setInvalidDecl();
6343 /// Find the constructor to use for inherited construction of a base class,
6344 /// and whether that base class constructor inherits the constructor from a
6345 /// virtual base class (in which case it won't actually invoke it).
6346 std::pair<CXXConstructorDecl *, bool>
6347 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6348 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6349 if (It == InheritedFromBases.end())
6350 return std::make_pair(nullptr, false);
6352 // This is an intermediary class.
6354 return std::make_pair(
6355 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6356 It->second->constructsVirtualBase());
6358 // This is the base class from which the constructor was inherited.
6359 return std::make_pair(Ctor, false);
6363 /// Is the special member function which would be selected to perform the
6364 /// specified operation on the specified class type a constexpr constructor?
6366 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6367 Sema::CXXSpecialMember CSM, unsigned Quals,
6369 CXXConstructorDecl *InheritedCtor = nullptr,
6370 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6371 // If we're inheriting a constructor, see if we need to call it for this base
6373 if (InheritedCtor) {
6374 assert(CSM == Sema::CXXDefaultConstructor);
6376 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6378 return BaseCtor->isConstexpr();
6381 if (CSM == Sema::CXXDefaultConstructor)
6382 return ClassDecl->hasConstexprDefaultConstructor();
6384 Sema::SpecialMemberOverloadResult SMOR =
6385 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6386 if (!SMOR.getMethod())
6387 // A constructor we wouldn't select can't be "involved in initializing"
6390 return SMOR.getMethod()->isConstexpr();
6393 /// Determine whether the specified special member function would be constexpr
6394 /// if it were implicitly defined.
6395 static bool defaultedSpecialMemberIsConstexpr(
6396 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6397 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6398 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6399 if (!S.getLangOpts().CPlusPlus11)
6402 // C++11 [dcl.constexpr]p4:
6403 // In the definition of a constexpr constructor [...]
6406 case Sema::CXXDefaultConstructor:
6409 // Since default constructor lookup is essentially trivial (and cannot
6410 // involve, for instance, template instantiation), we compute whether a
6411 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6413 // This is important for performance; we need to know whether the default
6414 // constructor is constexpr to determine whether the type is a literal type.
6415 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6417 case Sema::CXXCopyConstructor:
6418 case Sema::CXXMoveConstructor:
6419 // For copy or move constructors, we need to perform overload resolution.
6422 case Sema::CXXCopyAssignment:
6423 case Sema::CXXMoveAssignment:
6424 if (!S.getLangOpts().CPlusPlus14)
6426 // In C++1y, we need to perform overload resolution.
6430 case Sema::CXXDestructor:
6431 case Sema::CXXInvalid:
6435 // -- if the class is a non-empty union, or for each non-empty anonymous
6436 // union member of a non-union class, exactly one non-static data member
6437 // shall be initialized; [DR1359]
6439 // If we squint, this is guaranteed, since exactly one non-static data member
6440 // will be initialized (if the constructor isn't deleted), we just don't know
6442 if (Ctor && ClassDecl->isUnion())
6443 return CSM == Sema::CXXDefaultConstructor
6444 ? ClassDecl->hasInClassInitializer() ||
6445 !ClassDecl->hasVariantMembers()
6448 // -- the class shall not have any virtual base classes;
6449 if (Ctor && ClassDecl->getNumVBases())
6452 // C++1y [class.copy]p26:
6453 // -- [the class] is a literal type, and
6454 if (!Ctor && !ClassDecl->isLiteral())
6457 // -- every constructor involved in initializing [...] base class
6458 // sub-objects shall be a constexpr constructor;
6459 // -- the assignment operator selected to copy/move each direct base
6460 // class is a constexpr function, and
6461 for (const auto &B : ClassDecl->bases()) {
6462 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6463 if (!BaseType) continue;
6465 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6466 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6467 InheritedCtor, Inherited))
6471 // -- every constructor involved in initializing non-static data members
6472 // [...] shall be a constexpr constructor;
6473 // -- every non-static data member and base class sub-object shall be
6475 // -- for each non-static data member of X that is of class type (or array
6476 // thereof), the assignment operator selected to copy/move that member is
6477 // a constexpr function
6478 for (const auto *F : ClassDecl->fields()) {
6479 if (F->isInvalidDecl())
6481 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6483 QualType BaseType = S.Context.getBaseElementType(F->getType());
6484 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6485 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6486 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6487 BaseType.getCVRQualifiers(),
6488 ConstArg && !F->isMutable()))
6490 } else if (CSM == Sema::CXXDefaultConstructor) {
6495 // All OK, it's constexpr!
6499 static Sema::ImplicitExceptionSpecification
6500 ComputeDefaultedSpecialMemberExceptionSpec(
6501 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6502 Sema::InheritedConstructorInfo *ICI);
6504 static Sema::ImplicitExceptionSpecification
6505 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6506 auto CSM = S.getSpecialMember(MD);
6507 if (CSM != Sema::CXXInvalid)
6508 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6510 auto *CD = cast<CXXConstructorDecl>(MD);
6511 assert(CD->getInheritedConstructor() &&
6512 "only special members have implicit exception specs");
6513 Sema::InheritedConstructorInfo ICI(
6514 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6515 return ComputeDefaultedSpecialMemberExceptionSpec(
6516 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6519 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6520 CXXMethodDecl *MD) {
6521 FunctionProtoType::ExtProtoInfo EPI;
6523 // Build an exception specification pointing back at this member.
6524 EPI.ExceptionSpec.Type = EST_Unevaluated;
6525 EPI.ExceptionSpec.SourceDecl = MD;
6527 // Set the calling convention to the default for C++ instance methods.
6528 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6529 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6530 /*IsCXXMethod=*/true));
6534 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6535 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6536 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6539 // Evaluate the exception specification.
6540 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6541 auto ESI = IES.getExceptionSpec();
6543 // Update the type of the special member to use it.
6544 UpdateExceptionSpec(MD, ESI);
6546 // A user-provided destructor can be defined outside the class. When that
6547 // happens, be sure to update the exception specification on both
6549 const FunctionProtoType *CanonicalFPT =
6550 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6551 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6552 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6555 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6556 CXXRecordDecl *RD = MD->getParent();
6557 CXXSpecialMember CSM = getSpecialMember(MD);
6559 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6560 "not an explicitly-defaulted special member");
6562 // Whether this was the first-declared instance of the constructor.
6563 // This affects whether we implicitly add an exception spec and constexpr.
6564 bool First = MD == MD->getCanonicalDecl();
6566 bool HadError = false;
6568 // C++11 [dcl.fct.def.default]p1:
6569 // A function that is explicitly defaulted shall
6570 // -- be a special member function (checked elsewhere),
6571 // -- have the same type (except for ref-qualifiers, and except that a
6572 // copy operation can take a non-const reference) as an implicit
6574 // -- not have default arguments.
6575 // C++2a changes the second bullet to instead delete the function if it's
6576 // defaulted on its first declaration, unless it's "an assignment operator,
6577 // and its return type differs or its parameter type is not a reference".
6578 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First;
6579 bool ShouldDeleteForTypeMismatch = false;
6580 unsigned ExpectedParams = 1;
6581 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6583 if (MD->getNumParams() != ExpectedParams) {
6584 // This checks for default arguments: a copy or move constructor with a
6585 // default argument is classified as a default constructor, and assignment
6586 // operations and destructors can't have default arguments.
6587 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6588 << CSM << MD->getSourceRange();
6590 } else if (MD->isVariadic()) {
6591 if (DeleteOnTypeMismatch)
6592 ShouldDeleteForTypeMismatch = true;
6594 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6595 << CSM << MD->getSourceRange();
6600 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6602 bool CanHaveConstParam = false;
6603 if (CSM == CXXCopyConstructor)
6604 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6605 else if (CSM == CXXCopyAssignment)
6606 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6608 QualType ReturnType = Context.VoidTy;
6609 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6610 // Check for return type matching.
6611 ReturnType = Type->getReturnType();
6613 QualType DeclType = Context.getTypeDeclType(RD);
6614 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
6615 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
6617 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6618 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6619 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6623 // A defaulted special member cannot have cv-qualifiers.
6624 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
6625 if (DeleteOnTypeMismatch)
6626 ShouldDeleteForTypeMismatch = true;
6628 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6629 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6635 // Check for parameter type matching.
6636 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6637 bool HasConstParam = false;
6638 if (ExpectedParams && ArgType->isReferenceType()) {
6639 // Argument must be reference to possibly-const T.
6640 QualType ReferentType = ArgType->getPointeeType();
6641 HasConstParam = ReferentType.isConstQualified();
6643 if (ReferentType.isVolatileQualified()) {
6644 if (DeleteOnTypeMismatch)
6645 ShouldDeleteForTypeMismatch = true;
6647 Diag(MD->getLocation(),
6648 diag::err_defaulted_special_member_volatile_param) << CSM;
6653 if (HasConstParam && !CanHaveConstParam) {
6654 if (DeleteOnTypeMismatch)
6655 ShouldDeleteForTypeMismatch = true;
6656 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6657 Diag(MD->getLocation(),
6658 diag::err_defaulted_special_member_copy_const_param)
6659 << (CSM == CXXCopyAssignment);
6660 // FIXME: Explain why this special member can't be const.
6663 Diag(MD->getLocation(),
6664 diag::err_defaulted_special_member_move_const_param)
6665 << (CSM == CXXMoveAssignment);
6669 } else if (ExpectedParams) {
6670 // A copy assignment operator can take its argument by value, but a
6671 // defaulted one cannot.
6672 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6673 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6677 // C++11 [dcl.fct.def.default]p2:
6678 // An explicitly-defaulted function may be declared constexpr only if it
6679 // would have been implicitly declared as constexpr,
6680 // Do not apply this rule to members of class templates, since core issue 1358
6681 // makes such functions always instantiate to constexpr functions. For
6682 // functions which cannot be constexpr (for non-constructors in C++11 and for
6683 // destructors in C++1y), this is checked elsewhere.
6685 // FIXME: This should not apply if the member is deleted.
6686 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6688 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6689 : isa<CXXConstructorDecl>(MD)) &&
6690 MD->isConstexpr() && !Constexpr &&
6691 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6692 Diag(MD->getBeginLoc(), MD->isConsteval()
6693 ? diag::err_incorrect_defaulted_consteval
6694 : diag::err_incorrect_defaulted_constexpr)
6696 // FIXME: Explain why the special member can't be constexpr.
6701 // C++2a [dcl.fct.def.default]p3:
6702 // If a function is explicitly defaulted on its first declaration, it is
6703 // implicitly considered to be constexpr if the implicit declaration
6705 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified);
6707 if (!Type->hasExceptionSpec()) {
6708 // C++2a [except.spec]p3:
6709 // If a declaration of a function does not have a noexcept-specifier
6710 // [and] is defaulted on its first declaration, [...] the exception
6711 // specification is as specified below
6712 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6713 EPI.ExceptionSpec.Type = EST_Unevaluated;
6714 EPI.ExceptionSpec.SourceDecl = MD;
6715 MD->setType(Context.getFunctionType(ReturnType,
6716 llvm::makeArrayRef(&ArgType,
6722 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
6724 SetDeclDeleted(MD, MD->getLocation());
6725 if (!inTemplateInstantiation() && !HadError) {
6726 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
6727 if (ShouldDeleteForTypeMismatch) {
6728 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
6730 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6733 if (ShouldDeleteForTypeMismatch && !HadError) {
6734 Diag(MD->getLocation(),
6735 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
6738 // C++11 [dcl.fct.def.default]p4:
6739 // [For a] user-provided explicitly-defaulted function [...] if such a
6740 // function is implicitly defined as deleted, the program is ill-formed.
6741 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6742 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
6743 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6749 MD->setInvalidDecl();
6752 void Sema::CheckDelayedMemberExceptionSpecs() {
6753 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
6754 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
6756 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
6757 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
6759 // Perform any deferred checking of exception specifications for virtual
6761 for (auto &Check : Overriding)
6762 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6764 // Perform any deferred checking of exception specifications for befriended
6766 for (auto &Check : Equivalent)
6767 CheckEquivalentExceptionSpec(Check.second, Check.first);
6771 /// CRTP base class for visiting operations performed by a special member
6772 /// function (or inherited constructor).
6773 template<typename Derived>
6774 struct SpecialMemberVisitor {
6777 Sema::CXXSpecialMember CSM;
6778 Sema::InheritedConstructorInfo *ICI;
6780 // Properties of the special member, computed for convenience.
6781 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6783 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6784 Sema::InheritedConstructorInfo *ICI)
6785 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6787 case Sema::CXXDefaultConstructor:
6788 case Sema::CXXCopyConstructor:
6789 case Sema::CXXMoveConstructor:
6790 IsConstructor = true;
6792 case Sema::CXXCopyAssignment:
6793 case Sema::CXXMoveAssignment:
6794 IsAssignment = true;
6796 case Sema::CXXDestructor:
6798 case Sema::CXXInvalid:
6799 llvm_unreachable("invalid special member kind");
6802 if (MD->getNumParams()) {
6803 if (const ReferenceType *RT =
6804 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6805 ConstArg = RT->getPointeeType().isConstQualified();
6809 Derived &getDerived() { return static_cast<Derived&>(*this); }
6811 /// Is this a "move" special member?
6812 bool isMove() const {
6813 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6816 /// Look up the corresponding special member in the given class.
6817 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6818 unsigned Quals, bool IsMutable) {
6819 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6820 ConstArg && !IsMutable);
6823 /// Look up the constructor for the specified base class to see if it's
6824 /// overridden due to this being an inherited constructor.
6825 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6828 assert(CSM == Sema::CXXDefaultConstructor);
6830 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6831 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6836 /// A base or member subobject.
6837 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6839 /// Get the location to use for a subobject in diagnostics.
6840 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6841 // FIXME: For an indirect virtual base, the direct base leading to
6842 // the indirect virtual base would be a more useful choice.
6843 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6844 return B->getBaseTypeLoc();
6846 return Subobj.get<FieldDecl*>()->getLocation();
6850 /// Visit all non-virtual (direct) bases.
6851 VisitNonVirtualBases,
6852 /// Visit all direct bases, virtual or not.
6854 /// Visit all non-virtual bases, and all virtual bases if the class
6855 /// is not abstract.
6856 VisitPotentiallyConstructedBases,
6857 /// Visit all direct or virtual bases.
6861 // Visit the bases and members of the class.
6862 bool visit(BasesToVisit Bases) {
6863 CXXRecordDecl *RD = MD->getParent();
6865 if (Bases == VisitPotentiallyConstructedBases)
6866 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6868 for (auto &B : RD->bases())
6869 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6870 getDerived().visitBase(&B))
6873 if (Bases == VisitAllBases)
6874 for (auto &B : RD->vbases())
6875 if (getDerived().visitBase(&B))
6878 for (auto *F : RD->fields())
6879 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6880 getDerived().visitField(F))
6889 struct SpecialMemberDeletionInfo
6890 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6895 bool AllFieldsAreConst;
6897 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6898 Sema::CXXSpecialMember CSM,
6899 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6900 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6901 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6903 bool inUnion() const { return MD->getParent()->isUnion(); }
6905 Sema::CXXSpecialMember getEffectiveCSM() {
6906 return ICI ? Sema::CXXInvalid : CSM;
6909 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
6911 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6912 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6914 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6915 bool shouldDeleteForField(FieldDecl *FD);
6916 bool shouldDeleteForAllConstMembers();
6918 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6920 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6921 Sema::SpecialMemberOverloadResult SMOR,
6922 bool IsDtorCallInCtor);
6924 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6928 /// Is the given special member inaccessible when used on the given
6930 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6931 CXXMethodDecl *target) {
6932 /// If we're operating on a base class, the object type is the
6933 /// type of this special member.
6935 AccessSpecifier access = target->getAccess();
6936 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6937 objectTy = S.Context.getTypeDeclType(MD->getParent());
6938 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6940 // If we're operating on a field, the object type is the type of the field.
6942 objectTy = S.Context.getTypeDeclType(target->getParent());
6945 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6948 /// Check whether we should delete a special member due to the implicit
6949 /// definition containing a call to a special member of a subobject.
6950 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6951 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6952 bool IsDtorCallInCtor) {
6953 CXXMethodDecl *Decl = SMOR.getMethod();
6954 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6958 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6959 DiagKind = !Decl ? 0 : 1;
6960 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6962 else if (!isAccessible(Subobj, Decl))
6964 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6965 !Decl->isTrivial()) {
6966 // A member of a union must have a trivial corresponding special member.
6967 // As a weird special case, a destructor call from a union's constructor
6968 // must be accessible and non-deleted, but need not be trivial. Such a
6969 // destructor is never actually called, but is semantically checked as
6979 S.Diag(Field->getLocation(),
6980 diag::note_deleted_special_member_class_subobject)
6981 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6982 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
6984 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6985 S.Diag(Base->getBeginLoc(),
6986 diag::note_deleted_special_member_class_subobject)
6987 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
6988 << Base->getType() << DiagKind << IsDtorCallInCtor
6989 << /*IsObjCPtr*/false;
6993 S.NoteDeletedFunction(Decl);
6994 // FIXME: Explain inaccessibility if DiagKind == 3.
7000 /// Check whether we should delete a special member function due to having a
7001 /// direct or virtual base class or non-static data member of class type M.
7002 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
7003 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
7004 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
7005 bool IsMutable = Field && Field->isMutable();
7007 // C++11 [class.ctor]p5:
7008 // -- any direct or virtual base class, or non-static data member with no
7009 // brace-or-equal-initializer, has class type M (or array thereof) and
7010 // either M has no default constructor or overload resolution as applied
7011 // to M's default constructor results in an ambiguity or in a function
7012 // that is deleted or inaccessible
7013 // C++11 [class.copy]p11, C++11 [class.copy]p23:
7014 // -- a direct or virtual base class B that cannot be copied/moved because
7015 // overload resolution, as applied to B's corresponding special member,
7016 // results in an ambiguity or a function that is deleted or inaccessible
7017 // from the defaulted special member
7018 // C++11 [class.dtor]p5:
7019 // -- any direct or virtual base class [...] has a type with a destructor
7020 // that is deleted or inaccessible
7021 if (!(CSM == Sema::CXXDefaultConstructor &&
7022 Field && Field->hasInClassInitializer()) &&
7023 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
7027 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
7028 // -- any direct or virtual base class or non-static data member has a
7029 // type with a destructor that is deleted or inaccessible
7030 if (IsConstructor) {
7031 Sema::SpecialMemberOverloadResult SMOR =
7032 S.LookupSpecialMember(Class, Sema::CXXDestructor,
7033 false, false, false, false, false);
7034 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
7041 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
7042 FieldDecl *FD, QualType FieldType) {
7043 // The defaulted special functions are defined as deleted if this is a variant
7044 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
7046 if (!FieldType.hasNonTrivialObjCLifetime())
7049 // Don't make the defaulted default constructor defined as deleted if the
7050 // member has an in-class initializer.
7051 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
7055 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
7056 S.Diag(FD->getLocation(),
7057 diag::note_deleted_special_member_class_subobject)
7058 << getEffectiveCSM() << ParentClass << /*IsField*/true
7059 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
7065 /// Check whether we should delete a special member function due to the class
7066 /// having a particular direct or virtual base class.
7067 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
7068 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
7069 // If program is correct, BaseClass cannot be null, but if it is, the error
7070 // must be reported elsewhere.
7073 // If we have an inheriting constructor, check whether we're calling an
7074 // inherited constructor instead of a default constructor.
7075 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
7076 if (auto *BaseCtor = SMOR.getMethod()) {
7077 // Note that we do not check access along this path; other than that,
7078 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
7079 // FIXME: Check that the base has a usable destructor! Sink this into
7080 // shouldDeleteForClassSubobject.
7081 if (BaseCtor->isDeleted() && Diagnose) {
7082 S.Diag(Base->getBeginLoc(),
7083 diag::note_deleted_special_member_class_subobject)
7084 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
7085 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
7086 << /*IsObjCPtr*/false;
7087 S.NoteDeletedFunction(BaseCtor);
7089 return BaseCtor->isDeleted();
7091 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
7094 /// Check whether we should delete a special member function due to the class
7095 /// having a particular non-static data member.
7096 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
7097 QualType FieldType = S.Context.getBaseElementType(FD->getType());
7098 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
7100 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
7103 if (CSM == Sema::CXXDefaultConstructor) {
7104 // For a default constructor, all references must be initialized in-class
7105 // and, if a union, it must have a non-const member.
7106 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
7108 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7109 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
7112 // C++11 [class.ctor]p5: any non-variant non-static data member of
7113 // const-qualified type (or array thereof) with no
7114 // brace-or-equal-initializer does not have a user-provided default
7116 if (!inUnion() && FieldType.isConstQualified() &&
7117 !FD->hasInClassInitializer() &&
7118 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
7120 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
7121 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
7125 if (inUnion() && !FieldType.isConstQualified())
7126 AllFieldsAreConst = false;
7127 } else if (CSM == Sema::CXXCopyConstructor) {
7128 // For a copy constructor, data members must not be of rvalue reference
7130 if (FieldType->isRValueReferenceType()) {
7132 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
7133 << MD->getParent() << FD << FieldType;
7136 } else if (IsAssignment) {
7137 // For an assignment operator, data members must not be of reference type.
7138 if (FieldType->isReferenceType()) {
7140 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7141 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
7144 if (!FieldRecord && FieldType.isConstQualified()) {
7145 // C++11 [class.copy]p23:
7146 // -- a non-static data member of const non-class type (or array thereof)
7148 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
7149 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
7155 // Some additional restrictions exist on the variant members.
7156 if (!inUnion() && FieldRecord->isUnion() &&
7157 FieldRecord->isAnonymousStructOrUnion()) {
7158 bool AllVariantFieldsAreConst = true;
7160 // FIXME: Handle anonymous unions declared within anonymous unions.
7161 for (auto *UI : FieldRecord->fields()) {
7162 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
7164 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
7167 if (!UnionFieldType.isConstQualified())
7168 AllVariantFieldsAreConst = false;
7170 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
7171 if (UnionFieldRecord &&
7172 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
7173 UnionFieldType.getCVRQualifiers()))
7177 // At least one member in each anonymous union must be non-const
7178 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
7179 !FieldRecord->field_empty()) {
7181 S.Diag(FieldRecord->getLocation(),
7182 diag::note_deleted_default_ctor_all_const)
7183 << !!ICI << MD->getParent() << /*anonymous union*/1;
7187 // Don't check the implicit member of the anonymous union type.
7188 // This is technically non-conformant, but sanity demands it.
7192 if (shouldDeleteForClassSubobject(FieldRecord, FD,
7193 FieldType.getCVRQualifiers()))
7200 /// C++11 [class.ctor] p5:
7201 /// A defaulted default constructor for a class X is defined as deleted if
7202 /// X is a union and all of its variant members are of const-qualified type.
7203 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
7204 // This is a silly definition, because it gives an empty union a deleted
7205 // default constructor. Don't do that.
7206 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
7207 bool AnyFields = false;
7208 for (auto *F : MD->getParent()->fields())
7209 if ((AnyFields = !F->isUnnamedBitfield()))
7214 S.Diag(MD->getParent()->getLocation(),
7215 diag::note_deleted_default_ctor_all_const)
7216 << !!ICI << MD->getParent() << /*not anonymous union*/0;
7222 /// Determine whether a defaulted special member function should be defined as
7223 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
7224 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
7225 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
7226 InheritedConstructorInfo *ICI,
7228 if (MD->isInvalidDecl())
7230 CXXRecordDecl *RD = MD->getParent();
7231 assert(!RD->isDependentType() && "do deletion after instantiation");
7232 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
7235 // C++11 [expr.lambda.prim]p19:
7236 // The closure type associated with a lambda-expression has a
7237 // deleted (8.4.3) default constructor and a deleted copy
7238 // assignment operator.
7239 // C++2a adds back these operators if the lambda has no lambda-capture.
7240 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
7241 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
7243 Diag(RD->getLocation(), diag::note_lambda_decl);
7247 // For an anonymous struct or union, the copy and assignment special members
7248 // will never be used, so skip the check. For an anonymous union declared at
7249 // namespace scope, the constructor and destructor are used.
7250 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
7251 RD->isAnonymousStructOrUnion())
7254 // C++11 [class.copy]p7, p18:
7255 // If the class definition declares a move constructor or move assignment
7256 // operator, an implicitly declared copy constructor or copy assignment
7257 // operator is defined as deleted.
7258 if (MD->isImplicit() &&
7259 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
7260 CXXMethodDecl *UserDeclaredMove = nullptr;
7262 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
7263 // deletion of the corresponding copy operation, not both copy operations.
7264 // MSVC 2015 has adopted the standards conforming behavior.
7265 bool DeletesOnlyMatchingCopy =
7266 getLangOpts().MSVCCompat &&
7267 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
7269 if (RD->hasUserDeclaredMoveConstructor() &&
7270 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
7271 if (!Diagnose) return true;
7273 // Find any user-declared move constructor.
7274 for (auto *I : RD->ctors()) {
7275 if (I->isMoveConstructor()) {
7276 UserDeclaredMove = I;
7280 assert(UserDeclaredMove);
7281 } else if (RD->hasUserDeclaredMoveAssignment() &&
7282 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
7283 if (!Diagnose) return true;
7285 // Find any user-declared move assignment operator.
7286 for (auto *I : RD->methods()) {
7287 if (I->isMoveAssignmentOperator()) {
7288 UserDeclaredMove = I;
7292 assert(UserDeclaredMove);
7295 if (UserDeclaredMove) {
7296 Diag(UserDeclaredMove->getLocation(),
7297 diag::note_deleted_copy_user_declared_move)
7298 << (CSM == CXXCopyAssignment) << RD
7299 << UserDeclaredMove->isMoveAssignmentOperator();
7304 // Do access control from the special member function
7305 ContextRAII MethodContext(*this, MD);
7307 // C++11 [class.dtor]p5:
7308 // -- for a virtual destructor, lookup of the non-array deallocation function
7309 // results in an ambiguity or in a function that is deleted or inaccessible
7310 if (CSM == CXXDestructor && MD->isVirtual()) {
7311 FunctionDecl *OperatorDelete = nullptr;
7312 DeclarationName Name =
7313 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
7314 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
7315 OperatorDelete, /*Diagnose*/false)) {
7317 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
7322 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
7324 // Per DR1611, do not consider virtual bases of constructors of abstract
7325 // classes, since we are not going to construct them.
7326 // Per DR1658, do not consider virtual bases of destructors of abstract
7328 // Per DR2180, for assignment operators we only assign (and thus only
7329 // consider) direct bases.
7330 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
7331 : SMI.VisitPotentiallyConstructedBases))
7334 if (SMI.shouldDeleteForAllConstMembers())
7337 if (getLangOpts().CUDA) {
7338 // We should delete the special member in CUDA mode if target inference
7340 // For inherited constructors (non-null ICI), CSM may be passed so that MD
7341 // is treated as certain special member, which may not reflect what special
7342 // member MD really is. However inferCUDATargetForImplicitSpecialMember
7343 // expects CSM to match MD, therefore recalculate CSM.
7344 assert(ICI || CSM == getSpecialMember(MD));
7347 RealCSM = getSpecialMember(MD);
7349 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
7350 SMI.ConstArg, Diagnose);
7356 /// Perform lookup for a special member of the specified kind, and determine
7357 /// whether it is trivial. If the triviality can be determined without the
7358 /// lookup, skip it. This is intended for use when determining whether a
7359 /// special member of a containing object is trivial, and thus does not ever
7360 /// perform overload resolution for default constructors.
7362 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7363 /// member that was most likely to be intended to be trivial, if any.
7365 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
7366 /// determine whether the special member is trivial.
7367 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7368 Sema::CXXSpecialMember CSM, unsigned Quals,
7370 Sema::TrivialABIHandling TAH,
7371 CXXMethodDecl **Selected) {
7373 *Selected = nullptr;
7376 case Sema::CXXInvalid:
7377 llvm_unreachable("not a special member");
7379 case Sema::CXXDefaultConstructor:
7380 // C++11 [class.ctor]p5:
7381 // A default constructor is trivial if:
7382 // - all the [direct subobjects] have trivial default constructors
7384 // Note, no overload resolution is performed in this case.
7385 if (RD->hasTrivialDefaultConstructor())
7389 // If there's a default constructor which could have been trivial, dig it
7390 // out. Otherwise, if there's any user-provided default constructor, point
7391 // to that as an example of why there's not a trivial one.
7392 CXXConstructorDecl *DefCtor = nullptr;
7393 if (RD->needsImplicitDefaultConstructor())
7394 S.DeclareImplicitDefaultConstructor(RD);
7395 for (auto *CI : RD->ctors()) {
7396 if (!CI->isDefaultConstructor())
7399 if (!DefCtor->isUserProvided())
7403 *Selected = DefCtor;
7408 case Sema::CXXDestructor:
7409 // C++11 [class.dtor]p5:
7410 // A destructor is trivial if:
7411 // - all the direct [subobjects] have trivial destructors
7412 if (RD->hasTrivialDestructor() ||
7413 (TAH == Sema::TAH_ConsiderTrivialABI &&
7414 RD->hasTrivialDestructorForCall()))
7418 if (RD->needsImplicitDestructor())
7419 S.DeclareImplicitDestructor(RD);
7420 *Selected = RD->getDestructor();
7425 case Sema::CXXCopyConstructor:
7426 // C++11 [class.copy]p12:
7427 // A copy constructor is trivial if:
7428 // - the constructor selected to copy each direct [subobject] is trivial
7429 if (RD->hasTrivialCopyConstructor() ||
7430 (TAH == Sema::TAH_ConsiderTrivialABI &&
7431 RD->hasTrivialCopyConstructorForCall())) {
7432 if (Quals == Qualifiers::Const)
7433 // We must either select the trivial copy constructor or reach an
7434 // ambiguity; no need to actually perform overload resolution.
7436 } else if (!Selected) {
7439 // In C++98, we are not supposed to perform overload resolution here, but we
7440 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7441 // cases like B as having a non-trivial copy constructor:
7442 // struct A { template<typename T> A(T&); };
7443 // struct B { mutable A a; };
7444 goto NeedOverloadResolution;
7446 case Sema::CXXCopyAssignment:
7447 // C++11 [class.copy]p25:
7448 // A copy assignment operator is trivial if:
7449 // - the assignment operator selected to copy each direct [subobject] is
7451 if (RD->hasTrivialCopyAssignment()) {
7452 if (Quals == Qualifiers::Const)
7454 } else if (!Selected) {
7457 // In C++98, we are not supposed to perform overload resolution here, but we
7458 // treat that as a language defect.
7459 goto NeedOverloadResolution;
7461 case Sema::CXXMoveConstructor:
7462 case Sema::CXXMoveAssignment:
7463 NeedOverloadResolution:
7464 Sema::SpecialMemberOverloadResult SMOR =
7465 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7467 // The standard doesn't describe how to behave if the lookup is ambiguous.
7468 // We treat it as not making the member non-trivial, just like the standard
7469 // mandates for the default constructor. This should rarely matter, because
7470 // the member will also be deleted.
7471 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7474 if (!SMOR.getMethod()) {
7475 assert(SMOR.getKind() ==
7476 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7480 // We deliberately don't check if we found a deleted special member. We're
7483 *Selected = SMOR.getMethod();
7485 if (TAH == Sema::TAH_ConsiderTrivialABI &&
7486 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
7487 return SMOR.getMethod()->isTrivialForCall();
7488 return SMOR.getMethod()->isTrivial();
7491 llvm_unreachable("unknown special method kind");
7494 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7495 for (auto *CI : RD->ctors())
7496 if (!CI->isImplicit())
7499 // Look for constructor templates.
7500 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7501 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7502 if (CXXConstructorDecl *CD =
7503 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7510 /// The kind of subobject we are checking for triviality. The values of this
7511 /// enumeration are used in diagnostics.
7512 enum TrivialSubobjectKind {
7513 /// The subobject is a base class.
7515 /// The subobject is a non-static data member.
7517 /// The object is actually the complete object.
7521 /// Check whether the special member selected for a given type would be trivial.
7522 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7523 QualType SubType, bool ConstRHS,
7524 Sema::CXXSpecialMember CSM,
7525 TrivialSubobjectKind Kind,
7526 Sema::TrivialABIHandling TAH, bool Diagnose) {
7527 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7531 CXXMethodDecl *Selected;
7532 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7533 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
7540 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7541 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7542 << Kind << SubType.getUnqualifiedType();
7543 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7544 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7545 } else if (!Selected)
7546 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7547 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7548 else if (Selected->isUserProvided()) {
7549 if (Kind == TSK_CompleteObject)
7550 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7551 << Kind << SubType.getUnqualifiedType() << CSM;
7553 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7554 << Kind << SubType.getUnqualifiedType() << CSM;
7555 S.Diag(Selected->getLocation(), diag::note_declared_at);
7558 if (Kind != TSK_CompleteObject)
7559 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7560 << Kind << SubType.getUnqualifiedType() << CSM;
7562 // Explain why the defaulted or deleted special member isn't trivial.
7563 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
7571 /// Check whether the members of a class type allow a special member to be
7573 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7574 Sema::CXXSpecialMember CSM,
7576 Sema::TrivialABIHandling TAH,
7578 for (const auto *FI : RD->fields()) {
7579 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7582 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7584 // Pretend anonymous struct or union members are members of this class.
7585 if (FI->isAnonymousStructOrUnion()) {
7586 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7587 CSM, ConstArg, TAH, Diagnose))
7592 // C++11 [class.ctor]p5:
7593 // A default constructor is trivial if [...]
7594 // -- no non-static data member of its class has a
7595 // brace-or-equal-initializer
7596 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7598 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7602 // Objective C ARC 4.3.5:
7603 // [...] nontrivally ownership-qualified types are [...] not trivially
7604 // default constructible, copy constructible, move constructible, copy
7605 // assignable, move assignable, or destructible [...]
7606 if (FieldType.hasNonTrivialObjCLifetime()) {
7608 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7609 << RD << FieldType.getObjCLifetime();
7613 bool ConstRHS = ConstArg && !FI->isMutable();
7614 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7615 CSM, TSK_Field, TAH, Diagnose))
7622 /// Diagnose why the specified class does not have a trivial special member of
7624 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7625 QualType Ty = Context.getRecordType(RD);
7627 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7628 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7629 TSK_CompleteObject, TAH_IgnoreTrivialABI,
7633 /// Determine whether a defaulted or deleted special member function is trivial,
7634 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7635 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7636 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7637 TrivialABIHandling TAH, bool Diagnose) {
7638 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7640 CXXRecordDecl *RD = MD->getParent();
7642 bool ConstArg = false;
7644 // C++11 [class.copy]p12, p25: [DR1593]
7645 // A [special member] is trivial if [...] its parameter-type-list is
7646 // equivalent to the parameter-type-list of an implicit declaration [...]
7648 case CXXDefaultConstructor:
7650 // Trivial default constructors and destructors cannot have parameters.
7653 case CXXCopyConstructor:
7654 case CXXCopyAssignment: {
7655 // Trivial copy operations always have const, non-volatile parameter types.
7657 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7658 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7659 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7661 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7662 << Param0->getSourceRange() << Param0->getType()
7663 << Context.getLValueReferenceType(
7664 Context.getRecordType(RD).withConst());
7670 case CXXMoveConstructor:
7671 case CXXMoveAssignment: {
7672 // Trivial move operations always have non-cv-qualified parameters.
7673 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7674 const RValueReferenceType *RT =
7675 Param0->getType()->getAs<RValueReferenceType>();
7676 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7678 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7679 << Param0->getSourceRange() << Param0->getType()
7680 << Context.getRValueReferenceType(Context.getRecordType(RD));
7687 llvm_unreachable("not a special member");
7690 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7692 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7693 diag::note_nontrivial_default_arg)
7694 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7697 if (MD->isVariadic()) {
7699 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7703 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7704 // A copy/move [constructor or assignment operator] is trivial if
7705 // -- the [member] selected to copy/move each direct base class subobject
7708 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7709 // A [default constructor or destructor] is trivial if
7710 // -- all the direct base classes have trivial [default constructors or
7712 for (const auto &BI : RD->bases())
7713 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
7714 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
7717 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7718 // A copy/move [constructor or assignment operator] for a class X is
7720 // -- for each non-static data member of X that is of class type (or array
7721 // thereof), the constructor selected to copy/move that member is
7724 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7725 // A [default constructor or destructor] is trivial if
7726 // -- for all of the non-static data members of its class that are of class
7727 // type (or array thereof), each such class has a trivial [default
7728 // constructor or destructor]
7729 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
7732 // C++11 [class.dtor]p5:
7733 // A destructor is trivial if [...]
7734 // -- the destructor is not virtual
7735 if (CSM == CXXDestructor && MD->isVirtual()) {
7737 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7741 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7742 // A [special member] for class X is trivial if [...]
7743 // -- class X has no virtual functions and no virtual base classes
7744 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7748 if (RD->getNumVBases()) {
7749 // Check for virtual bases. We already know that the corresponding
7750 // member in all bases is trivial, so vbases must all be direct.
7751 CXXBaseSpecifier &BS = *RD->vbases_begin();
7752 assert(BS.isVirtual());
7753 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
7757 // Must have a virtual method.
7758 for (const auto *MI : RD->methods()) {
7759 if (MI->isVirtual()) {
7760 SourceLocation MLoc = MI->getBeginLoc();
7761 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7766 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7769 // Looks like it's trivial!
7774 struct FindHiddenVirtualMethod {
7776 CXXMethodDecl *Method;
7777 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7778 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7781 /// Check whether any most overridden method from MD in Methods
7782 static bool CheckMostOverridenMethods(
7783 const CXXMethodDecl *MD,
7784 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7785 if (MD->size_overridden_methods() == 0)
7786 return Methods.count(MD->getCanonicalDecl());
7787 for (const CXXMethodDecl *O : MD->overridden_methods())
7788 if (CheckMostOverridenMethods(O, Methods))
7794 /// Member lookup function that determines whether a given C++
7795 /// method overloads virtual methods in a base class without overriding any,
7796 /// to be used with CXXRecordDecl::lookupInBases().
7797 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7798 RecordDecl *BaseRecord =
7799 Specifier->getType()->getAs<RecordType>()->getDecl();
7801 DeclarationName Name = Method->getDeclName();
7802 assert(Name.getNameKind() == DeclarationName::Identifier);
7804 bool foundSameNameMethod = false;
7805 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7806 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7807 Path.Decls = Path.Decls.slice(1)) {
7808 NamedDecl *D = Path.Decls.front();
7809 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7810 MD = MD->getCanonicalDecl();
7811 foundSameNameMethod = true;
7812 // Interested only in hidden virtual methods.
7813 if (!MD->isVirtual())
7815 // If the method we are checking overrides a method from its base
7816 // don't warn about the other overloaded methods. Clang deviates from
7817 // GCC by only diagnosing overloads of inherited virtual functions that
7818 // do not override any other virtual functions in the base. GCC's
7819 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7820 // function from a base class. These cases may be better served by a
7821 // warning (not specific to virtual functions) on call sites when the
7822 // call would select a different function from the base class, were it
7824 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7825 if (!S->IsOverload(Method, MD, false))
7827 // Collect the overload only if its hidden.
7828 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7829 overloadedMethods.push_back(MD);
7833 if (foundSameNameMethod)
7834 OverloadedMethods.append(overloadedMethods.begin(),
7835 overloadedMethods.end());
7836 return foundSameNameMethod;
7839 } // end anonymous namespace
7841 /// Add the most overriden methods from MD to Methods
7842 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7843 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7844 if (MD->size_overridden_methods() == 0)
7845 Methods.insert(MD->getCanonicalDecl());
7847 for (const CXXMethodDecl *O : MD->overridden_methods())
7848 AddMostOverridenMethods(O, Methods);
7851 /// Check if a method overloads virtual methods in a base class without
7853 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7854 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7855 if (!MD->getDeclName().isIdentifier())
7858 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7859 /*bool RecordPaths=*/false,
7860 /*bool DetectVirtual=*/false);
7861 FindHiddenVirtualMethod FHVM;
7865 // Keep the base methods that were overridden or introduced in the subclass
7866 // by 'using' in a set. A base method not in this set is hidden.
7867 CXXRecordDecl *DC = MD->getParent();
7868 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7869 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7871 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7872 ND = shad->getTargetDecl();
7873 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7874 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7877 if (DC->lookupInBases(FHVM, Paths))
7878 OverloadedMethods = FHVM.OverloadedMethods;
7881 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7882 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7883 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7884 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7885 PartialDiagnostic PD = PDiag(
7886 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7887 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7888 Diag(overloadedMD->getLocation(), PD);
7892 /// Diagnose methods which overload virtual methods in a base class
7893 /// without overriding any.
7894 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7895 if (MD->isInvalidDecl())
7898 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7901 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7902 FindHiddenVirtualMethods(MD, OverloadedMethods);
7903 if (!OverloadedMethods.empty()) {
7904 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7905 << MD << (OverloadedMethods.size() > 1);
7907 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7911 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
7912 auto PrintDiagAndRemoveAttr = [&]() {
7913 // No diagnostics if this is a template instantiation.
7914 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind()))
7915 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
7916 diag::ext_cannot_use_trivial_abi) << &RD;
7917 RD.dropAttr<TrivialABIAttr>();
7920 // Ill-formed if the struct has virtual functions.
7921 if (RD.isPolymorphic()) {
7922 PrintDiagAndRemoveAttr();
7926 for (const auto &B : RD.bases()) {
7927 // Ill-formed if the base class is non-trivial for the purpose of calls or a
7929 if ((!B.getType()->isDependentType() &&
7930 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) ||
7932 PrintDiagAndRemoveAttr();
7937 for (const auto *FD : RD.fields()) {
7938 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
7939 // non-trivial for the purpose of calls.
7940 QualType FT = FD->getType();
7941 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
7942 PrintDiagAndRemoveAttr();
7946 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
7947 if (!RT->isDependentType() &&
7948 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
7949 PrintDiagAndRemoveAttr();
7955 void Sema::ActOnFinishCXXMemberSpecification(
7956 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
7957 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
7961 AdjustDeclIfTemplate(TagDecl);
7963 for (const ParsedAttr &AL : AttrList) {
7964 if (AL.getKind() != ParsedAttr::AT_Visibility)
7967 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored)
7971 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7972 // strict aliasing violation!
7973 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7974 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7976 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl));
7979 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7980 /// special functions, such as the default constructor, copy
7981 /// constructor, or destructor, to the given C++ class (C++
7982 /// [special]p1). This routine can only be executed just before the
7983 /// definition of the class is complete.
7984 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7985 if (ClassDecl->needsImplicitDefaultConstructor()) {
7986 ++getASTContext().NumImplicitDefaultConstructors;
7988 if (ClassDecl->hasInheritedConstructor())
7989 DeclareImplicitDefaultConstructor(ClassDecl);
7992 if (ClassDecl->needsImplicitCopyConstructor()) {
7993 ++getASTContext().NumImplicitCopyConstructors;
7995 // If the properties or semantics of the copy constructor couldn't be
7996 // determined while the class was being declared, force a declaration
7998 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7999 ClassDecl->hasInheritedConstructor())
8000 DeclareImplicitCopyConstructor(ClassDecl);
8001 // For the MS ABI we need to know whether the copy ctor is deleted. A
8002 // prerequisite for deleting the implicit copy ctor is that the class has a
8003 // move ctor or move assignment that is either user-declared or whose
8004 // semantics are inherited from a subobject. FIXME: We should provide a more
8005 // direct way for CodeGen to ask whether the constructor was deleted.
8006 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8007 (ClassDecl->hasUserDeclaredMoveConstructor() ||
8008 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8009 ClassDecl->hasUserDeclaredMoveAssignment() ||
8010 ClassDecl->needsOverloadResolutionForMoveAssignment()))
8011 DeclareImplicitCopyConstructor(ClassDecl);
8014 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
8015 ++getASTContext().NumImplicitMoveConstructors;
8017 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
8018 ClassDecl->hasInheritedConstructor())
8019 DeclareImplicitMoveConstructor(ClassDecl);
8022 if (ClassDecl->needsImplicitCopyAssignment()) {
8023 ++getASTContext().NumImplicitCopyAssignmentOperators;
8025 // If we have a dynamic class, then the copy assignment operator may be
8026 // virtual, so we have to declare it immediately. This ensures that, e.g.,
8027 // it shows up in the right place in the vtable and that we diagnose
8028 // problems with the implicit exception specification.
8029 if (ClassDecl->isDynamicClass() ||
8030 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
8031 ClassDecl->hasInheritedAssignment())
8032 DeclareImplicitCopyAssignment(ClassDecl);
8035 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
8036 ++getASTContext().NumImplicitMoveAssignmentOperators;
8038 // Likewise for the move assignment operator.
8039 if (ClassDecl->isDynamicClass() ||
8040 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
8041 ClassDecl->hasInheritedAssignment())
8042 DeclareImplicitMoveAssignment(ClassDecl);
8045 if (ClassDecl->needsImplicitDestructor()) {
8046 ++getASTContext().NumImplicitDestructors;
8048 // If we have a dynamic class, then the destructor may be virtual, so we
8049 // have to declare the destructor immediately. This ensures that, e.g., it
8050 // shows up in the right place in the vtable and that we diagnose problems
8051 // with the implicit exception specification.
8052 if (ClassDecl->isDynamicClass() ||
8053 ClassDecl->needsOverloadResolutionForDestructor())
8054 DeclareImplicitDestructor(ClassDecl);
8058 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
8062 // The order of template parameters is not important here. All names
8063 // get added to the same scope.
8064 SmallVector<TemplateParameterList *, 4> ParameterLists;
8066 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
8067 D = TD->getTemplatedDecl();
8069 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
8070 ParameterLists.push_back(PSD->getTemplateParameters());
8072 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
8073 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
8074 ParameterLists.push_back(DD->getTemplateParameterList(i));
8076 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8077 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
8078 ParameterLists.push_back(FTD->getTemplateParameters());
8082 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
8083 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
8084 ParameterLists.push_back(TD->getTemplateParameterList(i));
8086 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
8087 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
8088 ParameterLists.push_back(CTD->getTemplateParameters());
8093 for (TemplateParameterList *Params : ParameterLists) {
8094 if (Params->size() > 0)
8095 // Ignore explicit specializations; they don't contribute to the template
8098 for (NamedDecl *Param : *Params) {
8099 if (Param->getDeclName()) {
8101 IdResolver.AddDecl(Param);
8109 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8110 if (!RecordD) return;
8111 AdjustDeclIfTemplate(RecordD);
8112 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
8113 PushDeclContext(S, Record);
8116 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
8117 if (!RecordD) return;
8121 /// This is used to implement the constant expression evaluation part of the
8122 /// attribute enable_if extension. There is nothing in standard C++ which would
8123 /// require reentering parameters.
8124 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
8129 if (Param->getDeclName())
8130 IdResolver.AddDecl(Param);
8133 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
8134 /// parsing a top-level (non-nested) C++ class, and we are now
8135 /// parsing those parts of the given Method declaration that could
8136 /// not be parsed earlier (C++ [class.mem]p2), such as default
8137 /// arguments. This action should enter the scope of the given
8138 /// Method declaration as if we had just parsed the qualified method
8139 /// name. However, it should not bring the parameters into scope;
8140 /// that will be performed by ActOnDelayedCXXMethodParameter.
8141 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8144 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
8145 /// C++ method declaration. We're (re-)introducing the given
8146 /// function parameter into scope for use in parsing later parts of
8147 /// the method declaration. For example, we could see an
8148 /// ActOnParamDefaultArgument event for this parameter.
8149 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
8153 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
8155 // If this parameter has an unparsed default argument, clear it out
8156 // to make way for the parsed default argument.
8157 if (Param->hasUnparsedDefaultArg())
8158 Param->setDefaultArg(nullptr);
8161 if (Param->getDeclName())
8162 IdResolver.AddDecl(Param);
8165 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
8166 /// processing the delayed method declaration for Method. The method
8167 /// declaration is now considered finished. There may be a separate
8168 /// ActOnStartOfFunctionDef action later (not necessarily
8169 /// immediately!) for this method, if it was also defined inside the
8171 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
8175 AdjustDeclIfTemplate(MethodD);
8177 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
8179 // Now that we have our default arguments, check the constructor
8180 // again. It could produce additional diagnostics or affect whether
8181 // the class has implicitly-declared destructors, among other
8183 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
8184 CheckConstructor(Constructor);
8186 // Check the default arguments, which we may have added.
8187 if (!Method->isInvalidDecl())
8188 CheckCXXDefaultArguments(Method);
8191 // Emit the given diagnostic for each non-address-space qualifier.
8192 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
8193 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
8194 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8195 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
8196 bool DiagOccured = false;
8197 FTI.MethodQualifiers->forEachQualifier(
8198 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
8199 SourceLocation SL) {
8200 // This diagnostic should be emitted on any qualifier except an addr
8201 // space qualifier. However, forEachQualifier currently doesn't visit
8202 // addr space qualifiers, so there's no way to write this condition
8203 // right now; we just diagnose on everything.
8204 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
8212 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
8213 /// the well-formedness of the constructor declarator @p D with type @p
8214 /// R. If there are any errors in the declarator, this routine will
8215 /// emit diagnostics and set the invalid bit to true. In any case, the type
8216 /// will be updated to reflect a well-formed type for the constructor and
8218 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
8220 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8222 // C++ [class.ctor]p3:
8223 // A constructor shall not be virtual (10.3) or static (9.4). A
8224 // constructor can be invoked for a const, volatile or const
8225 // volatile object. A constructor shall not be declared const,
8226 // volatile, or const volatile (9.3.2).
8228 if (!D.isInvalidType())
8229 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8230 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
8231 << SourceRange(D.getIdentifierLoc());
8234 if (SC == SC_Static) {
8235 if (!D.isInvalidType())
8236 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
8237 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8238 << SourceRange(D.getIdentifierLoc());
8243 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8244 diagnoseIgnoredQualifiers(
8245 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
8246 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
8247 D.getDeclSpec().getRestrictSpecLoc(),
8248 D.getDeclSpec().getAtomicSpecLoc());
8252 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
8254 // C++0x [class.ctor]p4:
8255 // A constructor shall not be declared with a ref-qualifier.
8256 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8257 if (FTI.hasRefQualifier()) {
8258 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
8259 << FTI.RefQualifierIsLValueRef
8260 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8264 // Rebuild the function type "R" without any type qualifiers (in
8265 // case any of the errors above fired) and with "void" as the
8266 // return type, since constructors don't have return types.
8267 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8268 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
8271 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8272 EPI.TypeQuals = Qualifiers();
8273 EPI.RefQualifier = RQ_None;
8275 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
8278 /// CheckConstructor - Checks a fully-formed constructor for
8279 /// well-formedness, issuing any diagnostics required. Returns true if
8280 /// the constructor declarator is invalid.
8281 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
8282 CXXRecordDecl *ClassDecl
8283 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
8285 return Constructor->setInvalidDecl();
8287 // C++ [class.copy]p3:
8288 // A declaration of a constructor for a class X is ill-formed if
8289 // its first parameter is of type (optionally cv-qualified) X and
8290 // either there are no other parameters or else all other
8291 // parameters have default arguments.
8292 if (!Constructor->isInvalidDecl() &&
8293 ((Constructor->getNumParams() == 1) ||
8294 (Constructor->getNumParams() > 1 &&
8295 Constructor->getParamDecl(1)->hasDefaultArg())) &&
8296 Constructor->getTemplateSpecializationKind()
8297 != TSK_ImplicitInstantiation) {
8298 QualType ParamType = Constructor->getParamDecl(0)->getType();
8299 QualType ClassTy = Context.getTagDeclType(ClassDecl);
8300 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
8301 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
8302 const char *ConstRef
8303 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
8305 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
8306 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
8308 // FIXME: Rather that making the constructor invalid, we should endeavor
8310 Constructor->setInvalidDecl();
8315 /// CheckDestructor - Checks a fully-formed destructor definition for
8316 /// well-formedness, issuing any diagnostics required. Returns true
8318 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
8319 CXXRecordDecl *RD = Destructor->getParent();
8321 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
8324 if (!Destructor->isImplicit())
8325 Loc = Destructor->getLocation();
8327 Loc = RD->getLocation();
8329 // If we have a virtual destructor, look up the deallocation function
8330 if (FunctionDecl *OperatorDelete =
8331 FindDeallocationFunctionForDestructor(Loc, RD)) {
8332 Expr *ThisArg = nullptr;
8334 // If the notional 'delete this' expression requires a non-trivial
8335 // conversion from 'this' to the type of a destroying operator delete's
8336 // first parameter, perform that conversion now.
8337 if (OperatorDelete->isDestroyingOperatorDelete()) {
8338 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
8339 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
8340 // C++ [class.dtor]p13:
8341 // ... as if for the expression 'delete this' appearing in a
8342 // non-virtual destructor of the destructor's class.
8343 ContextRAII SwitchContext(*this, Destructor);
8345 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
8346 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
8347 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
8348 if (This.isInvalid()) {
8349 // FIXME: Register this as a context note so that it comes out
8350 // in the right order.
8351 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
8354 ThisArg = This.get();
8358 DiagnoseUseOfDecl(OperatorDelete, Loc);
8359 MarkFunctionReferenced(Loc, OperatorDelete);
8360 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
8367 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
8368 /// the well-formednes of the destructor declarator @p D with type @p
8369 /// R. If there are any errors in the declarator, this routine will
8370 /// emit diagnostics and set the declarator to invalid. Even if this happens,
8371 /// will be updated to reflect a well-formed type for the destructor and
8373 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
8375 // C++ [class.dtor]p1:
8376 // [...] A typedef-name that names a class is a class-name
8377 // (7.1.3); however, a typedef-name that names a class shall not
8378 // be used as the identifier in the declarator for a destructor
8380 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
8381 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
8382 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8383 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
8384 else if (const TemplateSpecializationType *TST =
8385 DeclaratorType->getAs<TemplateSpecializationType>())
8386 if (TST->isTypeAlias())
8387 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
8388 << DeclaratorType << 1;
8390 // C++ [class.dtor]p2:
8391 // A destructor is used to destroy objects of its class type. A
8392 // destructor takes no parameters, and no return type can be
8393 // specified for it (not even void). The address of a destructor
8394 // shall not be taken. A destructor shall not be static. A
8395 // destructor can be invoked for a const, volatile or const
8396 // volatile object. A destructor shall not be declared const,
8397 // volatile or const volatile (9.3.2).
8398 if (SC == SC_Static) {
8399 if (!D.isInvalidType())
8400 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
8401 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8402 << SourceRange(D.getIdentifierLoc())
8403 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8407 if (!D.isInvalidType()) {
8408 // Destructors don't have return types, but the parser will
8409 // happily parse something like:
8415 // The return type will be eliminated later.
8416 if (D.getDeclSpec().hasTypeSpecifier())
8417 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8418 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8419 << SourceRange(D.getIdentifierLoc());
8420 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8421 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8423 D.getDeclSpec().getConstSpecLoc(),
8424 D.getDeclSpec().getVolatileSpecLoc(),
8425 D.getDeclSpec().getRestrictSpecLoc(),
8426 D.getDeclSpec().getAtomicSpecLoc());
8431 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
8433 // C++0x [class.dtor]p2:
8434 // A destructor shall not be declared with a ref-qualifier.
8435 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8436 if (FTI.hasRefQualifier()) {
8437 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8438 << FTI.RefQualifierIsLValueRef
8439 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8443 // Make sure we don't have any parameters.
8444 if (FTIHasNonVoidParameters(FTI)) {
8445 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8447 // Delete the parameters.
8452 // Make sure the destructor isn't variadic.
8453 if (FTI.isVariadic) {
8454 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8458 // Rebuild the function type "R" without any type qualifiers or
8459 // parameters (in case any of the errors above fired) and with
8460 // "void" as the return type, since destructors don't have return
8462 if (!D.isInvalidType())
8465 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8466 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8467 EPI.Variadic = false;
8468 EPI.TypeQuals = Qualifiers();
8469 EPI.RefQualifier = RQ_None;
8470 return Context.getFunctionType(Context.VoidTy, None, EPI);
8473 static void extendLeft(SourceRange &R, SourceRange Before) {
8474 if (Before.isInvalid())
8476 R.setBegin(Before.getBegin());
8477 if (R.getEnd().isInvalid())
8478 R.setEnd(Before.getEnd());
8481 static void extendRight(SourceRange &R, SourceRange After) {
8482 if (After.isInvalid())
8484 if (R.getBegin().isInvalid())
8485 R.setBegin(After.getBegin());
8486 R.setEnd(After.getEnd());
8489 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8490 /// well-formednes of the conversion function declarator @p D with
8491 /// type @p R. If there are any errors in the declarator, this routine
8492 /// will emit diagnostics and return true. Otherwise, it will return
8493 /// false. Either way, the type @p R will be updated to reflect a
8494 /// well-formed type for the conversion operator.
8495 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8497 // C++ [class.conv.fct]p1:
8498 // Neither parameter types nor return type can be specified. The
8499 // type of a conversion function (8.3.5) is "function taking no
8500 // parameter returning conversion-type-id."
8501 if (SC == SC_Static) {
8502 if (!D.isInvalidType())
8503 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8504 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8505 << D.getName().getSourceRange();
8510 TypeSourceInfo *ConvTSI = nullptr;
8512 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8514 const DeclSpec &DS = D.getDeclSpec();
8515 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
8516 // Conversion functions don't have return types, but the parser will
8517 // happily parse something like:
8520 // float operator bool();
8523 // The return type will be changed later anyway.
8524 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8525 << SourceRange(DS.getTypeSpecTypeLoc())
8526 << SourceRange(D.getIdentifierLoc());
8528 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
8529 // It's also plausible that the user writes type qualifiers in the wrong
8531 // struct S { const operator int(); };
8532 // FIXME: we could provide a fixit to move the qualifiers onto the
8534 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
8535 << SourceRange(D.getIdentifierLoc()) << 0;
8539 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8541 // Make sure we don't have any parameters.
8542 if (Proto->getNumParams() > 0) {
8543 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8545 // Delete the parameters.
8546 D.getFunctionTypeInfo().freeParams();
8548 } else if (Proto->isVariadic()) {
8549 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8553 // Diagnose "&operator bool()" and other such nonsense. This
8554 // is actually a gcc extension which we don't support.
8555 if (Proto->getReturnType() != ConvType) {
8556 bool NeedsTypedef = false;
8557 SourceRange Before, After;
8559 // Walk the chunks and extract information on them for our diagnostic.
8560 bool PastFunctionChunk = false;
8561 for (auto &Chunk : D.type_objects()) {
8562 switch (Chunk.Kind) {
8563 case DeclaratorChunk::Function:
8564 if (!PastFunctionChunk) {
8565 if (Chunk.Fun.HasTrailingReturnType) {
8566 TypeSourceInfo *TRT = nullptr;
8567 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8568 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8570 PastFunctionChunk = true;
8574 case DeclaratorChunk::Array:
8575 NeedsTypedef = true;
8576 extendRight(After, Chunk.getSourceRange());
8579 case DeclaratorChunk::Pointer:
8580 case DeclaratorChunk::BlockPointer:
8581 case DeclaratorChunk::Reference:
8582 case DeclaratorChunk::MemberPointer:
8583 case DeclaratorChunk::Pipe:
8584 extendLeft(Before, Chunk.getSourceRange());
8587 case DeclaratorChunk::Paren:
8588 extendLeft(Before, Chunk.Loc);
8589 extendRight(After, Chunk.EndLoc);
8594 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8595 After.isValid() ? After.getBegin() :
8596 D.getIdentifierLoc();
8597 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8598 DB << Before << After;
8600 if (!NeedsTypedef) {
8601 DB << /*don't need a typedef*/0;
8603 // If we can provide a correct fix-it hint, do so.
8604 if (After.isInvalid() && ConvTSI) {
8605 SourceLocation InsertLoc =
8606 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
8607 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8608 << FixItHint::CreateInsertionFromRange(
8609 InsertLoc, CharSourceRange::getTokenRange(Before))
8610 << FixItHint::CreateRemoval(Before);
8612 } else if (!Proto->getReturnType()->isDependentType()) {
8613 DB << /*typedef*/1 << Proto->getReturnType();
8614 } else if (getLangOpts().CPlusPlus11) {
8615 DB << /*alias template*/2 << Proto->getReturnType();
8617 DB << /*might not be fixable*/3;
8620 // Recover by incorporating the other type chunks into the result type.
8621 // Note, this does *not* change the name of the function. This is compatible
8622 // with the GCC extension:
8623 // struct S { &operator int(); } s;
8624 // int &r = s.operator int(); // ok in GCC
8625 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8626 ConvType = Proto->getReturnType();
8629 // C++ [class.conv.fct]p4:
8630 // The conversion-type-id shall not represent a function type nor
8632 if (ConvType->isArrayType()) {
8633 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8634 ConvType = Context.getPointerType(ConvType);
8636 } else if (ConvType->isFunctionType()) {
8637 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8638 ConvType = Context.getPointerType(ConvType);
8642 // Rebuild the function type "R" without any parameters (in case any
8643 // of the errors above fired) and with the conversion type as the
8645 if (D.isInvalidType())
8646 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8648 // C++0x explicit conversion operators.
8649 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a)
8650 Diag(DS.getExplicitSpecLoc(),
8651 getLangOpts().CPlusPlus11
8652 ? diag::warn_cxx98_compat_explicit_conversion_functions
8653 : diag::ext_explicit_conversion_functions)
8654 << SourceRange(DS.getExplicitSpecRange());
8657 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8658 /// the declaration of the given C++ conversion function. This routine
8659 /// is responsible for recording the conversion function in the C++
8660 /// class, if possible.
8661 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8662 assert(Conversion && "Expected to receive a conversion function declaration");
8664 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8666 // Make sure we aren't redeclaring the conversion function.
8667 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8669 // C++ [class.conv.fct]p1:
8670 // [...] A conversion function is never used to convert a
8671 // (possibly cv-qualified) object to the (possibly cv-qualified)
8672 // same object type (or a reference to it), to a (possibly
8673 // cv-qualified) base class of that type (or a reference to it),
8674 // or to (possibly cv-qualified) void.
8675 // FIXME: Suppress this warning if the conversion function ends up being a
8676 // virtual function that overrides a virtual function in a base class.
8678 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8679 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8680 ConvType = ConvTypeRef->getPointeeType();
8681 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8682 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8683 /* Suppress diagnostics for instantiations. */;
8684 else if (ConvType->isRecordType()) {
8685 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8686 if (ConvType == ClassType)
8687 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8689 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8690 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8691 << ClassType << ConvType;
8692 } else if (ConvType->isVoidType()) {
8693 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8694 << ClassType << ConvType;
8697 if (FunctionTemplateDecl *ConversionTemplate
8698 = Conversion->getDescribedFunctionTemplate())
8699 return ConversionTemplate;
8705 /// Utility class to accumulate and print a diagnostic listing the invalid
8706 /// specifier(s) on a declaration.
8707 struct BadSpecifierDiagnoser {
8708 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8709 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8710 ~BadSpecifierDiagnoser() {
8711 Diagnostic << Specifiers;
8714 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8715 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8717 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8718 return check(SpecLoc,
8719 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8721 void check(SourceLocation SpecLoc, const char *Spec) {
8722 if (SpecLoc.isInvalid()) return;
8723 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8724 if (!Specifiers.empty()) Specifiers += " ";
8729 Sema::SemaDiagnosticBuilder Diagnostic;
8730 std::string Specifiers;
8734 /// Check the validity of a declarator that we parsed for a deduction-guide.
8735 /// These aren't actually declarators in the grammar, so we need to check that
8736 /// the user didn't specify any pieces that are not part of the deduction-guide
8738 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8740 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8741 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8742 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8744 // C++ [temp.deduct.guide]p3:
8745 // A deduction-gide shall be declared in the same scope as the
8746 // corresponding class template.
8747 if (!CurContext->getRedeclContext()->Equals(
8748 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8749 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8750 << GuidedTemplateDecl;
8751 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8754 auto &DS = D.getMutableDeclSpec();
8755 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8756 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8757 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8758 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
8759 BadSpecifierDiagnoser Diagnoser(
8760 *this, D.getIdentifierLoc(),
8761 diag::err_deduction_guide_invalid_specifier);
8763 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8764 DS.ClearStorageClassSpecs();
8767 // 'explicit' is permitted.
8768 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8769 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8770 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8771 DS.ClearConstexprSpec();
8773 Diagnoser.check(DS.getConstSpecLoc(), "const");
8774 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8775 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8776 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8777 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8778 DS.ClearTypeQualifiers();
8780 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8781 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8782 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8783 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8784 DS.ClearTypeSpecType();
8787 if (D.isInvalidType())
8790 // Check the declarator is simple enough.
8791 bool FoundFunction = false;
8792 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8793 if (Chunk.Kind == DeclaratorChunk::Paren)
8795 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8796 Diag(D.getDeclSpec().getBeginLoc(),
8797 diag::err_deduction_guide_with_complex_decl)
8798 << D.getSourceRange();
8801 if (!Chunk.Fun.hasTrailingReturnType()) {
8802 Diag(D.getName().getBeginLoc(),
8803 diag::err_deduction_guide_no_trailing_return_type);
8807 // Check that the return type is written as a specialization of
8808 // the template specified as the deduction-guide's name.
8809 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8810 TypeSourceInfo *TSI = nullptr;
8811 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8812 assert(TSI && "deduction guide has valid type but invalid return type?");
8813 bool AcceptableReturnType = false;
8814 bool MightInstantiateToSpecialization = false;
8816 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8817 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8818 bool TemplateMatches =
8819 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8820 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8821 AcceptableReturnType = true;
8823 // This could still instantiate to the right type, unless we know it
8824 // names the wrong class template.
8825 auto *TD = SpecifiedName.getAsTemplateDecl();
8826 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8829 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8830 MightInstantiateToSpecialization = true;
8833 if (!AcceptableReturnType) {
8834 Diag(TSI->getTypeLoc().getBeginLoc(),
8835 diag::err_deduction_guide_bad_trailing_return_type)
8836 << GuidedTemplate << TSI->getType()
8837 << MightInstantiateToSpecialization
8838 << TSI->getTypeLoc().getSourceRange();
8841 // Keep going to check that we don't have any inner declarator pieces (we
8842 // could still have a function returning a pointer to a function).
8843 FoundFunction = true;
8846 if (D.isFunctionDefinition())
8847 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8850 //===----------------------------------------------------------------------===//
8851 // Namespace Handling
8852 //===----------------------------------------------------------------------===//
8854 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is
8856 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8858 IdentifierInfo *II, bool *IsInline,
8859 NamespaceDecl *PrevNS) {
8860 assert(*IsInline != PrevNS->isInline());
8862 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8863 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8864 // inline namespaces, with the intention of bringing names into namespace std.
8866 // We support this just well enough to get that case working; this is not
8867 // sufficient to support reopening namespaces as inline in general.
8868 if (*IsInline && II && II->getName().startswith("__atomic") &&
8869 S.getSourceManager().isInSystemHeader(Loc)) {
8870 // Mark all prior declarations of the namespace as inline.
8871 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8872 NS = NS->getPreviousDecl())
8873 NS->setInline(*IsInline);
8874 // Patch up the lookup table for the containing namespace. This isn't really
8875 // correct, but it's good enough for this particular case.
8876 for (auto *I : PrevNS->decls())
8877 if (auto *ND = dyn_cast<NamedDecl>(I))
8878 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8882 if (PrevNS->isInline())
8883 // The user probably just forgot the 'inline', so suggest that it
8885 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8886 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8888 S.Diag(Loc, diag::err_inline_namespace_mismatch);
8890 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8891 *IsInline = PrevNS->isInline();
8894 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8896 Decl *Sema::ActOnStartNamespaceDef(
8897 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
8898 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
8899 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
8900 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8901 // For anonymous namespace, take the location of the left brace.
8902 SourceLocation Loc = II ? IdentLoc : LBrace;
8903 bool IsInline = InlineLoc.isValid();
8904 bool IsInvalid = false;
8906 bool AddToKnown = false;
8907 Scope *DeclRegionScope = NamespcScope->getParent();
8909 NamespaceDecl *PrevNS = nullptr;
8911 // C++ [namespace.def]p2:
8912 // The identifier in an original-namespace-definition shall not
8913 // have been previously defined in the declarative region in
8914 // which the original-namespace-definition appears. The
8915 // identifier in an original-namespace-definition is the name of
8916 // the namespace. Subsequently in that declarative region, it is
8917 // treated as an original-namespace-name.
8919 // Since namespace names are unique in their scope, and we don't
8920 // look through using directives, just look for any ordinary names
8921 // as if by qualified name lookup.
8922 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8923 ForExternalRedeclaration);
8924 LookupQualifiedName(R, CurContext->getRedeclContext());
8925 NamedDecl *PrevDecl =
8926 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8927 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8930 // This is an extended namespace definition.
8931 if (IsInline != PrevNS->isInline())
8932 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8934 } else if (PrevDecl) {
8935 // This is an invalid name redefinition.
8936 Diag(Loc, diag::err_redefinition_different_kind)
8938 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8940 // Continue on to push Namespc as current DeclContext and return it.
8941 } else if (II->isStr("std") &&
8942 CurContext->getRedeclContext()->isTranslationUnit()) {
8943 // This is the first "real" definition of the namespace "std", so update
8944 // our cache of the "std" namespace to point at this definition.
8945 PrevNS = getStdNamespace();
8947 AddToKnown = !IsInline;
8949 // We've seen this namespace for the first time.
8950 AddToKnown = !IsInline;
8953 // Anonymous namespaces.
8955 // Determine whether the parent already has an anonymous namespace.
8956 DeclContext *Parent = CurContext->getRedeclContext();
8957 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8958 PrevNS = TU->getAnonymousNamespace();
8960 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8961 PrevNS = ND->getAnonymousNamespace();
8964 if (PrevNS && IsInline != PrevNS->isInline())
8965 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8969 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8970 StartLoc, Loc, II, PrevNS);
8972 Namespc->setInvalidDecl();
8974 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8975 AddPragmaAttributes(DeclRegionScope, Namespc);
8977 // FIXME: Should we be merging attributes?
8978 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8979 PushNamespaceVisibilityAttr(Attr, Loc);
8982 StdNamespace = Namespc;
8984 KnownNamespaces[Namespc] = false;
8987 PushOnScopeChains(Namespc, DeclRegionScope);
8989 // Link the anonymous namespace into its parent.
8990 DeclContext *Parent = CurContext->getRedeclContext();
8991 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8992 TU->setAnonymousNamespace(Namespc);
8994 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8997 CurContext->addDecl(Namespc);
8999 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
9000 // behaves as if it were replaced by
9001 // namespace unique { /* empty body */ }
9002 // using namespace unique;
9003 // namespace unique { namespace-body }
9004 // where all occurrences of 'unique' in a translation unit are
9005 // replaced by the same identifier and this identifier differs
9006 // from all other identifiers in the entire program.
9008 // We just create the namespace with an empty name and then add an
9009 // implicit using declaration, just like the standard suggests.
9011 // CodeGen enforces the "universally unique" aspect by giving all
9012 // declarations semantically contained within an anonymous
9013 // namespace internal linkage.
9016 UD = UsingDirectiveDecl::Create(Context, Parent,
9017 /* 'using' */ LBrace,
9018 /* 'namespace' */ SourceLocation(),
9019 /* qualifier */ NestedNameSpecifierLoc(),
9020 /* identifier */ SourceLocation(),
9022 /* Ancestor */ Parent);
9024 Parent->addDecl(UD);
9028 ActOnDocumentableDecl(Namespc);
9030 // Although we could have an invalid decl (i.e. the namespace name is a
9031 // redefinition), push it as current DeclContext and try to continue parsing.
9032 // FIXME: We should be able to push Namespc here, so that the each DeclContext
9033 // for the namespace has the declarations that showed up in that particular
9034 // namespace definition.
9035 PushDeclContext(NamespcScope, Namespc);
9039 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
9040 /// is a namespace alias, returns the namespace it points to.
9041 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
9042 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
9043 return AD->getNamespace();
9044 return dyn_cast_or_null<NamespaceDecl>(D);
9047 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
9048 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
9049 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
9050 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
9051 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
9052 Namespc->setRBraceLoc(RBrace);
9054 if (Namespc->hasAttr<VisibilityAttr>())
9055 PopPragmaVisibility(true, RBrace);
9056 // If this namespace contains an export-declaration, export it now.
9057 if (DeferredExportedNamespaces.erase(Namespc))
9058 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
9061 CXXRecordDecl *Sema::getStdBadAlloc() const {
9062 return cast_or_null<CXXRecordDecl>(
9063 StdBadAlloc.get(Context.getExternalSource()));
9066 EnumDecl *Sema::getStdAlignValT() const {
9067 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
9070 NamespaceDecl *Sema::getStdNamespace() const {
9071 return cast_or_null<NamespaceDecl>(
9072 StdNamespace.get(Context.getExternalSource()));
9075 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
9076 if (!StdExperimentalNamespaceCache) {
9077 if (auto Std = getStdNamespace()) {
9078 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
9079 SourceLocation(), LookupNamespaceName);
9080 if (!LookupQualifiedName(Result, Std) ||
9081 !(StdExperimentalNamespaceCache =
9082 Result.getAsSingle<NamespaceDecl>()))
9083 Result.suppressDiagnostics();
9086 return StdExperimentalNamespaceCache;
9091 enum UnsupportedSTLSelect {
9098 struct InvalidSTLDiagnoser {
9101 QualType TyForDiags;
9103 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
9104 const VarDecl *VD = nullptr) {
9106 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
9107 << TyForDiags << ((int)Sel);
9108 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
9109 assert(!Name.empty());
9113 if (Sel == USS_InvalidMember) {
9114 S.Diag(VD->getLocation(), diag::note_var_declared_here)
9115 << VD << VD->getSourceRange();
9122 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
9123 SourceLocation Loc) {
9124 assert(getLangOpts().CPlusPlus &&
9125 "Looking for comparison category type outside of C++.");
9127 // Check if we've already successfully checked the comparison category type
9128 // before. If so, skip checking it again.
9129 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
9130 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)])
9131 return Info->getType();
9135 std::string NameForDiags = "std::";
9136 NameForDiags += ComparisonCategories::getCategoryString(Kind);
9137 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
9142 assert(Info->Kind == Kind);
9143 assert(Info->Record);
9145 // Update the Record decl in case we encountered a forward declaration on our
9146 // first pass. FIXME: This is a bit of a hack.
9147 if (Info->Record->hasDefinition())
9148 Info->Record = Info->Record->getDefinition();
9150 // Use an elaborated type for diagnostics which has a name containing the
9151 // prepended 'std' namespace but not any inline namespace names.
9152 QualType TyForDiags = [&]() {
9154 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
9155 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
9158 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type))
9161 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags};
9163 if (!Info->Record->isTriviallyCopyable())
9164 return UnsupportedSTLError(USS_NonTrivial);
9166 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
9167 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
9168 // Tolerate empty base classes.
9169 if (Base->isEmpty())
9171 // Reject STL implementations which have at least one non-empty base.
9172 return UnsupportedSTLError();
9175 // Check that the STL has implemented the types using a single integer field.
9176 // This expectation allows better codegen for builtin operators. We require:
9177 // (1) The class has exactly one field.
9178 // (2) The field is an integral or enumeration type.
9179 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
9180 if (std::distance(FIt, FEnd) != 1 ||
9181 !FIt->getType()->isIntegralOrEnumerationType()) {
9182 return UnsupportedSTLError();
9185 // Build each of the require values and store them in Info.
9186 for (ComparisonCategoryResult CCR :
9187 ComparisonCategories::getPossibleResultsForType(Kind)) {
9188 StringRef MemName = ComparisonCategories::getResultString(CCR);
9189 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
9192 return UnsupportedSTLError(USS_MissingMember, MemName);
9194 VarDecl *VD = ValInfo->VD;
9195 assert(VD && "should not be null!");
9197 // Attempt to diagnose reasons why the STL definition of this type
9198 // might be foobar, including it failing to be a constant expression.
9199 // TODO Handle more ways the lookup or result can be invalid.
9200 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() ||
9201 !VD->checkInitIsICE())
9202 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
9204 // Attempt to evaluate the var decl as a constant expression and extract
9205 // the value of its first field as a ICE. If this fails, the STL
9206 // implementation is not supported.
9207 if (!ValInfo->hasValidIntValue())
9208 return UnsupportedSTLError();
9210 MarkVariableReferenced(Loc, VD);
9213 // We've successfully built the required types and expressions. Update
9214 // the cache and return the newly cached value.
9215 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
9216 return Info->getType();
9219 /// Retrieve the special "std" namespace, which may require us to
9220 /// implicitly define the namespace.
9221 NamespaceDecl *Sema::getOrCreateStdNamespace() {
9222 if (!StdNamespace) {
9223 // The "std" namespace has not yet been defined, so build one implicitly.
9224 StdNamespace = NamespaceDecl::Create(Context,
9225 Context.getTranslationUnitDecl(),
9227 SourceLocation(), SourceLocation(),
9228 &PP.getIdentifierTable().get("std"),
9229 /*PrevDecl=*/nullptr);
9230 getStdNamespace()->setImplicit(true);
9233 return getStdNamespace();
9236 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
9237 assert(getLangOpts().CPlusPlus &&
9238 "Looking for std::initializer_list outside of C++.");
9240 // We're looking for implicit instantiations of
9241 // template <typename E> class std::initializer_list.
9243 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
9246 ClassTemplateDecl *Template = nullptr;
9247 const TemplateArgument *Arguments = nullptr;
9249 if (const RecordType *RT = Ty->getAs<RecordType>()) {
9251 ClassTemplateSpecializationDecl *Specialization =
9252 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
9253 if (!Specialization)
9256 Template = Specialization->getSpecializedTemplate();
9257 Arguments = Specialization->getTemplateArgs().data();
9258 } else if (const TemplateSpecializationType *TST =
9259 Ty->getAs<TemplateSpecializationType>()) {
9260 Template = dyn_cast_or_null<ClassTemplateDecl>(
9261 TST->getTemplateName().getAsTemplateDecl());
9262 Arguments = TST->getArgs();
9267 if (!StdInitializerList) {
9268 // Haven't recognized std::initializer_list yet, maybe this is it.
9269 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
9270 if (TemplateClass->getIdentifier() !=
9271 &PP.getIdentifierTable().get("initializer_list") ||
9272 !getStdNamespace()->InEnclosingNamespaceSetOf(
9273 TemplateClass->getDeclContext()))
9275 // This is a template called std::initializer_list, but is it the right
9277 TemplateParameterList *Params = Template->getTemplateParameters();
9278 if (Params->getMinRequiredArguments() != 1)
9280 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
9283 // It's the right template.
9284 StdInitializerList = Template;
9287 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
9290 // This is an instance of std::initializer_list. Find the argument type.
9292 *Element = Arguments[0].getAsType();
9296 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
9297 NamespaceDecl *Std = S.getStdNamespace();
9299 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9303 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
9304 Loc, Sema::LookupOrdinaryName);
9305 if (!S.LookupQualifiedName(Result, Std)) {
9306 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
9309 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
9311 Result.suppressDiagnostics();
9312 // We found something weird. Complain about the first thing we found.
9313 NamedDecl *Found = *Result.begin();
9314 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
9318 // We found some template called std::initializer_list. Now verify that it's
9320 TemplateParameterList *Params = Template->getTemplateParameters();
9321 if (Params->getMinRequiredArguments() != 1 ||
9322 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
9323 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
9330 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
9331 if (!StdInitializerList) {
9332 StdInitializerList = LookupStdInitializerList(*this, Loc);
9333 if (!StdInitializerList)
9337 TemplateArgumentListInfo Args(Loc, Loc);
9338 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
9339 Context.getTrivialTypeSourceInfo(Element,
9341 return Context.getCanonicalType(
9342 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
9345 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
9346 // C++ [dcl.init.list]p2:
9347 // A constructor is an initializer-list constructor if its first parameter
9348 // is of type std::initializer_list<E> or reference to possibly cv-qualified
9349 // std::initializer_list<E> for some type E, and either there are no other
9350 // parameters or else all other parameters have default arguments.
9351 if (Ctor->getNumParams() < 1 ||
9352 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
9355 QualType ArgType = Ctor->getParamDecl(0)->getType();
9356 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
9357 ArgType = RT->getPointeeType().getUnqualifiedType();
9359 return isStdInitializerList(ArgType, nullptr);
9362 /// Determine whether a using statement is in a context where it will be
9363 /// apply in all contexts.
9364 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
9365 switch (CurContext->getDeclKind()) {
9366 case Decl::TranslationUnit:
9368 case Decl::LinkageSpec:
9369 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
9377 // Callback to only accept typo corrections that are namespaces.
9378 class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
9380 bool ValidateCandidate(const TypoCorrection &candidate) override {
9381 if (NamedDecl *ND = candidate.getCorrectionDecl())
9382 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
9386 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9387 return llvm::make_unique<NamespaceValidatorCCC>(*this);
9393 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
9395 SourceLocation IdentLoc,
9396 IdentifierInfo *Ident) {
9398 NamespaceValidatorCCC CCC{};
9399 if (TypoCorrection Corrected =
9400 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
9401 Sema::CTK_ErrorRecovery)) {
9402 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
9403 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
9404 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
9405 Ident->getName().equals(CorrectedStr);
9406 S.diagnoseTypo(Corrected,
9407 S.PDiag(diag::err_using_directive_member_suggest)
9408 << Ident << DC << DroppedSpecifier << SS.getRange(),
9409 S.PDiag(diag::note_namespace_defined_here));
9411 S.diagnoseTypo(Corrected,
9412 S.PDiag(diag::err_using_directive_suggest) << Ident,
9413 S.PDiag(diag::note_namespace_defined_here));
9415 R.addDecl(Corrected.getFoundDecl());
9421 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
9422 SourceLocation NamespcLoc, CXXScopeSpec &SS,
9423 SourceLocation IdentLoc,
9424 IdentifierInfo *NamespcName,
9425 const ParsedAttributesView &AttrList) {
9426 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9427 assert(NamespcName && "Invalid NamespcName.");
9428 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
9430 // This can only happen along a recovery path.
9431 while (S->isTemplateParamScope())
9433 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9435 UsingDirectiveDecl *UDir = nullptr;
9436 NestedNameSpecifier *Qualifier = nullptr;
9438 Qualifier = SS.getScopeRep();
9440 // Lookup namespace name.
9441 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
9442 LookupParsedName(R, S, &SS);
9443 if (R.isAmbiguous())
9448 // Allow "using namespace std;" or "using namespace ::std;" even if
9449 // "std" hasn't been defined yet, for GCC compatibility.
9450 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
9451 NamespcName->isStr("std")) {
9452 Diag(IdentLoc, diag::ext_using_undefined_std);
9453 R.addDecl(getOrCreateStdNamespace());
9456 // Otherwise, attempt typo correction.
9457 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
9461 NamedDecl *Named = R.getRepresentativeDecl();
9462 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
9463 assert(NS && "expected namespace decl");
9465 // The use of a nested name specifier may trigger deprecation warnings.
9466 DiagnoseUseOfDecl(Named, IdentLoc);
9468 // C++ [namespace.udir]p1:
9469 // A using-directive specifies that the names in the nominated
9470 // namespace can be used in the scope in which the
9471 // using-directive appears after the using-directive. During
9472 // unqualified name lookup (3.4.1), the names appear as if they
9473 // were declared in the nearest enclosing namespace which
9474 // contains both the using-directive and the nominated
9475 // namespace. [Note: in this context, "contains" means "contains
9476 // directly or indirectly". ]
9478 // Find enclosing context containing both using-directive and
9479 // nominated namespace.
9480 DeclContext *CommonAncestor = NS;
9481 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
9482 CommonAncestor = CommonAncestor->getParent();
9484 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
9485 SS.getWithLocInContext(Context),
9486 IdentLoc, Named, CommonAncestor);
9488 if (IsUsingDirectiveInToplevelContext(CurContext) &&
9489 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
9490 Diag(IdentLoc, diag::warn_using_directive_in_header);
9493 PushUsingDirective(S, UDir);
9495 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
9499 ProcessDeclAttributeList(S, UDir, AttrList);
9504 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
9505 // If the scope has an associated entity and the using directive is at
9506 // namespace or translation unit scope, add the UsingDirectiveDecl into
9507 // its lookup structure so qualified name lookup can find it.
9508 DeclContext *Ctx = S->getEntity();
9509 if (Ctx && !Ctx->isFunctionOrMethod())
9512 // Otherwise, it is at block scope. The using-directives will affect lookup
9513 // only to the end of the scope.
9514 S->PushUsingDirective(UDir);
9517 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
9518 SourceLocation UsingLoc,
9519 SourceLocation TypenameLoc, CXXScopeSpec &SS,
9520 UnqualifiedId &Name,
9521 SourceLocation EllipsisLoc,
9522 const ParsedAttributesView &AttrList) {
9523 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
9526 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
9530 switch (Name.getKind()) {
9531 case UnqualifiedIdKind::IK_ImplicitSelfParam:
9532 case UnqualifiedIdKind::IK_Identifier:
9533 case UnqualifiedIdKind::IK_OperatorFunctionId:
9534 case UnqualifiedIdKind::IK_LiteralOperatorId:
9535 case UnqualifiedIdKind::IK_ConversionFunctionId:
9538 case UnqualifiedIdKind::IK_ConstructorName:
9539 case UnqualifiedIdKind::IK_ConstructorTemplateId:
9540 // C++11 inheriting constructors.
9541 Diag(Name.getBeginLoc(),
9542 getLangOpts().CPlusPlus11
9543 ? diag::warn_cxx98_compat_using_decl_constructor
9544 : diag::err_using_decl_constructor)
9547 if (getLangOpts().CPlusPlus11) break;
9551 case UnqualifiedIdKind::IK_DestructorName:
9552 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
9555 case UnqualifiedIdKind::IK_TemplateId:
9556 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
9557 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9560 case UnqualifiedIdKind::IK_DeductionGuideName:
9561 llvm_unreachable("cannot parse qualified deduction guide name");
9564 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9565 DeclarationName TargetName = TargetNameInfo.getName();
9569 // Warn about access declarations.
9570 if (UsingLoc.isInvalid()) {
9571 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
9572 ? diag::err_access_decl
9573 : diag::warn_access_decl_deprecated)
9574 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9577 if (EllipsisLoc.isInvalid()) {
9578 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9579 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9582 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9583 !TargetNameInfo.containsUnexpandedParameterPack()) {
9584 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9585 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9586 EllipsisLoc = SourceLocation();
9591 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9592 SS, TargetNameInfo, EllipsisLoc, AttrList,
9593 /*IsInstantiation*/false);
9595 PushOnScopeChains(UD, S, /*AddToContext*/ false);
9600 /// Determine whether a using declaration considers the given
9601 /// declarations as "equivalent", e.g., if they are redeclarations of
9602 /// the same entity or are both typedefs of the same type.
9604 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9605 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9608 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9609 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9610 return Context.hasSameType(TD1->getUnderlyingType(),
9611 TD2->getUnderlyingType());
9617 /// Determines whether to create a using shadow decl for a particular
9618 /// decl, given the set of decls existing prior to this using lookup.
9619 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9620 const LookupResult &Previous,
9621 UsingShadowDecl *&PrevShadow) {
9622 // Diagnose finding a decl which is not from a base class of the
9623 // current class. We do this now because there are cases where this
9624 // function will silently decide not to build a shadow decl, which
9625 // will pre-empt further diagnostics.
9627 // We don't need to do this in C++11 because we do the check once on
9630 // FIXME: diagnose the following if we care enough:
9631 // struct A { int foo; };
9632 // struct B : A { using A::foo; };
9633 // template <class T> struct C : A {};
9634 // template <class T> struct D : C<T> { using B::foo; } // <---
9635 // This is invalid (during instantiation) in C++03 because B::foo
9636 // resolves to the using decl in B, which is not a base class of D<T>.
9637 // We can't diagnose it immediately because C<T> is an unknown
9638 // specialization. The UsingShadowDecl in D<T> then points directly
9639 // to A::foo, which will look well-formed when we instantiate.
9640 // The right solution is to not collapse the shadow-decl chain.
9641 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9642 DeclContext *OrigDC = Orig->getDeclContext();
9644 // Handle enums and anonymous structs.
9645 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9646 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9647 while (OrigRec->isAnonymousStructOrUnion())
9648 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9650 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9651 if (OrigDC == CurContext) {
9652 Diag(Using->getLocation(),
9653 diag::err_using_decl_nested_name_specifier_is_current_class)
9654 << Using->getQualifierLoc().getSourceRange();
9655 Diag(Orig->getLocation(), diag::note_using_decl_target);
9656 Using->setInvalidDecl();
9660 Diag(Using->getQualifierLoc().getBeginLoc(),
9661 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9662 << Using->getQualifier()
9663 << cast<CXXRecordDecl>(CurContext)
9664 << Using->getQualifierLoc().getSourceRange();
9665 Diag(Orig->getLocation(), diag::note_using_decl_target);
9666 Using->setInvalidDecl();
9671 if (Previous.empty()) return false;
9673 NamedDecl *Target = Orig;
9674 if (isa<UsingShadowDecl>(Target))
9675 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9677 // If the target happens to be one of the previous declarations, we
9678 // don't have a conflict.
9680 // FIXME: but we might be increasing its access, in which case we
9681 // should redeclare it.
9682 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9683 bool FoundEquivalentDecl = false;
9684 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9686 NamedDecl *D = (*I)->getUnderlyingDecl();
9687 // We can have UsingDecls in our Previous results because we use the same
9688 // LookupResult for checking whether the UsingDecl itself is a valid
9690 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9693 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9694 // C++ [class.mem]p19:
9695 // If T is the name of a class, then [every named member other than
9696 // a non-static data member] shall have a name different from T
9697 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
9698 !isa<IndirectFieldDecl>(Target) &&
9699 !isa<UnresolvedUsingValueDecl>(Target) &&
9700 DiagnoseClassNameShadow(
9702 DeclarationNameInfo(Using->getDeclName(), Using->getLocation())))
9706 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9707 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9708 PrevShadow = Shadow;
9709 FoundEquivalentDecl = true;
9710 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9711 // We don't conflict with an existing using shadow decl of an equivalent
9712 // declaration, but we're not a redeclaration of it.
9713 FoundEquivalentDecl = true;
9717 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9720 if (FoundEquivalentDecl)
9723 if (FunctionDecl *FD = Target->getAsFunction()) {
9724 NamedDecl *OldDecl = nullptr;
9725 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9726 /*IsForUsingDecl*/ true)) {
9730 case Ovl_NonFunction:
9731 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9734 // We found a decl with the exact signature.
9736 // If we're in a record, we want to hide the target, so we
9737 // return true (without a diagnostic) to tell the caller not to
9738 // build a shadow decl.
9739 if (CurContext->isRecord())
9742 // If we're not in a record, this is an error.
9743 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9747 Diag(Target->getLocation(), diag::note_using_decl_target);
9748 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9749 Using->setInvalidDecl();
9753 // Target is not a function.
9755 if (isa<TagDecl>(Target)) {
9756 // No conflict between a tag and a non-tag.
9757 if (!Tag) return false;
9759 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9760 Diag(Target->getLocation(), diag::note_using_decl_target);
9761 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9762 Using->setInvalidDecl();
9766 // No conflict between a tag and a non-tag.
9767 if (!NonTag) return false;
9769 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9770 Diag(Target->getLocation(), diag::note_using_decl_target);
9771 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9772 Using->setInvalidDecl();
9776 /// Determine whether a direct base class is a virtual base class.
9777 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9778 if (!Derived->getNumVBases())
9780 for (auto &B : Derived->bases())
9781 if (B.getType()->getAsCXXRecordDecl() == Base)
9782 return B.isVirtual();
9783 llvm_unreachable("not a direct base class");
9786 /// Builds a shadow declaration corresponding to a 'using' declaration.
9787 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9790 UsingShadowDecl *PrevDecl) {
9791 // If we resolved to another shadow declaration, just coalesce them.
9792 NamedDecl *Target = Orig;
9793 if (isa<UsingShadowDecl>(Target)) {
9794 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9795 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9798 NamedDecl *NonTemplateTarget = Target;
9799 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9800 NonTemplateTarget = TargetTD->getTemplatedDecl();
9802 UsingShadowDecl *Shadow;
9803 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
9804 bool IsVirtualBase =
9805 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9806 UD->getQualifier()->getAsRecordDecl());
9807 Shadow = ConstructorUsingShadowDecl::Create(
9808 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9810 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9813 UD->addShadowDecl(Shadow);
9815 Shadow->setAccess(UD->getAccess());
9816 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9817 Shadow->setInvalidDecl();
9819 Shadow->setPreviousDecl(PrevDecl);
9822 PushOnScopeChains(Shadow, S);
9824 CurContext->addDecl(Shadow);
9830 /// Hides a using shadow declaration. This is required by the current
9831 /// using-decl implementation when a resolvable using declaration in a
9832 /// class is followed by a declaration which would hide or override
9833 /// one or more of the using decl's targets; for example:
9835 /// struct Base { void foo(int); };
9836 /// struct Derived : Base {
9837 /// using Base::foo;
9841 /// The governing language is C++03 [namespace.udecl]p12:
9843 /// When a using-declaration brings names from a base class into a
9844 /// derived class scope, member functions in the derived class
9845 /// override and/or hide member functions with the same name and
9846 /// parameter types in a base class (rather than conflicting).
9848 /// There are two ways to implement this:
9849 /// (1) optimistically create shadow decls when they're not hidden
9850 /// by existing declarations, or
9851 /// (2) don't create any shadow decls (or at least don't make them
9852 /// visible) until we've fully parsed/instantiated the class.
9853 /// The problem with (1) is that we might have to retroactively remove
9854 /// a shadow decl, which requires several O(n) operations because the
9855 /// decl structures are (very reasonably) not designed for removal.
9856 /// (2) avoids this but is very fiddly and phase-dependent.
9857 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9858 if (Shadow->getDeclName().getNameKind() ==
9859 DeclarationName::CXXConversionFunctionName)
9860 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9862 // Remove it from the DeclContext...
9863 Shadow->getDeclContext()->removeDecl(Shadow);
9865 // ...and the scope, if applicable...
9867 S->RemoveDecl(Shadow);
9868 IdResolver.RemoveDecl(Shadow);
9871 // ...and the using decl.
9872 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9874 // TODO: complain somehow if Shadow was used. It shouldn't
9875 // be possible for this to happen, because...?
9878 /// Find the base specifier for a base class with the given type.
9879 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9880 QualType DesiredBase,
9881 bool &AnyDependentBases) {
9882 // Check whether the named type is a direct base class.
9883 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9884 for (auto &Base : Derived->bases()) {
9885 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9886 if (CanonicalDesiredBase == BaseType)
9888 if (BaseType->isDependentType())
9889 AnyDependentBases = true;
9895 class UsingValidatorCCC final : public CorrectionCandidateCallback {
9897 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9898 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9899 : HasTypenameKeyword(HasTypenameKeyword),
9900 IsInstantiation(IsInstantiation), OldNNS(NNS),
9901 RequireMemberOf(RequireMemberOf) {}
9903 bool ValidateCandidate(const TypoCorrection &Candidate) override {
9904 NamedDecl *ND = Candidate.getCorrectionDecl();
9906 // Keywords are not valid here.
9907 if (!ND || isa<NamespaceDecl>(ND))
9910 // Completely unqualified names are invalid for a 'using' declaration.
9911 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9914 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9917 if (RequireMemberOf) {
9918 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9919 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9920 // No-one ever wants a using-declaration to name an injected-class-name
9921 // of a base class, unless they're declaring an inheriting constructor.
9922 ASTContext &Ctx = ND->getASTContext();
9923 if (!Ctx.getLangOpts().CPlusPlus11)
9925 QualType FoundType = Ctx.getRecordType(FoundRecord);
9927 // Check that the injected-class-name is named as a member of its own
9928 // type; we don't want to suggest 'using Derived::Base;', since that
9929 // means something else.
9930 NestedNameSpecifier *Specifier =
9931 Candidate.WillReplaceSpecifier()
9932 ? Candidate.getCorrectionSpecifier()
9934 if (!Specifier->getAsType() ||
9935 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9938 // Check that this inheriting constructor declaration actually names a
9939 // direct base class of the current class.
9940 bool AnyDependentBases = false;
9941 if (!findDirectBaseWithType(RequireMemberOf,
9942 Ctx.getRecordType(FoundRecord),
9943 AnyDependentBases) &&
9947 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9948 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9951 // FIXME: Check that the base class member is accessible?
9954 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9955 if (FoundRecord && FoundRecord->isInjectedClassName())
9959 if (isa<TypeDecl>(ND))
9960 return HasTypenameKeyword || !IsInstantiation;
9962 return !HasTypenameKeyword;
9965 std::unique_ptr<CorrectionCandidateCallback> clone() override {
9966 return llvm::make_unique<UsingValidatorCCC>(*this);
9970 bool HasTypenameKeyword;
9971 bool IsInstantiation;
9972 NestedNameSpecifier *OldNNS;
9973 CXXRecordDecl *RequireMemberOf;
9975 } // end anonymous namespace
9977 /// Builds a using declaration.
9979 /// \param IsInstantiation - Whether this call arises from an
9980 /// instantiation of an unresolved using declaration. We treat
9981 /// the lookup differently for these declarations.
9982 NamedDecl *Sema::BuildUsingDeclaration(
9983 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
9984 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
9985 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
9986 const ParsedAttributesView &AttrList, bool IsInstantiation) {
9987 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9988 SourceLocation IdentLoc = NameInfo.getLoc();
9989 assert(IdentLoc.isValid() && "Invalid TargetName location.");
9991 // FIXME: We ignore attributes for now.
9993 // For an inheriting constructor declaration, the name of the using
9994 // declaration is the name of a constructor in this class, not in the
9996 DeclarationNameInfo UsingName = NameInfo;
9997 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9998 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9999 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10000 Context.getCanonicalType(Context.getRecordType(RD))));
10002 // Do the redeclaration lookup in the current scope.
10003 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
10004 ForVisibleRedeclaration);
10005 Previous.setHideTags(false);
10007 LookupName(Previous, S);
10009 // It is really dumb that we have to do this.
10010 LookupResult::Filter F = Previous.makeFilter();
10011 while (F.hasNext()) {
10012 NamedDecl *D = F.next();
10013 if (!isDeclInScope(D, CurContext, S))
10015 // If we found a local extern declaration that's not ordinarily visible,
10016 // and this declaration is being added to a non-block scope, ignore it.
10017 // We're only checking for scope conflicts here, not also for violations
10018 // of the linkage rules.
10019 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
10020 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
10025 assert(IsInstantiation && "no scope in non-instantiation");
10026 if (CurContext->isRecord())
10027 LookupQualifiedName(Previous, CurContext);
10029 // No redeclaration check is needed here; in non-member contexts we
10030 // diagnosed all possible conflicts with other using-declarations when
10031 // building the template:
10033 // For a dependent non-type using declaration, the only valid case is
10034 // if we instantiate to a single enumerator. We check for conflicts
10035 // between shadow declarations we introduce, and we check in the template
10036 // definition for conflicts between a non-type using declaration and any
10037 // other declaration, which together covers all cases.
10039 // A dependent typename using declaration will never successfully
10040 // instantiate, since it will always name a class member, so we reject
10041 // that in the template definition.
10045 // Check for invalid redeclarations.
10046 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
10047 SS, IdentLoc, Previous))
10050 // Check for bad qualifiers.
10051 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
10055 DeclContext *LookupContext = computeDeclContext(SS);
10057 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10058 if (!LookupContext || EllipsisLoc.isValid()) {
10059 if (HasTypenameKeyword) {
10060 // FIXME: not all declaration name kinds are legal here
10061 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
10062 UsingLoc, TypenameLoc,
10064 IdentLoc, NameInfo.getName(),
10067 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
10068 QualifierLoc, NameInfo, EllipsisLoc);
10071 CurContext->addDecl(D);
10075 auto Build = [&](bool Invalid) {
10077 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
10078 UsingName, HasTypenameKeyword);
10080 CurContext->addDecl(UD);
10081 UD->setInvalidDecl(Invalid);
10084 auto BuildInvalid = [&]{ return Build(true); };
10085 auto BuildValid = [&]{ return Build(false); };
10087 if (RequireCompleteDeclContext(SS, LookupContext))
10088 return BuildInvalid();
10090 // Look up the target name.
10091 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10093 // Unlike most lookups, we don't always want to hide tag
10094 // declarations: tag names are visible through the using declaration
10095 // even if hidden by ordinary names, *except* in a dependent context
10096 // where it's important for the sanity of two-phase lookup.
10097 if (!IsInstantiation)
10098 R.setHideTags(false);
10100 // For the purposes of this lookup, we have a base object type
10101 // equal to that of the current context.
10102 if (CurContext->isRecord()) {
10103 R.setBaseObjectType(
10104 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
10107 LookupQualifiedName(R, LookupContext);
10109 // Try to correct typos if possible. If constructor name lookup finds no
10110 // results, that means the named class has no explicit constructors, and we
10111 // suppressed declaring implicit ones (probably because it's dependent or
10114 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
10115 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
10116 // it will believe that glibc provides a ::gets in cases where it does not,
10117 // and will try to pull it into namespace std with a using-declaration.
10118 // Just ignore the using-declaration in that case.
10119 auto *II = NameInfo.getName().getAsIdentifierInfo();
10120 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
10121 CurContext->isStdNamespace() &&
10122 isa<TranslationUnitDecl>(LookupContext) &&
10123 getSourceManager().isInSystemHeader(UsingLoc))
10125 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
10126 dyn_cast<CXXRecordDecl>(CurContext));
10127 if (TypoCorrection Corrected =
10128 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
10129 CTK_ErrorRecovery)) {
10130 // We reject candidates where DroppedSpecifier == true, hence the
10131 // literal '0' below.
10132 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
10133 << NameInfo.getName() << LookupContext << 0
10136 // If we picked a correction with no attached Decl we can't do anything
10137 // useful with it, bail out.
10138 NamedDecl *ND = Corrected.getCorrectionDecl();
10140 return BuildInvalid();
10142 // If we corrected to an inheriting constructor, handle it as one.
10143 auto *RD = dyn_cast<CXXRecordDecl>(ND);
10144 if (RD && RD->isInjectedClassName()) {
10145 // The parent of the injected class name is the class itself.
10146 RD = cast<CXXRecordDecl>(RD->getParent());
10148 // Fix up the information we'll use to build the using declaration.
10149 if (Corrected.WillReplaceSpecifier()) {
10150 NestedNameSpecifierLocBuilder Builder;
10151 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
10152 QualifierLoc.getSourceRange());
10153 QualifierLoc = Builder.getWithLocInContext(Context);
10156 // In this case, the name we introduce is the name of a derived class
10158 auto *CurClass = cast<CXXRecordDecl>(CurContext);
10159 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
10160 Context.getCanonicalType(Context.getRecordType(CurClass))));
10161 UsingName.setNamedTypeInfo(nullptr);
10162 for (auto *Ctor : LookupConstructors(RD))
10166 // FIXME: Pick up all the declarations if we found an overloaded
10168 UsingName.setName(ND->getDeclName());
10172 Diag(IdentLoc, diag::err_no_member)
10173 << NameInfo.getName() << LookupContext << SS.getRange();
10174 return BuildInvalid();
10178 if (R.isAmbiguous())
10179 return BuildInvalid();
10181 if (HasTypenameKeyword) {
10182 // If we asked for a typename and got a non-type decl, error out.
10183 if (!R.getAsSingle<TypeDecl>()) {
10184 Diag(IdentLoc, diag::err_using_typename_non_type);
10185 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10186 Diag((*I)->getUnderlyingDecl()->getLocation(),
10187 diag::note_using_decl_target);
10188 return BuildInvalid();
10191 // If we asked for a non-typename and we got a type, error out,
10192 // but only if this is an instantiation of an unresolved using
10193 // decl. Otherwise just silently find the type name.
10194 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
10195 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
10196 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
10197 return BuildInvalid();
10201 // C++14 [namespace.udecl]p6:
10202 // A using-declaration shall not name a namespace.
10203 if (R.getAsSingle<NamespaceDecl>()) {
10204 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
10206 return BuildInvalid();
10209 // C++14 [namespace.udecl]p7:
10210 // A using-declaration shall not name a scoped enumerator.
10211 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
10212 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
10213 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
10215 return BuildInvalid();
10219 UsingDecl *UD = BuildValid();
10221 // Some additional rules apply to inheriting constructors.
10222 if (UsingName.getName().getNameKind() ==
10223 DeclarationName::CXXConstructorName) {
10224 // Suppress access diagnostics; the access check is instead performed at the
10225 // point of use for an inheriting constructor.
10226 R.suppressDiagnostics();
10227 if (CheckInheritingConstructorUsingDecl(UD))
10231 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
10232 UsingShadowDecl *PrevDecl = nullptr;
10233 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
10234 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
10240 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
10241 ArrayRef<NamedDecl *> Expansions) {
10242 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
10243 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
10244 isa<UsingPackDecl>(InstantiatedFrom));
10247 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
10248 UPD->setAccess(InstantiatedFrom->getAccess());
10249 CurContext->addDecl(UPD);
10253 /// Additional checks for a using declaration referring to a constructor name.
10254 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
10255 assert(!UD->hasTypename() && "expecting a constructor name");
10257 const Type *SourceType = UD->getQualifier()->getAsType();
10258 assert(SourceType &&
10259 "Using decl naming constructor doesn't have type in scope spec.");
10260 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
10262 // Check whether the named type is a direct base class.
10263 bool AnyDependentBases = false;
10264 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
10265 AnyDependentBases);
10266 if (!Base && !AnyDependentBases) {
10267 Diag(UD->getUsingLoc(),
10268 diag::err_using_decl_constructor_not_in_direct_base)
10269 << UD->getNameInfo().getSourceRange()
10270 << QualType(SourceType, 0) << TargetClass;
10271 UD->setInvalidDecl();
10276 Base->setInheritConstructors();
10281 /// Checks that the given using declaration is not an invalid
10282 /// redeclaration. Note that this is checking only for the using decl
10283 /// itself, not for any ill-formedness among the UsingShadowDecls.
10284 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
10285 bool HasTypenameKeyword,
10286 const CXXScopeSpec &SS,
10287 SourceLocation NameLoc,
10288 const LookupResult &Prev) {
10289 NestedNameSpecifier *Qual = SS.getScopeRep();
10291 // C++03 [namespace.udecl]p8:
10292 // C++0x [namespace.udecl]p10:
10293 // A using-declaration is a declaration and can therefore be used
10294 // repeatedly where (and only where) multiple declarations are
10297 // That's in non-member contexts.
10298 if (!CurContext->getRedeclContext()->isRecord()) {
10299 // A dependent qualifier outside a class can only ever resolve to an
10300 // enumeration type. Therefore it conflicts with any other non-type
10301 // declaration in the same scope.
10302 // FIXME: How should we check for dependent type-type conflicts at block
10304 if (Qual->isDependent() && !HasTypenameKeyword) {
10305 for (auto *D : Prev) {
10306 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
10307 bool OldCouldBeEnumerator =
10308 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
10310 OldCouldBeEnumerator ? diag::err_redefinition
10311 : diag::err_redefinition_different_kind)
10312 << Prev.getLookupName();
10313 Diag(D->getLocation(), diag::note_previous_definition);
10321 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
10325 NestedNameSpecifier *DQual;
10326 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
10327 DTypename = UD->hasTypename();
10328 DQual = UD->getQualifier();
10329 } else if (UnresolvedUsingValueDecl *UD
10330 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
10332 DQual = UD->getQualifier();
10333 } else if (UnresolvedUsingTypenameDecl *UD
10334 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
10336 DQual = UD->getQualifier();
10339 // using decls differ if one says 'typename' and the other doesn't.
10340 // FIXME: non-dependent using decls?
10341 if (HasTypenameKeyword != DTypename) continue;
10343 // using decls differ if they name different scopes (but note that
10344 // template instantiation can cause this check to trigger when it
10345 // didn't before instantiation).
10346 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
10347 Context.getCanonicalNestedNameSpecifier(DQual))
10350 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
10351 Diag(D->getLocation(), diag::note_using_decl) << 1;
10359 /// Checks that the given nested-name qualifier used in a using decl
10360 /// in the current context is appropriately related to the current
10361 /// scope. If an error is found, diagnoses it and returns true.
10362 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
10364 const CXXScopeSpec &SS,
10365 const DeclarationNameInfo &NameInfo,
10366 SourceLocation NameLoc) {
10367 DeclContext *NamedContext = computeDeclContext(SS);
10369 if (!CurContext->isRecord()) {
10370 // C++03 [namespace.udecl]p3:
10371 // C++0x [namespace.udecl]p8:
10372 // A using-declaration for a class member shall be a member-declaration.
10374 // If we weren't able to compute a valid scope, it might validly be a
10375 // dependent class scope or a dependent enumeration unscoped scope. If
10376 // we have a 'typename' keyword, the scope must resolve to a class type.
10377 if ((HasTypename && !NamedContext) ||
10378 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
10379 auto *RD = NamedContext
10380 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
10382 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
10385 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
10388 // If we have a complete, non-dependent source type, try to suggest a
10389 // way to get the same effect.
10393 // Find what this using-declaration was referring to.
10394 LookupResult R(*this, NameInfo, LookupOrdinaryName);
10395 R.setHideTags(false);
10396 R.suppressDiagnostics();
10397 LookupQualifiedName(R, RD);
10399 if (R.getAsSingle<TypeDecl>()) {
10400 if (getLangOpts().CPlusPlus11) {
10401 // Convert 'using X::Y;' to 'using Y = X::Y;'.
10402 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
10403 << 0 // alias declaration
10404 << FixItHint::CreateInsertion(SS.getBeginLoc(),
10405 NameInfo.getName().getAsString() +
10408 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
10409 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
10410 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
10411 << 1 // typedef declaration
10412 << FixItHint::CreateReplacement(UsingLoc, "typedef")
10413 << FixItHint::CreateInsertion(
10414 InsertLoc, " " + NameInfo.getName().getAsString());
10416 } else if (R.getAsSingle<VarDecl>()) {
10417 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10418 // repeating the type of the static data member here.
10420 if (getLangOpts().CPlusPlus11) {
10421 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10422 FixIt = FixItHint::CreateReplacement(
10423 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
10426 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10427 << 2 // reference declaration
10429 } else if (R.getAsSingle<EnumConstantDecl>()) {
10430 // Don't provide a fixit outside C++11 mode; we don't want to suggest
10431 // repeating the type of the enumeration here, and we can't do so if
10432 // the type is anonymous.
10434 if (getLangOpts().CPlusPlus11) {
10435 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
10436 FixIt = FixItHint::CreateReplacement(
10438 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
10441 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
10442 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
10448 // Otherwise, this might be valid.
10452 // The current scope is a record.
10454 // If the named context is dependent, we can't decide much.
10455 if (!NamedContext) {
10456 // FIXME: in C++0x, we can diagnose if we can prove that the
10457 // nested-name-specifier does not refer to a base class, which is
10458 // still possible in some cases.
10460 // Otherwise we have to conservatively report that things might be
10465 if (!NamedContext->isRecord()) {
10466 // Ideally this would point at the last name in the specifier,
10467 // but we don't have that level of source info.
10468 Diag(SS.getRange().getBegin(),
10469 diag::err_using_decl_nested_name_specifier_is_not_class)
10470 << SS.getScopeRep() << SS.getRange();
10474 if (!NamedContext->isDependentContext() &&
10475 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
10478 if (getLangOpts().CPlusPlus11) {
10479 // C++11 [namespace.udecl]p3:
10480 // In a using-declaration used as a member-declaration, the
10481 // nested-name-specifier shall name a base class of the class
10484 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
10485 cast<CXXRecordDecl>(NamedContext))) {
10486 if (CurContext == NamedContext) {
10488 diag::err_using_decl_nested_name_specifier_is_current_class)
10493 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
10494 Diag(SS.getRange().getBegin(),
10495 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10496 << SS.getScopeRep()
10497 << cast<CXXRecordDecl>(CurContext)
10506 // C++03 [namespace.udecl]p4:
10507 // A using-declaration used as a member-declaration shall refer
10508 // to a member of a base class of the class being defined [etc.].
10510 // Salient point: SS doesn't have to name a base class as long as
10511 // lookup only finds members from base classes. Therefore we can
10512 // diagnose here only if we can prove that that can't happen,
10513 // i.e. if the class hierarchies provably don't intersect.
10515 // TODO: it would be nice if "definitely valid" results were cached
10516 // in the UsingDecl and UsingShadowDecl so that these checks didn't
10517 // need to be repeated.
10519 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
10520 auto Collect = [&Bases](const CXXRecordDecl *Base) {
10521 Bases.insert(Base);
10525 // Collect all bases. Return false if we find a dependent base.
10526 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
10529 // Returns true if the base is dependent or is one of the accumulated base
10531 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
10532 return !Bases.count(Base);
10535 // Return false if the class has a dependent base or if it or one
10536 // of its bases is present in the base set of the current context.
10537 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
10538 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
10541 Diag(SS.getRange().getBegin(),
10542 diag::err_using_decl_nested_name_specifier_is_not_base_class)
10543 << SS.getScopeRep()
10544 << cast<CXXRecordDecl>(CurContext)
10550 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
10551 MultiTemplateParamsArg TemplateParamLists,
10552 SourceLocation UsingLoc, UnqualifiedId &Name,
10553 const ParsedAttributesView &AttrList,
10554 TypeResult Type, Decl *DeclFromDeclSpec) {
10555 // Skip up to the relevant declaration scope.
10556 while (S->isTemplateParamScope())
10557 S = S->getParent();
10558 assert((S->getFlags() & Scope::DeclScope) &&
10559 "got alias-declaration outside of declaration scope");
10561 if (Type.isInvalid())
10564 bool Invalid = false;
10565 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10566 TypeSourceInfo *TInfo = nullptr;
10567 GetTypeFromParser(Type.get(), &TInfo);
10569 if (DiagnoseClassNameShadow(CurContext, NameInfo))
10572 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10573 UPPC_DeclarationType)) {
10575 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10576 TInfo->getTypeLoc().getBeginLoc());
10579 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10580 TemplateParamLists.size()
10581 ? forRedeclarationInCurContext()
10582 : ForVisibleRedeclaration);
10583 LookupName(Previous, S);
10585 // Warn about shadowing the name of a template parameter.
10586 if (Previous.isSingleResult() &&
10587 Previous.getFoundDecl()->isTemplateParameter()) {
10588 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10592 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10593 "name in alias declaration must be an identifier");
10594 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10595 Name.StartLocation,
10596 Name.Identifier, TInfo);
10598 NewTD->setAccess(AS);
10601 NewTD->setInvalidDecl();
10603 ProcessDeclAttributeList(S, NewTD, AttrList);
10604 AddPragmaAttributes(S, NewTD);
10606 CheckTypedefForVariablyModifiedType(S, NewTD);
10607 Invalid |= NewTD->isInvalidDecl();
10609 bool Redeclaration = false;
10612 if (TemplateParamLists.size()) {
10613 TypeAliasTemplateDecl *OldDecl = nullptr;
10614 TemplateParameterList *OldTemplateParams = nullptr;
10616 if (TemplateParamLists.size() != 1) {
10617 Diag(UsingLoc, diag::err_alias_template_extra_headers)
10618 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10619 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10621 TemplateParameterList *TemplateParams = TemplateParamLists[0];
10623 // Check that we can declare a template here.
10624 if (CheckTemplateDeclScope(S, TemplateParams))
10627 // Only consider previous declarations in the same scope.
10628 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10629 /*ExplicitInstantiationOrSpecialization*/false);
10630 if (!Previous.empty()) {
10631 Redeclaration = true;
10633 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10634 if (!OldDecl && !Invalid) {
10635 Diag(UsingLoc, diag::err_redefinition_different_kind)
10636 << Name.Identifier;
10638 NamedDecl *OldD = Previous.getRepresentativeDecl();
10639 if (OldD->getLocation().isValid())
10640 Diag(OldD->getLocation(), diag::note_previous_definition);
10645 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10646 if (TemplateParameterListsAreEqual(TemplateParams,
10647 OldDecl->getTemplateParameters(),
10649 TPL_TemplateMatch))
10650 OldTemplateParams =
10651 OldDecl->getMostRecentDecl()->getTemplateParameters();
10655 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10657 !Context.hasSameType(OldTD->getUnderlyingType(),
10658 NewTD->getUnderlyingType())) {
10659 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10660 // but we can't reasonably accept it.
10661 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10662 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10663 if (OldTD->getLocation().isValid())
10664 Diag(OldTD->getLocation(), diag::note_previous_definition);
10670 // Merge any previous default template arguments into our parameters,
10671 // and check the parameter list.
10672 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10673 TPC_TypeAliasTemplate))
10676 TypeAliasTemplateDecl *NewDecl =
10677 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10678 Name.Identifier, TemplateParams,
10680 NewTD->setDescribedAliasTemplate(NewDecl);
10682 NewDecl->setAccess(AS);
10685 NewDecl->setInvalidDecl();
10686 else if (OldDecl) {
10687 NewDecl->setPreviousDecl(OldDecl);
10688 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10693 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10694 setTagNameForLinkagePurposes(TD, NewTD);
10695 handleTagNumbering(TD, S);
10697 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10701 PushOnScopeChains(NewND, S);
10702 ActOnDocumentableDecl(NewND);
10706 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10707 SourceLocation AliasLoc,
10708 IdentifierInfo *Alias, CXXScopeSpec &SS,
10709 SourceLocation IdentLoc,
10710 IdentifierInfo *Ident) {
10712 // Lookup the namespace name.
10713 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10714 LookupParsedName(R, S, &SS);
10716 if (R.isAmbiguous())
10720 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10721 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10725 assert(!R.isAmbiguous() && !R.empty());
10726 NamedDecl *ND = R.getRepresentativeDecl();
10728 // Check if we have a previous declaration with the same name.
10729 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10730 ForVisibleRedeclaration);
10731 LookupName(PrevR, S);
10733 // Check we're not shadowing a template parameter.
10734 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10735 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10739 // Filter out any other lookup result from an enclosing scope.
10740 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10741 /*AllowInlineNamespace*/false);
10743 // Find the previous declaration and check that we can redeclare it.
10744 NamespaceAliasDecl *Prev = nullptr;
10745 if (PrevR.isSingleResult()) {
10746 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10747 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10748 // We already have an alias with the same name that points to the same
10749 // namespace; check that it matches.
10750 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10752 } else if (isVisible(PrevDecl)) {
10753 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10755 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10756 << AD->getNamespace();
10759 } else if (isVisible(PrevDecl)) {
10760 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10761 ? diag::err_redefinition
10762 : diag::err_redefinition_different_kind;
10763 Diag(AliasLoc, DiagID) << Alias;
10764 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10769 // The use of a nested name specifier may trigger deprecation warnings.
10770 DiagnoseUseOfDecl(ND, IdentLoc);
10772 NamespaceAliasDecl *AliasDecl =
10773 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10774 Alias, SS.getWithLocInContext(Context),
10777 AliasDecl->setPreviousDecl(Prev);
10779 PushOnScopeChains(AliasDecl, S);
10784 struct SpecialMemberExceptionSpecInfo
10785 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10786 SourceLocation Loc;
10787 Sema::ImplicitExceptionSpecification ExceptSpec;
10789 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10790 Sema::CXXSpecialMember CSM,
10791 Sema::InheritedConstructorInfo *ICI,
10792 SourceLocation Loc)
10793 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10795 bool visitBase(CXXBaseSpecifier *Base);
10796 bool visitField(FieldDecl *FD);
10798 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10801 void visitSubobjectCall(Subobject Subobj,
10802 Sema::SpecialMemberOverloadResult SMOR);
10806 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10807 auto *RT = Base->getType()->getAs<RecordType>();
10811 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10812 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10813 if (auto *BaseCtor = SMOR.getMethod()) {
10814 visitSubobjectCall(Base, BaseCtor);
10818 visitClassSubobject(BaseClass, Base, 0);
10822 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10823 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10824 Expr *E = FD->getInClassInitializer();
10826 // FIXME: It's a little wasteful to build and throw away a
10827 // CXXDefaultInitExpr here.
10828 // FIXME: We should have a single context note pointing at Loc, and
10829 // this location should be MD->getLocation() instead, since that's
10830 // the location where we actually use the default init expression.
10831 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10833 ExceptSpec.CalledExpr(E);
10834 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10835 ->getAs<RecordType>()) {
10836 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10837 FD->getType().getCVRQualifiers());
10842 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10845 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10846 bool IsMutable = Field && Field->isMutable();
10847 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10850 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10851 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10852 // Note, if lookup fails, it doesn't matter what exception specification we
10853 // choose because the special member will be deleted.
10854 if (CXXMethodDecl *MD = SMOR.getMethod())
10855 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10859 /// RAII object to register a special member as being currently declared.
10860 struct ComputingExceptionSpec {
10863 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc)
10865 Sema::CodeSynthesisContext Ctx;
10866 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
10867 Ctx.PointOfInstantiation = Loc;
10869 S.pushCodeSynthesisContext(Ctx);
10871 ~ComputingExceptionSpec() {
10872 S.popCodeSynthesisContext();
10877 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
10878 llvm::APSInt Result;
10879 ExprResult Converted = CheckConvertedConstantExpression(
10880 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
10881 ExplicitSpec.setExpr(Converted.get());
10882 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
10883 ExplicitSpec.setKind(Result.getBoolValue()
10884 ? ExplicitSpecKind::ResolvedTrue
10885 : ExplicitSpecKind::ResolvedFalse);
10888 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
10892 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
10893 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
10894 if (!ExplicitExpr->isTypeDependent())
10895 tryResolveExplicitSpecifier(ES);
10899 static Sema::ImplicitExceptionSpecification
10900 ComputeDefaultedSpecialMemberExceptionSpec(
10901 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10902 Sema::InheritedConstructorInfo *ICI) {
10903 ComputingExceptionSpec CES(S, MD, Loc);
10905 CXXRecordDecl *ClassDecl = MD->getParent();
10907 // C++ [except.spec]p14:
10908 // An implicitly declared special member function (Clause 12) shall have an
10909 // exception-specification. [...]
10910 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
10911 if (ClassDecl->isInvalidDecl())
10912 return Info.ExceptSpec;
10914 // FIXME: If this diagnostic fires, we're probably missing a check for
10915 // attempting to resolve an exception specification before it's known
10916 // at a higher level.
10917 if (S.RequireCompleteType(MD->getLocation(),
10918 S.Context.getRecordType(ClassDecl),
10919 diag::err_exception_spec_incomplete_type))
10920 return Info.ExceptSpec;
10922 // C++1z [except.spec]p7:
10923 // [Look for exceptions thrown by] a constructor selected [...] to
10924 // initialize a potentially constructed subobject,
10925 // C++1z [except.spec]p8:
10926 // The exception specification for an implicitly-declared destructor, or a
10927 // destructor without a noexcept-specifier, is potentially-throwing if and
10928 // only if any of the destructors for any of its potentially constructed
10929 // subojects is potentially throwing.
10930 // FIXME: We respect the first rule but ignore the "potentially constructed"
10931 // in the second rule to resolve a core issue (no number yet) that would have
10933 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10934 // struct B : A {};
10935 // struct C : B { void f(); };
10936 // ... due to giving B::~B() a non-throwing exception specification.
10937 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10938 : Info.VisitAllBases);
10940 return Info.ExceptSpec;
10944 /// RAII object to register a special member as being currently declared.
10945 struct DeclaringSpecialMember {
10947 Sema::SpecialMemberDecl D;
10948 Sema::ContextRAII SavedContext;
10949 bool WasAlreadyBeingDeclared;
10951 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10952 : S(S), D(RD, CSM), SavedContext(S, RD) {
10953 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10954 if (WasAlreadyBeingDeclared)
10955 // This almost never happens, but if it does, ensure that our cache
10956 // doesn't contain a stale result.
10957 S.SpecialMemberCache.clear();
10959 // Register a note to be produced if we encounter an error while
10960 // declaring the special member.
10961 Sema::CodeSynthesisContext Ctx;
10962 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10963 // FIXME: We don't have a location to use here. Using the class's
10964 // location maintains the fiction that we declare all special members
10965 // with the class, but (1) it's not clear that lying about that helps our
10966 // users understand what's going on, and (2) there may be outer contexts
10967 // on the stack (some of which are relevant) and printing them exposes
10969 Ctx.PointOfInstantiation = RD->getLocation();
10971 Ctx.SpecialMember = CSM;
10972 S.pushCodeSynthesisContext(Ctx);
10975 ~DeclaringSpecialMember() {
10976 if (!WasAlreadyBeingDeclared) {
10977 S.SpecialMembersBeingDeclared.erase(D);
10978 S.popCodeSynthesisContext();
10982 /// Are we already trying to declare this special member?
10983 bool isAlreadyBeingDeclared() const {
10984 return WasAlreadyBeingDeclared;
10989 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10990 // Look up any existing declarations, but don't trigger declaration of all
10991 // implicit special members with this name.
10992 DeclarationName Name = FD->getDeclName();
10993 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10994 ForExternalRedeclaration);
10995 for (auto *D : FD->getParent()->lookup(Name))
10996 if (auto *Acceptable = R.getAcceptableDecl(D))
10997 R.addDecl(Acceptable);
10999 R.suppressDiagnostics();
11001 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
11004 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
11006 ArrayRef<QualType> Args) {
11007 // Build an exception specification pointing back at this constructor.
11008 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
11010 if (getLangOpts().OpenCLCPlusPlus) {
11011 // OpenCL: Implicitly defaulted special member are of the generic address
11013 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic);
11016 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
11017 SpecialMem->setType(QT);
11020 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
11021 CXXRecordDecl *ClassDecl) {
11022 // C++ [class.ctor]p5:
11023 // A default constructor for a class X is a constructor of class X
11024 // that can be called without an argument. If there is no
11025 // user-declared constructor for class X, a default constructor is
11026 // implicitly declared. An implicitly-declared default constructor
11027 // is an inline public member of its class.
11028 assert(ClassDecl->needsImplicitDefaultConstructor() &&
11029 "Should not build implicit default constructor!");
11031 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
11032 if (DSM.isAlreadyBeingDeclared())
11035 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11036 CXXDefaultConstructor,
11039 // Create the actual constructor declaration.
11040 CanQualType ClassType
11041 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11042 SourceLocation ClassLoc = ClassDecl->getLocation();
11043 DeclarationName Name
11044 = Context.DeclarationNames.getCXXConstructorName(ClassType);
11045 DeclarationNameInfo NameInfo(Name, ClassLoc);
11046 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
11047 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
11048 /*TInfo=*/nullptr, ExplicitSpecifier(),
11049 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11050 Constexpr ? CSK_constexpr : CSK_unspecified);
11051 DefaultCon->setAccess(AS_public);
11052 DefaultCon->setDefaulted();
11054 if (getLangOpts().CUDA) {
11055 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
11057 /* ConstRHS */ false,
11058 /* Diagnose */ false);
11061 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
11063 // We don't need to use SpecialMemberIsTrivial here; triviality for default
11064 // constructors is easy to compute.
11065 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
11067 // Note that we have declared this constructor.
11068 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
11070 Scope *S = getScopeForContext(ClassDecl);
11071 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
11073 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
11074 SetDeclDeleted(DefaultCon, ClassLoc);
11077 PushOnScopeChains(DefaultCon, S, false);
11078 ClassDecl->addDecl(DefaultCon);
11083 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
11084 CXXConstructorDecl *Constructor) {
11085 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
11086 !Constructor->doesThisDeclarationHaveABody() &&
11087 !Constructor->isDeleted()) &&
11088 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
11089 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11092 CXXRecordDecl *ClassDecl = Constructor->getParent();
11093 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
11095 SynthesizedFunctionScope Scope(*this, Constructor);
11097 // The exception specification is needed because we are defining the
11099 ResolveExceptionSpec(CurrentLocation,
11100 Constructor->getType()->castAs<FunctionProtoType>());
11101 MarkVTableUsed(CurrentLocation, ClassDecl);
11103 // Add a context note for diagnostics produced after this point.
11104 Scope.addContextNote(CurrentLocation);
11106 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
11107 Constructor->setInvalidDecl();
11111 SourceLocation Loc = Constructor->getEndLoc().isValid()
11112 ? Constructor->getEndLoc()
11113 : Constructor->getLocation();
11114 Constructor->setBody(new (Context) CompoundStmt(Loc));
11115 Constructor->markUsed(Context);
11117 if (ASTMutationListener *L = getASTMutationListener()) {
11118 L->CompletedImplicitDefinition(Constructor);
11121 DiagnoseUninitializedFields(*this, Constructor);
11124 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
11125 // Perform any delayed checks on exception specifications.
11126 CheckDelayedMemberExceptionSpecs();
11129 /// Find or create the fake constructor we synthesize to model constructing an
11130 /// object of a derived class via a constructor of a base class.
11131 CXXConstructorDecl *
11132 Sema::findInheritingConstructor(SourceLocation Loc,
11133 CXXConstructorDecl *BaseCtor,
11134 ConstructorUsingShadowDecl *Shadow) {
11135 CXXRecordDecl *Derived = Shadow->getParent();
11136 SourceLocation UsingLoc = Shadow->getLocation();
11138 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
11139 // For now we use the name of the base class constructor as a member of the
11140 // derived class to indicate a (fake) inherited constructor name.
11141 DeclarationName Name = BaseCtor->getDeclName();
11143 // Check to see if we already have a fake constructor for this inherited
11144 // constructor call.
11145 for (NamedDecl *Ctor : Derived->lookup(Name))
11146 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
11147 ->getInheritedConstructor()
11150 return cast<CXXConstructorDecl>(Ctor);
11152 DeclarationNameInfo NameInfo(Name, UsingLoc);
11153 TypeSourceInfo *TInfo =
11154 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
11155 FunctionProtoTypeLoc ProtoLoc =
11156 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
11158 // Check the inherited constructor is valid and find the list of base classes
11159 // from which it was inherited.
11160 InheritedConstructorInfo ICI(*this, Loc, Shadow);
11163 BaseCtor->isConstexpr() &&
11164 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
11165 false, BaseCtor, &ICI);
11167 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
11168 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
11169 BaseCtor->getExplicitSpecifier(), /*isInline=*/true,
11170 /*isImplicitlyDeclared=*/true,
11171 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified,
11172 InheritedConstructor(Shadow, BaseCtor));
11173 if (Shadow->isInvalidDecl())
11174 DerivedCtor->setInvalidDecl();
11176 // Build an unevaluated exception specification for this fake constructor.
11177 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
11178 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11179 EPI.ExceptionSpec.Type = EST_Unevaluated;
11180 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
11181 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
11182 FPT->getParamTypes(), EPI));
11184 // Build the parameter declarations.
11185 SmallVector<ParmVarDecl *, 16> ParamDecls;
11186 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
11187 TypeSourceInfo *TInfo =
11188 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
11189 ParmVarDecl *PD = ParmVarDecl::Create(
11190 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
11191 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
11192 PD->setScopeInfo(0, I);
11194 // Ensure attributes are propagated onto parameters (this matters for
11195 // format, pass_object_size, ...).
11196 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
11197 ParamDecls.push_back(PD);
11198 ProtoLoc.setParam(I, PD);
11201 // Set up the new constructor.
11202 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
11203 DerivedCtor->setAccess(BaseCtor->getAccess());
11204 DerivedCtor->setParams(ParamDecls);
11205 Derived->addDecl(DerivedCtor);
11207 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
11208 SetDeclDeleted(DerivedCtor, UsingLoc);
11210 return DerivedCtor;
11213 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
11214 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
11215 Ctor->getInheritedConstructor().getShadowDecl());
11216 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
11220 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
11221 CXXConstructorDecl *Constructor) {
11222 CXXRecordDecl *ClassDecl = Constructor->getParent();
11223 assert(Constructor->getInheritedConstructor() &&
11224 !Constructor->doesThisDeclarationHaveABody() &&
11225 !Constructor->isDeleted());
11226 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
11229 // Initializations are performed "as if by a defaulted default constructor",
11230 // so enter the appropriate scope.
11231 SynthesizedFunctionScope Scope(*this, Constructor);
11233 // The exception specification is needed because we are defining the
11235 ResolveExceptionSpec(CurrentLocation,
11236 Constructor->getType()->castAs<FunctionProtoType>());
11237 MarkVTableUsed(CurrentLocation, ClassDecl);
11239 // Add a context note for diagnostics produced after this point.
11240 Scope.addContextNote(CurrentLocation);
11242 ConstructorUsingShadowDecl *Shadow =
11243 Constructor->getInheritedConstructor().getShadowDecl();
11244 CXXConstructorDecl *InheritedCtor =
11245 Constructor->getInheritedConstructor().getConstructor();
11247 // [class.inhctor.init]p1:
11248 // initialization proceeds as if a defaulted default constructor is used to
11249 // initialize the D object and each base class subobject from which the
11250 // constructor was inherited
11252 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
11253 CXXRecordDecl *RD = Shadow->getParent();
11254 SourceLocation InitLoc = Shadow->getLocation();
11256 // Build explicit initializers for all base classes from which the
11257 // constructor was inherited.
11258 SmallVector<CXXCtorInitializer*, 8> Inits;
11259 for (bool VBase : {false, true}) {
11260 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
11261 if (B.isVirtual() != VBase)
11264 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
11268 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
11269 if (!BaseCtor.first)
11272 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
11273 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
11274 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
11276 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
11277 Inits.push_back(new (Context) CXXCtorInitializer(
11278 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
11279 SourceLocation()));
11283 // We now proceed as if for a defaulted default constructor, with the relevant
11284 // initializers replaced.
11286 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
11287 Constructor->setInvalidDecl();
11291 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
11292 Constructor->markUsed(Context);
11294 if (ASTMutationListener *L = getASTMutationListener()) {
11295 L->CompletedImplicitDefinition(Constructor);
11298 DiagnoseUninitializedFields(*this, Constructor);
11301 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
11302 // C++ [class.dtor]p2:
11303 // If a class has no user-declared destructor, a destructor is
11304 // declared implicitly. An implicitly-declared destructor is an
11305 // inline public member of its class.
11306 assert(ClassDecl->needsImplicitDestructor());
11308 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
11309 if (DSM.isAlreadyBeingDeclared())
11312 // Create the actual destructor declaration.
11313 CanQualType ClassType
11314 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
11315 SourceLocation ClassLoc = ClassDecl->getLocation();
11316 DeclarationName Name
11317 = Context.DeclarationNames.getCXXDestructorName(ClassType);
11318 DeclarationNameInfo NameInfo(Name, ClassLoc);
11319 CXXDestructorDecl *Destructor
11320 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
11321 QualType(), nullptr, /*isInline=*/true,
11322 /*isImplicitlyDeclared=*/true);
11323 Destructor->setAccess(AS_public);
11324 Destructor->setDefaulted();
11326 if (getLangOpts().CUDA) {
11327 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
11329 /* ConstRHS */ false,
11330 /* Diagnose */ false);
11333 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
11335 // We don't need to use SpecialMemberIsTrivial here; triviality for
11336 // destructors is easy to compute.
11337 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
11338 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
11339 ClassDecl->hasTrivialDestructorForCall());
11341 // Note that we have declared this destructor.
11342 ++getASTContext().NumImplicitDestructorsDeclared;
11344 Scope *S = getScopeForContext(ClassDecl);
11345 CheckImplicitSpecialMemberDeclaration(S, Destructor);
11347 // We can't check whether an implicit destructor is deleted before we complete
11348 // the definition of the class, because its validity depends on the alignment
11349 // of the class. We'll check this from ActOnFields once the class is complete.
11350 if (ClassDecl->isCompleteDefinition() &&
11351 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
11352 SetDeclDeleted(Destructor, ClassLoc);
11354 // Introduce this destructor into its scope.
11356 PushOnScopeChains(Destructor, S, false);
11357 ClassDecl->addDecl(Destructor);
11362 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
11363 CXXDestructorDecl *Destructor) {
11364 assert((Destructor->isDefaulted() &&
11365 !Destructor->doesThisDeclarationHaveABody() &&
11366 !Destructor->isDeleted()) &&
11367 "DefineImplicitDestructor - call it for implicit default dtor");
11368 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
11371 CXXRecordDecl *ClassDecl = Destructor->getParent();
11372 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
11374 SynthesizedFunctionScope Scope(*this, Destructor);
11376 // The exception specification is needed because we are defining the
11378 ResolveExceptionSpec(CurrentLocation,
11379 Destructor->getType()->castAs<FunctionProtoType>());
11380 MarkVTableUsed(CurrentLocation, ClassDecl);
11382 // Add a context note for diagnostics produced after this point.
11383 Scope.addContextNote(CurrentLocation);
11385 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11386 Destructor->getParent());
11388 if (CheckDestructor(Destructor)) {
11389 Destructor->setInvalidDecl();
11393 SourceLocation Loc = Destructor->getEndLoc().isValid()
11394 ? Destructor->getEndLoc()
11395 : Destructor->getLocation();
11396 Destructor->setBody(new (Context) CompoundStmt(Loc));
11397 Destructor->markUsed(Context);
11399 if (ASTMutationListener *L = getASTMutationListener()) {
11400 L->CompletedImplicitDefinition(Destructor);
11404 /// Perform any semantic analysis which needs to be delayed until all
11405 /// pending class member declarations have been parsed.
11406 void Sema::ActOnFinishCXXMemberDecls() {
11407 // If the context is an invalid C++ class, just suppress these checks.
11408 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
11409 if (Record->isInvalidDecl()) {
11410 DelayedOverridingExceptionSpecChecks.clear();
11411 DelayedEquivalentExceptionSpecChecks.clear();
11414 checkForMultipleExportedDefaultConstructors(*this, Record);
11418 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
11419 referenceDLLExportedClassMethods();
11421 if (!DelayedDllExportMemberFunctions.empty()) {
11422 SmallVector<CXXMethodDecl*, 4> WorkList;
11423 std::swap(DelayedDllExportMemberFunctions, WorkList);
11424 for (CXXMethodDecl *M : WorkList) {
11425 DefineImplicitSpecialMember(*this, M, M->getLocation());
11427 // Pass the method to the consumer to get emitted. This is not necessary
11428 // for explicit instantiation definitions, as they will get emitted
11430 if (M->getParent()->getTemplateSpecializationKind() !=
11431 TSK_ExplicitInstantiationDefinition)
11432 ActOnFinishInlineFunctionDef(M);
11437 void Sema::referenceDLLExportedClassMethods() {
11438 if (!DelayedDllExportClasses.empty()) {
11439 // Calling ReferenceDllExportedMembers might cause the current function to
11440 // be called again, so use a local copy of DelayedDllExportClasses.
11441 SmallVector<CXXRecordDecl *, 4> WorkList;
11442 std::swap(DelayedDllExportClasses, WorkList);
11443 for (CXXRecordDecl *Class : WorkList)
11444 ReferenceDllExportedMembers(*this, Class);
11448 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
11449 assert(getLangOpts().CPlusPlus11 &&
11450 "adjusting dtor exception specs was introduced in c++11");
11452 if (Destructor->isDependentContext())
11455 // C++11 [class.dtor]p3:
11456 // A declaration of a destructor that does not have an exception-
11457 // specification is implicitly considered to have the same exception-
11458 // specification as an implicit declaration.
11459 const FunctionProtoType *DtorType = Destructor->getType()->
11460 getAs<FunctionProtoType>();
11461 if (DtorType->hasExceptionSpec())
11464 // Replace the destructor's type, building off the existing one. Fortunately,
11465 // the only thing of interest in the destructor type is its extended info.
11466 // The return and arguments are fixed.
11467 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
11468 EPI.ExceptionSpec.Type = EST_Unevaluated;
11469 EPI.ExceptionSpec.SourceDecl = Destructor;
11470 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
11472 // FIXME: If the destructor has a body that could throw, and the newly created
11473 // spec doesn't allow exceptions, we should emit a warning, because this
11474 // change in behavior can break conforming C++03 programs at runtime.
11475 // However, we don't have a body or an exception specification yet, so it
11476 // needs to be done somewhere else.
11480 /// An abstract base class for all helper classes used in building the
11481 // copy/move operators. These classes serve as factory functions and help us
11482 // avoid using the same Expr* in the AST twice.
11483 class ExprBuilder {
11484 ExprBuilder(const ExprBuilder&) = delete;
11485 ExprBuilder &operator=(const ExprBuilder&) = delete;
11488 static Expr *assertNotNull(Expr *E) {
11489 assert(E && "Expression construction must not fail.");
11495 virtual ~ExprBuilder() {}
11497 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
11500 class RefBuilder: public ExprBuilder {
11505 Expr *build(Sema &S, SourceLocation Loc) const override {
11506 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
11509 RefBuilder(VarDecl *Var, QualType VarType)
11510 : Var(Var), VarType(VarType) {}
11513 class ThisBuilder: public ExprBuilder {
11515 Expr *build(Sema &S, SourceLocation Loc) const override {
11516 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
11520 class CastBuilder: public ExprBuilder {
11521 const ExprBuilder &Builder;
11523 ExprValueKind Kind;
11524 const CXXCastPath &Path;
11527 Expr *build(Sema &S, SourceLocation Loc) const override {
11528 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
11529 CK_UncheckedDerivedToBase, Kind,
11533 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
11534 const CXXCastPath &Path)
11535 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
11538 class DerefBuilder: public ExprBuilder {
11539 const ExprBuilder &Builder;
11542 Expr *build(Sema &S, SourceLocation Loc) const override {
11543 return assertNotNull(
11544 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
11547 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11550 class MemberBuilder: public ExprBuilder {
11551 const ExprBuilder &Builder;
11555 LookupResult &MemberLookup;
11558 Expr *build(Sema &S, SourceLocation Loc) const override {
11559 return assertNotNull(S.BuildMemberReferenceExpr(
11560 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
11561 nullptr, MemberLookup, nullptr, nullptr).get());
11564 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
11565 LookupResult &MemberLookup)
11566 : Builder(Builder), Type(Type), IsArrow(IsArrow),
11567 MemberLookup(MemberLookup) {}
11570 class MoveCastBuilder: public ExprBuilder {
11571 const ExprBuilder &Builder;
11574 Expr *build(Sema &S, SourceLocation Loc) const override {
11575 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
11578 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11581 class LvalueConvBuilder: public ExprBuilder {
11582 const ExprBuilder &Builder;
11585 Expr *build(Sema &S, SourceLocation Loc) const override {
11586 return assertNotNull(
11587 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
11590 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
11593 class SubscriptBuilder: public ExprBuilder {
11594 const ExprBuilder &Base;
11595 const ExprBuilder &Index;
11598 Expr *build(Sema &S, SourceLocation Loc) const override {
11599 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
11600 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
11603 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
11604 : Base(Base), Index(Index) {}
11607 } // end anonymous namespace
11609 /// When generating a defaulted copy or move assignment operator, if a field
11610 /// should be copied with __builtin_memcpy rather than via explicit assignments,
11611 /// do so. This optimization only applies for arrays of scalars, and for arrays
11612 /// of class type where the selected copy/move-assignment operator is trivial.
11614 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
11615 const ExprBuilder &ToB, const ExprBuilder &FromB) {
11616 // Compute the size of the memory buffer to be copied.
11617 QualType SizeType = S.Context.getSizeType();
11618 llvm::APInt Size(S.Context.getTypeSize(SizeType),
11619 S.Context.getTypeSizeInChars(T).getQuantity());
11621 // Take the address of the field references for "from" and "to". We
11622 // directly construct UnaryOperators here because semantic analysis
11623 // does not permit us to take the address of an xvalue.
11624 Expr *From = FromB.build(S, Loc);
11625 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
11626 S.Context.getPointerType(From->getType()),
11627 VK_RValue, OK_Ordinary, Loc, false);
11628 Expr *To = ToB.build(S, Loc);
11629 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
11630 S.Context.getPointerType(To->getType()),
11631 VK_RValue, OK_Ordinary, Loc, false);
11633 const Type *E = T->getBaseElementTypeUnsafe();
11634 bool NeedsCollectableMemCpy =
11635 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11637 // Create a reference to the __builtin_objc_memmove_collectable function
11638 StringRef MemCpyName = NeedsCollectableMemCpy ?
11639 "__builtin_objc_memmove_collectable" :
11640 "__builtin_memcpy";
11641 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11642 Sema::LookupOrdinaryName);
11643 S.LookupName(R, S.TUScope, true);
11645 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11647 // Something went horribly wrong earlier, and we will have complained
11649 return StmtError();
11651 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11652 VK_RValue, Loc, nullptr);
11653 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11655 Expr *CallArgs[] = {
11656 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11658 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11659 Loc, CallArgs, Loc);
11661 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11662 return Call.getAs<Stmt>();
11665 /// Builds a statement that copies/moves the given entity from \p From to
11668 /// This routine is used to copy/move the members of a class with an
11669 /// implicitly-declared copy/move assignment operator. When the entities being
11670 /// copied are arrays, this routine builds for loops to copy them.
11672 /// \param S The Sema object used for type-checking.
11674 /// \param Loc The location where the implicit copy/move is being generated.
11676 /// \param T The type of the expressions being copied/moved. Both expressions
11677 /// must have this type.
11679 /// \param To The expression we are copying/moving to.
11681 /// \param From The expression we are copying/moving from.
11683 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11684 /// Otherwise, it's a non-static member subobject.
11686 /// \param Copying Whether we're copying or moving.
11688 /// \param Depth Internal parameter recording the depth of the recursion.
11690 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11691 /// if a memcpy should be used instead.
11693 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11694 const ExprBuilder &To, const ExprBuilder &From,
11695 bool CopyingBaseSubobject, bool Copying,
11696 unsigned Depth = 0) {
11697 // C++11 [class.copy]p28:
11698 // Each subobject is assigned in the manner appropriate to its type:
11700 // - if the subobject is of class type, as if by a call to operator= with
11701 // the subobject as the object expression and the corresponding
11702 // subobject of x as a single function argument (as if by explicit
11703 // qualification; that is, ignoring any possible virtual overriding
11704 // functions in more derived classes);
11706 // C++03 [class.copy]p13:
11707 // - if the subobject is of class type, the copy assignment operator for
11708 // the class is used (as if by explicit qualification; that is,
11709 // ignoring any possible virtual overriding functions in more derived
11711 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11712 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11714 // Look for operator=.
11715 DeclarationName Name
11716 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11717 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11718 S.LookupQualifiedName(OpLookup, ClassDecl, false);
11720 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11722 if (!S.getLangOpts().CPlusPlus11) {
11723 LookupResult::Filter F = OpLookup.makeFilter();
11724 while (F.hasNext()) {
11725 NamedDecl *D = F.next();
11726 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11727 if (Method->isCopyAssignmentOperator() ||
11728 (!Copying && Method->isMoveAssignmentOperator()))
11736 // Suppress the protected check (C++ [class.protected]) for each of the
11737 // assignment operators we found. This strange dance is required when
11738 // we're assigning via a base classes's copy-assignment operator. To
11739 // ensure that we're getting the right base class subobject (without
11740 // ambiguities), we need to cast "this" to that subobject type; to
11741 // ensure that we don't go through the virtual call mechanism, we need
11742 // to qualify the operator= name with the base class (see below). However,
11743 // this means that if the base class has a protected copy assignment
11744 // operator, the protected member access check will fail. So, we
11745 // rewrite "protected" access to "public" access in this case, since we
11746 // know by construction that we're calling from a derived class.
11747 if (CopyingBaseSubobject) {
11748 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11750 if (L.getAccess() == AS_protected)
11751 L.setAccess(AS_public);
11755 // Create the nested-name-specifier that will be used to qualify the
11756 // reference to operator=; this is required to suppress the virtual
11759 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11760 SS.MakeTrivial(S.Context,
11761 NestedNameSpecifier::Create(S.Context, nullptr, false,
11765 // Create the reference to operator=.
11766 ExprResult OpEqualRef
11767 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
11768 SS, /*TemplateKWLoc=*/SourceLocation(),
11769 /*FirstQualifierInScope=*/nullptr,
11771 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11772 /*SuppressQualifierCheck=*/true);
11773 if (OpEqualRef.isInvalid())
11774 return StmtError();
11776 // Build the call to the assignment operator.
11778 Expr *FromInst = From.build(S, Loc);
11779 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11780 OpEqualRef.getAs<Expr>(),
11781 Loc, FromInst, Loc);
11782 if (Call.isInvalid())
11783 return StmtError();
11785 // If we built a call to a trivial 'operator=' while copying an array,
11786 // bail out. We'll replace the whole shebang with a memcpy.
11787 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11788 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11789 return StmtResult((Stmt*)nullptr);
11791 // Convert to an expression-statement, and clean up any produced
11793 return S.ActOnExprStmt(Call);
11796 // - if the subobject is of scalar type, the built-in assignment
11797 // operator is used.
11798 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11800 ExprResult Assignment = S.CreateBuiltinBinOp(
11801 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11802 if (Assignment.isInvalid())
11803 return StmtError();
11804 return S.ActOnExprStmt(Assignment);
11807 // - if the subobject is an array, each element is assigned, in the
11808 // manner appropriate to the element type;
11810 // Construct a loop over the array bounds, e.g.,
11812 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11814 // that will copy each of the array elements.
11815 QualType SizeType = S.Context.getSizeType();
11817 // Create the iteration variable.
11818 IdentifierInfo *IterationVarName = nullptr;
11820 SmallString<8> Str;
11821 llvm::raw_svector_ostream OS(Str);
11822 OS << "__i" << Depth;
11823 IterationVarName = &S.Context.Idents.get(OS.str());
11825 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11826 IterationVarName, SizeType,
11827 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11830 // Initialize the iteration variable to zero.
11831 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11832 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11834 // Creates a reference to the iteration variable.
11835 RefBuilder IterationVarRef(IterationVar, SizeType);
11836 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11838 // Create the DeclStmt that holds the iteration variable.
11839 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11841 // Subscript the "from" and "to" expressions with the iteration variable.
11842 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11843 MoveCastBuilder FromIndexMove(FromIndexCopy);
11844 const ExprBuilder *FromIndex;
11846 FromIndex = &FromIndexCopy;
11848 FromIndex = &FromIndexMove;
11850 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11852 // Build the copy/move for an individual element of the array.
11854 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11855 ToIndex, *FromIndex, CopyingBaseSubobject,
11856 Copying, Depth + 1);
11857 // Bail out if copying fails or if we determined that we should use memcpy.
11858 if (Copy.isInvalid() || !Copy.get())
11861 // Create the comparison against the array bound.
11863 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11865 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11866 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11867 BO_NE, S.Context.BoolTy,
11868 VK_RValue, OK_Ordinary, Loc, FPOptions());
11870 // Create the pre-increment of the iteration variable. We can determine
11871 // whether the increment will overflow based on the value of the array
11873 Expr *Increment = new (S.Context)
11874 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType,
11875 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue());
11877 // Construct the loop that copies all elements of this array.
11878 return S.ActOnForStmt(
11879 Loc, Loc, InitStmt,
11880 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11881 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11885 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11886 const ExprBuilder &To, const ExprBuilder &From,
11887 bool CopyingBaseSubobject, bool Copying) {
11888 // Maybe we should use a memcpy?
11889 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11890 T.isTriviallyCopyableType(S.Context))
11891 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11893 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11894 CopyingBaseSubobject,
11897 // If we ended up picking a trivial assignment operator for an array of a
11898 // non-trivially-copyable class type, just emit a memcpy.
11899 if (!Result.isInvalid() && !Result.get())
11900 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11905 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11906 // Note: The following rules are largely analoguous to the copy
11907 // constructor rules. Note that virtual bases are not taken into account
11908 // for determining the argument type of the operator. Note also that
11909 // operators taking an object instead of a reference are allowed.
11910 assert(ClassDecl->needsImplicitCopyAssignment());
11912 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11913 if (DSM.isAlreadyBeingDeclared())
11916 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11917 if (Context.getLangOpts().OpenCLCPlusPlus)
11918 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
11919 QualType RetType = Context.getLValueReferenceType(ArgType);
11920 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11922 ArgType = ArgType.withConst();
11924 ArgType = Context.getLValueReferenceType(ArgType);
11926 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11930 // An implicitly-declared copy assignment operator is an inline public
11931 // member of its class.
11932 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11933 SourceLocation ClassLoc = ClassDecl->getLocation();
11934 DeclarationNameInfo NameInfo(Name, ClassLoc);
11935 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
11936 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11937 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11938 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
11940 CopyAssignment->setAccess(AS_public);
11941 CopyAssignment->setDefaulted();
11942 CopyAssignment->setImplicit();
11944 if (getLangOpts().CUDA) {
11945 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11947 /* ConstRHS */ Const,
11948 /* Diagnose */ false);
11951 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
11953 // Add the parameter to the operator.
11954 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11955 ClassLoc, ClassLoc,
11956 /*Id=*/nullptr, ArgType,
11957 /*TInfo=*/nullptr, SC_None,
11959 CopyAssignment->setParams(FromParam);
11961 CopyAssignment->setTrivial(
11962 ClassDecl->needsOverloadResolutionForCopyAssignment()
11963 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11964 : ClassDecl->hasTrivialCopyAssignment());
11966 // Note that we have added this copy-assignment operator.
11967 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
11969 Scope *S = getScopeForContext(ClassDecl);
11970 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11972 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11973 SetDeclDeleted(CopyAssignment, ClassLoc);
11976 PushOnScopeChains(CopyAssignment, S, false);
11977 ClassDecl->addDecl(CopyAssignment);
11979 return CopyAssignment;
11982 /// Diagnose an implicit copy operation for a class which is odr-used, but
11983 /// which is deprecated because the class has a user-declared copy constructor,
11984 /// copy assignment operator, or destructor.
11985 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11986 assert(CopyOp->isImplicit());
11988 CXXRecordDecl *RD = CopyOp->getParent();
11989 CXXMethodDecl *UserDeclaredOperation = nullptr;
11991 // In Microsoft mode, assignment operations don't affect constructors and
11993 if (RD->hasUserDeclaredDestructor()) {
11994 UserDeclaredOperation = RD->getDestructor();
11995 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11996 RD->hasUserDeclaredCopyConstructor() &&
11997 !S.getLangOpts().MSVCCompat) {
11998 // Find any user-declared copy constructor.
11999 for (auto *I : RD->ctors()) {
12000 if (I->isCopyConstructor()) {
12001 UserDeclaredOperation = I;
12005 assert(UserDeclaredOperation);
12006 } else if (isa<CXXConstructorDecl>(CopyOp) &&
12007 RD->hasUserDeclaredCopyAssignment() &&
12008 !S.getLangOpts().MSVCCompat) {
12009 // Find any user-declared move assignment operator.
12010 for (auto *I : RD->methods()) {
12011 if (I->isCopyAssignmentOperator()) {
12012 UserDeclaredOperation = I;
12016 assert(UserDeclaredOperation);
12019 if (UserDeclaredOperation) {
12020 S.Diag(UserDeclaredOperation->getLocation(),
12021 diag::warn_deprecated_copy_operation)
12022 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
12023 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
12027 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
12028 CXXMethodDecl *CopyAssignOperator) {
12029 assert((CopyAssignOperator->isDefaulted() &&
12030 CopyAssignOperator->isOverloadedOperator() &&
12031 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
12032 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
12033 !CopyAssignOperator->isDeleted()) &&
12034 "DefineImplicitCopyAssignment called for wrong function");
12035 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
12038 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
12039 if (ClassDecl->isInvalidDecl()) {
12040 CopyAssignOperator->setInvalidDecl();
12044 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
12046 // The exception specification is needed because we are defining the
12048 ResolveExceptionSpec(CurrentLocation,
12049 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
12051 // Add a context note for diagnostics produced after this point.
12052 Scope.addContextNote(CurrentLocation);
12054 // C++11 [class.copy]p18:
12055 // The [definition of an implicitly declared copy assignment operator] is
12056 // deprecated if the class has a user-declared copy constructor or a
12057 // user-declared destructor.
12058 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
12059 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
12061 // C++0x [class.copy]p30:
12062 // The implicitly-defined or explicitly-defaulted copy assignment operator
12063 // for a non-union class X performs memberwise copy assignment of its
12064 // subobjects. The direct base classes of X are assigned first, in the
12065 // order of their declaration in the base-specifier-list, and then the
12066 // immediate non-static data members of X are assigned, in the order in
12067 // which they were declared in the class definition.
12069 // The statements that form the synthesized function body.
12070 SmallVector<Stmt*, 8> Statements;
12072 // The parameter for the "other" object, which we are copying from.
12073 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
12074 Qualifiers OtherQuals = Other->getType().getQualifiers();
12075 QualType OtherRefType = Other->getType();
12076 if (const LValueReferenceType *OtherRef
12077 = OtherRefType->getAs<LValueReferenceType>()) {
12078 OtherRefType = OtherRef->getPointeeType();
12079 OtherQuals = OtherRefType.getQualifiers();
12082 // Our location for everything implicitly-generated.
12083 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
12084 ? CopyAssignOperator->getEndLoc()
12085 : CopyAssignOperator->getLocation();
12087 // Builds a DeclRefExpr for the "other" object.
12088 RefBuilder OtherRef(Other, OtherRefType);
12090 // Builds the "this" pointer.
12093 // Assign base classes.
12094 bool Invalid = false;
12095 for (auto &Base : ClassDecl->bases()) {
12096 // Form the assignment:
12097 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
12098 QualType BaseType = Base.getType().getUnqualifiedType();
12099 if (!BaseType->isRecordType()) {
12104 CXXCastPath BasePath;
12105 BasePath.push_back(&Base);
12107 // Construct the "from" expression, which is an implicit cast to the
12108 // appropriately-qualified base type.
12109 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
12110 VK_LValue, BasePath);
12112 // Dereference "this".
12113 DerefBuilder DerefThis(This);
12114 CastBuilder To(DerefThis,
12115 Context.getQualifiedType(
12116 BaseType, CopyAssignOperator->getMethodQualifiers()),
12117 VK_LValue, BasePath);
12120 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
12122 /*CopyingBaseSubobject=*/true,
12124 if (Copy.isInvalid()) {
12125 CopyAssignOperator->setInvalidDecl();
12129 // Success! Record the copy.
12130 Statements.push_back(Copy.getAs<Expr>());
12133 // Assign non-static members.
12134 for (auto *Field : ClassDecl->fields()) {
12135 // FIXME: We should form some kind of AST representation for the implied
12136 // memcpy in a union copy operation.
12137 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12140 if (Field->isInvalidDecl()) {
12145 // Check for members of reference type; we can't copy those.
12146 if (Field->getType()->isReferenceType()) {
12147 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12148 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12149 Diag(Field->getLocation(), diag::note_declared_at);
12154 // Check for members of const-qualified, non-class type.
12155 QualType BaseType = Context.getBaseElementType(Field->getType());
12156 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12157 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12158 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12159 Diag(Field->getLocation(), diag::note_declared_at);
12164 // Suppress assigning zero-width bitfields.
12165 if (Field->isZeroLengthBitField(Context))
12168 QualType FieldType = Field->getType().getNonReferenceType();
12169 if (FieldType->isIncompleteArrayType()) {
12170 assert(ClassDecl->hasFlexibleArrayMember() &&
12171 "Incomplete array type is not valid");
12175 // Build references to the field in the object we're copying from and to.
12176 CXXScopeSpec SS; // Intentionally empty
12177 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12179 MemberLookup.addDecl(Field);
12180 MemberLookup.resolveKind();
12182 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
12184 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
12186 // Build the copy of this field.
12187 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
12189 /*CopyingBaseSubobject=*/false,
12191 if (Copy.isInvalid()) {
12192 CopyAssignOperator->setInvalidDecl();
12196 // Success! Record the copy.
12197 Statements.push_back(Copy.getAs<Stmt>());
12201 // Add a "return *this;"
12202 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12204 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12205 if (Return.isInvalid())
12208 Statements.push_back(Return.getAs<Stmt>());
12212 CopyAssignOperator->setInvalidDecl();
12218 CompoundScopeRAII CompoundScope(*this);
12219 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12220 /*isStmtExpr=*/false);
12221 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12223 CopyAssignOperator->setBody(Body.getAs<Stmt>());
12224 CopyAssignOperator->markUsed(Context);
12226 if (ASTMutationListener *L = getASTMutationListener()) {
12227 L->CompletedImplicitDefinition(CopyAssignOperator);
12231 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
12232 assert(ClassDecl->needsImplicitMoveAssignment());
12234 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
12235 if (DSM.isAlreadyBeingDeclared())
12238 // Note: The following rules are largely analoguous to the move
12239 // constructor rules.
12241 QualType ArgType = Context.getTypeDeclType(ClassDecl);
12242 if (Context.getLangOpts().OpenCLCPlusPlus)
12243 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12244 QualType RetType = Context.getLValueReferenceType(ArgType);
12245 ArgType = Context.getRValueReferenceType(ArgType);
12247 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12251 // An implicitly-declared move assignment operator is an inline public
12252 // member of its class.
12253 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
12254 SourceLocation ClassLoc = ClassDecl->getLocation();
12255 DeclarationNameInfo NameInfo(Name, ClassLoc);
12256 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
12257 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
12258 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
12259 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified,
12261 MoveAssignment->setAccess(AS_public);
12262 MoveAssignment->setDefaulted();
12263 MoveAssignment->setImplicit();
12265 if (getLangOpts().CUDA) {
12266 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
12268 /* ConstRHS */ false,
12269 /* Diagnose */ false);
12272 // Build an exception specification pointing back at this member.
12273 FunctionProtoType::ExtProtoInfo EPI =
12274 getImplicitMethodEPI(*this, MoveAssignment);
12275 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
12277 // Add the parameter to the operator.
12278 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
12279 ClassLoc, ClassLoc,
12280 /*Id=*/nullptr, ArgType,
12281 /*TInfo=*/nullptr, SC_None,
12283 MoveAssignment->setParams(FromParam);
12285 MoveAssignment->setTrivial(
12286 ClassDecl->needsOverloadResolutionForMoveAssignment()
12287 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
12288 : ClassDecl->hasTrivialMoveAssignment());
12290 // Note that we have added this copy-assignment operator.
12291 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
12293 Scope *S = getScopeForContext(ClassDecl);
12294 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
12296 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
12297 ClassDecl->setImplicitMoveAssignmentIsDeleted();
12298 SetDeclDeleted(MoveAssignment, ClassLoc);
12302 PushOnScopeChains(MoveAssignment, S, false);
12303 ClassDecl->addDecl(MoveAssignment);
12305 return MoveAssignment;
12308 /// Check if we're implicitly defining a move assignment operator for a class
12309 /// with virtual bases. Such a move assignment might move-assign the virtual
12310 /// base multiple times.
12311 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
12312 SourceLocation CurrentLocation) {
12313 assert(!Class->isDependentContext() && "should not define dependent move");
12315 // Only a virtual base could get implicitly move-assigned multiple times.
12316 // Only a non-trivial move assignment can observe this. We only want to
12317 // diagnose if we implicitly define an assignment operator that assigns
12318 // two base classes, both of which move-assign the same virtual base.
12319 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
12320 Class->getNumBases() < 2)
12323 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
12324 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
12327 for (auto &BI : Class->bases()) {
12328 Worklist.push_back(&BI);
12329 while (!Worklist.empty()) {
12330 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
12331 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
12333 // If the base has no non-trivial move assignment operators,
12334 // we don't care about moves from it.
12335 if (!Base->hasNonTrivialMoveAssignment())
12338 // If there's nothing virtual here, skip it.
12339 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
12342 // If we're not actually going to call a move assignment for this base,
12343 // or the selected move assignment is trivial, skip it.
12344 Sema::SpecialMemberOverloadResult SMOR =
12345 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
12346 /*ConstArg*/false, /*VolatileArg*/false,
12347 /*RValueThis*/true, /*ConstThis*/false,
12348 /*VolatileThis*/false);
12349 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
12350 !SMOR.getMethod()->isMoveAssignmentOperator())
12353 if (BaseSpec->isVirtual()) {
12354 // We're going to move-assign this virtual base, and its move
12355 // assignment operator is not trivial. If this can happen for
12356 // multiple distinct direct bases of Class, diagnose it. (If it
12357 // only happens in one base, we'll diagnose it when synthesizing
12358 // that base class's move assignment operator.)
12359 CXXBaseSpecifier *&Existing =
12360 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
12362 if (Existing && Existing != &BI) {
12363 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
12365 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
12366 << (Base->getCanonicalDecl() ==
12367 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12368 << Base << Existing->getType() << Existing->getSourceRange();
12369 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
12370 << (Base->getCanonicalDecl() ==
12371 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
12372 << Base << BI.getType() << BaseSpec->getSourceRange();
12374 // Only diagnose each vbase once.
12375 Existing = nullptr;
12378 // Only walk over bases that have defaulted move assignment operators.
12379 // We assume that any user-provided move assignment operator handles
12380 // the multiple-moves-of-vbase case itself somehow.
12381 if (!SMOR.getMethod()->isDefaulted())
12384 // We're going to move the base classes of Base. Add them to the list.
12385 for (auto &BI : Base->bases())
12386 Worklist.push_back(&BI);
12392 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
12393 CXXMethodDecl *MoveAssignOperator) {
12394 assert((MoveAssignOperator->isDefaulted() &&
12395 MoveAssignOperator->isOverloadedOperator() &&
12396 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
12397 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
12398 !MoveAssignOperator->isDeleted()) &&
12399 "DefineImplicitMoveAssignment called for wrong function");
12400 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
12403 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
12404 if (ClassDecl->isInvalidDecl()) {
12405 MoveAssignOperator->setInvalidDecl();
12409 // C++0x [class.copy]p28:
12410 // The implicitly-defined or move assignment operator for a non-union class
12411 // X performs memberwise move assignment of its subobjects. The direct base
12412 // classes of X are assigned first, in the order of their declaration in the
12413 // base-specifier-list, and then the immediate non-static data members of X
12414 // are assigned, in the order in which they were declared in the class
12417 // Issue a warning if our implicit move assignment operator will move
12418 // from a virtual base more than once.
12419 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
12421 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
12423 // The exception specification is needed because we are defining the
12425 ResolveExceptionSpec(CurrentLocation,
12426 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
12428 // Add a context note for diagnostics produced after this point.
12429 Scope.addContextNote(CurrentLocation);
12431 // The statements that form the synthesized function body.
12432 SmallVector<Stmt*, 8> Statements;
12434 // The parameter for the "other" object, which we are move from.
12435 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
12436 QualType OtherRefType = Other->getType()->
12437 getAs<RValueReferenceType>()->getPointeeType();
12439 // Our location for everything implicitly-generated.
12440 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
12441 ? MoveAssignOperator->getEndLoc()
12442 : MoveAssignOperator->getLocation();
12444 // Builds a reference to the "other" object.
12445 RefBuilder OtherRef(Other, OtherRefType);
12447 MoveCastBuilder MoveOther(OtherRef);
12449 // Builds the "this" pointer.
12452 // Assign base classes.
12453 bool Invalid = false;
12454 for (auto &Base : ClassDecl->bases()) {
12455 // C++11 [class.copy]p28:
12456 // It is unspecified whether subobjects representing virtual base classes
12457 // are assigned more than once by the implicitly-defined copy assignment
12459 // FIXME: Do not assign to a vbase that will be assigned by some other base
12460 // class. For a move-assignment, this can result in the vbase being moved
12463 // Form the assignment:
12464 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
12465 QualType BaseType = Base.getType().getUnqualifiedType();
12466 if (!BaseType->isRecordType()) {
12471 CXXCastPath BasePath;
12472 BasePath.push_back(&Base);
12474 // Construct the "from" expression, which is an implicit cast to the
12475 // appropriately-qualified base type.
12476 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
12478 // Dereference "this".
12479 DerefBuilder DerefThis(This);
12481 // Implicitly cast "this" to the appropriately-qualified base type.
12482 CastBuilder To(DerefThis,
12483 Context.getQualifiedType(
12484 BaseType, MoveAssignOperator->getMethodQualifiers()),
12485 VK_LValue, BasePath);
12488 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
12490 /*CopyingBaseSubobject=*/true,
12491 /*Copying=*/false);
12492 if (Move.isInvalid()) {
12493 MoveAssignOperator->setInvalidDecl();
12497 // Success! Record the move.
12498 Statements.push_back(Move.getAs<Expr>());
12501 // Assign non-static members.
12502 for (auto *Field : ClassDecl->fields()) {
12503 // FIXME: We should form some kind of AST representation for the implied
12504 // memcpy in a union copy operation.
12505 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
12508 if (Field->isInvalidDecl()) {
12513 // Check for members of reference type; we can't move those.
12514 if (Field->getType()->isReferenceType()) {
12515 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12516 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
12517 Diag(Field->getLocation(), diag::note_declared_at);
12522 // Check for members of const-qualified, non-class type.
12523 QualType BaseType = Context.getBaseElementType(Field->getType());
12524 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
12525 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
12526 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
12527 Diag(Field->getLocation(), diag::note_declared_at);
12532 // Suppress assigning zero-width bitfields.
12533 if (Field->isZeroLengthBitField(Context))
12536 QualType FieldType = Field->getType().getNonReferenceType();
12537 if (FieldType->isIncompleteArrayType()) {
12538 assert(ClassDecl->hasFlexibleArrayMember() &&
12539 "Incomplete array type is not valid");
12543 // Build references to the field in the object we're copying from and to.
12544 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
12546 MemberLookup.addDecl(Field);
12547 MemberLookup.resolveKind();
12548 MemberBuilder From(MoveOther, OtherRefType,
12549 /*IsArrow=*/false, MemberLookup);
12550 MemberBuilder To(This, getCurrentThisType(),
12551 /*IsArrow=*/true, MemberLookup);
12553 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
12554 "Member reference with rvalue base must be rvalue except for reference "
12555 "members, which aren't allowed for move assignment.");
12557 // Build the move of this field.
12558 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
12560 /*CopyingBaseSubobject=*/false,
12561 /*Copying=*/false);
12562 if (Move.isInvalid()) {
12563 MoveAssignOperator->setInvalidDecl();
12567 // Success! Record the copy.
12568 Statements.push_back(Move.getAs<Stmt>());
12572 // Add a "return *this;"
12573 ExprResult ThisObj =
12574 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
12576 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
12577 if (Return.isInvalid())
12580 Statements.push_back(Return.getAs<Stmt>());
12584 MoveAssignOperator->setInvalidDecl();
12590 CompoundScopeRAII CompoundScope(*this);
12591 Body = ActOnCompoundStmt(Loc, Loc, Statements,
12592 /*isStmtExpr=*/false);
12593 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
12595 MoveAssignOperator->setBody(Body.getAs<Stmt>());
12596 MoveAssignOperator->markUsed(Context);
12598 if (ASTMutationListener *L = getASTMutationListener()) {
12599 L->CompletedImplicitDefinition(MoveAssignOperator);
12603 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
12604 CXXRecordDecl *ClassDecl) {
12605 // C++ [class.copy]p4:
12606 // If the class definition does not explicitly declare a copy
12607 // constructor, one is declared implicitly.
12608 assert(ClassDecl->needsImplicitCopyConstructor());
12610 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
12611 if (DSM.isAlreadyBeingDeclared())
12614 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12615 QualType ArgType = ClassType;
12616 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
12618 ArgType = ArgType.withConst();
12620 if (Context.getLangOpts().OpenCLCPlusPlus)
12621 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic);
12623 ArgType = Context.getLValueReferenceType(ArgType);
12625 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12626 CXXCopyConstructor,
12629 DeclarationName Name
12630 = Context.DeclarationNames.getCXXConstructorName(
12631 Context.getCanonicalType(ClassType));
12632 SourceLocation ClassLoc = ClassDecl->getLocation();
12633 DeclarationNameInfo NameInfo(Name, ClassLoc);
12635 // An implicitly-declared copy constructor is an inline public
12636 // member of its class.
12637 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
12638 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12639 ExplicitSpecifier(),
12641 /*isImplicitlyDeclared=*/true,
12642 Constexpr ? CSK_constexpr : CSK_unspecified);
12643 CopyConstructor->setAccess(AS_public);
12644 CopyConstructor->setDefaulted();
12646 if (getLangOpts().CUDA) {
12647 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12649 /* ConstRHS */ Const,
12650 /* Diagnose */ false);
12653 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
12655 // Add the parameter to the constructor.
12656 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12657 ClassLoc, ClassLoc,
12658 /*IdentifierInfo=*/nullptr,
12659 ArgType, /*TInfo=*/nullptr,
12661 CopyConstructor->setParams(FromParam);
12663 CopyConstructor->setTrivial(
12664 ClassDecl->needsOverloadResolutionForCopyConstructor()
12665 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12666 : ClassDecl->hasTrivialCopyConstructor());
12668 CopyConstructor->setTrivialForCall(
12669 ClassDecl->hasAttr<TrivialABIAttr>() ||
12670 (ClassDecl->needsOverloadResolutionForCopyConstructor()
12671 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
12672 TAH_ConsiderTrivialABI)
12673 : ClassDecl->hasTrivialCopyConstructorForCall()));
12675 // Note that we have declared this constructor.
12676 ++getASTContext().NumImplicitCopyConstructorsDeclared;
12678 Scope *S = getScopeForContext(ClassDecl);
12679 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12681 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12682 ClassDecl->setImplicitCopyConstructorIsDeleted();
12683 SetDeclDeleted(CopyConstructor, ClassLoc);
12687 PushOnScopeChains(CopyConstructor, S, false);
12688 ClassDecl->addDecl(CopyConstructor);
12690 return CopyConstructor;
12693 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12694 CXXConstructorDecl *CopyConstructor) {
12695 assert((CopyConstructor->isDefaulted() &&
12696 CopyConstructor->isCopyConstructor() &&
12697 !CopyConstructor->doesThisDeclarationHaveABody() &&
12698 !CopyConstructor->isDeleted()) &&
12699 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12700 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12703 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12704 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12706 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12708 // The exception specification is needed because we are defining the
12710 ResolveExceptionSpec(CurrentLocation,
12711 CopyConstructor->getType()->castAs<FunctionProtoType>());
12712 MarkVTableUsed(CurrentLocation, ClassDecl);
12714 // Add a context note for diagnostics produced after this point.
12715 Scope.addContextNote(CurrentLocation);
12717 // C++11 [class.copy]p7:
12718 // The [definition of an implicitly declared copy constructor] is
12719 // deprecated if the class has a user-declared copy assignment operator
12720 // or a user-declared destructor.
12721 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12722 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12724 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12725 CopyConstructor->setInvalidDecl();
12727 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
12728 ? CopyConstructor->getEndLoc()
12729 : CopyConstructor->getLocation();
12730 Sema::CompoundScopeRAII CompoundScope(*this);
12731 CopyConstructor->setBody(
12732 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12733 CopyConstructor->markUsed(Context);
12736 if (ASTMutationListener *L = getASTMutationListener()) {
12737 L->CompletedImplicitDefinition(CopyConstructor);
12741 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12742 CXXRecordDecl *ClassDecl) {
12743 assert(ClassDecl->needsImplicitMoveConstructor());
12745 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12746 if (DSM.isAlreadyBeingDeclared())
12749 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12751 QualType ArgType = ClassType;
12752 if (Context.getLangOpts().OpenCLCPlusPlus)
12753 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic);
12754 ArgType = Context.getRValueReferenceType(ArgType);
12756 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12757 CXXMoveConstructor,
12760 DeclarationName Name
12761 = Context.DeclarationNames.getCXXConstructorName(
12762 Context.getCanonicalType(ClassType));
12763 SourceLocation ClassLoc = ClassDecl->getLocation();
12764 DeclarationNameInfo NameInfo(Name, ClassLoc);
12766 // C++11 [class.copy]p11:
12767 // An implicitly-declared copy/move constructor is an inline public
12768 // member of its class.
12769 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12770 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12771 ExplicitSpecifier(),
12773 /*isImplicitlyDeclared=*/true,
12774 Constexpr ? CSK_constexpr : CSK_unspecified);
12775 MoveConstructor->setAccess(AS_public);
12776 MoveConstructor->setDefaulted();
12778 if (getLangOpts().CUDA) {
12779 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12781 /* ConstRHS */ false,
12782 /* Diagnose */ false);
12785 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
12787 // Add the parameter to the constructor.
12788 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12789 ClassLoc, ClassLoc,
12790 /*IdentifierInfo=*/nullptr,
12791 ArgType, /*TInfo=*/nullptr,
12793 MoveConstructor->setParams(FromParam);
12795 MoveConstructor->setTrivial(
12796 ClassDecl->needsOverloadResolutionForMoveConstructor()
12797 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12798 : ClassDecl->hasTrivialMoveConstructor());
12800 MoveConstructor->setTrivialForCall(
12801 ClassDecl->hasAttr<TrivialABIAttr>() ||
12802 (ClassDecl->needsOverloadResolutionForMoveConstructor()
12803 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
12804 TAH_ConsiderTrivialABI)
12805 : ClassDecl->hasTrivialMoveConstructorForCall()));
12807 // Note that we have declared this constructor.
12808 ++getASTContext().NumImplicitMoveConstructorsDeclared;
12810 Scope *S = getScopeForContext(ClassDecl);
12811 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12813 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12814 ClassDecl->setImplicitMoveConstructorIsDeleted();
12815 SetDeclDeleted(MoveConstructor, ClassLoc);
12819 PushOnScopeChains(MoveConstructor, S, false);
12820 ClassDecl->addDecl(MoveConstructor);
12822 return MoveConstructor;
12825 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12826 CXXConstructorDecl *MoveConstructor) {
12827 assert((MoveConstructor->isDefaulted() &&
12828 MoveConstructor->isMoveConstructor() &&
12829 !MoveConstructor->doesThisDeclarationHaveABody() &&
12830 !MoveConstructor->isDeleted()) &&
12831 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12832 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12835 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12836 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12838 SynthesizedFunctionScope Scope(*this, MoveConstructor);
12840 // The exception specification is needed because we are defining the
12842 ResolveExceptionSpec(CurrentLocation,
12843 MoveConstructor->getType()->castAs<FunctionProtoType>());
12844 MarkVTableUsed(CurrentLocation, ClassDecl);
12846 // Add a context note for diagnostics produced after this point.
12847 Scope.addContextNote(CurrentLocation);
12849 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12850 MoveConstructor->setInvalidDecl();
12852 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
12853 ? MoveConstructor->getEndLoc()
12854 : MoveConstructor->getLocation();
12855 Sema::CompoundScopeRAII CompoundScope(*this);
12856 MoveConstructor->setBody(ActOnCompoundStmt(
12857 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12858 MoveConstructor->markUsed(Context);
12861 if (ASTMutationListener *L = getASTMutationListener()) {
12862 L->CompletedImplicitDefinition(MoveConstructor);
12866 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12867 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12870 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12871 SourceLocation CurrentLocation,
12872 CXXConversionDecl *Conv) {
12873 SynthesizedFunctionScope Scope(*this, Conv);
12874 assert(!Conv->getReturnType()->isUndeducedType());
12876 CXXRecordDecl *Lambda = Conv->getParent();
12877 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12878 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12880 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12881 CallOp = InstantiateFunctionDeclaration(
12882 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12886 Invoker = InstantiateFunctionDeclaration(
12887 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12892 if (CallOp->isInvalidDecl())
12895 // Mark the call operator referenced (and add to pending instantiations
12897 // For both the conversion and static-invoker template specializations
12898 // we construct their body's in this function, so no need to add them
12899 // to the PendingInstantiations.
12900 MarkFunctionReferenced(CurrentLocation, CallOp);
12902 // Fill in the __invoke function with a dummy implementation. IR generation
12903 // will fill in the actual details. Update its type in case it contained
12905 Invoker->markUsed(Context);
12906 Invoker->setReferenced();
12907 Invoker->setType(Conv->getReturnType()->getPointeeType());
12908 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12910 // Construct the body of the conversion function { return __invoke; }.
12911 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12912 VK_LValue, Conv->getLocation());
12913 assert(FunctionRef && "Can't refer to __invoke function?");
12914 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12915 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12916 Conv->getLocation()));
12917 Conv->markUsed(Context);
12918 Conv->setReferenced();
12920 if (ASTMutationListener *L = getASTMutationListener()) {
12921 L->CompletedImplicitDefinition(Conv);
12922 L->CompletedImplicitDefinition(Invoker);
12928 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12929 SourceLocation CurrentLocation,
12930 CXXConversionDecl *Conv)
12932 assert(!Conv->getParent()->isGenericLambda());
12934 SynthesizedFunctionScope Scope(*this, Conv);
12936 // Copy-initialize the lambda object as needed to capture it.
12937 Expr *This = ActOnCXXThis(CurrentLocation).get();
12938 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12940 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12941 Conv->getLocation(),
12944 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12945 // behavior. Note that only the general conversion function does this
12946 // (since it's unusable otherwise); in the case where we inline the
12947 // block literal, it has block literal lifetime semantics.
12948 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12949 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12950 CK_CopyAndAutoreleaseBlockObject,
12951 BuildBlock.get(), nullptr, VK_RValue);
12953 if (BuildBlock.isInvalid()) {
12954 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12955 Conv->setInvalidDecl();
12959 // Create the return statement that returns the block from the conversion
12961 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12962 if (Return.isInvalid()) {
12963 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12964 Conv->setInvalidDecl();
12968 // Set the body of the conversion function.
12969 Stmt *ReturnS = Return.get();
12970 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12971 Conv->getLocation()));
12972 Conv->markUsed(Context);
12974 // We're done; notify the mutation listener, if any.
12975 if (ASTMutationListener *L = getASTMutationListener()) {
12976 L->CompletedImplicitDefinition(Conv);
12980 /// Determine whether the given list arguments contains exactly one
12981 /// "real" (non-default) argument.
12982 static bool hasOneRealArgument(MultiExprArg Args) {
12983 switch (Args.size()) {
12988 if (!Args[1]->isDefaultArgument())
12993 return !Args[0]->isDefaultArgument();
13000 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13001 NamedDecl *FoundDecl,
13002 CXXConstructorDecl *Constructor,
13003 MultiExprArg ExprArgs,
13004 bool HadMultipleCandidates,
13005 bool IsListInitialization,
13006 bool IsStdInitListInitialization,
13007 bool RequiresZeroInit,
13008 unsigned ConstructKind,
13009 SourceRange ParenRange) {
13010 bool Elidable = false;
13012 // C++0x [class.copy]p34:
13013 // When certain criteria are met, an implementation is allowed to
13014 // omit the copy/move construction of a class object, even if the
13015 // copy/move constructor and/or destructor for the object have
13016 // side effects. [...]
13017 // - when a temporary class object that has not been bound to a
13018 // reference (12.2) would be copied/moved to a class object
13019 // with the same cv-unqualified type, the copy/move operation
13020 // can be omitted by constructing the temporary object
13021 // directly into the target of the omitted copy/move
13022 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
13023 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
13024 Expr *SubExpr = ExprArgs[0];
13025 Elidable = SubExpr->isTemporaryObject(
13026 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
13029 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
13030 FoundDecl, Constructor,
13031 Elidable, ExprArgs, HadMultipleCandidates,
13032 IsListInitialization,
13033 IsStdInitListInitialization, RequiresZeroInit,
13034 ConstructKind, ParenRange);
13038 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13039 NamedDecl *FoundDecl,
13040 CXXConstructorDecl *Constructor,
13042 MultiExprArg ExprArgs,
13043 bool HadMultipleCandidates,
13044 bool IsListInitialization,
13045 bool IsStdInitListInitialization,
13046 bool RequiresZeroInit,
13047 unsigned ConstructKind,
13048 SourceRange ParenRange) {
13049 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
13050 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
13051 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
13052 return ExprError();
13055 return BuildCXXConstructExpr(
13056 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
13057 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
13058 RequiresZeroInit, ConstructKind, ParenRange);
13061 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
13062 /// including handling of its default argument expressions.
13064 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
13065 CXXConstructorDecl *Constructor,
13067 MultiExprArg ExprArgs,
13068 bool HadMultipleCandidates,
13069 bool IsListInitialization,
13070 bool IsStdInitListInitialization,
13071 bool RequiresZeroInit,
13072 unsigned ConstructKind,
13073 SourceRange ParenRange) {
13074 assert(declaresSameEntity(
13075 Constructor->getParent(),
13076 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
13077 "given constructor for wrong type");
13078 MarkFunctionReferenced(ConstructLoc, Constructor);
13079 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
13080 return ExprError();
13082 return CXXConstructExpr::Create(
13083 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
13084 ExprArgs, HadMultipleCandidates, IsListInitialization,
13085 IsStdInitListInitialization, RequiresZeroInit,
13086 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
13090 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
13091 assert(Field->hasInClassInitializer());
13093 // If we already have the in-class initializer nothing needs to be done.
13094 if (Field->getInClassInitializer())
13095 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13097 // If we might have already tried and failed to instantiate, don't try again.
13098 if (Field->isInvalidDecl())
13099 return ExprError();
13101 // Maybe we haven't instantiated the in-class initializer. Go check the
13102 // pattern FieldDecl to see if it has one.
13103 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
13105 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
13106 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
13107 DeclContext::lookup_result Lookup =
13108 ClassPattern->lookup(Field->getDeclName());
13110 // Lookup can return at most two results: the pattern for the field, or the
13111 // injected class name of the parent record. No other member can have the
13112 // same name as the field.
13113 // In modules mode, lookup can return multiple results (coming from
13114 // different modules).
13115 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
13116 "more than two lookup results for field name");
13117 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
13119 assert(isa<CXXRecordDecl>(Lookup[0]) &&
13120 "cannot have other non-field member with same name");
13121 for (auto L : Lookup)
13122 if (isa<FieldDecl>(L)) {
13123 Pattern = cast<FieldDecl>(L);
13126 assert(Pattern && "We must have set the Pattern!");
13129 if (!Pattern->hasInClassInitializer() ||
13130 InstantiateInClassInitializer(Loc, Field, Pattern,
13131 getTemplateInstantiationArgs(Field))) {
13132 // Don't diagnose this again.
13133 Field->setInvalidDecl();
13134 return ExprError();
13136 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
13140 // If the brace-or-equal-initializer of a non-static data member
13141 // invokes a defaulted default constructor of its class or of an
13142 // enclosing class in a potentially evaluated subexpression, the
13143 // program is ill-formed.
13145 // This resolution is unworkable: the exception specification of the
13146 // default constructor can be needed in an unevaluated context, in
13147 // particular, in the operand of a noexcept-expression, and we can be
13148 // unable to compute an exception specification for an enclosed class.
13150 // Any attempt to resolve the exception specification of a defaulted default
13151 // constructor before the initializer is lexically complete will ultimately
13152 // come here at which point we can diagnose it.
13153 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
13154 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
13155 << OutermostClass << Field;
13156 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
13157 // Recover by marking the field invalid, unless we're in a SFINAE context.
13158 if (!isSFINAEContext())
13159 Field->setInvalidDecl();
13160 return ExprError();
13163 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
13164 if (VD->isInvalidDecl()) return;
13166 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
13167 if (ClassDecl->isInvalidDecl()) return;
13168 if (ClassDecl->hasIrrelevantDestructor()) return;
13169 if (ClassDecl->isDependentContext()) return;
13171 if (VD->isNoDestroy(getASTContext()))
13174 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13176 // If this is an array, we'll require the destructor during initialization, so
13177 // we can skip over this. We still want to emit exit-time destructor warnings
13179 if (!VD->getType()->isArrayType()) {
13180 MarkFunctionReferenced(VD->getLocation(), Destructor);
13181 CheckDestructorAccess(VD->getLocation(), Destructor,
13182 PDiag(diag::err_access_dtor_var)
13183 << VD->getDeclName() << VD->getType());
13184 DiagnoseUseOfDecl(Destructor, VD->getLocation());
13187 if (Destructor->isTrivial()) return;
13188 if (!VD->hasGlobalStorage()) return;
13190 // Emit warning for non-trivial dtor in global scope (a real global,
13191 // class-static, function-static).
13192 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
13194 // TODO: this should be re-enabled for static locals by !CXAAtExit
13195 if (!VD->isStaticLocal())
13196 Diag(VD->getLocation(), diag::warn_global_destructor);
13199 /// Given a constructor and the set of arguments provided for the
13200 /// constructor, convert the arguments and add any required default arguments
13201 /// to form a proper call to this constructor.
13203 /// \returns true if an error occurred, false otherwise.
13205 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
13206 MultiExprArg ArgsPtr,
13207 SourceLocation Loc,
13208 SmallVectorImpl<Expr*> &ConvertedArgs,
13209 bool AllowExplicit,
13210 bool IsListInitialization) {
13211 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
13212 unsigned NumArgs = ArgsPtr.size();
13213 Expr **Args = ArgsPtr.data();
13215 const FunctionProtoType *Proto
13216 = Constructor->getType()->getAs<FunctionProtoType>();
13217 assert(Proto && "Constructor without a prototype?");
13218 unsigned NumParams = Proto->getNumParams();
13220 // If too few arguments are available, we'll fill in the rest with defaults.
13221 if (NumArgs < NumParams)
13222 ConvertedArgs.reserve(NumParams);
13224 ConvertedArgs.reserve(NumArgs);
13226 VariadicCallType CallType =
13227 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
13228 SmallVector<Expr *, 8> AllArgs;
13229 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
13231 llvm::makeArrayRef(Args, NumArgs),
13233 CallType, AllowExplicit,
13234 IsListInitialization);
13235 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
13237 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
13239 CheckConstructorCall(Constructor,
13240 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
13247 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
13248 const FunctionDecl *FnDecl) {
13249 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
13250 if (isa<NamespaceDecl>(DC)) {
13251 return SemaRef.Diag(FnDecl->getLocation(),
13252 diag::err_operator_new_delete_declared_in_namespace)
13253 << FnDecl->getDeclName();
13256 if (isa<TranslationUnitDecl>(DC) &&
13257 FnDecl->getStorageClass() == SC_Static) {
13258 return SemaRef.Diag(FnDecl->getLocation(),
13259 diag::err_operator_new_delete_declared_static)
13260 << FnDecl->getDeclName();
13267 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) {
13268 QualType QTy = PtrTy->getPointeeType();
13269 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy);
13270 return SemaRef.Context.getPointerType(QTy);
13274 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
13275 CanQualType ExpectedResultType,
13276 CanQualType ExpectedFirstParamType,
13277 unsigned DependentParamTypeDiag,
13278 unsigned InvalidParamTypeDiag) {
13279 QualType ResultType =
13280 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
13282 // Check that the result type is not dependent.
13283 if (ResultType->isDependentType())
13284 return SemaRef.Diag(FnDecl->getLocation(),
13285 diag::err_operator_new_delete_dependent_result_type)
13286 << FnDecl->getDeclName() << ExpectedResultType;
13288 // The operator is valid on any address space for OpenCL.
13289 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13290 if (auto *PtrTy = ResultType->getAs<PointerType>()) {
13291 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13295 // Check that the result type is what we expect.
13296 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
13297 return SemaRef.Diag(FnDecl->getLocation(),
13298 diag::err_operator_new_delete_invalid_result_type)
13299 << FnDecl->getDeclName() << ExpectedResultType;
13301 // A function template must have at least 2 parameters.
13302 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
13303 return SemaRef.Diag(FnDecl->getLocation(),
13304 diag::err_operator_new_delete_template_too_few_parameters)
13305 << FnDecl->getDeclName();
13307 // The function decl must have at least 1 parameter.
13308 if (FnDecl->getNumParams() == 0)
13309 return SemaRef.Diag(FnDecl->getLocation(),
13310 diag::err_operator_new_delete_too_few_parameters)
13311 << FnDecl->getDeclName();
13313 // Check the first parameter type is not dependent.
13314 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
13315 if (FirstParamType->isDependentType())
13316 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
13317 << FnDecl->getDeclName() << ExpectedFirstParamType;
13319 // Check that the first parameter type is what we expect.
13320 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
13321 // The operator is valid on any address space for OpenCL.
13323 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) {
13324 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
13327 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
13328 ExpectedFirstParamType)
13329 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
13330 << FnDecl->getDeclName() << ExpectedFirstParamType;
13336 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
13337 // C++ [basic.stc.dynamic.allocation]p1:
13338 // A program is ill-formed if an allocation function is declared in a
13339 // namespace scope other than global scope or declared static in global
13341 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13344 CanQualType SizeTy =
13345 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
13347 // C++ [basic.stc.dynamic.allocation]p1:
13348 // The return type shall be void*. The first parameter shall have type
13350 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
13352 diag::err_operator_new_dependent_param_type,
13353 diag::err_operator_new_param_type))
13356 // C++ [basic.stc.dynamic.allocation]p1:
13357 // The first parameter shall not have an associated default argument.
13358 if (FnDecl->getParamDecl(0)->hasDefaultArg())
13359 return SemaRef.Diag(FnDecl->getLocation(),
13360 diag::err_operator_new_default_arg)
13361 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
13367 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
13368 // C++ [basic.stc.dynamic.deallocation]p1:
13369 // A program is ill-formed if deallocation functions are declared in a
13370 // namespace scope other than global scope or declared static in global
13372 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
13375 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
13378 // Within a class C, the first parameter of a destroying operator delete
13379 // shall be of type C *. The first parameter of any other deallocation
13380 // function shall be of type void *.
13381 CanQualType ExpectedFirstParamType =
13382 MD && MD->isDestroyingOperatorDelete()
13383 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
13384 SemaRef.Context.getRecordType(MD->getParent())))
13385 : SemaRef.Context.VoidPtrTy;
13387 // C++ [basic.stc.dynamic.deallocation]p2:
13388 // Each deallocation function shall return void
13389 if (CheckOperatorNewDeleteTypes(
13390 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
13391 diag::err_operator_delete_dependent_param_type,
13392 diag::err_operator_delete_param_type))
13396 // A destroying operator delete shall be a usual deallocation function.
13397 if (MD && !MD->getParent()->isDependentContext() &&
13398 MD->isDestroyingOperatorDelete() &&
13399 !SemaRef.isUsualDeallocationFunction(MD)) {
13400 SemaRef.Diag(MD->getLocation(),
13401 diag::err_destroying_operator_delete_not_usual);
13408 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
13409 /// of this overloaded operator is well-formed. If so, returns false;
13410 /// otherwise, emits appropriate diagnostics and returns true.
13411 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
13412 assert(FnDecl && FnDecl->isOverloadedOperator() &&
13413 "Expected an overloaded operator declaration");
13415 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
13417 // C++ [over.oper]p5:
13418 // The allocation and deallocation functions, operator new,
13419 // operator new[], operator delete and operator delete[], are
13420 // described completely in 3.7.3. The attributes and restrictions
13421 // found in the rest of this subclause do not apply to them unless
13422 // explicitly stated in 3.7.3.
13423 if (Op == OO_Delete || Op == OO_Array_Delete)
13424 return CheckOperatorDeleteDeclaration(*this, FnDecl);
13426 if (Op == OO_New || Op == OO_Array_New)
13427 return CheckOperatorNewDeclaration(*this, FnDecl);
13429 // C++ [over.oper]p6:
13430 // An operator function shall either be a non-static member
13431 // function or be a non-member function and have at least one
13432 // parameter whose type is a class, a reference to a class, an
13433 // enumeration, or a reference to an enumeration.
13434 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
13435 if (MethodDecl->isStatic())
13436 return Diag(FnDecl->getLocation(),
13437 diag::err_operator_overload_static) << FnDecl->getDeclName();
13439 bool ClassOrEnumParam = false;
13440 for (auto Param : FnDecl->parameters()) {
13441 QualType ParamType = Param->getType().getNonReferenceType();
13442 if (ParamType->isDependentType() || ParamType->isRecordType() ||
13443 ParamType->isEnumeralType()) {
13444 ClassOrEnumParam = true;
13449 if (!ClassOrEnumParam)
13450 return Diag(FnDecl->getLocation(),
13451 diag::err_operator_overload_needs_class_or_enum)
13452 << FnDecl->getDeclName();
13455 // C++ [over.oper]p8:
13456 // An operator function cannot have default arguments (8.3.6),
13457 // except where explicitly stated below.
13459 // Only the function-call operator allows default arguments
13460 // (C++ [over.call]p1).
13461 if (Op != OO_Call) {
13462 for (auto Param : FnDecl->parameters()) {
13463 if (Param->hasDefaultArg())
13464 return Diag(Param->getLocation(),
13465 diag::err_operator_overload_default_arg)
13466 << FnDecl->getDeclName() << Param->getDefaultArgRange();
13470 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
13471 { false, false, false }
13472 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
13473 , { Unary, Binary, MemberOnly }
13474 #include "clang/Basic/OperatorKinds.def"
13477 bool CanBeUnaryOperator = OperatorUses[Op][0];
13478 bool CanBeBinaryOperator = OperatorUses[Op][1];
13479 bool MustBeMemberOperator = OperatorUses[Op][2];
13481 // C++ [over.oper]p8:
13482 // [...] Operator functions cannot have more or fewer parameters
13483 // than the number required for the corresponding operator, as
13484 // described in the rest of this subclause.
13485 unsigned NumParams = FnDecl->getNumParams()
13486 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
13487 if (Op != OO_Call &&
13488 ((NumParams == 1 && !CanBeUnaryOperator) ||
13489 (NumParams == 2 && !CanBeBinaryOperator) ||
13490 (NumParams < 1) || (NumParams > 2))) {
13491 // We have the wrong number of parameters.
13492 unsigned ErrorKind;
13493 if (CanBeUnaryOperator && CanBeBinaryOperator) {
13494 ErrorKind = 2; // 2 -> unary or binary.
13495 } else if (CanBeUnaryOperator) {
13496 ErrorKind = 0; // 0 -> unary
13498 assert(CanBeBinaryOperator &&
13499 "All non-call overloaded operators are unary or binary!");
13500 ErrorKind = 1; // 1 -> binary
13503 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
13504 << FnDecl->getDeclName() << NumParams << ErrorKind;
13507 // Overloaded operators other than operator() cannot be variadic.
13508 if (Op != OO_Call &&
13509 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
13510 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
13511 << FnDecl->getDeclName();
13514 // Some operators must be non-static member functions.
13515 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
13516 return Diag(FnDecl->getLocation(),
13517 diag::err_operator_overload_must_be_member)
13518 << FnDecl->getDeclName();
13521 // C++ [over.inc]p1:
13522 // The user-defined function called operator++ implements the
13523 // prefix and postfix ++ operator. If this function is a member
13524 // function with no parameters, or a non-member function with one
13525 // parameter of class or enumeration type, it defines the prefix
13526 // increment operator ++ for objects of that type. If the function
13527 // is a member function with one parameter (which shall be of type
13528 // int) or a non-member function with two parameters (the second
13529 // of which shall be of type int), it defines the postfix
13530 // increment operator ++ for objects of that type.
13531 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
13532 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
13533 QualType ParamType = LastParam->getType();
13535 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
13536 !ParamType->isDependentType())
13537 return Diag(LastParam->getLocation(),
13538 diag::err_operator_overload_post_incdec_must_be_int)
13539 << LastParam->getType() << (Op == OO_MinusMinus);
13546 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
13547 FunctionTemplateDecl *TpDecl) {
13548 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
13550 // Must have one or two template parameters.
13551 if (TemplateParams->size() == 1) {
13552 NonTypeTemplateParmDecl *PmDecl =
13553 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
13555 // The template parameter must be a char parameter pack.
13556 if (PmDecl && PmDecl->isTemplateParameterPack() &&
13557 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
13560 } else if (TemplateParams->size() == 2) {
13561 TemplateTypeParmDecl *PmType =
13562 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
13563 NonTypeTemplateParmDecl *PmArgs =
13564 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
13566 // The second template parameter must be a parameter pack with the
13567 // first template parameter as its type.
13568 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
13569 PmArgs->isTemplateParameterPack()) {
13570 const TemplateTypeParmType *TArgs =
13571 PmArgs->getType()->getAs<TemplateTypeParmType>();
13572 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
13573 TArgs->getIndex() == PmType->getIndex()) {
13574 if (!SemaRef.inTemplateInstantiation())
13575 SemaRef.Diag(TpDecl->getLocation(),
13576 diag::ext_string_literal_operator_template);
13582 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
13583 diag::err_literal_operator_template)
13584 << TpDecl->getTemplateParameters()->getSourceRange();
13588 /// CheckLiteralOperatorDeclaration - Check whether the declaration
13589 /// of this literal operator function is well-formed. If so, returns
13590 /// false; otherwise, emits appropriate diagnostics and returns true.
13591 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
13592 if (isa<CXXMethodDecl>(FnDecl)) {
13593 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
13594 << FnDecl->getDeclName();
13598 if (FnDecl->isExternC()) {
13599 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
13600 if (const LinkageSpecDecl *LSD =
13601 FnDecl->getDeclContext()->getExternCContext())
13602 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
13606 // This might be the definition of a literal operator template.
13607 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
13609 // This might be a specialization of a literal operator template.
13611 TpDecl = FnDecl->getPrimaryTemplate();
13613 // template <char...> type operator "" name() and
13614 // template <class T, T...> type operator "" name() are the only valid
13615 // template signatures, and the only valid signatures with no parameters.
13617 if (FnDecl->param_size() != 0) {
13618 Diag(FnDecl->getLocation(),
13619 diag::err_literal_operator_template_with_params);
13623 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
13626 } else if (FnDecl->param_size() == 1) {
13627 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
13629 QualType ParamType = Param->getType().getUnqualifiedType();
13631 // Only unsigned long long int, long double, any character type, and const
13632 // char * are allowed as the only parameters.
13633 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
13634 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
13635 Context.hasSameType(ParamType, Context.CharTy) ||
13636 Context.hasSameType(ParamType, Context.WideCharTy) ||
13637 Context.hasSameType(ParamType, Context.Char8Ty) ||
13638 Context.hasSameType(ParamType, Context.Char16Ty) ||
13639 Context.hasSameType(ParamType, Context.Char32Ty)) {
13640 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
13641 QualType InnerType = Ptr->getPointeeType();
13643 // Pointer parameter must be a const char *.
13644 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
13646 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
13647 Diag(Param->getSourceRange().getBegin(),
13648 diag::err_literal_operator_param)
13649 << ParamType << "'const char *'" << Param->getSourceRange();
13653 } else if (ParamType->isRealFloatingType()) {
13654 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13655 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
13658 } else if (ParamType->isIntegerType()) {
13659 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
13660 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
13664 Diag(Param->getSourceRange().getBegin(),
13665 diag::err_literal_operator_invalid_param)
13666 << ParamType << Param->getSourceRange();
13670 } else if (FnDecl->param_size() == 2) {
13671 FunctionDecl::param_iterator Param = FnDecl->param_begin();
13673 // First, verify that the first parameter is correct.
13675 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
13677 // Two parameter function must have a pointer to const as a
13678 // first parameter; let's strip those qualifiers.
13679 const PointerType *PT = FirstParamType->getAs<PointerType>();
13682 Diag((*Param)->getSourceRange().getBegin(),
13683 diag::err_literal_operator_param)
13684 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13688 QualType PointeeType = PT->getPointeeType();
13689 // First parameter must be const
13690 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13691 Diag((*Param)->getSourceRange().getBegin(),
13692 diag::err_literal_operator_param)
13693 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13697 QualType InnerType = PointeeType.getUnqualifiedType();
13698 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
13699 // const char32_t* are allowed as the first parameter to a two-parameter
13701 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13702 Context.hasSameType(InnerType, Context.WideCharTy) ||
13703 Context.hasSameType(InnerType, Context.Char8Ty) ||
13704 Context.hasSameType(InnerType, Context.Char16Ty) ||
13705 Context.hasSameType(InnerType, Context.Char32Ty))) {
13706 Diag((*Param)->getSourceRange().getBegin(),
13707 diag::err_literal_operator_param)
13708 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13712 // Move on to the second and final parameter.
13715 // The second parameter must be a std::size_t.
13716 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13717 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13718 Diag((*Param)->getSourceRange().getBegin(),
13719 diag::err_literal_operator_param)
13720 << SecondParamType << Context.getSizeType()
13721 << (*Param)->getSourceRange();
13725 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13729 // Parameters are good.
13731 // A parameter-declaration-clause containing a default argument is not
13732 // equivalent to any of the permitted forms.
13733 for (auto Param : FnDecl->parameters()) {
13734 if (Param->hasDefaultArg()) {
13735 Diag(Param->getDefaultArgRange().getBegin(),
13736 diag::err_literal_operator_default_argument)
13737 << Param->getDefaultArgRange();
13742 StringRef LiteralName
13743 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13744 if (LiteralName[0] != '_' &&
13745 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13746 // C++11 [usrlit.suffix]p1:
13747 // Literal suffix identifiers that do not start with an underscore
13748 // are reserved for future standardization.
13749 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13750 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13756 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13757 /// linkage specification, including the language and (if present)
13758 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13759 /// language string literal. LBraceLoc, if valid, provides the location of
13760 /// the '{' brace. Otherwise, this linkage specification does not
13761 /// have any braces.
13762 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13764 SourceLocation LBraceLoc) {
13765 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13766 if (!Lit->isAscii()) {
13767 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13768 << LangStr->getSourceRange();
13772 StringRef Lang = Lit->getString();
13773 LinkageSpecDecl::LanguageIDs Language;
13775 Language = LinkageSpecDecl::lang_c;
13776 else if (Lang == "C++")
13777 Language = LinkageSpecDecl::lang_cxx;
13779 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13780 << LangStr->getSourceRange();
13784 // FIXME: Add all the various semantics of linkage specifications
13786 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13787 LangStr->getExprLoc(), Language,
13788 LBraceLoc.isValid());
13789 CurContext->addDecl(D);
13790 PushDeclContext(S, D);
13794 /// ActOnFinishLinkageSpecification - Complete the definition of
13795 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13796 /// valid, it's the position of the closing '}' brace in a linkage
13797 /// specification that uses braces.
13798 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13800 SourceLocation RBraceLoc) {
13801 if (RBraceLoc.isValid()) {
13802 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13803 LSDecl->setRBraceLoc(RBraceLoc);
13806 return LinkageSpec;
13809 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13810 const ParsedAttributesView &AttrList,
13811 SourceLocation SemiLoc) {
13812 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13813 // Attribute declarations appertain to empty declaration so we handle
13815 ProcessDeclAttributeList(S, ED, AttrList);
13817 CurContext->addDecl(ED);
13821 /// Perform semantic analysis for the variable declaration that
13822 /// occurs within a C++ catch clause, returning the newly-created
13824 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13825 TypeSourceInfo *TInfo,
13826 SourceLocation StartLoc,
13827 SourceLocation Loc,
13828 IdentifierInfo *Name) {
13829 bool Invalid = false;
13830 QualType ExDeclType = TInfo->getType();
13832 // Arrays and functions decay.
13833 if (ExDeclType->isArrayType())
13834 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13835 else if (ExDeclType->isFunctionType())
13836 ExDeclType = Context.getPointerType(ExDeclType);
13838 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13839 // The exception-declaration shall not denote a pointer or reference to an
13840 // incomplete type, other than [cv] void*.
13841 // N2844 forbids rvalue references.
13842 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13843 Diag(Loc, diag::err_catch_rvalue_ref);
13847 if (ExDeclType->isVariablyModifiedType()) {
13848 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13852 QualType BaseType = ExDeclType;
13853 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13854 unsigned DK = diag::err_catch_incomplete;
13855 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13856 BaseType = Ptr->getPointeeType();
13858 DK = diag::err_catch_incomplete_ptr;
13859 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13860 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13861 BaseType = Ref->getPointeeType();
13863 DK = diag::err_catch_incomplete_ref;
13865 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13866 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13869 if (!Invalid && !ExDeclType->isDependentType() &&
13870 RequireNonAbstractType(Loc, ExDeclType,
13871 diag::err_abstract_type_in_decl,
13872 AbstractVariableType))
13875 // Only the non-fragile NeXT runtime currently supports C++ catches
13876 // of ObjC types, and no runtime supports catching ObjC types by value.
13877 if (!Invalid && getLangOpts().ObjC) {
13878 QualType T = ExDeclType;
13879 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13880 T = RT->getPointeeType();
13882 if (T->isObjCObjectType()) {
13883 Diag(Loc, diag::err_objc_object_catch);
13885 } else if (T->isObjCObjectPointerType()) {
13886 // FIXME: should this be a test for macosx-fragile specifically?
13887 if (getLangOpts().ObjCRuntime.isFragile())
13888 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13892 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13893 ExDeclType, TInfo, SC_None);
13894 ExDecl->setExceptionVariable(true);
13896 // In ARC, infer 'retaining' for variables of retainable type.
13897 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13900 if (!Invalid && !ExDeclType->isDependentType()) {
13901 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13902 // Insulate this from anything else we might currently be parsing.
13903 EnterExpressionEvaluationContext scope(
13904 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13906 // C++ [except.handle]p16:
13907 // The object declared in an exception-declaration or, if the
13908 // exception-declaration does not specify a name, a temporary (12.2) is
13909 // copy-initialized (8.5) from the exception object. [...]
13910 // The object is destroyed when the handler exits, after the destruction
13911 // of any automatic objects initialized within the handler.
13913 // We just pretend to initialize the object with itself, then make sure
13914 // it can be destroyed later.
13915 QualType initType = Context.getExceptionObjectType(ExDeclType);
13917 InitializedEntity entity =
13918 InitializedEntity::InitializeVariable(ExDecl);
13919 InitializationKind initKind =
13920 InitializationKind::CreateCopy(Loc, SourceLocation());
13922 Expr *opaqueValue =
13923 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13924 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13925 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13926 if (result.isInvalid())
13929 // If the constructor used was non-trivial, set this as the
13931 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13932 if (!construct->getConstructor()->isTrivial()) {
13933 Expr *init = MaybeCreateExprWithCleanups(construct);
13934 ExDecl->setInit(init);
13937 // And make sure it's destructable.
13938 FinalizeVarWithDestructor(ExDecl, recordType);
13944 ExDecl->setInvalidDecl();
13949 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13951 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13952 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13953 bool Invalid = D.isInvalidType();
13955 // Check for unexpanded parameter packs.
13956 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13957 UPPC_ExceptionType)) {
13958 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13959 D.getIdentifierLoc());
13963 IdentifierInfo *II = D.getIdentifier();
13964 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13965 LookupOrdinaryName,
13966 ForVisibleRedeclaration)) {
13967 // The scope should be freshly made just for us. There is just no way
13968 // it contains any previous declaration, except for function parameters in
13969 // a function-try-block's catch statement.
13970 assert(!S->isDeclScope(PrevDecl));
13971 if (isDeclInScope(PrevDecl, CurContext, S)) {
13972 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13973 << D.getIdentifier();
13974 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13976 } else if (PrevDecl->isTemplateParameter())
13977 // Maybe we will complain about the shadowed template parameter.
13978 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13981 if (D.getCXXScopeSpec().isSet() && !Invalid) {
13982 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13983 << D.getCXXScopeSpec().getRange();
13987 VarDecl *ExDecl = BuildExceptionDeclaration(
13988 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
13990 ExDecl->setInvalidDecl();
13992 // Add the exception declaration into this scope.
13994 PushOnScopeChains(ExDecl, S);
13996 CurContext->addDecl(ExDecl);
13998 ProcessDeclAttributes(S, ExDecl, D);
14002 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14004 Expr *AssertMessageExpr,
14005 SourceLocation RParenLoc) {
14006 StringLiteral *AssertMessage =
14007 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
14009 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
14012 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
14013 AssertMessage, RParenLoc, false);
14016 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
14018 StringLiteral *AssertMessage,
14019 SourceLocation RParenLoc,
14021 assert(AssertExpr != nullptr && "Expected non-null condition");
14022 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
14024 // In a static_assert-declaration, the constant-expression shall be a
14025 // constant expression that can be contextually converted to bool.
14026 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
14027 if (Converted.isInvalid())
14031 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
14032 diag::err_static_assert_expression_is_not_constant,
14033 /*AllowFold=*/false).isInvalid())
14036 if (!Failed && !Cond) {
14037 SmallString<256> MsgBuffer;
14038 llvm::raw_svector_ostream Msg(MsgBuffer);
14040 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
14042 Expr *InnerCond = nullptr;
14043 std::string InnerCondDescription;
14044 std::tie(InnerCond, InnerCondDescription) =
14045 findFailedBooleanCondition(Converted.get());
14046 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
14047 && !isa<IntegerLiteral>(InnerCond)) {
14048 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
14049 << InnerCondDescription << !AssertMessage
14050 << Msg.str() << InnerCond->getSourceRange();
14052 Diag(StaticAssertLoc, diag::err_static_assert_failed)
14053 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
14059 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
14060 /*DiscardedValue*/false,
14061 /*IsConstexpr*/true);
14062 if (FullAssertExpr.isInvalid())
14065 AssertExpr = FullAssertExpr.get();
14067 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
14068 AssertExpr, AssertMessage, RParenLoc,
14071 CurContext->addDecl(Decl);
14075 /// Perform semantic analysis of the given friend type declaration.
14077 /// \returns A friend declaration that.
14078 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
14079 SourceLocation FriendLoc,
14080 TypeSourceInfo *TSInfo) {
14081 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
14083 QualType T = TSInfo->getType();
14084 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
14086 // C++03 [class.friend]p2:
14087 // An elaborated-type-specifier shall be used in a friend declaration
14090 // * The class-key of the elaborated-type-specifier is required.
14091 if (!CodeSynthesisContexts.empty()) {
14092 // Do not complain about the form of friend template types during any kind
14093 // of code synthesis. For template instantiation, we will have complained
14094 // when the template was defined.
14096 if (!T->isElaboratedTypeSpecifier()) {
14097 // If we evaluated the type to a record type, suggest putting
14099 if (const RecordType *RT = T->getAs<RecordType>()) {
14100 RecordDecl *RD = RT->getDecl();
14102 SmallString<16> InsertionText(" ");
14103 InsertionText += RD->getKindName();
14105 Diag(TypeRange.getBegin(),
14106 getLangOpts().CPlusPlus11 ?
14107 diag::warn_cxx98_compat_unelaborated_friend_type :
14108 diag::ext_unelaborated_friend_type)
14109 << (unsigned) RD->getTagKind()
14111 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
14115 getLangOpts().CPlusPlus11 ?
14116 diag::warn_cxx98_compat_nonclass_type_friend :
14117 diag::ext_nonclass_type_friend)
14121 } else if (T->getAs<EnumType>()) {
14123 getLangOpts().CPlusPlus11 ?
14124 diag::warn_cxx98_compat_enum_friend :
14125 diag::ext_enum_friend)
14130 // C++11 [class.friend]p3:
14131 // A friend declaration that does not declare a function shall have one
14132 // of the following forms:
14133 // friend elaborated-type-specifier ;
14134 // friend simple-type-specifier ;
14135 // friend typename-specifier ;
14136 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
14137 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
14140 // If the type specifier in a friend declaration designates a (possibly
14141 // cv-qualified) class type, that class is declared as a friend; otherwise,
14142 // the friend declaration is ignored.
14143 return FriendDecl::Create(Context, CurContext,
14144 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
14148 /// Handle a friend tag declaration where the scope specifier was
14150 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
14151 unsigned TagSpec, SourceLocation TagLoc,
14152 CXXScopeSpec &SS, IdentifierInfo *Name,
14153 SourceLocation NameLoc,
14154 const ParsedAttributesView &Attr,
14155 MultiTemplateParamsArg TempParamLists) {
14156 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14158 bool IsMemberSpecialization = false;
14159 bool Invalid = false;
14161 if (TemplateParameterList *TemplateParams =
14162 MatchTemplateParametersToScopeSpecifier(
14163 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
14164 IsMemberSpecialization, Invalid)) {
14165 if (TemplateParams->size() > 0) {
14166 // This is a declaration of a class template.
14170 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
14171 NameLoc, Attr, TemplateParams, AS_public,
14172 /*ModulePrivateLoc=*/SourceLocation(),
14173 FriendLoc, TempParamLists.size() - 1,
14174 TempParamLists.data()).get();
14176 // The "template<>" header is extraneous.
14177 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14178 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14179 IsMemberSpecialization = true;
14183 if (Invalid) return nullptr;
14185 bool isAllExplicitSpecializations = true;
14186 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
14187 if (TempParamLists[I]->size()) {
14188 isAllExplicitSpecializations = false;
14193 // FIXME: don't ignore attributes.
14195 // If it's explicit specializations all the way down, just forget
14196 // about the template header and build an appropriate non-templated
14197 // friend. TODO: for source fidelity, remember the headers.
14198 if (isAllExplicitSpecializations) {
14199 if (SS.isEmpty()) {
14200 bool Owned = false;
14201 bool IsDependent = false;
14202 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
14204 /*ModulePrivateLoc=*/SourceLocation(),
14205 MultiTemplateParamsArg(), Owned, IsDependent,
14206 /*ScopedEnumKWLoc=*/SourceLocation(),
14207 /*ScopedEnumUsesClassTag=*/false,
14208 /*UnderlyingType=*/TypeResult(),
14209 /*IsTypeSpecifier=*/false,
14210 /*IsTemplateParamOrArg=*/false);
14213 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
14214 ElaboratedTypeKeyword Keyword
14215 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14216 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
14221 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14222 if (isa<DependentNameType>(T)) {
14223 DependentNameTypeLoc TL =
14224 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14225 TL.setElaboratedKeywordLoc(TagLoc);
14226 TL.setQualifierLoc(QualifierLoc);
14227 TL.setNameLoc(NameLoc);
14229 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
14230 TL.setElaboratedKeywordLoc(TagLoc);
14231 TL.setQualifierLoc(QualifierLoc);
14232 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
14235 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14236 TSI, FriendLoc, TempParamLists);
14237 Friend->setAccess(AS_public);
14238 CurContext->addDecl(Friend);
14242 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
14246 // Handle the case of a templated-scope friend class. e.g.
14247 // template <class T> class A<T>::B;
14248 // FIXME: we don't support these right now.
14249 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
14250 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
14251 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
14252 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
14253 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
14254 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
14255 TL.setElaboratedKeywordLoc(TagLoc);
14256 TL.setQualifierLoc(SS.getWithLocInContext(Context));
14257 TL.setNameLoc(NameLoc);
14259 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
14260 TSI, FriendLoc, TempParamLists);
14261 Friend->setAccess(AS_public);
14262 Friend->setUnsupportedFriend(true);
14263 CurContext->addDecl(Friend);
14267 /// Handle a friend type declaration. This works in tandem with
14270 /// Notes on friend class templates:
14272 /// We generally treat friend class declarations as if they were
14273 /// declaring a class. So, for example, the elaborated type specifier
14274 /// in a friend declaration is required to obey the restrictions of a
14275 /// class-head (i.e. no typedefs in the scope chain), template
14276 /// parameters are required to match up with simple template-ids, &c.
14277 /// However, unlike when declaring a template specialization, it's
14278 /// okay to refer to a template specialization without an empty
14279 /// template parameter declaration, e.g.
14280 /// friend class A<T>::B<unsigned>;
14281 /// We permit this as a special case; if there are any template
14282 /// parameters present at all, require proper matching, i.e.
14283 /// template <> template \<class T> friend class A<int>::B;
14284 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
14285 MultiTemplateParamsArg TempParams) {
14286 SourceLocation Loc = DS.getBeginLoc();
14288 assert(DS.isFriendSpecified());
14289 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14291 // C++ [class.friend]p3:
14292 // A friend declaration that does not declare a function shall have one of
14293 // the following forms:
14294 // friend elaborated-type-specifier ;
14295 // friend simple-type-specifier ;
14296 // friend typename-specifier ;
14298 // Any declaration with a type qualifier does not have that form. (It's
14299 // legal to specify a qualified type as a friend, you just can't write the
14301 if (DS.getTypeQualifiers()) {
14302 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
14303 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
14304 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
14305 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
14306 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
14307 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
14308 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
14309 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
14310 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
14311 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
14314 // Try to convert the decl specifier to a type. This works for
14315 // friend templates because ActOnTag never produces a ClassTemplateDecl
14316 // for a TUK_Friend.
14317 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
14318 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
14319 QualType T = TSI->getType();
14320 if (TheDeclarator.isInvalidType())
14323 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
14326 // This is definitely an error in C++98. It's probably meant to
14327 // be forbidden in C++0x, too, but the specification is just
14330 // The problem is with declarations like the following:
14331 // template <T> friend A<T>::foo;
14332 // where deciding whether a class C is a friend or not now hinges
14333 // on whether there exists an instantiation of A that causes
14334 // 'foo' to equal C. There are restrictions on class-heads
14335 // (which we declare (by fiat) elaborated friend declarations to
14336 // be) that makes this tractable.
14338 // FIXME: handle "template <> friend class A<T>;", which
14339 // is possibly well-formed? Who even knows?
14340 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
14341 Diag(Loc, diag::err_tagless_friend_type_template)
14342 << DS.getSourceRange();
14346 // C++98 [class.friend]p1: A friend of a class is a function
14347 // or class that is not a member of the class . . .
14348 // This is fixed in DR77, which just barely didn't make the C++03
14349 // deadline. It's also a very silly restriction that seriously
14350 // affects inner classes and which nobody else seems to implement;
14351 // thus we never diagnose it, not even in -pedantic.
14353 // But note that we could warn about it: it's always useless to
14354 // friend one of your own members (it's not, however, worthless to
14355 // friend a member of an arbitrary specialization of your template).
14358 if (!TempParams.empty())
14359 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
14362 DS.getFriendSpecLoc());
14364 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
14369 D->setAccess(AS_public);
14370 CurContext->addDecl(D);
14375 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
14376 MultiTemplateParamsArg TemplateParams) {
14377 const DeclSpec &DS = D.getDeclSpec();
14379 assert(DS.isFriendSpecified());
14380 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
14382 SourceLocation Loc = D.getIdentifierLoc();
14383 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14385 // C++ [class.friend]p1
14386 // A friend of a class is a function or class....
14387 // Note that this sees through typedefs, which is intended.
14388 // It *doesn't* see through dependent types, which is correct
14389 // according to [temp.arg.type]p3:
14390 // If a declaration acquires a function type through a
14391 // type dependent on a template-parameter and this causes
14392 // a declaration that does not use the syntactic form of a
14393 // function declarator to have a function type, the program
14395 if (!TInfo->getType()->isFunctionType()) {
14396 Diag(Loc, diag::err_unexpected_friend);
14398 // It might be worthwhile to try to recover by creating an
14399 // appropriate declaration.
14403 // C++ [namespace.memdef]p3
14404 // - If a friend declaration in a non-local class first declares a
14405 // class or function, the friend class or function is a member
14406 // of the innermost enclosing namespace.
14407 // - The name of the friend is not found by simple name lookup
14408 // until a matching declaration is provided in that namespace
14409 // scope (either before or after the class declaration granting
14411 // - If a friend function is called, its name may be found by the
14412 // name lookup that considers functions from namespaces and
14413 // classes associated with the types of the function arguments.
14414 // - When looking for a prior declaration of a class or a function
14415 // declared as a friend, scopes outside the innermost enclosing
14416 // namespace scope are not considered.
14418 CXXScopeSpec &SS = D.getCXXScopeSpec();
14419 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
14420 assert(NameInfo.getName());
14422 // Check for unexpanded parameter packs.
14423 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
14424 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
14425 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
14428 // The context we found the declaration in, or in which we should
14429 // create the declaration.
14431 Scope *DCScope = S;
14432 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14433 ForExternalRedeclaration);
14435 // There are five cases here.
14436 // - There's no scope specifier and we're in a local class. Only look
14437 // for functions declared in the immediately-enclosing block scope.
14438 // We recover from invalid scope qualifiers as if they just weren't there.
14439 FunctionDecl *FunctionContainingLocalClass = nullptr;
14440 if ((SS.isInvalid() || !SS.isSet()) &&
14441 (FunctionContainingLocalClass =
14442 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
14443 // C++11 [class.friend]p11:
14444 // If a friend declaration appears in a local class and the name
14445 // specified is an unqualified name, a prior declaration is
14446 // looked up without considering scopes that are outside the
14447 // innermost enclosing non-class scope. For a friend function
14448 // declaration, if there is no prior declaration, the program is
14451 // Find the innermost enclosing non-class scope. This is the block
14452 // scope containing the local class definition (or for a nested class,
14453 // the outer local class).
14454 DCScope = S->getFnParent();
14456 // Look up the function name in the scope.
14457 Previous.clear(LookupLocalFriendName);
14458 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
14460 if (!Previous.empty()) {
14461 // All possible previous declarations must have the same context:
14462 // either they were declared at block scope or they are members of
14463 // one of the enclosing local classes.
14464 DC = Previous.getRepresentativeDecl()->getDeclContext();
14466 // This is ill-formed, but provide the context that we would have
14467 // declared the function in, if we were permitted to, for error recovery.
14468 DC = FunctionContainingLocalClass;
14470 adjustContextForLocalExternDecl(DC);
14472 // C++ [class.friend]p6:
14473 // A function can be defined in a friend declaration of a class if and
14474 // only if the class is a non-local class (9.8), the function name is
14475 // unqualified, and the function has namespace scope.
14476 if (D.isFunctionDefinition()) {
14477 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
14480 // - There's no scope specifier, in which case we just go to the
14481 // appropriate scope and look for a function or function template
14482 // there as appropriate.
14483 } else if (SS.isInvalid() || !SS.isSet()) {
14484 // C++11 [namespace.memdef]p3:
14485 // If the name in a friend declaration is neither qualified nor
14486 // a template-id and the declaration is a function or an
14487 // elaborated-type-specifier, the lookup to determine whether
14488 // the entity has been previously declared shall not consider
14489 // any scopes outside the innermost enclosing namespace.
14490 bool isTemplateId =
14491 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
14493 // Find the appropriate context according to the above.
14496 // Skip class contexts. If someone can cite chapter and verse
14497 // for this behavior, that would be nice --- it's what GCC and
14498 // EDG do, and it seems like a reasonable intent, but the spec
14499 // really only says that checks for unqualified existing
14500 // declarations should stop at the nearest enclosing namespace,
14501 // not that they should only consider the nearest enclosing
14503 while (DC->isRecord())
14504 DC = DC->getParent();
14506 DeclContext *LookupDC = DC;
14507 while (LookupDC->isTransparentContext())
14508 LookupDC = LookupDC->getParent();
14511 LookupQualifiedName(Previous, LookupDC);
14513 if (!Previous.empty()) {
14518 if (isTemplateId) {
14519 if (isa<TranslationUnitDecl>(LookupDC)) break;
14521 if (LookupDC->isFileContext()) break;
14523 LookupDC = LookupDC->getParent();
14526 DCScope = getScopeForDeclContext(S, DC);
14528 // - There's a non-dependent scope specifier, in which case we
14529 // compute it and do a previous lookup there for a function
14530 // or function template.
14531 } else if (!SS.getScopeRep()->isDependent()) {
14532 DC = computeDeclContext(SS);
14533 if (!DC) return nullptr;
14535 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
14537 LookupQualifiedName(Previous, DC);
14539 // C++ [class.friend]p1: A friend of a class is a function or
14540 // class that is not a member of the class . . .
14541 if (DC->Equals(CurContext))
14542 Diag(DS.getFriendSpecLoc(),
14543 getLangOpts().CPlusPlus11 ?
14544 diag::warn_cxx98_compat_friend_is_member :
14545 diag::err_friend_is_member);
14547 if (D.isFunctionDefinition()) {
14548 // C++ [class.friend]p6:
14549 // A function can be defined in a friend declaration of a class if and
14550 // only if the class is a non-local class (9.8), the function name is
14551 // unqualified, and the function has namespace scope.
14553 // FIXME: We should only do this if the scope specifier names the
14554 // innermost enclosing namespace; otherwise the fixit changes the
14555 // meaning of the code.
14556 SemaDiagnosticBuilder DB
14557 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
14559 DB << SS.getScopeRep();
14560 if (DC->isFileContext())
14561 DB << FixItHint::CreateRemoval(SS.getRange());
14565 // - There's a scope specifier that does not match any template
14566 // parameter lists, in which case we use some arbitrary context,
14567 // create a method or method template, and wait for instantiation.
14568 // - There's a scope specifier that does match some template
14569 // parameter lists, which we don't handle right now.
14571 if (D.isFunctionDefinition()) {
14572 // C++ [class.friend]p6:
14573 // A function can be defined in a friend declaration of a class if and
14574 // only if the class is a non-local class (9.8), the function name is
14575 // unqualified, and the function has namespace scope.
14576 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
14577 << SS.getScopeRep();
14581 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
14584 if (!DC->isRecord()) {
14586 switch (D.getName().getKind()) {
14587 case UnqualifiedIdKind::IK_ConstructorTemplateId:
14588 case UnqualifiedIdKind::IK_ConstructorName:
14591 case UnqualifiedIdKind::IK_DestructorName:
14594 case UnqualifiedIdKind::IK_ConversionFunctionId:
14597 case UnqualifiedIdKind::IK_DeductionGuideName:
14600 case UnqualifiedIdKind::IK_Identifier:
14601 case UnqualifiedIdKind::IK_ImplicitSelfParam:
14602 case UnqualifiedIdKind::IK_LiteralOperatorId:
14603 case UnqualifiedIdKind::IK_OperatorFunctionId:
14604 case UnqualifiedIdKind::IK_TemplateId:
14607 // This implies that it has to be an operator or function.
14608 if (DiagArg >= 0) {
14609 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
14614 // FIXME: This is an egregious hack to cope with cases where the scope stack
14615 // does not contain the declaration context, i.e., in an out-of-line
14616 // definition of a class.
14617 Scope FakeDCScope(S, Scope::DeclScope, Diags);
14619 FakeDCScope.setEntity(DC);
14620 DCScope = &FakeDCScope;
14623 bool AddToScope = true;
14624 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
14625 TemplateParams, AddToScope);
14626 if (!ND) return nullptr;
14628 assert(ND->getLexicalDeclContext() == CurContext);
14630 // If we performed typo correction, we might have added a scope specifier
14631 // and changed the decl context.
14632 DC = ND->getDeclContext();
14634 // Add the function declaration to the appropriate lookup tables,
14635 // adjusting the redeclarations list as necessary. We don't
14636 // want to do this yet if the friending class is dependent.
14638 // Also update the scope-based lookup if the target context's
14639 // lookup context is in lexical scope.
14640 if (!CurContext->isDependentContext()) {
14641 DC = DC->getRedeclContext();
14642 DC->makeDeclVisibleInContext(ND);
14643 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14644 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
14647 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
14648 D.getIdentifierLoc(), ND,
14649 DS.getFriendSpecLoc());
14650 FrD->setAccess(AS_public);
14651 CurContext->addDecl(FrD);
14653 if (ND->isInvalidDecl()) {
14654 FrD->setInvalidDecl();
14656 if (DC->isRecord()) CheckFriendAccess(ND);
14659 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
14660 FD = FTD->getTemplatedDecl();
14662 FD = cast<FunctionDecl>(ND);
14664 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
14665 // default argument expression, that declaration shall be a definition
14666 // and shall be the only declaration of the function or function
14667 // template in the translation unit.
14668 if (functionDeclHasDefaultArgument(FD)) {
14669 // We can't look at FD->getPreviousDecl() because it may not have been set
14670 // if we're in a dependent context. If the function is known to be a
14671 // redeclaration, we will have narrowed Previous down to the right decl.
14672 if (D.isRedeclaration()) {
14673 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
14674 Diag(Previous.getRepresentativeDecl()->getLocation(),
14675 diag::note_previous_declaration);
14676 } else if (!D.isFunctionDefinition())
14677 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
14680 // Mark templated-scope function declarations as unsupported.
14681 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
14682 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
14683 << SS.getScopeRep() << SS.getRange()
14684 << cast<CXXRecordDecl>(CurContext);
14685 FrD->setUnsupportedFriend(true);
14692 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14693 AdjustDeclIfTemplate(Dcl);
14695 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14697 Diag(DelLoc, diag::err_deleted_non_function);
14701 // Deleted function does not have a body.
14702 Fn->setWillHaveBody(false);
14704 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14705 // Don't consider the implicit declaration we generate for explicit
14706 // specializations. FIXME: Do not generate these implicit declarations.
14707 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14708 Prev->getPreviousDecl()) &&
14709 !Prev->isDefined()) {
14710 Diag(DelLoc, diag::err_deleted_decl_not_first);
14711 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14712 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14713 : diag::note_previous_declaration);
14715 // If the declaration wasn't the first, we delete the function anyway for
14717 Fn = Fn->getCanonicalDecl();
14720 // dllimport/dllexport cannot be deleted.
14721 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14722 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14723 Fn->setInvalidDecl();
14726 if (Fn->isDeleted())
14729 // See if we're deleting a function which is already known to override a
14730 // non-deleted virtual function.
14731 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14732 bool IssuedDiagnostic = false;
14733 for (const CXXMethodDecl *O : MD->overridden_methods()) {
14734 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14735 if (!IssuedDiagnostic) {
14736 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14737 IssuedDiagnostic = true;
14739 Diag(O->getLocation(), diag::note_overridden_virtual_function);
14742 // If this function was implicitly deleted because it was defaulted,
14743 // explain why it was deleted.
14744 if (IssuedDiagnostic && MD->isDefaulted())
14745 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14749 // C++11 [basic.start.main]p3:
14750 // A program that defines main as deleted [...] is ill-formed.
14752 Diag(DelLoc, diag::err_deleted_main);
14754 // C++11 [dcl.fct.def.delete]p4:
14755 // A deleted function is implicitly inline.
14756 Fn->setImplicitlyInline();
14757 Fn->setDeletedAsWritten();
14760 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14761 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14764 if (MD->getParent()->isDependentType()) {
14765 MD->setDefaulted();
14766 MD->setExplicitlyDefaulted();
14770 CXXSpecialMember Member = getSpecialMember(MD);
14771 if (Member == CXXInvalid) {
14772 if (!MD->isInvalidDecl())
14773 Diag(DefaultLoc, diag::err_default_special_members);
14777 MD->setDefaulted();
14778 MD->setExplicitlyDefaulted();
14780 // Unset that we will have a body for this function. We might not,
14781 // if it turns out to be trivial, and we don't need this marking now
14782 // that we've marked it as defaulted.
14783 MD->setWillHaveBody(false);
14785 // If this definition appears within the record, do the checking when
14786 // the record is complete.
14787 const FunctionDecl *Primary = MD;
14788 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14789 // Ask the template instantiation pattern that actually had the
14790 // '= default' on it.
14793 // If the method was defaulted on its first declaration, we will have
14794 // already performed the checking in CheckCompletedCXXClass. Such a
14795 // declaration doesn't trigger an implicit definition.
14796 if (Primary->getCanonicalDecl()->isDefaulted())
14799 CheckExplicitlyDefaultedSpecialMember(MD);
14801 if (!MD->isInvalidDecl())
14802 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14804 Diag(DefaultLoc, diag::err_default_special_members);
14808 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14809 for (Stmt *SubStmt : S->children()) {
14812 if (isa<ReturnStmt>(SubStmt))
14813 Self.Diag(SubStmt->getBeginLoc(),
14814 diag::err_return_in_constructor_handler);
14815 if (!isa<Expr>(SubStmt))
14816 SearchForReturnInStmt(Self, SubStmt);
14820 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14821 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14822 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14823 SearchForReturnInStmt(*this, Handler);
14827 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14828 const CXXMethodDecl *Old) {
14829 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14830 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14832 if (OldFT->hasExtParameterInfos()) {
14833 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14834 // A parameter of the overriding method should be annotated with noescape
14835 // if the corresponding parameter of the overridden method is annotated.
14836 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14837 !NewFT->getExtParameterInfo(I).isNoEscape()) {
14838 Diag(New->getParamDecl(I)->getLocation(),
14839 diag::warn_overriding_method_missing_noescape);
14840 Diag(Old->getParamDecl(I)->getLocation(),
14841 diag::note_overridden_marked_noescape);
14845 // Virtual overrides must have the same code_seg.
14846 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
14847 const auto *NewCSA = New->getAttr<CodeSegAttr>();
14848 if ((NewCSA || OldCSA) &&
14849 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
14850 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
14851 Diag(Old->getLocation(), diag::note_previous_declaration);
14855 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14857 // If the calling conventions match, everything is fine
14858 if (NewCC == OldCC)
14861 // If the calling conventions mismatch because the new function is static,
14862 // suppress the calling convention mismatch error; the error about static
14863 // function override (err_static_overrides_virtual from
14864 // Sema::CheckFunctionDeclaration) is more clear.
14865 if (New->getStorageClass() == SC_Static)
14868 Diag(New->getLocation(),
14869 diag::err_conflicting_overriding_cc_attributes)
14870 << New->getDeclName() << New->getType() << Old->getType();
14871 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14875 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14876 const CXXMethodDecl *Old) {
14877 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14878 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14880 if (Context.hasSameType(NewTy, OldTy) ||
14881 NewTy->isDependentType() || OldTy->isDependentType())
14884 // Check if the return types are covariant
14885 QualType NewClassTy, OldClassTy;
14887 /// Both types must be pointers or references to classes.
14888 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14889 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14890 NewClassTy = NewPT->getPointeeType();
14891 OldClassTy = OldPT->getPointeeType();
14893 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14894 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14895 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14896 NewClassTy = NewRT->getPointeeType();
14897 OldClassTy = OldRT->getPointeeType();
14902 // The return types aren't either both pointers or references to a class type.
14903 if (NewClassTy.isNull()) {
14904 Diag(New->getLocation(),
14905 diag::err_different_return_type_for_overriding_virtual_function)
14906 << New->getDeclName() << NewTy << OldTy
14907 << New->getReturnTypeSourceRange();
14908 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14909 << Old->getReturnTypeSourceRange();
14914 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14915 // C++14 [class.virtual]p8:
14916 // If the class type in the covariant return type of D::f differs from
14917 // that of B::f, the class type in the return type of D::f shall be
14918 // complete at the point of declaration of D::f or shall be the class
14920 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14921 if (!RT->isBeingDefined() &&
14922 RequireCompleteType(New->getLocation(), NewClassTy,
14923 diag::err_covariant_return_incomplete,
14924 New->getDeclName()))
14928 // Check if the new class derives from the old class.
14929 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14930 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14931 << New->getDeclName() << NewTy << OldTy
14932 << New->getReturnTypeSourceRange();
14933 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14934 << Old->getReturnTypeSourceRange();
14938 // Check if we the conversion from derived to base is valid.
14939 if (CheckDerivedToBaseConversion(
14940 NewClassTy, OldClassTy,
14941 diag::err_covariant_return_inaccessible_base,
14942 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14943 New->getLocation(), New->getReturnTypeSourceRange(),
14944 New->getDeclName(), nullptr)) {
14945 // FIXME: this note won't trigger for delayed access control
14946 // diagnostics, and it's impossible to get an undelayed error
14947 // here from access control during the original parse because
14948 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14949 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14950 << Old->getReturnTypeSourceRange();
14955 // The qualifiers of the return types must be the same.
14956 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14957 Diag(New->getLocation(),
14958 diag::err_covariant_return_type_different_qualifications)
14959 << New->getDeclName() << NewTy << OldTy
14960 << New->getReturnTypeSourceRange();
14961 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14962 << Old->getReturnTypeSourceRange();
14967 // The new class type must have the same or less qualifiers as the old type.
14968 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14969 Diag(New->getLocation(),
14970 diag::err_covariant_return_type_class_type_more_qualified)
14971 << New->getDeclName() << NewTy << OldTy
14972 << New->getReturnTypeSourceRange();
14973 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14974 << Old->getReturnTypeSourceRange();
14981 /// Mark the given method pure.
14983 /// \param Method the method to be marked pure.
14985 /// \param InitRange the source range that covers the "0" initializer.
14986 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14987 SourceLocation EndLoc = InitRange.getEnd();
14988 if (EndLoc.isValid())
14989 Method->setRangeEnd(EndLoc);
14991 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14996 if (!Method->isInvalidDecl())
14997 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14998 << Method->getDeclName() << InitRange;
15002 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
15003 if (D->getFriendObjectKind())
15004 Diag(D->getLocation(), diag::err_pure_friend);
15005 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
15006 CheckPureMethod(M, ZeroLoc);
15008 Diag(D->getLocation(), diag::err_illegal_initializer);
15011 /// Determine whether the given declaration is a global variable or
15012 /// static data member.
15013 static bool isNonlocalVariable(const Decl *D) {
15014 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
15015 return Var->hasGlobalStorage();
15020 /// Invoked when we are about to parse an initializer for the declaration
15023 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
15024 /// static data member of class X, names should be looked up in the scope of
15025 /// class X. If the declaration had a scope specifier, a scope will have
15026 /// been created and passed in for this purpose. Otherwise, S will be null.
15027 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
15028 // If there is no declaration, there was an error parsing it.
15029 if (!D || D->isInvalidDecl())
15032 // We will always have a nested name specifier here, but this declaration
15033 // might not be out of line if the specifier names the current namespace:
15036 if (S && D->isOutOfLine())
15037 EnterDeclaratorContext(S, D->getDeclContext());
15039 // If we are parsing the initializer for a static data member, push a
15040 // new expression evaluation context that is associated with this static
15042 if (isNonlocalVariable(D))
15043 PushExpressionEvaluationContext(
15044 ExpressionEvaluationContext::PotentiallyEvaluated, D);
15047 /// Invoked after we are finished parsing an initializer for the declaration D.
15048 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
15049 // If there is no declaration, there was an error parsing it.
15050 if (!D || D->isInvalidDecl())
15053 if (isNonlocalVariable(D))
15054 PopExpressionEvaluationContext();
15056 if (S && D->isOutOfLine())
15057 ExitDeclaratorContext(S);
15060 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
15061 /// C++ if/switch/while/for statement.
15062 /// e.g: "if (int x = f()) {...}"
15063 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
15065 // The declarator shall not specify a function or an array.
15066 // The type-specifier-seq shall not contain typedef and shall not declare a
15067 // new class or enumeration.
15068 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
15069 "Parser allowed 'typedef' as storage class of condition decl.");
15071 Decl *Dcl = ActOnDeclarator(S, D);
15075 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
15076 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
15077 << D.getSourceRange();
15084 void Sema::LoadExternalVTableUses() {
15085 if (!ExternalSource)
15088 SmallVector<ExternalVTableUse, 4> VTables;
15089 ExternalSource->ReadUsedVTables(VTables);
15090 SmallVector<VTableUse, 4> NewUses;
15091 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
15092 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
15093 = VTablesUsed.find(VTables[I].Record);
15094 // Even if a definition wasn't required before, it may be required now.
15095 if (Pos != VTablesUsed.end()) {
15096 if (!Pos->second && VTables[I].DefinitionRequired)
15097 Pos->second = true;
15101 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
15102 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
15105 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
15108 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
15109 bool DefinitionRequired) {
15110 // Ignore any vtable uses in unevaluated operands or for classes that do
15111 // not have a vtable.
15112 if (!Class->isDynamicClass() || Class->isDependentContext() ||
15113 CurContext->isDependentContext() || isUnevaluatedContext())
15115 // Do not mark as used if compiling for the device outside of the target
15117 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
15118 !isInOpenMPDeclareTargetContext() &&
15119 !isInOpenMPTargetExecutionDirective()) {
15120 if (!DefinitionRequired)
15121 MarkVirtualMembersReferenced(Loc, Class);
15125 // Try to insert this class into the map.
15126 LoadExternalVTableUses();
15127 Class = Class->getCanonicalDecl();
15128 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
15129 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
15131 // If we already had an entry, check to see if we are promoting this vtable
15132 // to require a definition. If so, we need to reappend to the VTableUses
15133 // list, since we may have already processed the first entry.
15134 if (DefinitionRequired && !Pos.first->second) {
15135 Pos.first->second = true;
15137 // Otherwise, we can early exit.
15141 // The Microsoft ABI requires that we perform the destructor body
15142 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
15143 // the deleting destructor is emitted with the vtable, not with the
15144 // destructor definition as in the Itanium ABI.
15145 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
15146 CXXDestructorDecl *DD = Class->getDestructor();
15147 if (DD && DD->isVirtual() && !DD->isDeleted()) {
15148 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
15149 // If this is an out-of-line declaration, marking it referenced will
15150 // not do anything. Manually call CheckDestructor to look up operator
15152 ContextRAII SavedContext(*this, DD);
15153 CheckDestructor(DD);
15155 MarkFunctionReferenced(Loc, Class->getDestructor());
15161 // Local classes need to have their virtual members marked
15162 // immediately. For all other classes, we mark their virtual members
15163 // at the end of the translation unit.
15164 if (Class->isLocalClass())
15165 MarkVirtualMembersReferenced(Loc, Class);
15167 VTableUses.push_back(std::make_pair(Class, Loc));
15170 bool Sema::DefineUsedVTables() {
15171 LoadExternalVTableUses();
15172 if (VTableUses.empty())
15175 // Note: The VTableUses vector could grow as a result of marking
15176 // the members of a class as "used", so we check the size each
15177 // time through the loop and prefer indices (which are stable) to
15178 // iterators (which are not).
15179 bool DefinedAnything = false;
15180 for (unsigned I = 0; I != VTableUses.size(); ++I) {
15181 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
15184 TemplateSpecializationKind ClassTSK =
15185 Class->getTemplateSpecializationKind();
15187 SourceLocation Loc = VTableUses[I].second;
15189 bool DefineVTable = true;
15191 // If this class has a key function, but that key function is
15192 // defined in another translation unit, we don't need to emit the
15193 // vtable even though we're using it.
15194 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
15195 if (KeyFunction && !KeyFunction->hasBody()) {
15196 // The key function is in another translation unit.
15197 DefineVTable = false;
15198 TemplateSpecializationKind TSK =
15199 KeyFunction->getTemplateSpecializationKind();
15200 assert(TSK != TSK_ExplicitInstantiationDefinition &&
15201 TSK != TSK_ImplicitInstantiation &&
15202 "Instantiations don't have key functions");
15204 } else if (!KeyFunction) {
15205 // If we have a class with no key function that is the subject
15206 // of an explicit instantiation declaration, suppress the
15207 // vtable; it will live with the explicit instantiation
15209 bool IsExplicitInstantiationDeclaration =
15210 ClassTSK == TSK_ExplicitInstantiationDeclaration;
15211 for (auto R : Class->redecls()) {
15212 TemplateSpecializationKind TSK
15213 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
15214 if (TSK == TSK_ExplicitInstantiationDeclaration)
15215 IsExplicitInstantiationDeclaration = true;
15216 else if (TSK == TSK_ExplicitInstantiationDefinition) {
15217 IsExplicitInstantiationDeclaration = false;
15222 if (IsExplicitInstantiationDeclaration)
15223 DefineVTable = false;
15226 // The exception specifications for all virtual members may be needed even
15227 // if we are not providing an authoritative form of the vtable in this TU.
15228 // We may choose to emit it available_externally anyway.
15229 if (!DefineVTable) {
15230 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
15234 // Mark all of the virtual members of this class as referenced, so
15235 // that we can build a vtable. Then, tell the AST consumer that a
15236 // vtable for this class is required.
15237 DefinedAnything = true;
15238 MarkVirtualMembersReferenced(Loc, Class);
15239 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
15240 if (VTablesUsed[Canonical])
15241 Consumer.HandleVTable(Class);
15243 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
15244 // no key function or the key function is inlined. Don't warn in C++ ABIs
15245 // that lack key functions, since the user won't be able to make one.
15246 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
15247 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
15248 const FunctionDecl *KeyFunctionDef = nullptr;
15249 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
15250 KeyFunctionDef->isInlined())) {
15251 Diag(Class->getLocation(),
15252 ClassTSK == TSK_ExplicitInstantiationDefinition
15253 ? diag::warn_weak_template_vtable
15254 : diag::warn_weak_vtable)
15259 VTableUses.clear();
15261 return DefinedAnything;
15264 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
15265 const CXXRecordDecl *RD) {
15266 for (const auto *I : RD->methods())
15267 if (I->isVirtual() && !I->isPure())
15268 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
15271 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
15272 const CXXRecordDecl *RD,
15273 bool ConstexprOnly) {
15274 // Mark all functions which will appear in RD's vtable as used.
15275 CXXFinalOverriderMap FinalOverriders;
15276 RD->getFinalOverriders(FinalOverriders);
15277 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
15278 E = FinalOverriders.end();
15280 for (OverridingMethods::const_iterator OI = I->second.begin(),
15281 OE = I->second.end();
15283 assert(OI->second.size() > 0 && "no final overrider");
15284 CXXMethodDecl *Overrider = OI->second.front().Method;
15286 // C++ [basic.def.odr]p2:
15287 // [...] A virtual member function is used if it is not pure. [...]
15288 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
15289 MarkFunctionReferenced(Loc, Overrider);
15293 // Only classes that have virtual bases need a VTT.
15294 if (RD->getNumVBases() == 0)
15297 for (const auto &I : RD->bases()) {
15298 const CXXRecordDecl *Base =
15299 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
15300 if (Base->getNumVBases() == 0)
15302 MarkVirtualMembersReferenced(Loc, Base);
15306 /// SetIvarInitializers - This routine builds initialization ASTs for the
15307 /// Objective-C implementation whose ivars need be initialized.
15308 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
15309 if (!getLangOpts().CPlusPlus)
15311 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
15312 SmallVector<ObjCIvarDecl*, 8> ivars;
15313 CollectIvarsToConstructOrDestruct(OID, ivars);
15316 SmallVector<CXXCtorInitializer*, 32> AllToInit;
15317 for (unsigned i = 0; i < ivars.size(); i++) {
15318 FieldDecl *Field = ivars[i];
15319 if (Field->isInvalidDecl())
15322 CXXCtorInitializer *Member;
15323 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
15324 InitializationKind InitKind =
15325 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
15327 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
15328 ExprResult MemberInit =
15329 InitSeq.Perform(*this, InitEntity, InitKind, None);
15330 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
15331 // Note, MemberInit could actually come back empty if no initialization
15332 // is required (e.g., because it would call a trivial default constructor)
15333 if (!MemberInit.get() || MemberInit.isInvalid())
15337 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
15339 MemberInit.getAs<Expr>(),
15341 AllToInit.push_back(Member);
15343 // Be sure that the destructor is accessible and is marked as referenced.
15344 if (const RecordType *RecordTy =
15345 Context.getBaseElementType(Field->getType())
15346 ->getAs<RecordType>()) {
15347 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
15348 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
15349 MarkFunctionReferenced(Field->getLocation(), Destructor);
15350 CheckDestructorAccess(Field->getLocation(), Destructor,
15351 PDiag(diag::err_access_dtor_ivar)
15352 << Context.getBaseElementType(Field->getType()));
15356 ObjCImplementation->setIvarInitializers(Context,
15357 AllToInit.data(), AllToInit.size());
15362 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
15363 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
15364 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
15365 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
15367 if (Ctor->isInvalidDecl())
15370 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
15372 // Target may not be determinable yet, for instance if this is a dependent
15373 // call in an uninstantiated template.
15375 const FunctionDecl *FNTarget = nullptr;
15376 (void)Target->hasBody(FNTarget);
15377 Target = const_cast<CXXConstructorDecl*>(
15378 cast_or_null<CXXConstructorDecl>(FNTarget));
15381 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
15382 // Avoid dereferencing a null pointer here.
15383 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
15385 if (!Current.insert(Canonical).second)
15388 // We know that beyond here, we aren't chaining into a cycle.
15389 if (!Target || !Target->isDelegatingConstructor() ||
15390 Target->isInvalidDecl() || Valid.count(TCanonical)) {
15391 Valid.insert(Current.begin(), Current.end());
15393 // We've hit a cycle.
15394 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
15395 Current.count(TCanonical)) {
15396 // If we haven't diagnosed this cycle yet, do so now.
15397 if (!Invalid.count(TCanonical)) {
15398 S.Diag((*Ctor->init_begin())->getSourceLocation(),
15399 diag::warn_delegating_ctor_cycle)
15402 // Don't add a note for a function delegating directly to itself.
15403 if (TCanonical != Canonical)
15404 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
15406 CXXConstructorDecl *C = Target;
15407 while (C->getCanonicalDecl() != Canonical) {
15408 const FunctionDecl *FNTarget = nullptr;
15409 (void)C->getTargetConstructor()->hasBody(FNTarget);
15410 assert(FNTarget && "Ctor cycle through bodiless function");
15412 C = const_cast<CXXConstructorDecl*>(
15413 cast<CXXConstructorDecl>(FNTarget));
15414 S.Diag(C->getLocation(), diag::note_which_delegates_to);
15418 Invalid.insert(Current.begin(), Current.end());
15421 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
15426 void Sema::CheckDelegatingCtorCycles() {
15427 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
15429 for (DelegatingCtorDeclsType::iterator
15430 I = DelegatingCtorDecls.begin(ExternalSource),
15431 E = DelegatingCtorDecls.end();
15433 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
15435 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
15436 (*CI)->setInvalidDecl();
15440 /// AST visitor that finds references to the 'this' expression.
15441 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
15445 explicit FindCXXThisExpr(Sema &S) : S(S) { }
15447 bool VisitCXXThisExpr(CXXThisExpr *E) {
15448 S.Diag(E->getLocation(), diag::err_this_static_member_func)
15449 << E->isImplicit();
15455 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
15456 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15460 TypeLoc TL = TSInfo->getTypeLoc();
15461 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15465 // C++11 [expr.prim.general]p3:
15466 // [The expression this] shall not appear before the optional
15467 // cv-qualifier-seq and it shall not appear within the declaration of a
15468 // static member function (although its type and value category are defined
15469 // within a static member function as they are within a non-static member
15470 // function). [ Note: this is because declaration matching does not occur
15471 // until the complete declarator is known. - end note ]
15472 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15473 FindCXXThisExpr Finder(*this);
15475 // If the return type came after the cv-qualifier-seq, check it now.
15476 if (Proto->hasTrailingReturn() &&
15477 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
15480 // Check the exception specification.
15481 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
15484 return checkThisInStaticMemberFunctionAttributes(Method);
15487 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
15488 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
15492 TypeLoc TL = TSInfo->getTypeLoc();
15493 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
15497 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
15498 FindCXXThisExpr Finder(*this);
15500 switch (Proto->getExceptionSpecType()) {
15502 case EST_Uninstantiated:
15503 case EST_Unevaluated:
15504 case EST_BasicNoexcept:
15506 case EST_DynamicNone:
15511 case EST_DependentNoexcept:
15512 case EST_NoexceptFalse:
15513 case EST_NoexceptTrue:
15514 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
15519 for (const auto &E : Proto->exceptions()) {
15520 if (!Finder.TraverseType(E))
15529 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
15530 FindCXXThisExpr Finder(*this);
15532 // Check attributes.
15533 for (const auto *A : Method->attrs()) {
15534 // FIXME: This should be emitted by tblgen.
15535 Expr *Arg = nullptr;
15536 ArrayRef<Expr *> Args;
15537 if (const auto *G = dyn_cast<GuardedByAttr>(A))
15539 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
15541 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
15542 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
15543 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
15544 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
15545 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
15546 Arg = ETLF->getSuccessValue();
15547 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
15548 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
15549 Arg = STLF->getSuccessValue();
15550 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
15551 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
15552 Arg = LR->getArg();
15553 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
15554 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
15555 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
15556 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15557 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
15558 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15559 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
15560 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
15561 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
15562 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
15564 if (Arg && !Finder.TraverseStmt(Arg))
15567 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
15568 if (!Finder.TraverseStmt(Args[I]))
15576 void Sema::checkExceptionSpecification(
15577 bool IsTopLevel, ExceptionSpecificationType EST,
15578 ArrayRef<ParsedType> DynamicExceptions,
15579 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
15580 SmallVectorImpl<QualType> &Exceptions,
15581 FunctionProtoType::ExceptionSpecInfo &ESI) {
15582 Exceptions.clear();
15584 if (EST == EST_Dynamic) {
15585 Exceptions.reserve(DynamicExceptions.size());
15586 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
15587 // FIXME: Preserve type source info.
15588 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
15591 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
15592 collectUnexpandedParameterPacks(ET, Unexpanded);
15593 if (!Unexpanded.empty()) {
15594 DiagnoseUnexpandedParameterPacks(
15595 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
15601 // Check that the type is valid for an exception spec, and
15603 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
15604 Exceptions.push_back(ET);
15606 ESI.Exceptions = Exceptions;
15610 if (isComputedNoexcept(EST)) {
15611 assert((NoexceptExpr->isTypeDependent() ||
15612 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
15614 "Parser should have made sure that the expression is boolean");
15615 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
15616 ESI.Type = EST_BasicNoexcept;
15620 ESI.NoexceptExpr = NoexceptExpr;
15625 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
15626 ExceptionSpecificationType EST,
15627 SourceRange SpecificationRange,
15628 ArrayRef<ParsedType> DynamicExceptions,
15629 ArrayRef<SourceRange> DynamicExceptionRanges,
15630 Expr *NoexceptExpr) {
15634 // Dig out the method we're referring to.
15635 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
15636 MethodD = FunTmpl->getTemplatedDecl();
15638 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
15642 // Check the exception specification.
15643 llvm::SmallVector<QualType, 4> Exceptions;
15644 FunctionProtoType::ExceptionSpecInfo ESI;
15645 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
15646 DynamicExceptionRanges, NoexceptExpr, Exceptions,
15649 // Update the exception specification on the function type.
15650 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
15652 if (Method->isStatic())
15653 checkThisInStaticMemberFunctionExceptionSpec(Method);
15655 if (Method->isVirtual()) {
15656 // Check overrides, which we previously had to delay.
15657 for (const CXXMethodDecl *O : Method->overridden_methods())
15658 CheckOverridingFunctionExceptionSpec(Method, O);
15662 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
15664 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
15665 SourceLocation DeclStart, Declarator &D,
15667 InClassInitStyle InitStyle,
15668 AccessSpecifier AS,
15669 const ParsedAttr &MSPropertyAttr) {
15670 IdentifierInfo *II = D.getIdentifier();
15672 Diag(DeclStart, diag::err_anonymous_property);
15675 SourceLocation Loc = D.getIdentifierLoc();
15677 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15678 QualType T = TInfo->getType();
15679 if (getLangOpts().CPlusPlus) {
15680 CheckExtraCXXDefaultArguments(D);
15682 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15683 UPPC_DataMemberType)) {
15684 D.setInvalidType();
15686 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15690 DiagnoseFunctionSpecifiers(D.getDeclSpec());
15692 if (D.getDeclSpec().isInlineSpecified())
15693 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15694 << getLangOpts().CPlusPlus17;
15695 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15696 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15697 diag::err_invalid_thread)
15698 << DeclSpec::getSpecifierName(TSCS);
15700 // Check to see if this name was declared as a member previously
15701 NamedDecl *PrevDecl = nullptr;
15702 LookupResult Previous(*this, II, Loc, LookupMemberName,
15703 ForVisibleRedeclaration);
15704 LookupName(Previous, S);
15705 switch (Previous.getResultKind()) {
15706 case LookupResult::Found:
15707 case LookupResult::FoundUnresolvedValue:
15708 PrevDecl = Previous.getAsSingle<NamedDecl>();
15711 case LookupResult::FoundOverloaded:
15712 PrevDecl = Previous.getRepresentativeDecl();
15715 case LookupResult::NotFound:
15716 case LookupResult::NotFoundInCurrentInstantiation:
15717 case LookupResult::Ambiguous:
15721 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15722 // Maybe we will complain about the shadowed template parameter.
15723 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15724 // Just pretend that we didn't see the previous declaration.
15725 PrevDecl = nullptr;
15728 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15729 PrevDecl = nullptr;
15731 SourceLocation TSSL = D.getBeginLoc();
15732 MSPropertyDecl *NewPD =
15733 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
15734 MSPropertyAttr.getPropertyDataGetter(),
15735 MSPropertyAttr.getPropertyDataSetter());
15736 ProcessDeclAttributes(TUScope, NewPD, D);
15737 NewPD->setAccess(AS);
15739 if (NewPD->isInvalidDecl())
15740 Record->setInvalidDecl();
15742 if (D.getDeclSpec().isModulePrivateSpecified())
15743 NewPD->setModulePrivate();
15745 if (NewPD->isInvalidDecl() && PrevDecl) {
15746 // Don't introduce NewFD into scope; there's already something
15747 // with the same name in the same scope.
15749 PushOnScopeChains(NewPD, S);
15751 Record->addDecl(NewPD);