1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.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->getLocStart(),
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->getLocStart(),
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->getLocStart(),
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->getLocStart(),
147 diag::err_lambda_capture_default_arg);
152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
153 const CXXMethodDecl *Method) {
154 // If we have an MSAny spec already, don't bother.
155 if (!Method || ComputedEST == EST_MSAny)
158 const FunctionProtoType *Proto
159 = Method->getType()->getAs<FunctionProtoType>();
160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
164 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
166 // If we have a throw-all spec at this point, ignore the function.
167 if (ComputedEST == EST_None)
171 // If this function can throw any exceptions, make a note of that.
177 // FIXME: If the call to this decl is using any of its default arguments, we
178 // need to search them for potentially-throwing calls.
179 // If this function has a basic noexcept, it doesn't affect the outcome.
180 case EST_BasicNoexcept:
182 // If we're still at noexcept(true) and there's a nothrow() callee,
183 // change to that specification.
184 case EST_DynamicNone:
185 if (ComputedEST == EST_BasicNoexcept)
186 ComputedEST = EST_DynamicNone;
188 // Check out noexcept specs.
189 case EST_ComputedNoexcept:
191 FunctionProtoType::NoexceptResult NR =
192 Proto->getNoexceptSpec(Self->Context);
193 assert(NR != FunctionProtoType::NR_NoNoexcept &&
194 "Must have noexcept result for EST_ComputedNoexcept.");
195 assert(NR != FunctionProtoType::NR_Dependent &&
196 "Should not generate implicit declarations for dependent cases, "
197 "and don't know how to handle them anyway.");
198 // noexcept(false) -> no spec on the new function
199 if (NR == FunctionProtoType::NR_Throw) {
201 ComputedEST = EST_None;
203 // noexcept(true) won't change anything either.
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->isConstexpr() != Old->isConstexpr()) {
642 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
643 << New << New->isConstexpr();
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 // FIXME: It's not clear what should happen if multiple declarations of a
662 // deduction guide have different explicitness. For now at least we simply
663 // reject any case where the explicitness changes.
664 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
665 if (NewGuide && NewGuide->isExplicitSpecified() !=
666 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
667 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
668 << NewGuide->isExplicitSpecified();
669 Diag(Old->getLocation(), diag::note_previous_declaration);
672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
673 // argument expression, that declaration shall be a definition and shall be
674 // the only declaration of the function or function template in the
676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
677 functionDeclHasDefaultArgument(Old)) {
678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
679 Diag(Old->getLocation(), diag::note_previous_declaration);
687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
688 MultiTemplateParamsArg TemplateParamLists) {
689 assert(D.isDecompositionDeclarator());
690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
692 // The syntax only allows a decomposition declarator as a simple-declaration
693 // or a for-range-declaration, but we parse it in more cases than that.
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(), getLangOpts().CPlusPlus1z
709 ? diag::warn_cxx14_compat_decomp_decl
710 : diag::ext_decomp_decl)
711 << Decomp.getSourceRange();
713 // The semantic context is always just the current context.
714 DeclContext *const DC = CurContext;
716 // C++1z [dcl.dcl]/8:
717 // The decl-specifier-seq shall contain only the type-specifier auto
718 // and cv-qualifiers.
719 auto &DS = D.getDeclSpec();
721 SmallVector<StringRef, 8> BadSpecifiers;
722 SmallVector<SourceLocation, 8> BadSpecifierLocs;
723 if (auto SCS = DS.getStorageClassSpec()) {
724 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
725 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
727 if (auto TSCS = DS.getThreadStorageClassSpec()) {
728 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
729 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
731 if (DS.isConstexprSpecified()) {
732 BadSpecifiers.push_back("constexpr");
733 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
735 if (DS.isInlineSpecified()) {
736 BadSpecifiers.push_back("inline");
737 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
739 if (!BadSpecifiers.empty()) {
740 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
741 Err << (int)BadSpecifiers.size()
742 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
743 // Don't add FixItHints to remove the specifiers; we do still respect
744 // them when building the underlying variable.
745 for (auto Loc : BadSpecifierLocs)
746 Err << SourceRange(Loc, Loc);
748 // We can't recover from it being declared as a typedef.
749 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
753 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
754 QualType R = TInfo->getType();
756 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
757 UPPC_DeclarationType))
760 // The syntax only allows a single ref-qualifier prior to the decomposition
761 // declarator. No other declarator chunks are permitted. Also check the type
763 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
764 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
765 (D.getNumTypeObjects() == 1 &&
766 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
767 Diag(Decomp.getLSquareLoc(),
768 (D.hasGroupingParens() ||
769 (D.getNumTypeObjects() &&
770 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
771 ? diag::err_decomp_decl_parens
772 : diag::err_decomp_decl_type)
775 // In most cases, there's no actual problem with an explicitly-specified
776 // type, but a function type won't work here, and ActOnVariableDeclarator
777 // shouldn't be called for such a type.
778 if (R->isFunctionType())
782 // Build the BindingDecls.
783 SmallVector<BindingDecl*, 8> Bindings;
785 // Build the BindingDecls.
786 for (auto &B : D.getDecompositionDeclarator().bindings()) {
787 // Check for name conflicts.
788 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
789 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
791 LookupName(Previous, S,
792 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
794 // It's not permitted to shadow a template parameter name.
795 if (Previous.isSingleResult() &&
796 Previous.getFoundDecl()->isTemplateParameter()) {
797 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
798 Previous.getFoundDecl());
802 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
803 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
804 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
805 /*AllowInlineNamespace*/false);
806 if (!Previous.empty()) {
807 auto *Old = Previous.getRepresentativeDecl();
808 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
809 Diag(Old->getLocation(), diag::note_previous_definition);
812 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
813 PushOnScopeChains(BD, S, true);
814 Bindings.push_back(BD);
815 ParsingInitForAutoVars.insert(BD);
818 // There are no prior lookup results for the variable itself, because it
820 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
821 Decomp.getLSquareLoc());
822 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
824 // Build the variable that holds the non-decomposed object.
825 bool AddToScope = true;
827 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
828 MultiTemplateParamsArg(), AddToScope, Bindings);
829 CurContext->addHiddenDecl(New);
831 if (isInOpenMPDeclareTargetContext())
832 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
837 static bool checkSimpleDecomposition(
838 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
839 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
840 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
841 if ((int64_t)Bindings.size() != NumElems) {
842 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
843 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
844 << (NumElems < Bindings.size());
849 for (auto *B : Bindings) {
850 SourceLocation Loc = B->getLocation();
851 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
854 E = GetInit(Loc, E.get(), I++);
857 B->setBinding(ElemType, E.get());
863 static bool checkArrayLikeDecomposition(Sema &S,
864 ArrayRef<BindingDecl *> Bindings,
865 ValueDecl *Src, QualType DecompType,
866 const llvm::APSInt &NumElems,
868 return checkSimpleDecomposition(
869 S, Bindings, Src, DecompType, NumElems, ElemType,
870 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
871 ExprResult E = S.ActOnIntegerConstant(Loc, I);
874 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
878 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
879 ValueDecl *Src, QualType DecompType,
880 const ConstantArrayType *CAT) {
881 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
882 llvm::APSInt(CAT->getSize()),
883 CAT->getElementType());
886 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
887 ValueDecl *Src, QualType DecompType,
888 const VectorType *VT) {
889 return checkArrayLikeDecomposition(
890 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
891 S.Context.getQualifiedType(VT->getElementType(),
892 DecompType.getQualifiers()));
895 static bool checkComplexDecomposition(Sema &S,
896 ArrayRef<BindingDecl *> Bindings,
897 ValueDecl *Src, QualType DecompType,
898 const ComplexType *CT) {
899 return checkSimpleDecomposition(
900 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
901 S.Context.getQualifiedType(CT->getElementType(),
902 DecompType.getQualifiers()),
903 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
904 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
908 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
909 TemplateArgumentListInfo &Args) {
911 llvm::raw_svector_ostream OS(SS);
913 for (auto &Arg : Args.arguments()) {
916 Arg.getArgument().print(PrintingPolicy, OS);
922 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
923 SourceLocation Loc, StringRef Trait,
924 TemplateArgumentListInfo &Args,
926 auto DiagnoseMissing = [&] {
928 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
933 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
934 NamespaceDecl *Std = S.getStdNamespace();
936 return DiagnoseMissing();
938 // Look up the trait itself, within namespace std. We can diagnose various
939 // problems with this lookup even if we've been asked to not diagnose a
940 // missing specialization, because this can only fail if the user has been
941 // declaring their own names in namespace std or we don't support the
942 // standard library implementation in use.
943 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
944 Loc, Sema::LookupOrdinaryName);
945 if (!S.LookupQualifiedName(Result, Std))
946 return DiagnoseMissing();
947 if (Result.isAmbiguous())
950 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
952 Result.suppressDiagnostics();
953 NamedDecl *Found = *Result.begin();
954 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
955 S.Diag(Found->getLocation(), diag::note_declared_at);
959 // Build the template-id.
960 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
961 if (TraitTy.isNull())
963 if (!S.isCompleteType(Loc, TraitTy)) {
965 S.RequireCompleteType(
966 Loc, TraitTy, DiagID,
967 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
971 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
972 assert(RD && "specialization of class template is not a class?");
974 // Look up the member of the trait type.
975 S.LookupQualifiedName(TraitMemberLookup, RD);
976 return TraitMemberLookup.isAmbiguous();
979 static TemplateArgumentLoc
980 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
982 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
983 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
986 static TemplateArgumentLoc
987 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
988 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
991 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
993 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
994 llvm::APSInt &Size) {
995 EnterExpressionEvaluationContext ContextRAII(
996 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
998 DeclarationName Value = S.PP.getIdentifierInfo("value");
999 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1001 // Form template argument list for tuple_size<T>.
1002 TemplateArgumentListInfo Args(Loc, Loc);
1003 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1005 // If there's no tuple_size specialization, it's not tuple-like.
1006 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1007 return IsTupleLike::NotTupleLike;
1009 // If we get this far, we've committed to the tuple interpretation, but
1010 // we can still fail if there actually isn't a usable ::value.
1012 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1014 TemplateArgumentListInfo &Args;
1015 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1016 : R(R), Args(Args) {}
1017 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1018 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1019 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1021 } Diagnoser(R, Args);
1024 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1025 return IsTupleLike::Error;
1029 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1031 return IsTupleLike::Error;
1033 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1035 return IsTupleLike::Error;
1037 return IsTupleLike::TupleLike;
1040 /// \return std::tuple_element<I, T>::type.
1041 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1042 unsigned I, QualType T) {
1043 // Form template argument list for tuple_element<I, T>.
1044 TemplateArgumentListInfo Args(Loc, Loc);
1046 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1047 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1049 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1050 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1051 if (lookupStdTypeTraitMember(
1052 S, R, Loc, "tuple_element", Args,
1053 diag::err_decomp_decl_std_tuple_element_not_specialized))
1056 auto *TD = R.getAsSingle<TypeDecl>();
1058 R.suppressDiagnostics();
1059 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1060 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1062 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1066 return S.Context.getTypeDeclType(TD);
1070 struct BindingDiagnosticTrap {
1072 DiagnosticErrorTrap Trap;
1075 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1076 : S(S), Trap(S.Diags), BD(BD) {}
1077 ~BindingDiagnosticTrap() {
1078 if (Trap.hasErrorOccurred())
1079 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1084 static bool checkTupleLikeDecomposition(Sema &S,
1085 ArrayRef<BindingDecl *> Bindings,
1086 VarDecl *Src, QualType DecompType,
1087 const llvm::APSInt &TupleSize) {
1088 if ((int64_t)Bindings.size() != TupleSize) {
1089 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1090 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1091 << (TupleSize < Bindings.size());
1095 if (Bindings.empty())
1098 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1101 // The unqualified-id get is looked up in the scope of E by class member
1103 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1104 bool UseMemberGet = false;
1105 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1106 if (auto *RD = DecompType->getAsCXXRecordDecl())
1107 S.LookupQualifiedName(MemberGet, RD);
1108 if (MemberGet.isAmbiguous())
1110 UseMemberGet = !MemberGet.empty();
1111 S.FilterAcceptableTemplateNames(MemberGet);
1115 for (auto *B : Bindings) {
1116 BindingDiagnosticTrap Trap(S, B);
1117 SourceLocation Loc = B->getLocation();
1119 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1123 // e is an lvalue if the type of the entity is an lvalue reference and
1124 // an xvalue otherwise
1125 if (!Src->getType()->isLValueReferenceType())
1126 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1127 E.get(), nullptr, VK_XValue);
1129 TemplateArgumentListInfo Args(Loc, Loc);
1131 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1134 // if [lookup of member get] finds at least one declaration, the
1135 // initializer is e.get<i-1>().
1136 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1137 CXXScopeSpec(), SourceLocation(), nullptr,
1138 MemberGet, &Args, nullptr);
1142 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1144 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1145 // in the associated namespaces.
1146 Expr *Get = UnresolvedLookupExpr::Create(
1147 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1148 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1149 UnresolvedSetIterator(), UnresolvedSetIterator());
1151 Expr *Arg = E.get();
1152 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1156 Expr *Init = E.get();
1158 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1159 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1163 // each vi is a variable of type "reference to T" initialized with the
1164 // initializer, where the reference is an lvalue reference if the
1165 // initializer is an lvalue and an rvalue reference otherwise
1167 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1168 if (RefType.isNull())
1170 auto *RefVD = VarDecl::Create(
1171 S.Context, Src->getDeclContext(), Loc, Loc,
1172 B->getDeclName().getAsIdentifierInfo(), RefType,
1173 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1174 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1175 RefVD->setTSCSpec(Src->getTSCSpec());
1176 RefVD->setImplicit();
1177 if (Src->isInlineSpecified())
1178 RefVD->setInlineSpecified();
1179 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1181 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1182 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1183 InitializationSequence Seq(S, Entity, Kind, Init);
1184 E = Seq.Perform(S, Entity, Kind, Init);
1187 E = S.ActOnFinishFullExpr(E.get(), Loc);
1190 RefVD->setInit(E.get());
1191 RefVD->checkInitIsICE();
1193 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1194 DeclarationNameInfo(B->getDeclName(), Loc),
1199 B->setBinding(T, E.get());
1206 /// Find the base class to decompose in a built-in decomposition of a class type.
1207 /// This base class search is, unfortunately, not quite like any other that we
1208 /// perform anywhere else in C++.
1209 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1211 const CXXRecordDecl *RD,
1212 CXXCastPath &BasePath) {
1213 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1214 CXXBasePath &Path) {
1215 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1218 const CXXRecordDecl *ClassWithFields = nullptr;
1219 if (RD->hasDirectFields())
1221 // Otherwise, all of E's non-static data members shall be public direct
1223 ClassWithFields = RD;
1227 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1228 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1229 // If no classes have fields, just decompose RD itself. (This will work
1230 // if and only if zero bindings were provided.)
1234 CXXBasePath *BestPath = nullptr;
1235 for (auto &P : Paths) {
1238 else if (!S.Context.hasSameType(P.back().Base->getType(),
1239 BestPath->back().Base->getType())) {
1241 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1242 << false << RD << BestPath->back().Base->getType()
1243 << P.back().Base->getType();
1245 } else if (P.Access < BestPath->Access) {
1250 // ... unambiguous ...
1251 QualType BaseType = BestPath->back().Base->getType();
1252 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1253 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1254 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1258 // ... public base class of E.
1259 if (BestPath->Access != AS_public) {
1260 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1262 for (auto &BS : *BestPath) {
1263 if (BS.Base->getAccessSpecifier() != AS_public) {
1264 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1265 << (BS.Base->getAccessSpecifier() == AS_protected)
1266 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1273 ClassWithFields = BaseType->getAsCXXRecordDecl();
1274 S.BuildBasePathArray(Paths, BasePath);
1277 // The above search did not check whether the selected class itself has base
1278 // classes with fields, so check that now.
1280 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1281 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1282 << (ClassWithFields == RD) << RD << ClassWithFields
1283 << Paths.front().back().Base->getType();
1287 return ClassWithFields;
1290 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1291 ValueDecl *Src, QualType DecompType,
1292 const CXXRecordDecl *RD) {
1293 CXXCastPath BasePath;
1294 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1297 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1298 DecompType.getQualifiers());
1300 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1301 unsigned NumFields =
1302 std::count_if(RD->field_begin(), RD->field_end(),
1303 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1304 assert(Bindings.size() != NumFields);
1305 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1306 << DecompType << (unsigned)Bindings.size() << NumFields
1307 << (NumFields < Bindings.size());
1311 // all of E's non-static data members shall be public [...] members,
1312 // E shall not have an anonymous union member, ...
1314 for (auto *FD : RD->fields()) {
1315 if (FD->isUnnamedBitfield())
1318 if (FD->isAnonymousStructOrUnion()) {
1319 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1320 << DecompType << FD->getType()->isUnionType();
1321 S.Diag(FD->getLocation(), diag::note_declared_at);
1325 // We have a real field to bind.
1326 if (I >= Bindings.size())
1327 return DiagnoseBadNumberOfBindings();
1328 auto *B = Bindings[I++];
1330 SourceLocation Loc = B->getLocation();
1331 if (FD->getAccess() != AS_public) {
1332 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1334 // Determine whether the access specifier was explicit.
1335 bool Implicit = true;
1336 for (const auto *D : RD->decls()) {
1337 if (declaresSameEntity(D, FD))
1339 if (isa<AccessSpecDecl>(D)) {
1345 S.Diag(FD->getLocation(), diag::note_access_natural)
1346 << (FD->getAccess() == AS_protected) << Implicit;
1350 // Initialize the binding to Src.FD.
1351 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1354 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1355 VK_LValue, &BasePath);
1358 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1360 DeclAccessPair::make(FD, FD->getAccess()),
1361 DeclarationNameInfo(FD->getDeclName(), Loc));
1365 // If the type of the member is T, the referenced type is cv T, where cv is
1366 // the cv-qualification of the decomposition expression.
1368 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1369 // 'const' to the type of the field.
1370 Qualifiers Q = DecompType.getQualifiers();
1371 if (FD->isMutable())
1373 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1376 if (I != Bindings.size())
1377 return DiagnoseBadNumberOfBindings();
1382 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1383 QualType DecompType = DD->getType();
1385 // If the type of the decomposition is dependent, then so is the type of
1387 if (DecompType->isDependentType()) {
1388 for (auto *B : DD->bindings())
1389 B->setType(Context.DependentTy);
1393 DecompType = DecompType.getNonReferenceType();
1394 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1396 // C++1z [dcl.decomp]/2:
1397 // If E is an array type [...]
1398 // As an extension, we also support decomposition of built-in complex and
1400 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1401 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1402 DD->setInvalidDecl();
1405 if (auto *VT = DecompType->getAs<VectorType>()) {
1406 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1407 DD->setInvalidDecl();
1410 if (auto *CT = DecompType->getAs<ComplexType>()) {
1411 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1412 DD->setInvalidDecl();
1416 // C++1z [dcl.decomp]/3:
1417 // if the expression std::tuple_size<E>::value is a well-formed integral
1418 // constant expression, [...]
1419 llvm::APSInt TupleSize(32);
1420 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1421 case IsTupleLike::Error:
1422 DD->setInvalidDecl();
1425 case IsTupleLike::TupleLike:
1426 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1427 DD->setInvalidDecl();
1430 case IsTupleLike::NotTupleLike:
1434 // C++1z [dcl.dcl]/8:
1435 // [E shall be of array or non-union class type]
1436 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1437 if (!RD || RD->isUnion()) {
1438 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1439 << DD << !RD << DecompType;
1440 DD->setInvalidDecl();
1444 // C++1z [dcl.decomp]/4:
1445 // all of E's non-static data members shall be [...] direct members of
1446 // E or of the same unambiguous public base class of E, ...
1447 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1448 DD->setInvalidDecl();
1451 /// \brief Merge the exception specifications of two variable declarations.
1453 /// This is called when there's a redeclaration of a VarDecl. The function
1454 /// checks if the redeclaration might have an exception specification and
1455 /// validates compatibility and merges the specs if necessary.
1456 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1457 // Shortcut if exceptions are disabled.
1458 if (!getLangOpts().CXXExceptions)
1461 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1462 "Should only be called if types are otherwise the same.");
1464 QualType NewType = New->getType();
1465 QualType OldType = Old->getType();
1467 // We're only interested in pointers and references to functions, as well
1468 // as pointers to member functions.
1469 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1470 NewType = R->getPointeeType();
1471 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1472 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1473 NewType = P->getPointeeType();
1474 OldType = OldType->getAs<PointerType>()->getPointeeType();
1475 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1476 NewType = M->getPointeeType();
1477 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1480 if (!NewType->isFunctionProtoType())
1483 // There's lots of special cases for functions. For function pointers, system
1484 // libraries are hopefully not as broken so that we don't need these
1486 if (CheckEquivalentExceptionSpec(
1487 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1488 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1489 New->setInvalidDecl();
1493 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1494 /// function declaration are well-formed according to C++
1495 /// [dcl.fct.default].
1496 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1497 unsigned NumParams = FD->getNumParams();
1500 // Find first parameter with a default argument
1501 for (p = 0; p < NumParams; ++p) {
1502 ParmVarDecl *Param = FD->getParamDecl(p);
1503 if (Param->hasDefaultArg())
1507 // C++11 [dcl.fct.default]p4:
1508 // In a given function declaration, each parameter subsequent to a parameter
1509 // with a default argument shall have a default argument supplied in this or
1510 // a previous declaration or shall be a function parameter pack. A default
1511 // argument shall not be redefined by a later declaration (not even to the
1513 unsigned LastMissingDefaultArg = 0;
1514 for (; p < NumParams; ++p) {
1515 ParmVarDecl *Param = FD->getParamDecl(p);
1516 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1517 if (Param->isInvalidDecl())
1518 /* We already complained about this parameter. */;
1519 else if (Param->getIdentifier())
1520 Diag(Param->getLocation(),
1521 diag::err_param_default_argument_missing_name)
1522 << Param->getIdentifier();
1524 Diag(Param->getLocation(),
1525 diag::err_param_default_argument_missing);
1527 LastMissingDefaultArg = p;
1531 if (LastMissingDefaultArg > 0) {
1532 // Some default arguments were missing. Clear out all of the
1533 // default arguments up to (and including) the last missing
1534 // default argument, so that we leave the function parameters
1535 // in a semantically valid state.
1536 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1537 ParmVarDecl *Param = FD->getParamDecl(p);
1538 if (Param->hasDefaultArg()) {
1539 Param->setDefaultArg(nullptr);
1545 // CheckConstexprParameterTypes - Check whether a function's parameter types
1546 // are all literal types. If so, return true. If not, produce a suitable
1547 // diagnostic and return false.
1548 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1549 const FunctionDecl *FD) {
1550 unsigned ArgIndex = 0;
1551 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1552 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1553 e = FT->param_type_end();
1554 i != e; ++i, ++ArgIndex) {
1555 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1556 SourceLocation ParamLoc = PD->getLocation();
1557 if (!(*i)->isDependentType() &&
1558 SemaRef.RequireLiteralType(ParamLoc, *i,
1559 diag::err_constexpr_non_literal_param,
1560 ArgIndex+1, PD->getSourceRange(),
1561 isa<CXXConstructorDecl>(FD)))
1567 /// \brief Get diagnostic %select index for tag kind for
1568 /// record diagnostic message.
1569 /// WARNING: Indexes apply to particular diagnostics only!
1571 /// \returns diagnostic %select index.
1572 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1574 case TTK_Struct: return 0;
1575 case TTK_Interface: return 1;
1576 case TTK_Class: return 2;
1577 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1581 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1582 // the requirements of a constexpr function definition or a constexpr
1583 // constructor definition. If so, return true. If not, produce appropriate
1584 // diagnostics and return false.
1586 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1587 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1588 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1589 if (MD && MD->isInstance()) {
1590 // C++11 [dcl.constexpr]p4:
1591 // The definition of a constexpr constructor shall satisfy the following
1593 // - the class shall not have any virtual base classes;
1594 const CXXRecordDecl *RD = MD->getParent();
1595 if (RD->getNumVBases()) {
1596 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1597 << isa<CXXConstructorDecl>(NewFD)
1598 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1599 for (const auto &I : RD->vbases())
1600 Diag(I.getLocStart(),
1601 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1606 if (!isa<CXXConstructorDecl>(NewFD)) {
1607 // C++11 [dcl.constexpr]p3:
1608 // The definition of a constexpr function shall satisfy the following
1610 // - it shall not be virtual;
1611 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1612 if (Method && Method->isVirtual()) {
1613 Method = Method->getCanonicalDecl();
1614 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1616 // If it's not obvious why this function is virtual, find an overridden
1617 // function which uses the 'virtual' keyword.
1618 const CXXMethodDecl *WrittenVirtual = Method;
1619 while (!WrittenVirtual->isVirtualAsWritten())
1620 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1621 if (WrittenVirtual != Method)
1622 Diag(WrittenVirtual->getLocation(),
1623 diag::note_overridden_virtual_function);
1627 // - its return type shall be a literal type;
1628 QualType RT = NewFD->getReturnType();
1629 if (!RT->isDependentType() &&
1630 RequireLiteralType(NewFD->getLocation(), RT,
1631 diag::err_constexpr_non_literal_return))
1635 // - each of its parameter types shall be a literal type;
1636 if (!CheckConstexprParameterTypes(*this, NewFD))
1642 /// Check the given declaration statement is legal within a constexpr function
1643 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1645 /// \return true if the body is OK (maybe only as an extension), false if we
1646 /// have diagnosed a problem.
1647 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1648 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1649 // C++11 [dcl.constexpr]p3 and p4:
1650 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1652 for (const auto *DclIt : DS->decls()) {
1653 switch (DclIt->getKind()) {
1654 case Decl::StaticAssert:
1656 case Decl::UsingShadow:
1657 case Decl::UsingDirective:
1658 case Decl::UnresolvedUsingTypename:
1659 case Decl::UnresolvedUsingValue:
1660 // - static_assert-declarations
1661 // - using-declarations,
1662 // - using-directives,
1666 case Decl::TypeAlias: {
1667 // - typedef declarations and alias-declarations that do not define
1668 // classes or enumerations,
1669 const auto *TN = cast<TypedefNameDecl>(DclIt);
1670 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1671 // Don't allow variably-modified types in constexpr functions.
1672 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1673 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1674 << TL.getSourceRange() << TL.getType()
1675 << isa<CXXConstructorDecl>(Dcl);
1682 case Decl::CXXRecord:
1683 // C++1y allows types to be defined, not just declared.
1684 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1685 SemaRef.Diag(DS->getLocStart(),
1686 SemaRef.getLangOpts().CPlusPlus14
1687 ? diag::warn_cxx11_compat_constexpr_type_definition
1688 : diag::ext_constexpr_type_definition)
1689 << isa<CXXConstructorDecl>(Dcl);
1692 case Decl::EnumConstant:
1693 case Decl::IndirectField:
1695 // These can only appear with other declarations which are banned in
1696 // C++11 and permitted in C++1y, so ignore them.
1700 case Decl::Decomposition: {
1701 // C++1y [dcl.constexpr]p3 allows anything except:
1702 // a definition of a variable of non-literal type or of static or
1703 // thread storage duration or for which no initialization is performed.
1704 const auto *VD = cast<VarDecl>(DclIt);
1705 if (VD->isThisDeclarationADefinition()) {
1706 if (VD->isStaticLocal()) {
1707 SemaRef.Diag(VD->getLocation(),
1708 diag::err_constexpr_local_var_static)
1709 << isa<CXXConstructorDecl>(Dcl)
1710 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1713 if (!VD->getType()->isDependentType() &&
1714 SemaRef.RequireLiteralType(
1715 VD->getLocation(), VD->getType(),
1716 diag::err_constexpr_local_var_non_literal_type,
1717 isa<CXXConstructorDecl>(Dcl)))
1719 if (!VD->getType()->isDependentType() &&
1720 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1721 SemaRef.Diag(VD->getLocation(),
1722 diag::err_constexpr_local_var_no_init)
1723 << isa<CXXConstructorDecl>(Dcl);
1727 SemaRef.Diag(VD->getLocation(),
1728 SemaRef.getLangOpts().CPlusPlus14
1729 ? diag::warn_cxx11_compat_constexpr_local_var
1730 : diag::ext_constexpr_local_var)
1731 << isa<CXXConstructorDecl>(Dcl);
1735 case Decl::NamespaceAlias:
1736 case Decl::Function:
1737 // These are disallowed in C++11 and permitted in C++1y. Allow them
1738 // everywhere as an extension.
1739 if (!Cxx1yLoc.isValid())
1740 Cxx1yLoc = DS->getLocStart();
1744 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1745 << isa<CXXConstructorDecl>(Dcl);
1753 /// Check that the given field is initialized within a constexpr constructor.
1755 /// \param Dcl The constexpr constructor being checked.
1756 /// \param Field The field being checked. This may be a member of an anonymous
1757 /// struct or union nested within the class being checked.
1758 /// \param Inits All declarations, including anonymous struct/union members and
1759 /// indirect members, for which any initialization was provided.
1760 /// \param Diagnosed Set to true if an error is produced.
1761 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1762 const FunctionDecl *Dcl,
1764 llvm::SmallSet<Decl*, 16> &Inits,
1766 if (Field->isInvalidDecl())
1769 if (Field->isUnnamedBitfield())
1772 // Anonymous unions with no variant members and empty anonymous structs do not
1773 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1774 // indirect fields don't need initializing.
1775 if (Field->isAnonymousStructOrUnion() &&
1776 (Field->getType()->isUnionType()
1777 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1778 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1781 if (!Inits.count(Field)) {
1783 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1786 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1787 } else if (Field->isAnonymousStructOrUnion()) {
1788 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1789 for (auto *I : RD->fields())
1790 // If an anonymous union contains an anonymous struct of which any member
1791 // is initialized, all members must be initialized.
1792 if (!RD->isUnion() || Inits.count(I))
1793 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1797 /// Check the provided statement is allowed in a constexpr function
1800 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1801 SmallVectorImpl<SourceLocation> &ReturnStmts,
1802 SourceLocation &Cxx1yLoc) {
1803 // - its function-body shall be [...] a compound-statement that contains only
1804 switch (S->getStmtClass()) {
1805 case Stmt::NullStmtClass:
1806 // - null statements,
1809 case Stmt::DeclStmtClass:
1810 // - static_assert-declarations
1811 // - using-declarations,
1812 // - using-directives,
1813 // - typedef declarations and alias-declarations that do not define
1814 // classes or enumerations,
1815 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1819 case Stmt::ReturnStmtClass:
1820 // - and exactly one return statement;
1821 if (isa<CXXConstructorDecl>(Dcl)) {
1822 // C++1y allows return statements in constexpr constructors.
1823 if (!Cxx1yLoc.isValid())
1824 Cxx1yLoc = S->getLocStart();
1828 ReturnStmts.push_back(S->getLocStart());
1831 case Stmt::CompoundStmtClass: {
1832 // C++1y allows compound-statements.
1833 if (!Cxx1yLoc.isValid())
1834 Cxx1yLoc = S->getLocStart();
1836 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1837 for (auto *BodyIt : CompStmt->body()) {
1838 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1845 case Stmt::AttributedStmtClass:
1846 if (!Cxx1yLoc.isValid())
1847 Cxx1yLoc = S->getLocStart();
1850 case Stmt::IfStmtClass: {
1851 // C++1y allows if-statements.
1852 if (!Cxx1yLoc.isValid())
1853 Cxx1yLoc = S->getLocStart();
1855 IfStmt *If = cast<IfStmt>(S);
1856 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1859 if (If->getElse() &&
1860 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1866 case Stmt::WhileStmtClass:
1867 case Stmt::DoStmtClass:
1868 case Stmt::ForStmtClass:
1869 case Stmt::CXXForRangeStmtClass:
1870 case Stmt::ContinueStmtClass:
1871 // C++1y allows all of these. We don't allow them as extensions in C++11,
1872 // because they don't make sense without variable mutation.
1873 if (!SemaRef.getLangOpts().CPlusPlus14)
1875 if (!Cxx1yLoc.isValid())
1876 Cxx1yLoc = S->getLocStart();
1877 for (Stmt *SubStmt : S->children())
1879 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1884 case Stmt::SwitchStmtClass:
1885 case Stmt::CaseStmtClass:
1886 case Stmt::DefaultStmtClass:
1887 case Stmt::BreakStmtClass:
1888 // C++1y allows switch-statements, and since they don't need variable
1889 // mutation, we can reasonably allow them in C++11 as an extension.
1890 if (!Cxx1yLoc.isValid())
1891 Cxx1yLoc = S->getLocStart();
1892 for (Stmt *SubStmt : S->children())
1894 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1903 // C++1y allows expression-statements.
1904 if (!Cxx1yLoc.isValid())
1905 Cxx1yLoc = S->getLocStart();
1909 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1910 << isa<CXXConstructorDecl>(Dcl);
1914 /// Check the body for the given constexpr function declaration only contains
1915 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1917 /// \return true if the body is OK, false if we have diagnosed a problem.
1918 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1919 if (isa<CXXTryStmt>(Body)) {
1920 // C++11 [dcl.constexpr]p3:
1921 // The definition of a constexpr function shall satisfy the following
1922 // constraints: [...]
1923 // - its function-body shall be = delete, = default, or a
1924 // compound-statement
1926 // C++11 [dcl.constexpr]p4:
1927 // In the definition of a constexpr constructor, [...]
1928 // - its function-body shall not be a function-try-block;
1929 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1930 << isa<CXXConstructorDecl>(Dcl);
1934 SmallVector<SourceLocation, 4> ReturnStmts;
1936 // - its function-body shall be [...] a compound-statement that contains only
1937 // [... list of cases ...]
1938 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1939 SourceLocation Cxx1yLoc;
1940 for (auto *BodyIt : CompBody->body()) {
1941 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1945 if (Cxx1yLoc.isValid())
1947 getLangOpts().CPlusPlus14
1948 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1949 : diag::ext_constexpr_body_invalid_stmt)
1950 << isa<CXXConstructorDecl>(Dcl);
1952 if (const CXXConstructorDecl *Constructor
1953 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1954 const CXXRecordDecl *RD = Constructor->getParent();
1956 // - every non-variant non-static data member and base class sub-object
1957 // shall be initialized;
1959 // - if the class is a union having variant members, exactly one of them
1960 // shall be initialized;
1961 if (RD->isUnion()) {
1962 if (Constructor->getNumCtorInitializers() == 0 &&
1963 RD->hasVariantMembers()) {
1964 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1967 } else if (!Constructor->isDependentContext() &&
1968 !Constructor->isDelegatingConstructor()) {
1969 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1971 // Skip detailed checking if we have enough initializers, and we would
1972 // allow at most one initializer per member.
1973 bool AnyAnonStructUnionMembers = false;
1974 unsigned Fields = 0;
1975 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1976 E = RD->field_end(); I != E; ++I, ++Fields) {
1977 if (I->isAnonymousStructOrUnion()) {
1978 AnyAnonStructUnionMembers = true;
1983 // - if the class is a union-like class, but is not a union, for each of
1984 // its anonymous union members having variant members, exactly one of
1985 // them shall be initialized;
1986 if (AnyAnonStructUnionMembers ||
1987 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1988 // Check initialization of non-static data members. Base classes are
1989 // always initialized so do not need to be checked. Dependent bases
1990 // might not have initializers in the member initializer list.
1991 llvm::SmallSet<Decl*, 16> Inits;
1992 for (const auto *I: Constructor->inits()) {
1993 if (FieldDecl *FD = I->getMember())
1995 else if (IndirectFieldDecl *ID = I->getIndirectMember())
1996 Inits.insert(ID->chain_begin(), ID->chain_end());
1999 bool Diagnosed = false;
2000 for (auto *I : RD->fields())
2001 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2007 if (ReturnStmts.empty()) {
2008 // C++1y doesn't require constexpr functions to contain a 'return'
2009 // statement. We still do, unless the return type might be void, because
2010 // otherwise if there's no return statement, the function cannot
2011 // be used in a core constant expression.
2012 bool OK = getLangOpts().CPlusPlus14 &&
2013 (Dcl->getReturnType()->isVoidType() ||
2014 Dcl->getReturnType()->isDependentType());
2015 Diag(Dcl->getLocation(),
2016 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2017 : diag::err_constexpr_body_no_return);
2020 } else if (ReturnStmts.size() > 1) {
2021 Diag(ReturnStmts.back(),
2022 getLangOpts().CPlusPlus14
2023 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2024 : diag::ext_constexpr_body_multiple_return);
2025 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2026 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2030 // C++11 [dcl.constexpr]p5:
2031 // if no function argument values exist such that the function invocation
2032 // substitution would produce a constant expression, the program is
2033 // ill-formed; no diagnostic required.
2034 // C++11 [dcl.constexpr]p3:
2035 // - every constructor call and implicit conversion used in initializing the
2036 // return value shall be one of those allowed in a constant expression.
2037 // C++11 [dcl.constexpr]p4:
2038 // - every constructor involved in initializing non-static data members and
2039 // base class sub-objects shall be a constexpr constructor.
2040 SmallVector<PartialDiagnosticAt, 8> Diags;
2041 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2042 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2043 << isa<CXXConstructorDecl>(Dcl);
2044 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2045 Diag(Diags[I].first, Diags[I].second);
2046 // Don't return false here: we allow this for compatibility in
2053 /// isCurrentClassName - Determine whether the identifier II is the
2054 /// name of the class type currently being defined. In the case of
2055 /// nested classes, this will only return true if II is the name of
2056 /// the innermost class.
2057 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2058 const CXXScopeSpec *SS) {
2059 assert(getLangOpts().CPlusPlus && "No class names in C!");
2061 CXXRecordDecl *CurDecl;
2062 if (SS && SS->isSet() && !SS->isInvalid()) {
2063 DeclContext *DC = computeDeclContext(*SS, true);
2064 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2066 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2068 if (CurDecl && CurDecl->getIdentifier())
2069 return &II == CurDecl->getIdentifier();
2073 /// \brief Determine whether the identifier II is a typo for the name of
2074 /// the class type currently being defined. If so, update it to the identifier
2075 /// that should have been used.
2076 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2077 assert(getLangOpts().CPlusPlus && "No class names in C!");
2079 if (!getLangOpts().SpellChecking)
2082 CXXRecordDecl *CurDecl;
2083 if (SS && SS->isSet() && !SS->isInvalid()) {
2084 DeclContext *DC = computeDeclContext(*SS, true);
2085 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2087 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2089 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2090 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2091 < II->getLength()) {
2092 II = CurDecl->getIdentifier();
2099 /// \brief Determine whether the given class is a base class of the given
2100 /// class, including looking at dependent bases.
2101 static bool findCircularInheritance(const CXXRecordDecl *Class,
2102 const CXXRecordDecl *Current) {
2103 SmallVector<const CXXRecordDecl*, 8> Queue;
2105 Class = Class->getCanonicalDecl();
2107 for (const auto &I : Current->bases()) {
2108 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2112 Base = Base->getDefinition();
2116 if (Base->getCanonicalDecl() == Class)
2119 Queue.push_back(Base);
2125 Current = Queue.pop_back_val();
2131 /// \brief Check the validity of a C++ base class specifier.
2133 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2134 /// and returns NULL otherwise.
2136 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2137 SourceRange SpecifierRange,
2138 bool Virtual, AccessSpecifier Access,
2139 TypeSourceInfo *TInfo,
2140 SourceLocation EllipsisLoc) {
2141 QualType BaseType = TInfo->getType();
2143 // C++ [class.union]p1:
2144 // A union shall not have base classes.
2145 if (Class->isUnion()) {
2146 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2151 if (EllipsisLoc.isValid() &&
2152 !TInfo->getType()->containsUnexpandedParameterPack()) {
2153 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2154 << TInfo->getTypeLoc().getSourceRange();
2155 EllipsisLoc = SourceLocation();
2158 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2160 if (BaseType->isDependentType()) {
2161 // Make sure that we don't have circular inheritance among our dependent
2162 // bases. For non-dependent bases, the check for completeness below handles
2164 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2165 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2166 ((BaseDecl = BaseDecl->getDefinition()) &&
2167 findCircularInheritance(Class, BaseDecl))) {
2168 Diag(BaseLoc, diag::err_circular_inheritance)
2169 << BaseType << Context.getTypeDeclType(Class);
2171 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2172 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2179 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2180 Class->getTagKind() == TTK_Class,
2181 Access, TInfo, EllipsisLoc);
2184 // Base specifiers must be record types.
2185 if (!BaseType->isRecordType()) {
2186 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2190 // C++ [class.union]p1:
2191 // A union shall not be used as a base class.
2192 if (BaseType->isUnionType()) {
2193 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2197 // For the MS ABI, propagate DLL attributes to base class templates.
2198 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2199 if (Attr *ClassAttr = getDLLAttr(Class)) {
2200 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2201 BaseType->getAsCXXRecordDecl())) {
2202 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2208 // C++ [class.derived]p2:
2209 // The class-name in a base-specifier shall not be an incompletely
2211 if (RequireCompleteType(BaseLoc, BaseType,
2212 diag::err_incomplete_base_class, SpecifierRange)) {
2213 Class->setInvalidDecl();
2217 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2218 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2219 assert(BaseDecl && "Record type has no declaration");
2220 BaseDecl = BaseDecl->getDefinition();
2221 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2222 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2223 assert(CXXBaseDecl && "Base type is not a C++ type");
2225 // A class which contains a flexible array member is not suitable for use as a
2227 // - If the layout determines that a base comes before another base,
2228 // the flexible array member would index into the subsequent base.
2229 // - If the layout determines that base comes before the derived class,
2230 // the flexible array member would index into the derived class.
2231 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2232 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2233 << CXXBaseDecl->getDeclName();
2238 // If a class is marked final and it appears as a base-type-specifier in
2239 // base-clause, the program is ill-formed.
2240 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2241 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2242 << CXXBaseDecl->getDeclName()
2243 << FA->isSpelledAsSealed();
2244 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2245 << CXXBaseDecl->getDeclName() << FA->getRange();
2249 if (BaseDecl->isInvalidDecl())
2250 Class->setInvalidDecl();
2252 // Create the base specifier.
2253 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2254 Class->getTagKind() == TTK_Class,
2255 Access, TInfo, EllipsisLoc);
2258 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2259 /// one entry in the base class list of a class specifier, for
2261 /// class foo : public bar, virtual private baz {
2262 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2264 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2265 ParsedAttributes &Attributes,
2266 bool Virtual, AccessSpecifier Access,
2267 ParsedType basetype, SourceLocation BaseLoc,
2268 SourceLocation EllipsisLoc) {
2272 AdjustDeclIfTemplate(classdecl);
2273 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2277 // We haven't yet attached the base specifiers.
2278 Class->setIsParsingBaseSpecifiers();
2280 // We do not support any C++11 attributes on base-specifiers yet.
2281 // Diagnose any attributes we see.
2282 if (!Attributes.empty()) {
2283 for (AttributeList *Attr = Attributes.getList(); Attr;
2284 Attr = Attr->getNext()) {
2285 if (Attr->isInvalid() ||
2286 Attr->getKind() == AttributeList::IgnoredAttribute)
2288 Diag(Attr->getLoc(),
2289 Attr->getKind() == AttributeList::UnknownAttribute
2290 ? diag::warn_unknown_attribute_ignored
2291 : diag::err_base_specifier_attribute)
2296 TypeSourceInfo *TInfo = nullptr;
2297 GetTypeFromParser(basetype, &TInfo);
2299 if (EllipsisLoc.isInvalid() &&
2300 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2304 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2305 Virtual, Access, TInfo,
2309 Class->setInvalidDecl();
2314 /// Use small set to collect indirect bases. As this is only used
2315 /// locally, there's no need to abstract the small size parameter.
2316 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2318 /// \brief Recursively add the bases of Type. Don't add Type itself.
2320 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2321 const QualType &Type)
2323 // Even though the incoming type is a base, it might not be
2324 // a class -- it could be a template parm, for instance.
2325 if (auto Rec = Type->getAs<RecordType>()) {
2326 auto Decl = Rec->getAsCXXRecordDecl();
2328 // Iterate over its bases.
2329 for (const auto &BaseSpec : Decl->bases()) {
2330 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2331 .getUnqualifiedType();
2332 if (Set.insert(Base).second)
2333 // If we've not already seen it, recurse.
2334 NoteIndirectBases(Context, Set, Base);
2339 /// \brief Performs the actual work of attaching the given base class
2340 /// specifiers to a C++ class.
2341 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2342 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2346 // Used to keep track of which base types we have already seen, so
2347 // that we can properly diagnose redundant direct base types. Note
2348 // that the key is always the unqualified canonical type of the base
2350 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2352 // Used to track indirect bases so we can see if a direct base is
2354 IndirectBaseSet IndirectBaseTypes;
2356 // Copy non-redundant base specifiers into permanent storage.
2357 unsigned NumGoodBases = 0;
2358 bool Invalid = false;
2359 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2360 QualType NewBaseType
2361 = Context.getCanonicalType(Bases[idx]->getType());
2362 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2364 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2366 // C++ [class.mi]p3:
2367 // A class shall not be specified as a direct base class of a
2368 // derived class more than once.
2369 Diag(Bases[idx]->getLocStart(),
2370 diag::err_duplicate_base_class)
2371 << KnownBase->getType()
2372 << Bases[idx]->getSourceRange();
2374 // Delete the duplicate base class specifier; we're going to
2375 // overwrite its pointer later.
2376 Context.Deallocate(Bases[idx]);
2380 // Okay, add this new base class.
2381 KnownBase = Bases[idx];
2382 Bases[NumGoodBases++] = Bases[idx];
2384 // Note this base's direct & indirect bases, if there could be ambiguity.
2385 if (Bases.size() > 1)
2386 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2388 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2389 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2390 if (Class->isInterface() &&
2391 (!RD->isInterface() ||
2392 KnownBase->getAccessSpecifier() != AS_public)) {
2393 // The Microsoft extension __interface does not permit bases that
2394 // are not themselves public interfaces.
2395 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2396 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2397 << RD->getSourceRange();
2400 if (RD->hasAttr<WeakAttr>())
2401 Class->addAttr(WeakAttr::CreateImplicit(Context));
2406 // Attach the remaining base class specifiers to the derived class.
2407 Class->setBases(Bases.data(), NumGoodBases);
2409 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2410 // Check whether this direct base is inaccessible due to ambiguity.
2411 QualType BaseType = Bases[idx]->getType();
2412 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2413 .getUnqualifiedType();
2415 if (IndirectBaseTypes.count(CanonicalBase)) {
2416 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2417 /*DetectVirtual=*/true);
2419 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2423 if (Paths.isAmbiguous(CanonicalBase))
2424 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2425 << BaseType << getAmbiguousPathsDisplayString(Paths)
2426 << Bases[idx]->getSourceRange();
2428 assert(Bases[idx]->isVirtual());
2431 // Delete the base class specifier, since its data has been copied
2432 // into the CXXRecordDecl.
2433 Context.Deallocate(Bases[idx]);
2439 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2440 /// class, after checking whether there are any duplicate base
2442 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2443 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2444 if (!ClassDecl || Bases.empty())
2447 AdjustDeclIfTemplate(ClassDecl);
2448 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2451 /// \brief Determine whether the type \p Derived is a C++ class that is
2452 /// derived from the type \p Base.
2453 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2454 if (!getLangOpts().CPlusPlus)
2457 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2461 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2465 // If either the base or the derived type is invalid, don't try to
2466 // check whether one is derived from the other.
2467 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2470 // FIXME: In a modules build, do we need the entire path to be visible for us
2471 // to be able to use the inheritance relationship?
2472 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2475 return DerivedRD->isDerivedFrom(BaseRD);
2478 /// \brief Determine whether the type \p Derived is a C++ class that is
2479 /// derived from the type \p Base.
2480 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2481 CXXBasePaths &Paths) {
2482 if (!getLangOpts().CPlusPlus)
2485 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2489 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2493 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2496 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2499 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2500 CXXCastPath &BasePathArray) {
2501 assert(BasePathArray.empty() && "Base path array must be empty!");
2502 assert(Paths.isRecordingPaths() && "Must record paths!");
2504 const CXXBasePath &Path = Paths.front();
2506 // We first go backward and check if we have a virtual base.
2507 // FIXME: It would be better if CXXBasePath had the base specifier for
2508 // the nearest virtual base.
2510 for (unsigned I = Path.size(); I != 0; --I) {
2511 if (Path[I - 1].Base->isVirtual()) {
2517 // Now add all bases.
2518 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2519 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2522 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2523 /// conversion (where Derived and Base are class types) is
2524 /// well-formed, meaning that the conversion is unambiguous (and
2525 /// that all of the base classes are accessible). Returns true
2526 /// and emits a diagnostic if the code is ill-formed, returns false
2527 /// otherwise. Loc is the location where this routine should point to
2528 /// if there is an error, and Range is the source range to highlight
2529 /// if there is an error.
2531 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2532 /// diagnostic for the respective type of error will be suppressed, but the
2533 /// check for ill-formed code will still be performed.
2535 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2536 unsigned InaccessibleBaseID,
2537 unsigned AmbigiousBaseConvID,
2538 SourceLocation Loc, SourceRange Range,
2539 DeclarationName Name,
2540 CXXCastPath *BasePath,
2541 bool IgnoreAccess) {
2542 // First, determine whether the path from Derived to Base is
2543 // ambiguous. This is slightly more expensive than checking whether
2544 // the Derived to Base conversion exists, because here we need to
2545 // explore multiple paths to determine if there is an ambiguity.
2546 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2547 /*DetectVirtual=*/false);
2548 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2549 assert(DerivationOkay &&
2550 "Can only be used with a derived-to-base conversion");
2551 (void)DerivationOkay;
2553 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
2554 if (!IgnoreAccess) {
2555 // Check that the base class can be accessed.
2556 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
2557 InaccessibleBaseID)) {
2558 case AR_inaccessible:
2567 // Build a base path if necessary.
2569 BuildBasePathArray(Paths, *BasePath);
2573 if (AmbigiousBaseConvID) {
2574 // We know that the derived-to-base conversion is ambiguous, and
2575 // we're going to produce a diagnostic. Perform the derived-to-base
2576 // search just one more time to compute all of the possible paths so
2577 // that we can print them out. This is more expensive than any of
2578 // the previous derived-to-base checks we've done, but at this point
2579 // performance isn't as much of an issue.
2581 Paths.setRecordingPaths(true);
2582 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2583 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2586 // Build up a textual representation of the ambiguous paths, e.g.,
2587 // D -> B -> A, that will be used to illustrate the ambiguous
2588 // conversions in the diagnostic. We only print one of the paths
2589 // to each base class subobject.
2590 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2592 Diag(Loc, AmbigiousBaseConvID)
2593 << Derived << Base << PathDisplayStr << Range << Name;
2599 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2600 SourceLocation Loc, SourceRange Range,
2601 CXXCastPath *BasePath,
2602 bool IgnoreAccess) {
2603 return CheckDerivedToBaseConversion(
2604 Derived, Base, diag::err_upcast_to_inaccessible_base,
2605 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2606 BasePath, IgnoreAccess);
2610 /// @brief Builds a string representing ambiguous paths from a
2611 /// specific derived class to different subobjects of the same base
2614 /// This function builds a string that can be used in error messages
2615 /// to show the different paths that one can take through the
2616 /// inheritance hierarchy to go from the derived class to different
2617 /// subobjects of a base class. The result looks something like this:
2619 /// struct D -> struct B -> struct A
2620 /// struct D -> struct C -> struct A
2622 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2623 std::string PathDisplayStr;
2624 std::set<unsigned> DisplayedPaths;
2625 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2626 Path != Paths.end(); ++Path) {
2627 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2628 // We haven't displayed a path to this particular base
2629 // class subobject yet.
2630 PathDisplayStr += "\n ";
2631 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2632 for (CXXBasePath::const_iterator Element = Path->begin();
2633 Element != Path->end(); ++Element)
2634 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2638 return PathDisplayStr;
2641 //===----------------------------------------------------------------------===//
2642 // C++ class member Handling
2643 //===----------------------------------------------------------------------===//
2645 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2646 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2647 SourceLocation ASLoc,
2648 SourceLocation ColonLoc,
2649 AttributeList *Attrs) {
2650 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2651 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2653 CurContext->addHiddenDecl(ASDecl);
2654 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2657 /// CheckOverrideControl - Check C++11 override control semantics.
2658 void Sema::CheckOverrideControl(NamedDecl *D) {
2659 if (D->isInvalidDecl())
2662 // We only care about "override" and "final" declarations.
2663 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2666 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2668 // We can't check dependent instance methods.
2669 if (MD && MD->isInstance() &&
2670 (MD->getParent()->hasAnyDependentBases() ||
2671 MD->getType()->isDependentType()))
2674 if (MD && !MD->isVirtual()) {
2675 // If we have a non-virtual method, check if if hides a virtual method.
2676 // (In that case, it's most likely the method has the wrong type.)
2677 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2678 FindHiddenVirtualMethods(MD, OverloadedMethods);
2680 if (!OverloadedMethods.empty()) {
2681 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2682 Diag(OA->getLocation(),
2683 diag::override_keyword_hides_virtual_member_function)
2684 << "override" << (OverloadedMethods.size() > 1);
2685 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2686 Diag(FA->getLocation(),
2687 diag::override_keyword_hides_virtual_member_function)
2688 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2689 << (OverloadedMethods.size() > 1);
2691 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2692 MD->setInvalidDecl();
2695 // Fall through into the general case diagnostic.
2696 // FIXME: We might want to attempt typo correction here.
2699 if (!MD || !MD->isVirtual()) {
2700 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2701 Diag(OA->getLocation(),
2702 diag::override_keyword_only_allowed_on_virtual_member_functions)
2703 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2704 D->dropAttr<OverrideAttr>();
2706 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2707 Diag(FA->getLocation(),
2708 diag::override_keyword_only_allowed_on_virtual_member_functions)
2709 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2710 << FixItHint::CreateRemoval(FA->getLocation());
2711 D->dropAttr<FinalAttr>();
2716 // C++11 [class.virtual]p5:
2717 // If a function is marked with the virt-specifier override and
2718 // does not override a member function of a base class, the program is
2720 bool HasOverriddenMethods =
2721 MD->begin_overridden_methods() != MD->end_overridden_methods();
2722 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2723 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2724 << MD->getDeclName();
2727 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2728 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2730 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2731 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2734 SourceLocation Loc = MD->getLocation();
2735 SourceLocation SpellingLoc = Loc;
2736 if (getSourceManager().isMacroArgExpansion(Loc))
2737 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2738 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2739 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2742 if (MD->size_overridden_methods() > 0) {
2743 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2744 ? diag::warn_destructor_marked_not_override_overriding
2745 : diag::warn_function_marked_not_override_overriding;
2746 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2747 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2748 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2752 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2753 /// function overrides a virtual member function marked 'final', according to
2754 /// C++11 [class.virtual]p4.
2755 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2756 const CXXMethodDecl *Old) {
2757 FinalAttr *FA = Old->getAttr<FinalAttr>();
2761 Diag(New->getLocation(), diag::err_final_function_overridden)
2762 << New->getDeclName()
2763 << FA->isSpelledAsSealed();
2764 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2768 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2769 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2770 // FIXME: Destruction of ObjC lifetime types has side-effects.
2771 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2772 return !RD->isCompleteDefinition() ||
2773 !RD->hasTrivialDefaultConstructor() ||
2774 !RD->hasTrivialDestructor();
2778 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2779 for (AttributeList *it = list; it != nullptr; it = it->getNext())
2780 if (it->isDeclspecPropertyAttribute())
2785 // Check if there is a field shadowing.
2786 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2787 DeclarationName FieldName,
2788 const CXXRecordDecl *RD) {
2789 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2792 // To record a shadowed field in a base
2793 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2794 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2795 CXXBasePath &Path) {
2796 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2797 // Record an ambiguous path directly
2798 if (Bases.find(Base) != Bases.end())
2800 for (const auto Field : Base->lookup(FieldName)) {
2801 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2802 Field->getAccess() != AS_private) {
2803 assert(Field->getAccess() != AS_none);
2804 assert(Bases.find(Base) == Bases.end());
2805 Bases[Base] = Field;
2812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2813 /*DetectVirtual=*/true);
2814 if (!RD->lookupInBases(FieldShadowed, Paths))
2817 for (const auto &P : Paths) {
2818 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2819 auto It = Bases.find(Base);
2820 // Skip duplicated bases
2821 if (It == Bases.end())
2823 auto BaseField = It->second;
2824 assert(BaseField->getAccess() != AS_private);
2826 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2827 Diag(Loc, diag::warn_shadow_field)
2828 << FieldName.getAsString() << RD->getName() << Base->getName();
2829 Diag(BaseField->getLocation(), diag::note_shadow_field);
2835 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2836 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2837 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2838 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2839 /// present (but parsing it has been deferred).
2841 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2842 MultiTemplateParamsArg TemplateParameterLists,
2843 Expr *BW, const VirtSpecifiers &VS,
2844 InClassInitStyle InitStyle) {
2845 const DeclSpec &DS = D.getDeclSpec();
2846 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2847 DeclarationName Name = NameInfo.getName();
2848 SourceLocation Loc = NameInfo.getLoc();
2850 // For anonymous bitfields, the location should point to the type.
2851 if (Loc.isInvalid())
2852 Loc = D.getLocStart();
2854 Expr *BitWidth = static_cast<Expr*>(BW);
2856 assert(isa<CXXRecordDecl>(CurContext));
2857 assert(!DS.isFriendSpecified());
2859 bool isFunc = D.isDeclarationOfFunction();
2861 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2862 // The Microsoft extension __interface only permits public member functions
2863 // and prohibits constructors, destructors, operators, non-public member
2864 // functions, static methods and data members.
2865 unsigned InvalidDecl;
2866 bool ShowDeclName = true;
2868 InvalidDecl = (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) ? 0 : 1;
2869 else if (AS != AS_public)
2871 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2873 else switch (Name.getNameKind()) {
2874 case DeclarationName::CXXConstructorName:
2876 ShowDeclName = false;
2879 case DeclarationName::CXXDestructorName:
2881 ShowDeclName = false;
2884 case DeclarationName::CXXOperatorName:
2885 case DeclarationName::CXXConversionFunctionName:
2896 Diag(Loc, diag::err_invalid_member_in_interface)
2897 << (InvalidDecl-1) << Name;
2899 Diag(Loc, diag::err_invalid_member_in_interface)
2900 << (InvalidDecl-1) << "";
2905 // C++ 9.2p6: A member shall not be declared to have automatic storage
2906 // duration (auto, register) or with the extern storage-class-specifier.
2907 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2908 // data members and cannot be applied to names declared const or static,
2909 // and cannot be applied to reference members.
2910 switch (DS.getStorageClassSpec()) {
2911 case DeclSpec::SCS_unspecified:
2912 case DeclSpec::SCS_typedef:
2913 case DeclSpec::SCS_static:
2915 case DeclSpec::SCS_mutable:
2917 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2919 // FIXME: It would be nicer if the keyword was ignored only for this
2920 // declarator. Otherwise we could get follow-up errors.
2921 D.getMutableDeclSpec().ClearStorageClassSpecs();
2925 Diag(DS.getStorageClassSpecLoc(),
2926 diag::err_storageclass_invalid_for_member);
2927 D.getMutableDeclSpec().ClearStorageClassSpecs();
2931 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2932 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2935 if (DS.isConstexprSpecified() && isInstField) {
2936 SemaDiagnosticBuilder B =
2937 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2938 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2939 if (InitStyle == ICIS_NoInit) {
2941 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2942 B << FixItHint::CreateRemoval(ConstexprLoc);
2944 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2945 D.getMutableDeclSpec().ClearConstexprSpec();
2946 const char *PrevSpec;
2948 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2949 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2951 assert(!Failed && "Making a constexpr member const shouldn't fail");
2955 const char *PrevSpec;
2957 if (D.getMutableDeclSpec().SetStorageClassSpec(
2958 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2959 Context.getPrintingPolicy())) {
2960 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2961 "This is the only DeclSpec that should fail to be applied");
2964 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
2965 isInstField = false;
2972 CXXScopeSpec &SS = D.getCXXScopeSpec();
2974 // Data members must have identifiers for names.
2975 if (!Name.isIdentifier()) {
2976 Diag(Loc, diag::err_bad_variable_name)
2981 IdentifierInfo *II = Name.getAsIdentifierInfo();
2983 // Member field could not be with "template" keyword.
2984 // So TemplateParameterLists should be empty in this case.
2985 if (TemplateParameterLists.size()) {
2986 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
2987 if (TemplateParams->size()) {
2988 // There is no such thing as a member field template.
2989 Diag(D.getIdentifierLoc(), diag::err_template_member)
2991 << SourceRange(TemplateParams->getTemplateLoc(),
2992 TemplateParams->getRAngleLoc());
2994 // There is an extraneous 'template<>' for this member.
2995 Diag(TemplateParams->getTemplateLoc(),
2996 diag::err_template_member_noparams)
2998 << SourceRange(TemplateParams->getTemplateLoc(),
2999 TemplateParams->getRAngleLoc());
3004 if (SS.isSet() && !SS.isInvalid()) {
3005 // The user provided a superfluous scope specifier inside a class
3011 if (DeclContext *DC = computeDeclContext(SS, false))
3012 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
3014 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3015 << Name << SS.getRange();
3020 AttributeList *MSPropertyAttr =
3021 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
3022 if (MSPropertyAttr) {
3023 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3024 BitWidth, InitStyle, AS, MSPropertyAttr);
3027 isInstField = false;
3029 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3030 BitWidth, InitStyle, AS);
3035 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3037 Member = HandleDeclarator(S, D, TemplateParameterLists);
3041 // Non-instance-fields can't have a bitfield.
3043 if (Member->isInvalidDecl()) {
3044 // don't emit another diagnostic.
3045 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3046 // C++ 9.6p3: A bit-field shall not be a static member.
3047 // "static member 'A' cannot be a bit-field"
3048 Diag(Loc, diag::err_static_not_bitfield)
3049 << Name << BitWidth->getSourceRange();
3050 } else if (isa<TypedefDecl>(Member)) {
3051 // "typedef member 'x' cannot be a bit-field"
3052 Diag(Loc, diag::err_typedef_not_bitfield)
3053 << Name << BitWidth->getSourceRange();
3055 // A function typedef ("typedef int f(); f a;").
3056 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3057 Diag(Loc, diag::err_not_integral_type_bitfield)
3058 << Name << cast<ValueDecl>(Member)->getType()
3059 << BitWidth->getSourceRange();
3063 Member->setInvalidDecl();
3066 Member->setAccess(AS);
3068 // If we have declared a member function template or static data member
3069 // template, set the access of the templated declaration as well.
3070 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3071 FunTmpl->getTemplatedDecl()->setAccess(AS);
3072 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3073 VarTmpl->getTemplatedDecl()->setAccess(AS);
3076 if (VS.isOverrideSpecified())
3077 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3078 if (VS.isFinalSpecified())
3079 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3080 VS.isFinalSpelledSealed()));
3082 if (VS.getLastLocation().isValid()) {
3083 // Update the end location of a method that has a virt-specifiers.
3084 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3085 MD->setRangeEnd(VS.getLastLocation());
3088 CheckOverrideControl(Member);
3090 assert((Name || isInstField) && "No identifier for non-field ?");
3093 FieldDecl *FD = cast<FieldDecl>(Member);
3094 FieldCollector->Add(FD);
3096 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3097 // Remember all explicit private FieldDecls that have a name, no side
3098 // effects and are not part of a dependent type declaration.
3099 if (!FD->isImplicit() && FD->getDeclName() &&
3100 FD->getAccess() == AS_private &&
3101 !FD->hasAttr<UnusedAttr>() &&
3102 !FD->getParent()->isDependentContext() &&
3103 !InitializationHasSideEffects(*FD))
3104 UnusedPrivateFields.insert(FD);
3112 class UninitializedFieldVisitor
3113 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3115 // List of Decls to generate a warning on. Also remove Decls that become
3117 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3118 // List of base classes of the record. Classes are removed after their
3120 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3121 // Vector of decls to be removed from the Decl set prior to visiting the
3122 // nodes. These Decls may have been initialized in the prior initializer.
3123 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3124 // If non-null, add a note to the warning pointing back to the constructor.
3125 const CXXConstructorDecl *Constructor;
3126 // Variables to hold state when processing an initializer list. When
3127 // InitList is true, special case initialization of FieldDecls matching
3128 // InitListFieldDecl.
3130 FieldDecl *InitListFieldDecl;
3131 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3134 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3135 UninitializedFieldVisitor(Sema &S,
3136 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3137 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3138 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3139 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3141 // Returns true if the use of ME is not an uninitialized use.
3142 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3143 bool CheckReferenceOnly) {
3144 llvm::SmallVector<FieldDecl*, 4> Fields;
3145 bool ReferenceField = false;
3147 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3150 Fields.push_back(FD);
3151 if (FD->getType()->isReferenceType())
3152 ReferenceField = true;
3153 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3156 // Binding a reference to an unintialized field is not an
3157 // uninitialized use.
3158 if (CheckReferenceOnly && !ReferenceField)
3161 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3162 // Discard the first field since it is the field decl that is being
3164 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3165 UsedFieldIndex.push_back((*I)->getFieldIndex());
3168 for (auto UsedIter = UsedFieldIndex.begin(),
3169 UsedEnd = UsedFieldIndex.end(),
3170 OrigIter = InitFieldIndex.begin(),
3171 OrigEnd = InitFieldIndex.end();
3172 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3173 if (*UsedIter < *OrigIter)
3175 if (*UsedIter > *OrigIter)
3182 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3184 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3187 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3189 MemberExpr *FieldME = ME;
3191 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3194 while (MemberExpr *SubME =
3195 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3197 if (isa<VarDecl>(SubME->getMemberDecl()))
3200 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3201 if (!FD->isAnonymousStructOrUnion())
3204 if (!FieldME->getType().isPODType(S.Context))
3205 AllPODFields = false;
3207 Base = SubME->getBase();
3210 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3213 if (AddressOf && AllPODFields)
3216 ValueDecl* FoundVD = FieldME->getMemberDecl();
3218 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3219 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3220 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3223 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3224 QualType T = BaseCast->getType();
3225 if (T->isPointerType() &&
3226 BaseClasses.count(T->getPointeeType())) {
3227 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3228 << T->getPointeeType() << FoundVD;
3233 if (!Decls.count(FoundVD))
3236 const bool IsReference = FoundVD->getType()->isReferenceType();
3238 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3239 // Special checking for initializer lists.
3240 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3244 // Prevent double warnings on use of unbounded references.
3245 if (CheckReferenceOnly && !IsReference)
3249 unsigned diag = IsReference
3250 ? diag::warn_reference_field_is_uninit
3251 : diag::warn_field_is_uninit;
3252 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3254 S.Diag(Constructor->getLocation(),
3255 diag::note_uninit_in_this_constructor)
3256 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3260 void HandleValue(Expr *E, bool AddressOf) {
3261 E = E->IgnoreParens();
3263 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3264 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3265 AddressOf /*AddressOf*/);
3269 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3270 Visit(CO->getCond());
3271 HandleValue(CO->getTrueExpr(), AddressOf);
3272 HandleValue(CO->getFalseExpr(), AddressOf);
3276 if (BinaryConditionalOperator *BCO =
3277 dyn_cast<BinaryConditionalOperator>(E)) {
3278 Visit(BCO->getCond());
3279 HandleValue(BCO->getFalseExpr(), AddressOf);
3283 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3284 HandleValue(OVE->getSourceExpr(), AddressOf);
3288 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3289 switch (BO->getOpcode()) {
3294 HandleValue(BO->getLHS(), AddressOf);
3295 Visit(BO->getRHS());
3298 Visit(BO->getLHS());
3299 HandleValue(BO->getRHS(), AddressOf);
3307 void CheckInitListExpr(InitListExpr *ILE) {
3308 InitFieldIndex.push_back(0);
3309 for (auto Child : ILE->children()) {
3310 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3311 CheckInitListExpr(SubList);
3315 ++InitFieldIndex.back();
3317 InitFieldIndex.pop_back();
3320 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3321 FieldDecl *Field, const Type *BaseClass) {
3322 // Remove Decls that may have been initialized in the previous
3324 for (ValueDecl* VD : DeclsToRemove)
3326 DeclsToRemove.clear();
3328 Constructor = FieldConstructor;
3329 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3333 InitListFieldDecl = Field;
3334 InitFieldIndex.clear();
3335 CheckInitListExpr(ILE);
3344 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3347 void VisitMemberExpr(MemberExpr *ME) {
3348 // All uses of unbounded reference fields will warn.
3349 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3352 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3353 if (E->getCastKind() == CK_LValueToRValue) {
3354 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3358 Inherited::VisitImplicitCastExpr(E);
3361 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3362 if (E->getConstructor()->isCopyConstructor()) {
3363 Expr *ArgExpr = E->getArg(0);
3364 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3365 if (ILE->getNumInits() == 1)
3366 ArgExpr = ILE->getInit(0);
3367 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3368 if (ICE->getCastKind() == CK_NoOp)
3369 ArgExpr = ICE->getSubExpr();
3370 HandleValue(ArgExpr, false /*AddressOf*/);
3373 Inherited::VisitCXXConstructExpr(E);
3376 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3377 Expr *Callee = E->getCallee();
3378 if (isa<MemberExpr>(Callee)) {
3379 HandleValue(Callee, false /*AddressOf*/);
3380 for (auto Arg : E->arguments())
3385 Inherited::VisitCXXMemberCallExpr(E);
3388 void VisitCallExpr(CallExpr *E) {
3389 // Treat std::move as a use.
3390 if (E->getNumArgs() == 1) {
3391 if (FunctionDecl *FD = E->getDirectCallee()) {
3392 if (FD->isInStdNamespace() && FD->getIdentifier() &&
3393 FD->getIdentifier()->isStr("move")) {
3394 HandleValue(E->getArg(0), false /*AddressOf*/);
3400 Inherited::VisitCallExpr(E);
3403 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3404 Expr *Callee = E->getCallee();
3406 if (isa<UnresolvedLookupExpr>(Callee))
3407 return Inherited::VisitCXXOperatorCallExpr(E);
3410 for (auto Arg : E->arguments())
3411 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3414 void VisitBinaryOperator(BinaryOperator *E) {
3415 // If a field assignment is detected, remove the field from the
3416 // uninitiailized field set.
3417 if (E->getOpcode() == BO_Assign)
3418 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3419 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3420 if (!FD->getType()->isReferenceType())
3421 DeclsToRemove.push_back(FD);
3423 if (E->isCompoundAssignmentOp()) {
3424 HandleValue(E->getLHS(), false /*AddressOf*/);
3429 Inherited::VisitBinaryOperator(E);
3432 void VisitUnaryOperator(UnaryOperator *E) {
3433 if (E->isIncrementDecrementOp()) {
3434 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3437 if (E->getOpcode() == UO_AddrOf) {
3438 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3439 HandleValue(ME->getBase(), true /*AddressOf*/);
3444 Inherited::VisitUnaryOperator(E);
3448 // Diagnose value-uses of fields to initialize themselves, e.g.
3450 // where foo is not also a parameter to the constructor.
3451 // Also diagnose across field uninitialized use such as
3453 // TODO: implement -Wuninitialized and fold this into that framework.
3454 static void DiagnoseUninitializedFields(
3455 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3457 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3458 Constructor->getLocation())) {
3462 if (Constructor->isInvalidDecl())
3465 const CXXRecordDecl *RD = Constructor->getParent();
3467 if (RD->getDescribedClassTemplate())
3470 // Holds fields that are uninitialized.
3471 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3473 // At the beginning, all fields are uninitialized.
3474 for (auto *I : RD->decls()) {
3475 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3476 UninitializedFields.insert(FD);
3477 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3478 UninitializedFields.insert(IFD->getAnonField());
3482 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3483 for (auto I : RD->bases())
3484 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3486 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3489 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3490 UninitializedFields,
3491 UninitializedBaseClasses);
3493 for (const auto *FieldInit : Constructor->inits()) {
3494 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3497 Expr *InitExpr = FieldInit->getInit();
3501 if (CXXDefaultInitExpr *Default =
3502 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3503 InitExpr = Default->getExpr();
3506 // In class initializers will point to the constructor.
3507 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3508 FieldInit->getAnyMember(),
3509 FieldInit->getBaseClass());
3511 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3512 FieldInit->getAnyMember(),
3513 FieldInit->getBaseClass());
3519 /// \brief Enter a new C++ default initializer scope. After calling this, the
3520 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3521 /// parsing or instantiating the initializer failed.
3522 void Sema::ActOnStartCXXInClassMemberInitializer() {
3523 // Create a synthetic function scope to represent the call to the constructor
3524 // that notionally surrounds a use of this initializer.
3525 PushFunctionScope();
3528 /// \brief This is invoked after parsing an in-class initializer for a
3529 /// non-static C++ class member, and after instantiating an in-class initializer
3530 /// in a class template. Such actions are deferred until the class is complete.
3531 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3532 SourceLocation InitLoc,
3534 // Pop the notional constructor scope we created earlier.
3535 PopFunctionScopeInfo(nullptr, D);
3537 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3538 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3539 "must set init style when field is created");
3542 D->setInvalidDecl();
3544 FD->removeInClassInitializer();
3548 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3549 FD->setInvalidDecl();
3550 FD->removeInClassInitializer();
3554 ExprResult Init = InitExpr;
3555 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3556 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3557 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3558 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3559 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3560 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3561 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3562 if (Init.isInvalid()) {
3563 FD->setInvalidDecl();
3568 // C++11 [class.base.init]p7:
3569 // The initialization of each base and member constitutes a
3571 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3572 if (Init.isInvalid()) {
3573 FD->setInvalidDecl();
3577 InitExpr = Init.get();
3579 FD->setInClassInitializer(InitExpr);
3582 /// \brief Find the direct and/or virtual base specifiers that
3583 /// correspond to the given base type, for use in base initialization
3584 /// within a constructor.
3585 static bool FindBaseInitializer(Sema &SemaRef,
3586 CXXRecordDecl *ClassDecl,
3588 const CXXBaseSpecifier *&DirectBaseSpec,
3589 const CXXBaseSpecifier *&VirtualBaseSpec) {
3590 // First, check for a direct base class.
3591 DirectBaseSpec = nullptr;
3592 for (const auto &Base : ClassDecl->bases()) {
3593 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3594 // We found a direct base of this type. That's what we're
3596 DirectBaseSpec = &Base;
3601 // Check for a virtual base class.
3602 // FIXME: We might be able to short-circuit this if we know in advance that
3603 // there are no virtual bases.
3604 VirtualBaseSpec = nullptr;
3605 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3606 // We haven't found a base yet; search the class hierarchy for a
3607 // virtual base class.
3608 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3609 /*DetectVirtual=*/false);
3610 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3611 SemaRef.Context.getTypeDeclType(ClassDecl),
3613 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3614 Path != Paths.end(); ++Path) {
3615 if (Path->back().Base->isVirtual()) {
3616 VirtualBaseSpec = Path->back().Base;
3623 return DirectBaseSpec || VirtualBaseSpec;
3626 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3628 Sema::ActOnMemInitializer(Decl *ConstructorD,
3631 IdentifierInfo *MemberOrBase,
3632 ParsedType TemplateTypeTy,
3634 SourceLocation IdLoc,
3636 SourceLocation EllipsisLoc) {
3637 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3638 DS, IdLoc, InitList,
3642 /// \brief Handle a C++ member initializer using parentheses syntax.
3644 Sema::ActOnMemInitializer(Decl *ConstructorD,
3647 IdentifierInfo *MemberOrBase,
3648 ParsedType TemplateTypeTy,
3650 SourceLocation IdLoc,
3651 SourceLocation LParenLoc,
3652 ArrayRef<Expr *> Args,
3653 SourceLocation RParenLoc,
3654 SourceLocation EllipsisLoc) {
3655 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3657 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3658 DS, IdLoc, List, EllipsisLoc);
3663 // Callback to only accept typo corrections that can be a valid C++ member
3664 // intializer: either a non-static field member or a base class.
3665 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3667 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3668 : ClassDecl(ClassDecl) {}
3670 bool ValidateCandidate(const TypoCorrection &candidate) override {
3671 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3672 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3673 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3674 return isa<TypeDecl>(ND);
3680 CXXRecordDecl *ClassDecl;
3685 /// \brief Handle a C++ member initializer.
3687 Sema::BuildMemInitializer(Decl *ConstructorD,
3690 IdentifierInfo *MemberOrBase,
3691 ParsedType TemplateTypeTy,
3693 SourceLocation IdLoc,
3695 SourceLocation EllipsisLoc) {
3696 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3697 if (!Res.isUsable())
3704 AdjustDeclIfTemplate(ConstructorD);
3706 CXXConstructorDecl *Constructor
3707 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3709 // The user wrote a constructor initializer on a function that is
3710 // not a C++ constructor. Ignore the error for now, because we may
3711 // have more member initializers coming; we'll diagnose it just
3712 // once in ActOnMemInitializers.
3716 CXXRecordDecl *ClassDecl = Constructor->getParent();
3718 // C++ [class.base.init]p2:
3719 // Names in a mem-initializer-id are looked up in the scope of the
3720 // constructor's class and, if not found in that scope, are looked
3721 // up in the scope containing the constructor's definition.
3722 // [Note: if the constructor's class contains a member with the
3723 // same name as a direct or virtual base class of the class, a
3724 // mem-initializer-id naming the member or base class and composed
3725 // of a single identifier refers to the class member. A
3726 // mem-initializer-id for the hidden base class may be specified
3727 // using a qualified name. ]
3728 if (!SS.getScopeRep() && !TemplateTypeTy) {
3729 // Look for a member, first.
3730 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3731 if (!Result.empty()) {
3733 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3734 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3735 if (EllipsisLoc.isValid())
3736 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3738 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3740 return BuildMemberInitializer(Member, Init, IdLoc);
3744 // It didn't name a member, so see if it names a class.
3746 TypeSourceInfo *TInfo = nullptr;
3748 if (TemplateTypeTy) {
3749 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3750 } else if (DS.getTypeSpecType() == TST_decltype) {
3751 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3752 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3753 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3756 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3757 LookupParsedName(R, S, &SS);
3759 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3761 if (R.isAmbiguous()) return true;
3763 // We don't want access-control diagnostics here.
3764 R.suppressDiagnostics();
3766 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3767 bool NotUnknownSpecialization = false;
3768 DeclContext *DC = computeDeclContext(SS, false);
3769 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3770 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3772 if (!NotUnknownSpecialization) {
3773 // When the scope specifier can refer to a member of an unknown
3774 // specialization, we take it as a type name.
3775 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3776 SS.getWithLocInContext(Context),
3777 *MemberOrBase, IdLoc);
3778 if (BaseType.isNull())
3782 R.setLookupName(MemberOrBase);
3786 // If no results were found, try to correct typos.
3787 TypoCorrection Corr;
3788 if (R.empty() && BaseType.isNull() &&
3789 (Corr = CorrectTypo(
3790 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3791 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3792 CTK_ErrorRecovery, ClassDecl))) {
3793 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3794 // We have found a non-static data member with a similar
3795 // name to what was typed; complain and initialize that
3798 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3799 << MemberOrBase << true);
3800 return BuildMemberInitializer(Member, Init, IdLoc);
3801 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3802 const CXXBaseSpecifier *DirectBaseSpec;
3803 const CXXBaseSpecifier *VirtualBaseSpec;
3804 if (FindBaseInitializer(*this, ClassDecl,
3805 Context.getTypeDeclType(Type),
3806 DirectBaseSpec, VirtualBaseSpec)) {
3807 // We have found a direct or virtual base class with a
3808 // similar name to what was typed; complain and initialize
3811 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3812 << MemberOrBase << false,
3813 PDiag() /*Suppress note, we provide our own.*/);
3815 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3817 Diag(BaseSpec->getLocStart(),
3818 diag::note_base_class_specified_here)
3819 << BaseSpec->getType()
3820 << BaseSpec->getSourceRange();
3827 if (!TyD && BaseType.isNull()) {
3828 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3829 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3834 if (BaseType.isNull()) {
3835 BaseType = Context.getTypeDeclType(TyD);
3836 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3838 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3840 TInfo = Context.CreateTypeSourceInfo(BaseType);
3841 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3842 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3843 TL.setElaboratedKeywordLoc(SourceLocation());
3844 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3850 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3852 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3855 /// Checks a member initializer expression for cases where reference (or
3856 /// pointer) members are bound to by-value parameters (or their addresses).
3857 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3859 SourceLocation IdLoc) {
3860 QualType MemberTy = Member->getType();
3862 // We only handle pointers and references currently.
3863 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3864 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3867 const bool IsPointer = MemberTy->isPointerType();
3869 if (const UnaryOperator *Op
3870 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3871 // The only case we're worried about with pointers requires taking the
3873 if (Op->getOpcode() != UO_AddrOf)
3876 Init = Op->getSubExpr();
3878 // We only handle address-of expression initializers for pointers.
3883 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3884 // We only warn when referring to a non-reference parameter declaration.
3885 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3886 if (!Parameter || Parameter->getType()->isReferenceType())
3889 S.Diag(Init->getExprLoc(),
3890 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3891 : diag::warn_bind_ref_member_to_parameter)
3892 << Member << Parameter << Init->getSourceRange();
3894 // Other initializers are fine.
3898 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3899 << (unsigned)IsPointer;
3903 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3904 SourceLocation IdLoc) {
3905 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3906 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3907 assert((DirectMember || IndirectMember) &&
3908 "Member must be a FieldDecl or IndirectFieldDecl");
3910 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3913 if (Member->isInvalidDecl())
3917 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3918 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3919 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3920 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3922 // Template instantiation doesn't reconstruct ParenListExprs for us.
3926 SourceRange InitRange = Init->getSourceRange();
3928 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3929 // Can't check initialization for a member of dependent type or when
3930 // any of the arguments are type-dependent expressions.
3931 DiscardCleanupsInEvaluationContext();
3933 bool InitList = false;
3934 if (isa<InitListExpr>(Init)) {
3939 // Initialize the member.
3940 InitializedEntity MemberEntity =
3941 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3942 : InitializedEntity::InitializeMember(IndirectMember,
3944 InitializationKind Kind =
3945 InitList ? InitializationKind::CreateDirectList(IdLoc)
3946 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3947 InitRange.getEnd());
3949 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3950 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3952 if (MemberInit.isInvalid())
3955 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3957 // C++11 [class.base.init]p7:
3958 // The initialization of each base and member constitutes a
3960 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3961 if (MemberInit.isInvalid())
3964 Init = MemberInit.get();
3968 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
3969 InitRange.getBegin(), Init,
3970 InitRange.getEnd());
3972 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
3973 InitRange.getBegin(), Init,
3974 InitRange.getEnd());
3979 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
3980 CXXRecordDecl *ClassDecl) {
3981 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
3982 if (!LangOpts.CPlusPlus11)
3983 return Diag(NameLoc, diag::err_delegating_ctor)
3984 << TInfo->getTypeLoc().getLocalSourceRange();
3985 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
3987 bool InitList = true;
3988 MultiExprArg Args = Init;
3989 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3991 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3994 SourceRange InitRange = Init->getSourceRange();
3995 // Initialize the object.
3996 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
3997 QualType(ClassDecl->getTypeForDecl(), 0));
3998 InitializationKind Kind =
3999 InitList ? InitializationKind::CreateDirectList(NameLoc)
4000 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4001 InitRange.getEnd());
4002 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4003 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4005 if (DelegationInit.isInvalid())
4008 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4009 "Delegating constructor with no target?");
4011 // C++11 [class.base.init]p7:
4012 // The initialization of each base and member constitutes a
4014 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4015 InitRange.getBegin());
4016 if (DelegationInit.isInvalid())
4019 // If we are in a dependent context, template instantiation will
4020 // perform this type-checking again. Just save the arguments that we
4021 // received in a ParenListExpr.
4022 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4023 // of the information that we have about the base
4024 // initializer. However, deconstructing the ASTs is a dicey process,
4025 // and this approach is far more likely to get the corner cases right.
4026 if (CurContext->isDependentContext())
4027 DelegationInit = Init;
4029 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4030 DelegationInit.getAs<Expr>(),
4031 InitRange.getEnd());
4035 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4036 Expr *Init, CXXRecordDecl *ClassDecl,
4037 SourceLocation EllipsisLoc) {
4038 SourceLocation BaseLoc
4039 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4041 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4042 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4043 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4045 // C++ [class.base.init]p2:
4046 // [...] Unless the mem-initializer-id names a nonstatic data
4047 // member of the constructor's class or a direct or virtual base
4048 // of that class, the mem-initializer is ill-formed. A
4049 // mem-initializer-list can initialize a base class using any
4050 // name that denotes that base class type.
4051 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4053 SourceRange InitRange = Init->getSourceRange();
4054 if (EllipsisLoc.isValid()) {
4055 // This is a pack expansion.
4056 if (!BaseType->containsUnexpandedParameterPack()) {
4057 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4058 << SourceRange(BaseLoc, InitRange.getEnd());
4060 EllipsisLoc = SourceLocation();
4063 // Check for any unexpanded parameter packs.
4064 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4067 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4071 // Check for direct and virtual base classes.
4072 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4073 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4075 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4077 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4079 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4082 // C++ [base.class.init]p2:
4083 // Unless the mem-initializer-id names a nonstatic data member of the
4084 // constructor's class or a direct or virtual base of that class, the
4085 // mem-initializer is ill-formed.
4086 if (!DirectBaseSpec && !VirtualBaseSpec) {
4087 // If the class has any dependent bases, then it's possible that
4088 // one of those types will resolve to the same type as
4089 // BaseType. Therefore, just treat this as a dependent base
4090 // class initialization. FIXME: Should we try to check the
4091 // initialization anyway? It seems odd.
4092 if (ClassDecl->hasAnyDependentBases())
4095 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4096 << BaseType << Context.getTypeDeclType(ClassDecl)
4097 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4102 DiscardCleanupsInEvaluationContext();
4104 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4105 /*IsVirtual=*/false,
4106 InitRange.getBegin(), Init,
4107 InitRange.getEnd(), EllipsisLoc);
4110 // C++ [base.class.init]p2:
4111 // If a mem-initializer-id is ambiguous because it designates both
4112 // a direct non-virtual base class and an inherited virtual base
4113 // class, the mem-initializer is ill-formed.
4114 if (DirectBaseSpec && VirtualBaseSpec)
4115 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4116 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4118 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4120 BaseSpec = VirtualBaseSpec;
4122 // Initialize the base.
4123 bool InitList = true;
4124 MultiExprArg Args = Init;
4125 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4127 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4130 InitializedEntity BaseEntity =
4131 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4132 InitializationKind Kind =
4133 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4134 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4135 InitRange.getEnd());
4136 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4137 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4138 if (BaseInit.isInvalid())
4141 // C++11 [class.base.init]p7:
4142 // The initialization of each base and member constitutes a
4144 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4145 if (BaseInit.isInvalid())
4148 // If we are in a dependent context, template instantiation will
4149 // perform this type-checking again. Just save the arguments that we
4150 // received in a ParenListExpr.
4151 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4152 // of the information that we have about the base
4153 // initializer. However, deconstructing the ASTs is a dicey process,
4154 // and this approach is far more likely to get the corner cases right.
4155 if (CurContext->isDependentContext())
4158 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4159 BaseSpec->isVirtual(),
4160 InitRange.getBegin(),
4161 BaseInit.getAs<Expr>(),
4162 InitRange.getEnd(), EllipsisLoc);
4165 // Create a static_cast\<T&&>(expr).
4166 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4167 if (T.isNull()) T = E->getType();
4168 QualType TargetType = SemaRef.BuildReferenceType(
4169 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4170 SourceLocation ExprLoc = E->getLocStart();
4171 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4172 TargetType, ExprLoc);
4174 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4175 SourceRange(ExprLoc, ExprLoc),
4176 E->getSourceRange()).get();
4179 /// ImplicitInitializerKind - How an implicit base or member initializer should
4180 /// initialize its base or member.
4181 enum ImplicitInitializerKind {
4189 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4190 ImplicitInitializerKind ImplicitInitKind,
4191 CXXBaseSpecifier *BaseSpec,
4192 bool IsInheritedVirtualBase,
4193 CXXCtorInitializer *&CXXBaseInit) {
4194 InitializedEntity InitEntity
4195 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4196 IsInheritedVirtualBase);
4198 ExprResult BaseInit;
4200 switch (ImplicitInitKind) {
4203 InitializationKind InitKind
4204 = InitializationKind::CreateDefault(Constructor->getLocation());
4205 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4206 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4212 bool Moving = ImplicitInitKind == IIK_Move;
4213 ParmVarDecl *Param = Constructor->getParamDecl(0);
4214 QualType ParamType = Param->getType().getNonReferenceType();
4217 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4218 SourceLocation(), Param, false,
4219 Constructor->getLocation(), ParamType,
4220 VK_LValue, nullptr);
4222 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4224 // Cast to the base class to avoid ambiguities.
4226 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4227 ParamType.getQualifiers());
4230 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4233 CXXCastPath BasePath;
4234 BasePath.push_back(BaseSpec);
4235 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4236 CK_UncheckedDerivedToBase,
4237 Moving ? VK_XValue : VK_LValue,
4240 InitializationKind InitKind
4241 = InitializationKind::CreateDirect(Constructor->getLocation(),
4242 SourceLocation(), SourceLocation());
4243 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4244 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4249 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4250 if (BaseInit.isInvalid())
4254 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4255 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4257 BaseSpec->isVirtual(),
4259 BaseInit.getAs<Expr>(),
4266 static bool RefersToRValueRef(Expr *MemRef) {
4267 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4268 return Referenced->getType()->isRValueReferenceType();
4272 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4273 ImplicitInitializerKind ImplicitInitKind,
4274 FieldDecl *Field, IndirectFieldDecl *Indirect,
4275 CXXCtorInitializer *&CXXMemberInit) {
4276 if (Field->isInvalidDecl())
4279 SourceLocation Loc = Constructor->getLocation();
4281 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4282 bool Moving = ImplicitInitKind == IIK_Move;
4283 ParmVarDecl *Param = Constructor->getParamDecl(0);
4284 QualType ParamType = Param->getType().getNonReferenceType();
4286 // Suppress copying zero-width bitfields.
4287 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4290 Expr *MemberExprBase =
4291 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4292 SourceLocation(), Param, false,
4293 Loc, ParamType, VK_LValue, nullptr);
4295 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4298 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4301 // Build a reference to this field within the parameter.
4303 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4304 Sema::LookupMemberName);
4305 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4306 : cast<ValueDecl>(Field), AS_public);
4307 MemberLookup.resolveKind();
4309 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4313 /*TemplateKWLoc=*/SourceLocation(),
4314 /*FirstQualifierInScope=*/nullptr,
4316 /*TemplateArgs=*/nullptr,
4318 if (CtorArg.isInvalid())
4321 // C++11 [class.copy]p15:
4322 // - if a member m has rvalue reference type T&&, it is direct-initialized
4323 // with static_cast<T&&>(x.m);
4324 if (RefersToRValueRef(CtorArg.get())) {
4325 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4328 InitializedEntity Entity =
4329 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4331 : InitializedEntity::InitializeMember(Field, nullptr,
4334 // Direct-initialize to use the copy constructor.
4335 InitializationKind InitKind =
4336 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4338 Expr *CtorArgE = CtorArg.getAs<Expr>();
4339 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4340 ExprResult MemberInit =
4341 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4342 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4343 if (MemberInit.isInvalid())
4347 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4348 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4350 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4351 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4355 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4356 "Unhandled implicit init kind!");
4358 QualType FieldBaseElementType =
4359 SemaRef.Context.getBaseElementType(Field->getType());
4361 if (FieldBaseElementType->isRecordType()) {
4362 InitializedEntity InitEntity =
4363 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4365 : InitializedEntity::InitializeMember(Field, nullptr,
4367 InitializationKind InitKind =
4368 InitializationKind::CreateDefault(Loc);
4370 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4371 ExprResult MemberInit =
4372 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4374 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4375 if (MemberInit.isInvalid())
4379 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4385 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4392 if (!Field->getParent()->isUnion()) {
4393 if (FieldBaseElementType->isReferenceType()) {
4394 SemaRef.Diag(Constructor->getLocation(),
4395 diag::err_uninitialized_member_in_ctor)
4396 << (int)Constructor->isImplicit()
4397 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4398 << 0 << Field->getDeclName();
4399 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4403 if (FieldBaseElementType.isConstQualified()) {
4404 SemaRef.Diag(Constructor->getLocation(),
4405 diag::err_uninitialized_member_in_ctor)
4406 << (int)Constructor->isImplicit()
4407 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4408 << 1 << Field->getDeclName();
4409 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4414 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4416 // Default-initialize Objective-C pointers to NULL.
4418 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4420 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4425 // Nothing to initialize.
4426 CXXMemberInit = nullptr;
4431 struct BaseAndFieldInfo {
4433 CXXConstructorDecl *Ctor;
4434 bool AnyErrorsInInits;
4435 ImplicitInitializerKind IIK;
4436 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4437 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4438 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4440 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4441 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4442 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4443 if (Ctor->getInheritedConstructor())
4445 else if (Generated && Ctor->isCopyConstructor())
4447 else if (Generated && Ctor->isMoveConstructor())
4453 bool isImplicitCopyOrMove() const {
4464 llvm_unreachable("Invalid ImplicitInitializerKind!");
4467 bool addFieldInitializer(CXXCtorInitializer *Init) {
4468 AllToInit.push_back(Init);
4470 // Check whether this initializer makes the field "used".
4471 if (Init->getInit()->HasSideEffects(S.Context))
4472 S.UnusedPrivateFields.remove(Init->getAnyMember());
4477 bool isInactiveUnionMember(FieldDecl *Field) {
4478 RecordDecl *Record = Field->getParent();
4479 if (!Record->isUnion())
4482 if (FieldDecl *Active =
4483 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4484 return Active != Field->getCanonicalDecl();
4486 // In an implicit copy or move constructor, ignore any in-class initializer.
4487 if (isImplicitCopyOrMove())
4490 // If there's no explicit initialization, the field is active only if it
4491 // has an in-class initializer...
4492 if (Field->hasInClassInitializer())
4494 // ... or it's an anonymous struct or union whose class has an in-class
4496 if (!Field->isAnonymousStructOrUnion())
4498 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4499 return !FieldRD->hasInClassInitializer();
4502 /// \brief Determine whether the given field is, or is within, a union member
4503 /// that is inactive (because there was an initializer given for a different
4504 /// member of the union, or because the union was not initialized at all).
4505 bool isWithinInactiveUnionMember(FieldDecl *Field,
4506 IndirectFieldDecl *Indirect) {
4508 return isInactiveUnionMember(Field);
4510 for (auto *C : Indirect->chain()) {
4511 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4512 if (Field && isInactiveUnionMember(Field))
4520 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4522 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4523 if (T->isIncompleteArrayType())
4526 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4527 if (!ArrayT->getSize())
4530 T = ArrayT->getElementType();
4536 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4538 IndirectFieldDecl *Indirect = nullptr) {
4539 if (Field->isInvalidDecl())
4542 // Overwhelmingly common case: we have a direct initializer for this field.
4543 if (CXXCtorInitializer *Init =
4544 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4545 return Info.addFieldInitializer(Init);
4547 // C++11 [class.base.init]p8:
4548 // if the entity is a non-static data member that has a
4549 // brace-or-equal-initializer and either
4550 // -- the constructor's class is a union and no other variant member of that
4551 // union is designated by a mem-initializer-id or
4552 // -- the constructor's class is not a union, and, if the entity is a member
4553 // of an anonymous union, no other member of that union is designated by
4554 // a mem-initializer-id,
4555 // the entity is initialized as specified in [dcl.init].
4557 // We also apply the same rules to handle anonymous structs within anonymous
4559 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4562 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4564 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4565 if (DIE.isInvalid())
4567 CXXCtorInitializer *Init;
4569 Init = new (SemaRef.Context)
4570 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4571 SourceLocation(), DIE.get(), SourceLocation());
4573 Init = new (SemaRef.Context)
4574 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4575 SourceLocation(), DIE.get(), SourceLocation());
4576 return Info.addFieldInitializer(Init);
4579 // Don't initialize incomplete or zero-length arrays.
4580 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4583 // Don't try to build an implicit initializer if there were semantic
4584 // errors in any of the initializers (and therefore we might be
4585 // missing some that the user actually wrote).
4586 if (Info.AnyErrorsInInits)
4589 CXXCtorInitializer *Init = nullptr;
4590 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4597 return Info.addFieldInitializer(Init);
4601 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4602 CXXCtorInitializer *Initializer) {
4603 assert(Initializer->isDelegatingInitializer());
4604 Constructor->setNumCtorInitializers(1);
4605 CXXCtorInitializer **initializer =
4606 new (Context) CXXCtorInitializer*[1];
4607 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4608 Constructor->setCtorInitializers(initializer);
4610 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4611 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4612 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4615 DelegatingCtorDecls.push_back(Constructor);
4617 DiagnoseUninitializedFields(*this, Constructor);
4622 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4623 ArrayRef<CXXCtorInitializer *> Initializers) {
4624 if (Constructor->isDependentContext()) {
4625 // Just store the initializers as written, they will be checked during
4627 if (!Initializers.empty()) {
4628 Constructor->setNumCtorInitializers(Initializers.size());
4629 CXXCtorInitializer **baseOrMemberInitializers =
4630 new (Context) CXXCtorInitializer*[Initializers.size()];
4631 memcpy(baseOrMemberInitializers, Initializers.data(),
4632 Initializers.size() * sizeof(CXXCtorInitializer*));
4633 Constructor->setCtorInitializers(baseOrMemberInitializers);
4636 // Let template instantiation know whether we had errors.
4638 Constructor->setInvalidDecl();
4643 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4645 // We need to build the initializer AST according to order of construction
4646 // and not what user specified in the Initializers list.
4647 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4651 bool HadError = false;
4653 for (unsigned i = 0; i < Initializers.size(); i++) {
4654 CXXCtorInitializer *Member = Initializers[i];
4656 if (Member->isBaseInitializer())
4657 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4659 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4661 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4662 for (auto *C : F->chain()) {
4663 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4664 if (FD && FD->getParent()->isUnion())
4665 Info.ActiveUnionMember.insert(std::make_pair(
4666 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4668 } else if (FieldDecl *FD = Member->getMember()) {
4669 if (FD->getParent()->isUnion())
4670 Info.ActiveUnionMember.insert(std::make_pair(
4671 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4676 // Keep track of the direct virtual bases.
4677 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4678 for (auto &I : ClassDecl->bases()) {
4680 DirectVBases.insert(&I);
4683 // Push virtual bases before others.
4684 for (auto &VBase : ClassDecl->vbases()) {
4685 if (CXXCtorInitializer *Value
4686 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4687 // [class.base.init]p7, per DR257:
4688 // A mem-initializer where the mem-initializer-id names a virtual base
4689 // class is ignored during execution of a constructor of any class that
4690 // is not the most derived class.
4691 if (ClassDecl->isAbstract()) {
4692 // FIXME: Provide a fixit to remove the base specifier. This requires
4693 // tracking the location of the associated comma for a base specifier.
4694 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4695 << VBase.getType() << ClassDecl;
4696 DiagnoseAbstractType(ClassDecl);
4699 Info.AllToInit.push_back(Value);
4700 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4701 // [class.base.init]p8, per DR257:
4702 // If a given [...] base class is not named by a mem-initializer-id
4703 // [...] and the entity is not a virtual base class of an abstract
4704 // class, then [...] the entity is default-initialized.
4705 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4706 CXXCtorInitializer *CXXBaseInit;
4707 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4708 &VBase, IsInheritedVirtualBase,
4714 Info.AllToInit.push_back(CXXBaseInit);
4718 // Non-virtual bases.
4719 for (auto &Base : ClassDecl->bases()) {
4720 // Virtuals are in the virtual base list and already constructed.
4721 if (Base.isVirtual())
4724 if (CXXCtorInitializer *Value
4725 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4726 Info.AllToInit.push_back(Value);
4727 } else if (!AnyErrors) {
4728 CXXCtorInitializer *CXXBaseInit;
4729 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4730 &Base, /*IsInheritedVirtualBase=*/false,
4736 Info.AllToInit.push_back(CXXBaseInit);
4741 for (auto *Mem : ClassDecl->decls()) {
4742 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4743 // C++ [class.bit]p2:
4744 // A declaration for a bit-field that omits the identifier declares an
4745 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4747 if (F->isUnnamedBitfield())
4750 // If we're not generating the implicit copy/move constructor, then we'll
4751 // handle anonymous struct/union fields based on their individual
4753 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4756 if (CollectFieldInitializer(*this, Info, F))
4761 // Beyond this point, we only consider default initialization.
4762 if (Info.isImplicitCopyOrMove())
4765 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4766 if (F->getType()->isIncompleteArrayType()) {
4767 assert(ClassDecl->hasFlexibleArrayMember() &&
4768 "Incomplete array type is not valid");
4772 // Initialize each field of an anonymous struct individually.
4773 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4780 unsigned NumInitializers = Info.AllToInit.size();
4781 if (NumInitializers > 0) {
4782 Constructor->setNumCtorInitializers(NumInitializers);
4783 CXXCtorInitializer **baseOrMemberInitializers =
4784 new (Context) CXXCtorInitializer*[NumInitializers];
4785 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4786 NumInitializers * sizeof(CXXCtorInitializer*));
4787 Constructor->setCtorInitializers(baseOrMemberInitializers);
4789 // Constructors implicitly reference the base and member
4791 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4792 Constructor->getParent());
4798 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4799 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4800 const RecordDecl *RD = RT->getDecl();
4801 if (RD->isAnonymousStructOrUnion()) {
4802 for (auto *Field : RD->fields())
4803 PopulateKeysForFields(Field, IdealInits);
4807 IdealInits.push_back(Field->getCanonicalDecl());
4810 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4811 return Context.getCanonicalType(BaseType).getTypePtr();
4814 static const void *GetKeyForMember(ASTContext &Context,
4815 CXXCtorInitializer *Member) {
4816 if (!Member->isAnyMemberInitializer())
4817 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4819 return Member->getAnyMember()->getCanonicalDecl();
4822 static void DiagnoseBaseOrMemInitializerOrder(
4823 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4824 ArrayRef<CXXCtorInitializer *> Inits) {
4825 if (Constructor->getDeclContext()->isDependentContext())
4828 // Don't check initializers order unless the warning is enabled at the
4829 // location of at least one initializer.
4830 bool ShouldCheckOrder = false;
4831 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4832 CXXCtorInitializer *Init = Inits[InitIndex];
4833 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4834 Init->getSourceLocation())) {
4835 ShouldCheckOrder = true;
4839 if (!ShouldCheckOrder)
4842 // Build the list of bases and members in the order that they'll
4843 // actually be initialized. The explicit initializers should be in
4844 // this same order but may be missing things.
4845 SmallVector<const void*, 32> IdealInitKeys;
4847 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4849 // 1. Virtual bases.
4850 for (const auto &VBase : ClassDecl->vbases())
4851 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4853 // 2. Non-virtual bases.
4854 for (const auto &Base : ClassDecl->bases()) {
4855 if (Base.isVirtual())
4857 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4860 // 3. Direct fields.
4861 for (auto *Field : ClassDecl->fields()) {
4862 if (Field->isUnnamedBitfield())
4865 PopulateKeysForFields(Field, IdealInitKeys);
4868 unsigned NumIdealInits = IdealInitKeys.size();
4869 unsigned IdealIndex = 0;
4871 CXXCtorInitializer *PrevInit = nullptr;
4872 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4873 CXXCtorInitializer *Init = Inits[InitIndex];
4874 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4876 // Scan forward to try to find this initializer in the idealized
4877 // initializers list.
4878 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4879 if (InitKey == IdealInitKeys[IdealIndex])
4882 // If we didn't find this initializer, it must be because we
4883 // scanned past it on a previous iteration. That can only
4884 // happen if we're out of order; emit a warning.
4885 if (IdealIndex == NumIdealInits && PrevInit) {
4886 Sema::SemaDiagnosticBuilder D =
4887 SemaRef.Diag(PrevInit->getSourceLocation(),
4888 diag::warn_initializer_out_of_order);
4890 if (PrevInit->isAnyMemberInitializer())
4891 D << 0 << PrevInit->getAnyMember()->getDeclName();
4893 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4895 if (Init->isAnyMemberInitializer())
4896 D << 0 << Init->getAnyMember()->getDeclName();
4898 D << 1 << Init->getTypeSourceInfo()->getType();
4900 // Move back to the initializer's location in the ideal list.
4901 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4902 if (InitKey == IdealInitKeys[IdealIndex])
4905 assert(IdealIndex < NumIdealInits &&
4906 "initializer not found in initializer list");
4914 bool CheckRedundantInit(Sema &S,
4915 CXXCtorInitializer *Init,
4916 CXXCtorInitializer *&PrevInit) {
4922 if (FieldDecl *Field = Init->getAnyMember())
4923 S.Diag(Init->getSourceLocation(),
4924 diag::err_multiple_mem_initialization)
4925 << Field->getDeclName()
4926 << Init->getSourceRange();
4928 const Type *BaseClass = Init->getBaseClass();
4929 assert(BaseClass && "neither field nor base");
4930 S.Diag(Init->getSourceLocation(),
4931 diag::err_multiple_base_initialization)
4932 << QualType(BaseClass, 0)
4933 << Init->getSourceRange();
4935 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4936 << 0 << PrevInit->getSourceRange();
4941 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4942 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4944 bool CheckRedundantUnionInit(Sema &S,
4945 CXXCtorInitializer *Init,
4946 RedundantUnionMap &Unions) {
4947 FieldDecl *Field = Init->getAnyMember();
4948 RecordDecl *Parent = Field->getParent();
4949 NamedDecl *Child = Field;
4951 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4952 if (Parent->isUnion()) {
4953 UnionEntry &En = Unions[Parent];
4954 if (En.first && En.first != Child) {
4955 S.Diag(Init->getSourceLocation(),
4956 diag::err_multiple_mem_union_initialization)
4957 << Field->getDeclName()
4958 << Init->getSourceRange();
4959 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4960 << 0 << En.second->getSourceRange();
4967 if (!Parent->isAnonymousStructOrUnion())
4972 Parent = cast<RecordDecl>(Parent->getDeclContext());
4979 /// ActOnMemInitializers - Handle the member initializers for a constructor.
4980 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
4981 SourceLocation ColonLoc,
4982 ArrayRef<CXXCtorInitializer*> MemInits,
4984 if (!ConstructorDecl)
4987 AdjustDeclIfTemplate(ConstructorDecl);
4989 CXXConstructorDecl *Constructor
4990 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
4993 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
4997 // Mapping for the duplicate initializers check.
4998 // For member initializers, this is keyed with a FieldDecl*.
4999 // For base initializers, this is keyed with a Type*.
5000 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5002 // Mapping for the inconsistent anonymous-union initializers check.
5003 RedundantUnionMap MemberUnions;
5005 bool HadError = false;
5006 for (unsigned i = 0; i < MemInits.size(); i++) {
5007 CXXCtorInitializer *Init = MemInits[i];
5009 // Set the source order index.
5010 Init->setSourceOrder(i);
5012 if (Init->isAnyMemberInitializer()) {
5013 const void *Key = GetKeyForMember(Context, Init);
5014 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5015 CheckRedundantUnionInit(*this, Init, MemberUnions))
5017 } else if (Init->isBaseInitializer()) {
5018 const void *Key = GetKeyForMember(Context, Init);
5019 if (CheckRedundantInit(*this, Init, Members[Key]))
5022 assert(Init->isDelegatingInitializer());
5023 // This must be the only initializer
5024 if (MemInits.size() != 1) {
5025 Diag(Init->getSourceLocation(),
5026 diag::err_delegating_initializer_alone)
5027 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5028 // We will treat this as being the only initializer.
5030 SetDelegatingInitializer(Constructor, MemInits[i]);
5031 // Return immediately as the initializer is set.
5039 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5041 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5043 DiagnoseUninitializedFields(*this, Constructor);
5047 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5048 CXXRecordDecl *ClassDecl) {
5049 // Ignore dependent contexts. Also ignore unions, since their members never
5050 // have destructors implicitly called.
5051 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5054 // FIXME: all the access-control diagnostics are positioned on the
5055 // field/base declaration. That's probably good; that said, the
5056 // user might reasonably want to know why the destructor is being
5057 // emitted, and we currently don't say.
5059 // Non-static data members.
5060 for (auto *Field : ClassDecl->fields()) {
5061 if (Field->isInvalidDecl())
5064 // Don't destroy incomplete or zero-length arrays.
5065 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5068 QualType FieldType = Context.getBaseElementType(Field->getType());
5070 const RecordType* RT = FieldType->getAs<RecordType>();
5074 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5075 if (FieldClassDecl->isInvalidDecl())
5077 if (FieldClassDecl->hasIrrelevantDestructor())
5079 // The destructor for an implicit anonymous union member is never invoked.
5080 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5083 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5084 assert(Dtor && "No dtor found for FieldClassDecl!");
5085 CheckDestructorAccess(Field->getLocation(), Dtor,
5086 PDiag(diag::err_access_dtor_field)
5087 << Field->getDeclName()
5090 MarkFunctionReferenced(Location, Dtor);
5091 DiagnoseUseOfDecl(Dtor, Location);
5094 // We only potentially invoke the destructors of potentially constructed
5096 bool VisitVirtualBases = !ClassDecl->isAbstract();
5098 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5101 for (const auto &Base : ClassDecl->bases()) {
5102 // Bases are always records in a well-formed non-dependent class.
5103 const RecordType *RT = Base.getType()->getAs<RecordType>();
5105 // Remember direct virtual bases.
5106 if (Base.isVirtual()) {
5107 if (!VisitVirtualBases)
5109 DirectVirtualBases.insert(RT);
5112 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5113 // If our base class is invalid, we probably can't get its dtor anyway.
5114 if (BaseClassDecl->isInvalidDecl())
5116 if (BaseClassDecl->hasIrrelevantDestructor())
5119 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5120 assert(Dtor && "No dtor found for BaseClassDecl!");
5122 // FIXME: caret should be on the start of the class name
5123 CheckDestructorAccess(Base.getLocStart(), Dtor,
5124 PDiag(diag::err_access_dtor_base)
5126 << Base.getSourceRange(),
5127 Context.getTypeDeclType(ClassDecl));
5129 MarkFunctionReferenced(Location, Dtor);
5130 DiagnoseUseOfDecl(Dtor, Location);
5133 if (!VisitVirtualBases)
5137 for (const auto &VBase : ClassDecl->vbases()) {
5138 // Bases are always records in a well-formed non-dependent class.
5139 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5141 // Ignore direct virtual bases.
5142 if (DirectVirtualBases.count(RT))
5145 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5146 // If our base class is invalid, we probably can't get its dtor anyway.
5147 if (BaseClassDecl->isInvalidDecl())
5149 if (BaseClassDecl->hasIrrelevantDestructor())
5152 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5153 assert(Dtor && "No dtor found for BaseClassDecl!");
5154 if (CheckDestructorAccess(
5155 ClassDecl->getLocation(), Dtor,
5156 PDiag(diag::err_access_dtor_vbase)
5157 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5158 Context.getTypeDeclType(ClassDecl)) ==
5160 CheckDerivedToBaseConversion(
5161 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5162 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5163 SourceRange(), DeclarationName(), nullptr);
5166 MarkFunctionReferenced(Location, Dtor);
5167 DiagnoseUseOfDecl(Dtor, Location);
5171 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5175 if (CXXConstructorDecl *Constructor
5176 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5177 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5178 DiagnoseUninitializedFields(*this, Constructor);
5182 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5183 if (!getLangOpts().CPlusPlus)
5186 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5190 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5191 // class template specialization here, but doing so breaks a lot of code.
5193 // We can't answer whether something is abstract until it has a
5194 // definition. If it's currently being defined, we'll walk back
5195 // over all the declarations when we have a full definition.
5196 const CXXRecordDecl *Def = RD->getDefinition();
5197 if (!Def || Def->isBeingDefined())
5200 return RD->isAbstract();
5203 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5204 TypeDiagnoser &Diagnoser) {
5205 if (!isAbstractType(Loc, T))
5208 T = Context.getBaseElementType(T);
5209 Diagnoser.diagnose(*this, Loc, T);
5210 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5214 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5215 // Check if we've already emitted the list of pure virtual functions
5217 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5220 // If the diagnostic is suppressed, don't emit the notes. We're only
5221 // going to emit them once, so try to attach them to a diagnostic we're
5222 // actually going to show.
5223 if (Diags.isLastDiagnosticIgnored())
5226 CXXFinalOverriderMap FinalOverriders;
5227 RD->getFinalOverriders(FinalOverriders);
5229 // Keep a set of seen pure methods so we won't diagnose the same method
5231 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5233 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5234 MEnd = FinalOverriders.end();
5237 for (OverridingMethods::iterator SO = M->second.begin(),
5238 SOEnd = M->second.end();
5239 SO != SOEnd; ++SO) {
5240 // C++ [class.abstract]p4:
5241 // A class is abstract if it contains or inherits at least one
5242 // pure virtual function for which the final overrider is pure
5246 if (SO->second.size() != 1)
5249 if (!SO->second.front().Method->isPure())
5252 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5255 Diag(SO->second.front().Method->getLocation(),
5256 diag::note_pure_virtual_function)
5257 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5261 if (!PureVirtualClassDiagSet)
5262 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5263 PureVirtualClassDiagSet->insert(RD);
5267 struct AbstractUsageInfo {
5269 CXXRecordDecl *Record;
5270 CanQualType AbstractType;
5273 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5274 : S(S), Record(Record),
5275 AbstractType(S.Context.getCanonicalType(
5276 S.Context.getTypeDeclType(Record))),
5279 void DiagnoseAbstractType() {
5280 if (Invalid) return;
5281 S.DiagnoseAbstractType(Record);
5285 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5288 struct CheckAbstractUsage {
5289 AbstractUsageInfo &Info;
5290 const NamedDecl *Ctx;
5292 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5293 : Info(Info), Ctx(Ctx) {}
5295 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5296 switch (TL.getTypeLocClass()) {
5297 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5298 #define TYPELOC(CLASS, PARENT) \
5299 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5300 #include "clang/AST/TypeLocNodes.def"
5304 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5305 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5306 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5307 if (!TL.getParam(I))
5310 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5311 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5315 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5316 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5319 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5320 // Visit the type parameters from a permissive context.
5321 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5322 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5323 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5324 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5325 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5326 // TODO: other template argument types?
5330 // Visit pointee types from a permissive context.
5331 #define CheckPolymorphic(Type) \
5332 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5333 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5335 CheckPolymorphic(PointerTypeLoc)
5336 CheckPolymorphic(ReferenceTypeLoc)
5337 CheckPolymorphic(MemberPointerTypeLoc)
5338 CheckPolymorphic(BlockPointerTypeLoc)
5339 CheckPolymorphic(AtomicTypeLoc)
5341 /// Handle all the types we haven't given a more specific
5342 /// implementation for above.
5343 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5344 // Every other kind of type that we haven't called out already
5345 // that has an inner type is either (1) sugar or (2) contains that
5346 // inner type in some way as a subobject.
5347 if (TypeLoc Next = TL.getNextTypeLoc())
5348 return Visit(Next, Sel);
5350 // If there's no inner type and we're in a permissive context,
5352 if (Sel == Sema::AbstractNone) return;
5354 // Check whether the type matches the abstract type.
5355 QualType T = TL.getType();
5356 if (T->isArrayType()) {
5357 Sel = Sema::AbstractArrayType;
5358 T = Info.S.Context.getBaseElementType(T);
5360 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5361 if (CT != Info.AbstractType) return;
5363 // It matched; do some magic.
5364 if (Sel == Sema::AbstractArrayType) {
5365 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5366 << T << TL.getSourceRange();
5368 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5369 << Sel << T << TL.getSourceRange();
5371 Info.DiagnoseAbstractType();
5375 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5376 Sema::AbstractDiagSelID Sel) {
5377 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5382 /// Check for invalid uses of an abstract type in a method declaration.
5383 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5384 CXXMethodDecl *MD) {
5385 // No need to do the check on definitions, which require that
5386 // the return/param types be complete.
5387 if (MD->doesThisDeclarationHaveABody())
5390 // For safety's sake, just ignore it if we don't have type source
5391 // information. This should never happen for non-implicit methods,
5393 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5394 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5397 /// Check for invalid uses of an abstract type within a class definition.
5398 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5399 CXXRecordDecl *RD) {
5400 for (auto *D : RD->decls()) {
5401 if (D->isImplicit()) continue;
5403 // Methods and method templates.
5404 if (isa<CXXMethodDecl>(D)) {
5405 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5406 } else if (isa<FunctionTemplateDecl>(D)) {
5407 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5408 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5410 // Fields and static variables.
5411 } else if (isa<FieldDecl>(D)) {
5412 FieldDecl *FD = cast<FieldDecl>(D);
5413 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5414 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5415 } else if (isa<VarDecl>(D)) {
5416 VarDecl *VD = cast<VarDecl>(D);
5417 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5418 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5420 // Nested classes and class templates.
5421 } else if (isa<CXXRecordDecl>(D)) {
5422 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5423 } else if (isa<ClassTemplateDecl>(D)) {
5424 CheckAbstractClassUsage(Info,
5425 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5430 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5431 Attr *ClassAttr = getDLLAttr(Class);
5435 assert(ClassAttr->getKind() == attr::DLLExport);
5437 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5439 if (TSK == TSK_ExplicitInstantiationDeclaration)
5440 // Don't go any further if this is just an explicit instantiation
5444 for (Decl *Member : Class->decls()) {
5445 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5449 if (Member->getAttr<DLLExportAttr>()) {
5450 if (MD->isUserProvided()) {
5451 // Instantiate non-default class member functions ...
5453 // .. except for certain kinds of template specializations.
5454 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5457 S.MarkFunctionReferenced(Class->getLocation(), MD);
5459 // The function will be passed to the consumer when its definition is
5461 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5462 MD->isCopyAssignmentOperator() ||
5463 MD->isMoveAssignmentOperator()) {
5464 // Synthesize and instantiate non-trivial implicit methods, explicitly
5465 // defaulted methods, and the copy and move assignment operators. The
5466 // latter are exported even if they are trivial, because the address of
5467 // an operator can be taken and should compare equal across libraries.
5468 DiagnosticErrorTrap Trap(S.Diags);
5469 S.MarkFunctionReferenced(Class->getLocation(), MD);
5470 if (Trap.hasErrorOccurred()) {
5471 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5472 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5476 // There is no later point when we will see the definition of this
5477 // function, so pass it to the consumer now.
5478 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5484 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5485 CXXRecordDecl *Class) {
5486 // Only the MS ABI has default constructor closures, so we don't need to do
5487 // this semantic checking anywhere else.
5488 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5491 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5492 for (Decl *Member : Class->decls()) {
5493 // Look for exported default constructors.
5494 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5495 if (!CD || !CD->isDefaultConstructor())
5497 auto *Attr = CD->getAttr<DLLExportAttr>();
5501 // If the class is non-dependent, mark the default arguments as ODR-used so
5502 // that we can properly codegen the constructor closure.
5503 if (!Class->isDependentContext()) {
5504 for (ParmVarDecl *PD : CD->parameters()) {
5505 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5506 S.DiscardCleanupsInEvaluationContext();
5510 if (LastExportedDefaultCtor) {
5511 S.Diag(LastExportedDefaultCtor->getLocation(),
5512 diag::err_attribute_dll_ambiguous_default_ctor)
5514 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5515 << CD->getDeclName();
5518 LastExportedDefaultCtor = CD;
5522 /// \brief Check class-level dllimport/dllexport attribute.
5523 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5524 Attr *ClassAttr = getDLLAttr(Class);
5526 // MSVC inherits DLL attributes to partial class template specializations.
5527 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5528 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5529 if (Attr *TemplateAttr =
5530 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5531 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5532 A->setInherited(true);
5541 if (!Class->isExternallyVisible()) {
5542 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5543 << Class << ClassAttr;
5547 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5548 !ClassAttr->isInherited()) {
5549 // Diagnose dll attributes on members of class with dll attribute.
5550 for (Decl *Member : Class->decls()) {
5551 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5553 InheritableAttr *MemberAttr = getDLLAttr(Member);
5554 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5557 Diag(MemberAttr->getLocation(),
5558 diag::err_attribute_dll_member_of_dll_class)
5559 << MemberAttr << ClassAttr;
5560 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5561 Member->setInvalidDecl();
5565 if (Class->getDescribedClassTemplate())
5566 // Don't inherit dll attribute until the template is instantiated.
5569 // The class is either imported or exported.
5570 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5572 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5574 // Ignore explicit dllexport on explicit class template instantiation declarations.
5575 if (ClassExported && !ClassAttr->isInherited() &&
5576 TSK == TSK_ExplicitInstantiationDeclaration) {
5577 Class->dropAttr<DLLExportAttr>();
5581 // Force declaration of implicit members so they can inherit the attribute.
5582 ForceDeclarationOfImplicitMembers(Class);
5584 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5585 // seem to be true in practice?
5587 for (Decl *Member : Class->decls()) {
5588 VarDecl *VD = dyn_cast<VarDecl>(Member);
5589 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5591 // Only methods and static fields inherit the attributes.
5596 // Don't process deleted methods.
5597 if (MD->isDeleted())
5600 if (MD->isInlined()) {
5601 // MinGW does not import or export inline methods.
5602 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5603 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5606 // MSVC versions before 2015 don't export the move assignment operators
5607 // and move constructor, so don't attempt to import/export them if
5608 // we have a definition.
5609 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5610 if ((MD->isMoveAssignmentOperator() ||
5611 (Ctor && Ctor->isMoveConstructor())) &&
5612 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5615 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5616 // operator is exported anyway.
5617 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5618 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5623 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5626 if (!getDLLAttr(Member)) {
5628 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5629 NewAttr->setInherited(true);
5630 Member->addAttr(NewAttr);
5635 DelayedDllExportClasses.push_back(Class);
5638 /// \brief Perform propagation of DLL attributes from a derived class to a
5639 /// templated base class for MS compatibility.
5640 void Sema::propagateDLLAttrToBaseClassTemplate(
5641 CXXRecordDecl *Class, Attr *ClassAttr,
5642 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5644 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5645 // If the base class template has a DLL attribute, don't try to change it.
5649 auto TSK = BaseTemplateSpec->getSpecializationKind();
5650 if (!getDLLAttr(BaseTemplateSpec) &&
5651 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5652 TSK == TSK_ImplicitInstantiation)) {
5653 // The template hasn't been instantiated yet (or it has, but only as an
5654 // explicit instantiation declaration or implicit instantiation, which means
5655 // we haven't codegenned any members yet), so propagate the attribute.
5656 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5657 NewAttr->setInherited(true);
5658 BaseTemplateSpec->addAttr(NewAttr);
5660 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5661 // needs to be run again to work see the new attribute. Otherwise this will
5662 // get run whenever the template is instantiated.
5663 if (TSK != TSK_Undeclared)
5664 checkClassLevelDLLAttribute(BaseTemplateSpec);
5669 if (getDLLAttr(BaseTemplateSpec)) {
5670 // The template has already been specialized or instantiated with an
5671 // attribute, explicitly or through propagation. We should not try to change
5676 // The template was previously instantiated or explicitly specialized without
5677 // a dll attribute, It's too late for us to add an attribute, so warn that
5678 // this is unsupported.
5679 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5680 << BaseTemplateSpec->isExplicitSpecialization();
5681 Diag(ClassAttr->getLocation(), diag::note_attribute);
5682 if (BaseTemplateSpec->isExplicitSpecialization()) {
5683 Diag(BaseTemplateSpec->getLocation(),
5684 diag::note_template_class_explicit_specialization_was_here)
5685 << BaseTemplateSpec;
5687 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5688 diag::note_template_class_instantiation_was_here)
5689 << BaseTemplateSpec;
5693 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5694 SourceLocation DefaultLoc) {
5695 switch (S.getSpecialMember(MD)) {
5696 case Sema::CXXDefaultConstructor:
5697 S.DefineImplicitDefaultConstructor(DefaultLoc,
5698 cast<CXXConstructorDecl>(MD));
5700 case Sema::CXXCopyConstructor:
5701 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5703 case Sema::CXXCopyAssignment:
5704 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5706 case Sema::CXXDestructor:
5707 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5709 case Sema::CXXMoveConstructor:
5710 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5712 case Sema::CXXMoveAssignment:
5713 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5715 case Sema::CXXInvalid:
5716 llvm_unreachable("Invalid special member.");
5720 /// \brief Perform semantic checks on a class definition that has been
5721 /// completing, introducing implicitly-declared members, checking for
5722 /// abstract types, etc.
5723 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5727 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5728 AbstractUsageInfo Info(*this, Record);
5729 CheckAbstractClassUsage(Info, Record);
5732 // If this is not an aggregate type and has no user-declared constructor,
5733 // complain about any non-static data members of reference or const scalar
5734 // type, since they will never get initializers.
5735 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5736 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5737 !Record->isLambda()) {
5738 bool Complained = false;
5739 for (const auto *F : Record->fields()) {
5740 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5743 if (F->getType()->isReferenceType() ||
5744 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5746 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5747 << Record->getTagKind() << Record;
5751 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5752 << F->getType()->isReferenceType()
5753 << F->getDeclName();
5758 if (Record->getIdentifier()) {
5759 // C++ [class.mem]p13:
5760 // If T is the name of a class, then each of the following shall have a
5761 // name different from T:
5762 // - every member of every anonymous union that is a member of class T.
5764 // C++ [class.mem]p14:
5765 // In addition, if class T has a user-declared constructor (12.1), every
5766 // non-static data member of class T shall have a name different from T.
5767 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5768 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5771 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5772 isa<IndirectFieldDecl>(D)) {
5773 Diag(D->getLocation(), diag::err_member_name_of_class)
5774 << D->getDeclName();
5780 // Warn if the class has virtual methods but non-virtual public destructor.
5781 if (Record->isPolymorphic() && !Record->isDependentType()) {
5782 CXXDestructorDecl *dtor = Record->getDestructor();
5783 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5784 !Record->hasAttr<FinalAttr>())
5785 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5786 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5789 if (Record->isAbstract()) {
5790 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5791 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5792 << FA->isSpelledAsSealed();
5793 DiagnoseAbstractType(Record);
5797 bool HasMethodWithOverrideControl = false,
5798 HasOverridingMethodWithoutOverrideControl = false;
5799 if (!Record->isDependentType()) {
5800 for (auto *M : Record->methods()) {
5801 // See if a method overloads virtual methods in a base
5802 // class without overriding any.
5804 DiagnoseHiddenVirtualMethods(M);
5805 if (M->hasAttr<OverrideAttr>())
5806 HasMethodWithOverrideControl = true;
5807 else if (M->size_overridden_methods() > 0)
5808 HasOverridingMethodWithoutOverrideControl = true;
5809 // Check whether the explicitly-defaulted special members are valid.
5810 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5811 CheckExplicitlyDefaultedSpecialMember(M);
5813 // For an explicitly defaulted or deleted special member, we defer
5814 // determining triviality until the class is complete. That time is now!
5815 CXXSpecialMember CSM = getSpecialMember(M);
5816 if (!M->isImplicit() && !M->isUserProvided()) {
5817 if (CSM != CXXInvalid) {
5818 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5820 // Inform the class that we've finished declaring this member.
5821 Record->finishedDefaultedOrDeletedMember(M);
5825 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5826 M->hasAttr<DLLExportAttr>()) {
5827 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5829 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5830 CSM == CXXDestructor))
5831 M->dropAttr<DLLExportAttr>();
5833 if (M->hasAttr<DLLExportAttr>()) {
5834 DefineImplicitSpecialMember(*this, M, M->getLocation());
5835 ActOnFinishInlineFunctionDef(M);
5841 if (HasMethodWithOverrideControl &&
5842 HasOverridingMethodWithoutOverrideControl) {
5843 // At least one method has the 'override' control declared.
5844 // Diagnose all other overridden methods which do not have 'override' specified on them.
5845 for (auto *M : Record->methods())
5846 DiagnoseAbsenceOfOverrideControl(M);
5849 // ms_struct is a request to use the same ABI rules as MSVC. Check
5850 // whether this class uses any C++ features that are implemented
5851 // completely differently in MSVC, and if so, emit a diagnostic.
5852 // That diagnostic defaults to an error, but we allow projects to
5853 // map it down to a warning (or ignore it). It's a fairly common
5854 // practice among users of the ms_struct pragma to mass-annotate
5855 // headers, sweeping up a bunch of types that the project doesn't
5856 // really rely on MSVC-compatible layout for. We must therefore
5857 // support "ms_struct except for C++ stuff" as a secondary ABI.
5858 if (Record->isMsStruct(Context) &&
5859 (Record->isPolymorphic() || Record->getNumBases())) {
5860 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5863 checkClassLevelDLLAttribute(Record);
5866 /// Look up the special member function that would be called by a special
5867 /// member function for a subobject of class type.
5869 /// \param Class The class type of the subobject.
5870 /// \param CSM The kind of special member function.
5871 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5872 /// \param ConstRHS True if this is a copy operation with a const object
5873 /// on its RHS, that is, if the argument to the outer special member
5874 /// function is 'const' and this is not a field marked 'mutable'.
5875 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
5876 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5877 unsigned FieldQuals, bool ConstRHS) {
5878 unsigned LHSQuals = 0;
5879 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5880 LHSQuals = FieldQuals;
5882 unsigned RHSQuals = FieldQuals;
5883 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5886 RHSQuals |= Qualifiers::Const;
5888 return S.LookupSpecialMember(Class, CSM,
5889 RHSQuals & Qualifiers::Const,
5890 RHSQuals & Qualifiers::Volatile,
5892 LHSQuals & Qualifiers::Const,
5893 LHSQuals & Qualifiers::Volatile);
5896 class Sema::InheritedConstructorInfo {
5898 SourceLocation UseLoc;
5900 /// A mapping from the base classes through which the constructor was
5901 /// inherited to the using shadow declaration in that base class (or a null
5902 /// pointer if the constructor was declared in that base class).
5903 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5907 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5908 ConstructorUsingShadowDecl *Shadow)
5909 : S(S), UseLoc(UseLoc) {
5910 bool DiagnosedMultipleConstructedBases = false;
5911 CXXRecordDecl *ConstructedBase = nullptr;
5912 UsingDecl *ConstructedBaseUsing = nullptr;
5914 // Find the set of such base class subobjects and check that there's a
5915 // unique constructed subobject.
5916 for (auto *D : Shadow->redecls()) {
5917 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
5918 auto *DNominatedBase = DShadow->getNominatedBaseClass();
5919 auto *DConstructedBase = DShadow->getConstructedBaseClass();
5921 InheritedFromBases.insert(
5922 std::make_pair(DNominatedBase->getCanonicalDecl(),
5923 DShadow->getNominatedBaseClassShadowDecl()));
5924 if (DShadow->constructsVirtualBase())
5925 InheritedFromBases.insert(
5926 std::make_pair(DConstructedBase->getCanonicalDecl(),
5927 DShadow->getConstructedBaseClassShadowDecl()));
5929 assert(DNominatedBase == DConstructedBase);
5931 // [class.inhctor.init]p2:
5932 // If the constructor was inherited from multiple base class subobjects
5933 // of type B, the program is ill-formed.
5934 if (!ConstructedBase) {
5935 ConstructedBase = DConstructedBase;
5936 ConstructedBaseUsing = D->getUsingDecl();
5937 } else if (ConstructedBase != DConstructedBase &&
5938 !Shadow->isInvalidDecl()) {
5939 if (!DiagnosedMultipleConstructedBases) {
5940 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
5941 << Shadow->getTargetDecl();
5942 S.Diag(ConstructedBaseUsing->getLocation(),
5943 diag::note_ambiguous_inherited_constructor_using)
5945 DiagnosedMultipleConstructedBases = true;
5947 S.Diag(D->getUsingDecl()->getLocation(),
5948 diag::note_ambiguous_inherited_constructor_using)
5949 << DConstructedBase;
5953 if (DiagnosedMultipleConstructedBases)
5954 Shadow->setInvalidDecl();
5957 /// Find the constructor to use for inherited construction of a base class,
5958 /// and whether that base class constructor inherits the constructor from a
5959 /// virtual base class (in which case it won't actually invoke it).
5960 std::pair<CXXConstructorDecl *, bool>
5961 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
5962 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
5963 if (It == InheritedFromBases.end())
5964 return std::make_pair(nullptr, false);
5966 // This is an intermediary class.
5968 return std::make_pair(
5969 S.findInheritingConstructor(UseLoc, Ctor, It->second),
5970 It->second->constructsVirtualBase());
5972 // This is the base class from which the constructor was inherited.
5973 return std::make_pair(Ctor, false);
5977 /// Is the special member function which would be selected to perform the
5978 /// specified operation on the specified class type a constexpr constructor?
5980 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
5981 Sema::CXXSpecialMember CSM, unsigned Quals,
5983 CXXConstructorDecl *InheritedCtor = nullptr,
5984 Sema::InheritedConstructorInfo *Inherited = nullptr) {
5985 // If we're inheriting a constructor, see if we need to call it for this base
5987 if (InheritedCtor) {
5988 assert(CSM == Sema::CXXDefaultConstructor);
5990 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
5992 return BaseCtor->isConstexpr();
5995 if (CSM == Sema::CXXDefaultConstructor)
5996 return ClassDecl->hasConstexprDefaultConstructor();
5998 Sema::SpecialMemberOverloadResult SMOR =
5999 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6000 if (!SMOR.getMethod())
6001 // A constructor we wouldn't select can't be "involved in initializing"
6004 return SMOR.getMethod()->isConstexpr();
6007 /// Determine whether the specified special member function would be constexpr
6008 /// if it were implicitly defined.
6009 static bool defaultedSpecialMemberIsConstexpr(
6010 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6011 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6012 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6013 if (!S.getLangOpts().CPlusPlus11)
6016 // C++11 [dcl.constexpr]p4:
6017 // In the definition of a constexpr constructor [...]
6020 case Sema::CXXDefaultConstructor:
6023 // Since default constructor lookup is essentially trivial (and cannot
6024 // involve, for instance, template instantiation), we compute whether a
6025 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6027 // This is important for performance; we need to know whether the default
6028 // constructor is constexpr to determine whether the type is a literal type.
6029 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6031 case Sema::CXXCopyConstructor:
6032 case Sema::CXXMoveConstructor:
6033 // For copy or move constructors, we need to perform overload resolution.
6036 case Sema::CXXCopyAssignment:
6037 case Sema::CXXMoveAssignment:
6038 if (!S.getLangOpts().CPlusPlus14)
6040 // In C++1y, we need to perform overload resolution.
6044 case Sema::CXXDestructor:
6045 case Sema::CXXInvalid:
6049 // -- if the class is a non-empty union, or for each non-empty anonymous
6050 // union member of a non-union class, exactly one non-static data member
6051 // shall be initialized; [DR1359]
6053 // If we squint, this is guaranteed, since exactly one non-static data member
6054 // will be initialized (if the constructor isn't deleted), we just don't know
6056 if (Ctor && ClassDecl->isUnion())
6057 return CSM == Sema::CXXDefaultConstructor
6058 ? ClassDecl->hasInClassInitializer() ||
6059 !ClassDecl->hasVariantMembers()
6062 // -- the class shall not have any virtual base classes;
6063 if (Ctor && ClassDecl->getNumVBases())
6066 // C++1y [class.copy]p26:
6067 // -- [the class] is a literal type, and
6068 if (!Ctor && !ClassDecl->isLiteral())
6071 // -- every constructor involved in initializing [...] base class
6072 // sub-objects shall be a constexpr constructor;
6073 // -- the assignment operator selected to copy/move each direct base
6074 // class is a constexpr function, and
6075 for (const auto &B : ClassDecl->bases()) {
6076 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6077 if (!BaseType) continue;
6079 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6080 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6081 InheritedCtor, Inherited))
6085 // -- every constructor involved in initializing non-static data members
6086 // [...] shall be a constexpr constructor;
6087 // -- every non-static data member and base class sub-object shall be
6089 // -- for each non-static data member of X that is of class type (or array
6090 // thereof), the assignment operator selected to copy/move that member is
6091 // a constexpr function
6092 for (const auto *F : ClassDecl->fields()) {
6093 if (F->isInvalidDecl())
6095 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6097 QualType BaseType = S.Context.getBaseElementType(F->getType());
6098 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6099 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6100 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6101 BaseType.getCVRQualifiers(),
6102 ConstArg && !F->isMutable()))
6104 } else if (CSM == Sema::CXXDefaultConstructor) {
6109 // All OK, it's constexpr!
6113 static Sema::ImplicitExceptionSpecification
6114 ComputeDefaultedSpecialMemberExceptionSpec(
6115 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6116 Sema::InheritedConstructorInfo *ICI);
6118 static Sema::ImplicitExceptionSpecification
6119 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6120 auto CSM = S.getSpecialMember(MD);
6121 if (CSM != Sema::CXXInvalid)
6122 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6124 auto *CD = cast<CXXConstructorDecl>(MD);
6125 assert(CD->getInheritedConstructor() &&
6126 "only special members have implicit exception specs");
6127 Sema::InheritedConstructorInfo ICI(
6128 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6129 return ComputeDefaultedSpecialMemberExceptionSpec(
6130 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6133 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6134 CXXMethodDecl *MD) {
6135 FunctionProtoType::ExtProtoInfo EPI;
6137 // Build an exception specification pointing back at this member.
6138 EPI.ExceptionSpec.Type = EST_Unevaluated;
6139 EPI.ExceptionSpec.SourceDecl = MD;
6141 // Set the calling convention to the default for C++ instance methods.
6142 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6143 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6144 /*IsCXXMethod=*/true));
6148 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6149 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6150 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6153 // Evaluate the exception specification.
6154 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6155 auto ESI = IES.getExceptionSpec();
6157 // Update the type of the special member to use it.
6158 UpdateExceptionSpec(MD, ESI);
6160 // A user-provided destructor can be defined outside the class. When that
6161 // happens, be sure to update the exception specification on both
6163 const FunctionProtoType *CanonicalFPT =
6164 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6165 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6166 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6169 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6170 CXXRecordDecl *RD = MD->getParent();
6171 CXXSpecialMember CSM = getSpecialMember(MD);
6173 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6174 "not an explicitly-defaulted special member");
6176 // Whether this was the first-declared instance of the constructor.
6177 // This affects whether we implicitly add an exception spec and constexpr.
6178 bool First = MD == MD->getCanonicalDecl();
6180 bool HadError = false;
6182 // C++11 [dcl.fct.def.default]p1:
6183 // A function that is explicitly defaulted shall
6184 // -- be a special member function (checked elsewhere),
6185 // -- have the same type (except for ref-qualifiers, and except that a
6186 // copy operation can take a non-const reference) as an implicit
6188 // -- not have default arguments.
6189 unsigned ExpectedParams = 1;
6190 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6192 if (MD->getNumParams() != ExpectedParams) {
6193 // This also checks for default arguments: a copy or move constructor with a
6194 // default argument is classified as a default constructor, and assignment
6195 // operations and destructors can't have default arguments.
6196 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6197 << CSM << MD->getSourceRange();
6199 } else if (MD->isVariadic()) {
6200 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6201 << CSM << MD->getSourceRange();
6205 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6207 bool CanHaveConstParam = false;
6208 if (CSM == CXXCopyConstructor)
6209 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6210 else if (CSM == CXXCopyAssignment)
6211 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6213 QualType ReturnType = Context.VoidTy;
6214 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6215 // Check for return type matching.
6216 ReturnType = Type->getReturnType();
6217 QualType ExpectedReturnType =
6218 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6219 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6220 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6221 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6225 // A defaulted special member cannot have cv-qualifiers.
6226 if (Type->getTypeQuals()) {
6227 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6228 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6233 // Check for parameter type matching.
6234 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6235 bool HasConstParam = false;
6236 if (ExpectedParams && ArgType->isReferenceType()) {
6237 // Argument must be reference to possibly-const T.
6238 QualType ReferentType = ArgType->getPointeeType();
6239 HasConstParam = ReferentType.isConstQualified();
6241 if (ReferentType.isVolatileQualified()) {
6242 Diag(MD->getLocation(),
6243 diag::err_defaulted_special_member_volatile_param) << CSM;
6247 if (HasConstParam && !CanHaveConstParam) {
6248 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6249 Diag(MD->getLocation(),
6250 diag::err_defaulted_special_member_copy_const_param)
6251 << (CSM == CXXCopyAssignment);
6252 // FIXME: Explain why this special member can't be const.
6254 Diag(MD->getLocation(),
6255 diag::err_defaulted_special_member_move_const_param)
6256 << (CSM == CXXMoveAssignment);
6260 } else if (ExpectedParams) {
6261 // A copy assignment operator can take its argument by value, but a
6262 // defaulted one cannot.
6263 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6264 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6268 // C++11 [dcl.fct.def.default]p2:
6269 // An explicitly-defaulted function may be declared constexpr only if it
6270 // would have been implicitly declared as constexpr,
6271 // Do not apply this rule to members of class templates, since core issue 1358
6272 // makes such functions always instantiate to constexpr functions. For
6273 // functions which cannot be constexpr (for non-constructors in C++11 and for
6274 // destructors in C++1y), this is checked elsewhere.
6275 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6277 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6278 : isa<CXXConstructorDecl>(MD)) &&
6279 MD->isConstexpr() && !Constexpr &&
6280 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6281 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6282 // FIXME: Explain why the special member can't be constexpr.
6286 // and may have an explicit exception-specification only if it is compatible
6287 // with the exception-specification on the implicit declaration.
6288 if (Type->hasExceptionSpec()) {
6289 // Delay the check if this is the first declaration of the special member,
6290 // since we may not have parsed some necessary in-class initializers yet.
6292 // If the exception specification needs to be instantiated, do so now,
6293 // before we clobber it with an EST_Unevaluated specification below.
6294 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6295 InstantiateExceptionSpec(MD->getLocStart(), MD);
6296 Type = MD->getType()->getAs<FunctionProtoType>();
6298 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6300 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6303 // If a function is explicitly defaulted on its first declaration,
6305 // -- it is implicitly considered to be constexpr if the implicit
6306 // definition would be,
6307 MD->setConstexpr(Constexpr);
6309 // -- it is implicitly considered to have the same exception-specification
6310 // as if it had been implicitly declared,
6311 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6312 EPI.ExceptionSpec.Type = EST_Unevaluated;
6313 EPI.ExceptionSpec.SourceDecl = MD;
6314 MD->setType(Context.getFunctionType(ReturnType,
6315 llvm::makeArrayRef(&ArgType,
6320 if (ShouldDeleteSpecialMember(MD, CSM)) {
6322 SetDeclDeleted(MD, MD->getLocation());
6324 // C++11 [dcl.fct.def.default]p4:
6325 // [For a] user-provided explicitly-defaulted function [...] if such a
6326 // function is implicitly defined as deleted, the program is ill-formed.
6327 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6328 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6334 MD->setInvalidDecl();
6337 /// Check whether the exception specification provided for an
6338 /// explicitly-defaulted special member matches the exception specification
6339 /// that would have been generated for an implicit special member, per
6340 /// C++11 [dcl.fct.def.default]p2.
6341 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6342 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6343 // If the exception specification was explicitly specified but hadn't been
6344 // parsed when the method was defaulted, grab it now.
6345 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6347 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6349 // Compute the implicit exception specification.
6350 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6351 /*IsCXXMethod=*/true);
6352 FunctionProtoType::ExtProtoInfo EPI(CC);
6353 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6354 EPI.ExceptionSpec = IES.getExceptionSpec();
6355 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6356 Context.getFunctionType(Context.VoidTy, None, EPI));
6358 // Ensure that it matches.
6359 CheckEquivalentExceptionSpec(
6360 PDiag(diag::err_incorrect_defaulted_exception_spec)
6361 << getSpecialMember(MD), PDiag(),
6362 ImplicitType, SourceLocation(),
6363 SpecifiedType, MD->getLocation());
6366 void Sema::CheckDelayedMemberExceptionSpecs() {
6367 decltype(DelayedExceptionSpecChecks) Checks;
6368 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6370 std::swap(Checks, DelayedExceptionSpecChecks);
6371 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6373 // Perform any deferred checking of exception specifications for virtual
6375 for (auto &Check : Checks)
6376 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6378 // Check that any explicitly-defaulted methods have exception specifications
6379 // compatible with their implicit exception specifications.
6380 for (auto &Spec : Specs)
6381 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6385 /// CRTP base class for visiting operations performed by a special member
6386 /// function (or inherited constructor).
6387 template<typename Derived>
6388 struct SpecialMemberVisitor {
6391 Sema::CXXSpecialMember CSM;
6392 Sema::InheritedConstructorInfo *ICI;
6394 // Properties of the special member, computed for convenience.
6395 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6397 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6398 Sema::InheritedConstructorInfo *ICI)
6399 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6401 case Sema::CXXDefaultConstructor:
6402 case Sema::CXXCopyConstructor:
6403 case Sema::CXXMoveConstructor:
6404 IsConstructor = true;
6406 case Sema::CXXCopyAssignment:
6407 case Sema::CXXMoveAssignment:
6408 IsAssignment = true;
6410 case Sema::CXXDestructor:
6412 case Sema::CXXInvalid:
6413 llvm_unreachable("invalid special member kind");
6416 if (MD->getNumParams()) {
6417 if (const ReferenceType *RT =
6418 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6419 ConstArg = RT->getPointeeType().isConstQualified();
6423 Derived &getDerived() { return static_cast<Derived&>(*this); }
6425 /// Is this a "move" special member?
6426 bool isMove() const {
6427 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6430 /// Look up the corresponding special member in the given class.
6431 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6432 unsigned Quals, bool IsMutable) {
6433 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6434 ConstArg && !IsMutable);
6437 /// Look up the constructor for the specified base class to see if it's
6438 /// overridden due to this being an inherited constructor.
6439 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6442 assert(CSM == Sema::CXXDefaultConstructor);
6444 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6445 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6450 /// A base or member subobject.
6451 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6453 /// Get the location to use for a subobject in diagnostics.
6454 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6455 // FIXME: For an indirect virtual base, the direct base leading to
6456 // the indirect virtual base would be a more useful choice.
6457 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6458 return B->getBaseTypeLoc();
6460 return Subobj.get<FieldDecl*>()->getLocation();
6464 /// Visit all non-virtual (direct) bases.
6465 VisitNonVirtualBases,
6466 /// Visit all direct bases, virtual or not.
6468 /// Visit all non-virtual bases, and all virtual bases if the class
6469 /// is not abstract.
6470 VisitPotentiallyConstructedBases,
6471 /// Visit all direct or virtual bases.
6475 // Visit the bases and members of the class.
6476 bool visit(BasesToVisit Bases) {
6477 CXXRecordDecl *RD = MD->getParent();
6479 if (Bases == VisitPotentiallyConstructedBases)
6480 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6482 for (auto &B : RD->bases())
6483 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6484 getDerived().visitBase(&B))
6487 if (Bases == VisitAllBases)
6488 for (auto &B : RD->vbases())
6489 if (getDerived().visitBase(&B))
6492 for (auto *F : RD->fields())
6493 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6494 getDerived().visitField(F))
6503 struct SpecialMemberDeletionInfo
6504 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6509 bool AllFieldsAreConst;
6511 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6512 Sema::CXXSpecialMember CSM,
6513 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6514 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6515 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6517 bool inUnion() const { return MD->getParent()->isUnion(); }
6519 Sema::CXXSpecialMember getEffectiveCSM() {
6520 return ICI ? Sema::CXXInvalid : CSM;
6523 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6524 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6526 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6527 bool shouldDeleteForField(FieldDecl *FD);
6528 bool shouldDeleteForAllConstMembers();
6530 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6532 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6533 Sema::SpecialMemberOverloadResult SMOR,
6534 bool IsDtorCallInCtor);
6536 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6540 /// Is the given special member inaccessible when used on the given
6542 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6543 CXXMethodDecl *target) {
6544 /// If we're operating on a base class, the object type is the
6545 /// type of this special member.
6547 AccessSpecifier access = target->getAccess();
6548 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6549 objectTy = S.Context.getTypeDeclType(MD->getParent());
6550 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6552 // If we're operating on a field, the object type is the type of the field.
6554 objectTy = S.Context.getTypeDeclType(target->getParent());
6557 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6560 /// Check whether we should delete a special member due to the implicit
6561 /// definition containing a call to a special member of a subobject.
6562 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6563 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6564 bool IsDtorCallInCtor) {
6565 CXXMethodDecl *Decl = SMOR.getMethod();
6566 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6570 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6571 DiagKind = !Decl ? 0 : 1;
6572 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6574 else if (!isAccessible(Subobj, Decl))
6576 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6577 !Decl->isTrivial()) {
6578 // A member of a union must have a trivial corresponding special member.
6579 // As a weird special case, a destructor call from a union's constructor
6580 // must be accessible and non-deleted, but need not be trivial. Such a
6581 // destructor is never actually called, but is semantically checked as
6591 S.Diag(Field->getLocation(),
6592 diag::note_deleted_special_member_class_subobject)
6593 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6594 << Field << DiagKind << IsDtorCallInCtor;
6596 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6597 S.Diag(Base->getLocStart(),
6598 diag::note_deleted_special_member_class_subobject)
6599 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6600 << Base->getType() << DiagKind << IsDtorCallInCtor;
6604 S.NoteDeletedFunction(Decl);
6605 // FIXME: Explain inaccessibility if DiagKind == 3.
6611 /// Check whether we should delete a special member function due to having a
6612 /// direct or virtual base class or non-static data member of class type M.
6613 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6614 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6615 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6616 bool IsMutable = Field && Field->isMutable();
6618 // C++11 [class.ctor]p5:
6619 // -- any direct or virtual base class, or non-static data member with no
6620 // brace-or-equal-initializer, has class type M (or array thereof) and
6621 // either M has no default constructor or overload resolution as applied
6622 // to M's default constructor results in an ambiguity or in a function
6623 // that is deleted or inaccessible
6624 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6625 // -- a direct or virtual base class B that cannot be copied/moved because
6626 // overload resolution, as applied to B's corresponding special member,
6627 // results in an ambiguity or a function that is deleted or inaccessible
6628 // from the defaulted special member
6629 // C++11 [class.dtor]p5:
6630 // -- any direct or virtual base class [...] has a type with a destructor
6631 // that is deleted or inaccessible
6632 if (!(CSM == Sema::CXXDefaultConstructor &&
6633 Field && Field->hasInClassInitializer()) &&
6634 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6638 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6639 // -- any direct or virtual base class or non-static data member has a
6640 // type with a destructor that is deleted or inaccessible
6641 if (IsConstructor) {
6642 Sema::SpecialMemberOverloadResult SMOR =
6643 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6644 false, false, false, false, false);
6645 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6652 /// Check whether we should delete a special member function due to the class
6653 /// having a particular direct or virtual base class.
6654 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6655 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6656 // If program is correct, BaseClass cannot be null, but if it is, the error
6657 // must be reported elsewhere.
6660 // If we have an inheriting constructor, check whether we're calling an
6661 // inherited constructor instead of a default constructor.
6662 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6663 if (auto *BaseCtor = SMOR.getMethod()) {
6664 // Note that we do not check access along this path; other than that,
6665 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6666 // FIXME: Check that the base has a usable destructor! Sink this into
6667 // shouldDeleteForClassSubobject.
6668 if (BaseCtor->isDeleted() && Diagnose) {
6669 S.Diag(Base->getLocStart(),
6670 diag::note_deleted_special_member_class_subobject)
6671 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6672 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6673 S.NoteDeletedFunction(BaseCtor);
6675 return BaseCtor->isDeleted();
6677 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6680 /// Check whether we should delete a special member function due to the class
6681 /// having a particular non-static data member.
6682 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6683 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6684 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6686 if (CSM == Sema::CXXDefaultConstructor) {
6687 // For a default constructor, all references must be initialized in-class
6688 // and, if a union, it must have a non-const member.
6689 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6691 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6692 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6695 // C++11 [class.ctor]p5: any non-variant non-static data member of
6696 // const-qualified type (or array thereof) with no
6697 // brace-or-equal-initializer does not have a user-provided default
6699 if (!inUnion() && FieldType.isConstQualified() &&
6700 !FD->hasInClassInitializer() &&
6701 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6703 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6704 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6708 if (inUnion() && !FieldType.isConstQualified())
6709 AllFieldsAreConst = false;
6710 } else if (CSM == Sema::CXXCopyConstructor) {
6711 // For a copy constructor, data members must not be of rvalue reference
6713 if (FieldType->isRValueReferenceType()) {
6715 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6716 << MD->getParent() << FD << FieldType;
6719 } else if (IsAssignment) {
6720 // For an assignment operator, data members must not be of reference type.
6721 if (FieldType->isReferenceType()) {
6723 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6724 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6727 if (!FieldRecord && FieldType.isConstQualified()) {
6728 // C++11 [class.copy]p23:
6729 // -- a non-static data member of const non-class type (or array thereof)
6731 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6732 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6738 // Some additional restrictions exist on the variant members.
6739 if (!inUnion() && FieldRecord->isUnion() &&
6740 FieldRecord->isAnonymousStructOrUnion()) {
6741 bool AllVariantFieldsAreConst = true;
6743 // FIXME: Handle anonymous unions declared within anonymous unions.
6744 for (auto *UI : FieldRecord->fields()) {
6745 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6747 if (!UnionFieldType.isConstQualified())
6748 AllVariantFieldsAreConst = false;
6750 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6751 if (UnionFieldRecord &&
6752 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6753 UnionFieldType.getCVRQualifiers()))
6757 // At least one member in each anonymous union must be non-const
6758 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6759 !FieldRecord->field_empty()) {
6761 S.Diag(FieldRecord->getLocation(),
6762 diag::note_deleted_default_ctor_all_const)
6763 << !!ICI << MD->getParent() << /*anonymous union*/1;
6767 // Don't check the implicit member of the anonymous union type.
6768 // This is technically non-conformant, but sanity demands it.
6772 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6773 FieldType.getCVRQualifiers()))
6780 /// C++11 [class.ctor] p5:
6781 /// A defaulted default constructor for a class X is defined as deleted if
6782 /// X is a union and all of its variant members are of const-qualified type.
6783 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6784 // This is a silly definition, because it gives an empty union a deleted
6785 // default constructor. Don't do that.
6786 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6787 bool AnyFields = false;
6788 for (auto *F : MD->getParent()->fields())
6789 if ((AnyFields = !F->isUnnamedBitfield()))
6794 S.Diag(MD->getParent()->getLocation(),
6795 diag::note_deleted_default_ctor_all_const)
6796 << !!ICI << MD->getParent() << /*not anonymous union*/0;
6802 /// Determine whether a defaulted special member function should be defined as
6803 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6804 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6805 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6806 InheritedConstructorInfo *ICI,
6808 if (MD->isInvalidDecl())
6810 CXXRecordDecl *RD = MD->getParent();
6811 assert(!RD->isDependentType() && "do deletion after instantiation");
6812 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6815 // C++11 [expr.lambda.prim]p19:
6816 // The closure type associated with a lambda-expression has a
6817 // deleted (8.4.3) default constructor and a deleted copy
6818 // assignment operator.
6819 if (RD->isLambda() &&
6820 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6822 Diag(RD->getLocation(), diag::note_lambda_decl);
6826 // For an anonymous struct or union, the copy and assignment special members
6827 // will never be used, so skip the check. For an anonymous union declared at
6828 // namespace scope, the constructor and destructor are used.
6829 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6830 RD->isAnonymousStructOrUnion())
6833 // C++11 [class.copy]p7, p18:
6834 // If the class definition declares a move constructor or move assignment
6835 // operator, an implicitly declared copy constructor or copy assignment
6836 // operator is defined as deleted.
6837 if (MD->isImplicit() &&
6838 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6839 CXXMethodDecl *UserDeclaredMove = nullptr;
6841 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6842 // deletion of the corresponding copy operation, not both copy operations.
6843 // MSVC 2015 has adopted the standards conforming behavior.
6844 bool DeletesOnlyMatchingCopy =
6845 getLangOpts().MSVCCompat &&
6846 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6848 if (RD->hasUserDeclaredMoveConstructor() &&
6849 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6850 if (!Diagnose) return true;
6852 // Find any user-declared move constructor.
6853 for (auto *I : RD->ctors()) {
6854 if (I->isMoveConstructor()) {
6855 UserDeclaredMove = I;
6859 assert(UserDeclaredMove);
6860 } else if (RD->hasUserDeclaredMoveAssignment() &&
6861 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6862 if (!Diagnose) return true;
6864 // Find any user-declared move assignment operator.
6865 for (auto *I : RD->methods()) {
6866 if (I->isMoveAssignmentOperator()) {
6867 UserDeclaredMove = I;
6871 assert(UserDeclaredMove);
6874 if (UserDeclaredMove) {
6875 Diag(UserDeclaredMove->getLocation(),
6876 diag::note_deleted_copy_user_declared_move)
6877 << (CSM == CXXCopyAssignment) << RD
6878 << UserDeclaredMove->isMoveAssignmentOperator();
6883 // Do access control from the special member function
6884 ContextRAII MethodContext(*this, MD);
6886 // C++11 [class.dtor]p5:
6887 // -- for a virtual destructor, lookup of the non-array deallocation function
6888 // results in an ambiguity or in a function that is deleted or inaccessible
6889 if (CSM == CXXDestructor && MD->isVirtual()) {
6890 FunctionDecl *OperatorDelete = nullptr;
6891 DeclarationName Name =
6892 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6893 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6894 OperatorDelete, /*Diagnose*/false)) {
6896 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6901 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6903 // Per DR1611, do not consider virtual bases of constructors of abstract
6904 // classes, since we are not going to construct them.
6905 // Per DR1658, do not consider virtual bases of destructors of abstract
6907 // Per DR2180, for assignment operators we only assign (and thus only
6908 // consider) direct bases.
6909 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6910 : SMI.VisitPotentiallyConstructedBases))
6913 if (SMI.shouldDeleteForAllConstMembers())
6916 if (getLangOpts().CUDA) {
6917 // We should delete the special member in CUDA mode if target inference
6919 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
6926 /// Perform lookup for a special member of the specified kind, and determine
6927 /// whether it is trivial. If the triviality can be determined without the
6928 /// lookup, skip it. This is intended for use when determining whether a
6929 /// special member of a containing object is trivial, and thus does not ever
6930 /// perform overload resolution for default constructors.
6932 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
6933 /// member that was most likely to be intended to be trivial, if any.
6934 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
6935 Sema::CXXSpecialMember CSM, unsigned Quals,
6936 bool ConstRHS, CXXMethodDecl **Selected) {
6938 *Selected = nullptr;
6941 case Sema::CXXInvalid:
6942 llvm_unreachable("not a special member");
6944 case Sema::CXXDefaultConstructor:
6945 // C++11 [class.ctor]p5:
6946 // A default constructor is trivial if:
6947 // - all the [direct subobjects] have trivial default constructors
6949 // Note, no overload resolution is performed in this case.
6950 if (RD->hasTrivialDefaultConstructor())
6954 // If there's a default constructor which could have been trivial, dig it
6955 // out. Otherwise, if there's any user-provided default constructor, point
6956 // to that as an example of why there's not a trivial one.
6957 CXXConstructorDecl *DefCtor = nullptr;
6958 if (RD->needsImplicitDefaultConstructor())
6959 S.DeclareImplicitDefaultConstructor(RD);
6960 for (auto *CI : RD->ctors()) {
6961 if (!CI->isDefaultConstructor())
6964 if (!DefCtor->isUserProvided())
6968 *Selected = DefCtor;
6973 case Sema::CXXDestructor:
6974 // C++11 [class.dtor]p5:
6975 // A destructor is trivial if:
6976 // - all the direct [subobjects] have trivial destructors
6977 if (RD->hasTrivialDestructor())
6981 if (RD->needsImplicitDestructor())
6982 S.DeclareImplicitDestructor(RD);
6983 *Selected = RD->getDestructor();
6988 case Sema::CXXCopyConstructor:
6989 // C++11 [class.copy]p12:
6990 // A copy constructor is trivial if:
6991 // - the constructor selected to copy each direct [subobject] is trivial
6992 if (RD->hasTrivialCopyConstructor()) {
6993 if (Quals == Qualifiers::Const)
6994 // We must either select the trivial copy constructor or reach an
6995 // ambiguity; no need to actually perform overload resolution.
6997 } else if (!Selected) {
7000 // In C++98, we are not supposed to perform overload resolution here, but we
7001 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7002 // cases like B as having a non-trivial copy constructor:
7003 // struct A { template<typename T> A(T&); };
7004 // struct B { mutable A a; };
7005 goto NeedOverloadResolution;
7007 case Sema::CXXCopyAssignment:
7008 // C++11 [class.copy]p25:
7009 // A copy assignment operator is trivial if:
7010 // - the assignment operator selected to copy each direct [subobject] is
7012 if (RD->hasTrivialCopyAssignment()) {
7013 if (Quals == Qualifiers::Const)
7015 } else if (!Selected) {
7018 // In C++98, we are not supposed to perform overload resolution here, but we
7019 // treat that as a language defect.
7020 goto NeedOverloadResolution;
7022 case Sema::CXXMoveConstructor:
7023 case Sema::CXXMoveAssignment:
7024 NeedOverloadResolution:
7025 Sema::SpecialMemberOverloadResult SMOR =
7026 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7028 // The standard doesn't describe how to behave if the lookup is ambiguous.
7029 // We treat it as not making the member non-trivial, just like the standard
7030 // mandates for the default constructor. This should rarely matter, because
7031 // the member will also be deleted.
7032 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7035 if (!SMOR.getMethod()) {
7036 assert(SMOR.getKind() ==
7037 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7041 // We deliberately don't check if we found a deleted special member. We're
7044 *Selected = SMOR.getMethod();
7045 return SMOR.getMethod()->isTrivial();
7048 llvm_unreachable("unknown special method kind");
7051 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7052 for (auto *CI : RD->ctors())
7053 if (!CI->isImplicit())
7056 // Look for constructor templates.
7057 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7058 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7059 if (CXXConstructorDecl *CD =
7060 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7067 /// The kind of subobject we are checking for triviality. The values of this
7068 /// enumeration are used in diagnostics.
7069 enum TrivialSubobjectKind {
7070 /// The subobject is a base class.
7072 /// The subobject is a non-static data member.
7074 /// The object is actually the complete object.
7078 /// Check whether the special member selected for a given type would be trivial.
7079 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7080 QualType SubType, bool ConstRHS,
7081 Sema::CXXSpecialMember CSM,
7082 TrivialSubobjectKind Kind,
7084 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7088 CXXMethodDecl *Selected;
7089 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7090 ConstRHS, Diagnose ? &Selected : nullptr))
7097 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7098 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7099 << Kind << SubType.getUnqualifiedType();
7100 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7101 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7102 } else if (!Selected)
7103 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7104 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7105 else if (Selected->isUserProvided()) {
7106 if (Kind == TSK_CompleteObject)
7107 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7108 << Kind << SubType.getUnqualifiedType() << CSM;
7110 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7111 << Kind << SubType.getUnqualifiedType() << CSM;
7112 S.Diag(Selected->getLocation(), diag::note_declared_at);
7115 if (Kind != TSK_CompleteObject)
7116 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7117 << Kind << SubType.getUnqualifiedType() << CSM;
7119 // Explain why the defaulted or deleted special member isn't trivial.
7120 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7127 /// Check whether the members of a class type allow a special member to be
7129 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7130 Sema::CXXSpecialMember CSM,
7131 bool ConstArg, bool Diagnose) {
7132 for (const auto *FI : RD->fields()) {
7133 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7136 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7138 // Pretend anonymous struct or union members are members of this class.
7139 if (FI->isAnonymousStructOrUnion()) {
7140 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7141 CSM, ConstArg, Diagnose))
7146 // C++11 [class.ctor]p5:
7147 // A default constructor is trivial if [...]
7148 // -- no non-static data member of its class has a
7149 // brace-or-equal-initializer
7150 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7152 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7156 // Objective C ARC 4.3.5:
7157 // [...] nontrivally ownership-qualified types are [...] not trivially
7158 // default constructible, copy constructible, move constructible, copy
7159 // assignable, move assignable, or destructible [...]
7160 if (FieldType.hasNonTrivialObjCLifetime()) {
7162 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7163 << RD << FieldType.getObjCLifetime();
7167 bool ConstRHS = ConstArg && !FI->isMutable();
7168 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7169 CSM, TSK_Field, Diagnose))
7176 /// Diagnose why the specified class does not have a trivial special member of
7178 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7179 QualType Ty = Context.getRecordType(RD);
7181 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7182 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7183 TSK_CompleteObject, /*Diagnose*/true);
7186 /// Determine whether a defaulted or deleted special member function is trivial,
7187 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7188 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7189 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7191 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7193 CXXRecordDecl *RD = MD->getParent();
7195 bool ConstArg = false;
7197 // C++11 [class.copy]p12, p25: [DR1593]
7198 // A [special member] is trivial if [...] its parameter-type-list is
7199 // equivalent to the parameter-type-list of an implicit declaration [...]
7201 case CXXDefaultConstructor:
7203 // Trivial default constructors and destructors cannot have parameters.
7206 case CXXCopyConstructor:
7207 case CXXCopyAssignment: {
7208 // Trivial copy operations always have const, non-volatile parameter types.
7210 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7211 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7212 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7214 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7215 << Param0->getSourceRange() << Param0->getType()
7216 << Context.getLValueReferenceType(
7217 Context.getRecordType(RD).withConst());
7223 case CXXMoveConstructor:
7224 case CXXMoveAssignment: {
7225 // Trivial move operations always have non-cv-qualified parameters.
7226 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7227 const RValueReferenceType *RT =
7228 Param0->getType()->getAs<RValueReferenceType>();
7229 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7231 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7232 << Param0->getSourceRange() << Param0->getType()
7233 << Context.getRValueReferenceType(Context.getRecordType(RD));
7240 llvm_unreachable("not a special member");
7243 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7245 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7246 diag::note_nontrivial_default_arg)
7247 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7250 if (MD->isVariadic()) {
7252 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7256 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7257 // A copy/move [constructor or assignment operator] is trivial if
7258 // -- the [member] selected to copy/move each direct base class subobject
7261 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7262 // A [default constructor or destructor] is trivial if
7263 // -- all the direct base classes have trivial [default constructors or
7265 for (const auto &BI : RD->bases())
7266 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7267 ConstArg, CSM, TSK_BaseClass, Diagnose))
7270 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7271 // A copy/move [constructor or assignment operator] for a class X is
7273 // -- for each non-static data member of X that is of class type (or array
7274 // thereof), the constructor selected to copy/move that member is
7277 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7278 // A [default constructor or destructor] is trivial if
7279 // -- for all of the non-static data members of its class that are of class
7280 // type (or array thereof), each such class has a trivial [default
7281 // constructor or destructor]
7282 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7285 // C++11 [class.dtor]p5:
7286 // A destructor is trivial if [...]
7287 // -- the destructor is not virtual
7288 if (CSM == CXXDestructor && MD->isVirtual()) {
7290 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7294 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7295 // A [special member] for class X is trivial if [...]
7296 // -- class X has no virtual functions and no virtual base classes
7297 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7301 if (RD->getNumVBases()) {
7302 // Check for virtual bases. We already know that the corresponding
7303 // member in all bases is trivial, so vbases must all be direct.
7304 CXXBaseSpecifier &BS = *RD->vbases_begin();
7305 assert(BS.isVirtual());
7306 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7310 // Must have a virtual method.
7311 for (const auto *MI : RD->methods()) {
7312 if (MI->isVirtual()) {
7313 SourceLocation MLoc = MI->getLocStart();
7314 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7319 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7322 // Looks like it's trivial!
7327 struct FindHiddenVirtualMethod {
7329 CXXMethodDecl *Method;
7330 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7331 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7334 /// Check whether any most overriden method from MD in Methods
7335 static bool CheckMostOverridenMethods(
7336 const CXXMethodDecl *MD,
7337 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7338 if (MD->size_overridden_methods() == 0)
7339 return Methods.count(MD->getCanonicalDecl());
7340 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7341 E = MD->end_overridden_methods();
7343 if (CheckMostOverridenMethods(*I, Methods))
7349 /// Member lookup function that determines whether a given C++
7350 /// method overloads virtual methods in a base class without overriding any,
7351 /// to be used with CXXRecordDecl::lookupInBases().
7352 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7353 RecordDecl *BaseRecord =
7354 Specifier->getType()->getAs<RecordType>()->getDecl();
7356 DeclarationName Name = Method->getDeclName();
7357 assert(Name.getNameKind() == DeclarationName::Identifier);
7359 bool foundSameNameMethod = false;
7360 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7361 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7362 Path.Decls = Path.Decls.slice(1)) {
7363 NamedDecl *D = Path.Decls.front();
7364 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7365 MD = MD->getCanonicalDecl();
7366 foundSameNameMethod = true;
7367 // Interested only in hidden virtual methods.
7368 if (!MD->isVirtual())
7370 // If the method we are checking overrides a method from its base
7371 // don't warn about the other overloaded methods. Clang deviates from
7372 // GCC by only diagnosing overloads of inherited virtual functions that
7373 // do not override any other virtual functions in the base. GCC's
7374 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7375 // function from a base class. These cases may be better served by a
7376 // warning (not specific to virtual functions) on call sites when the
7377 // call would select a different function from the base class, were it
7379 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7380 if (!S->IsOverload(Method, MD, false))
7382 // Collect the overload only if its hidden.
7383 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7384 overloadedMethods.push_back(MD);
7388 if (foundSameNameMethod)
7389 OverloadedMethods.append(overloadedMethods.begin(),
7390 overloadedMethods.end());
7391 return foundSameNameMethod;
7394 } // end anonymous namespace
7396 /// \brief Add the most overriden methods from MD to Methods
7397 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7398 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7399 if (MD->size_overridden_methods() == 0)
7400 Methods.insert(MD->getCanonicalDecl());
7401 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7402 E = MD->end_overridden_methods();
7404 AddMostOverridenMethods(*I, Methods);
7407 /// \brief Check if a method overloads virtual methods in a base class without
7409 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7410 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7411 if (!MD->getDeclName().isIdentifier())
7414 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7415 /*bool RecordPaths=*/false,
7416 /*bool DetectVirtual=*/false);
7417 FindHiddenVirtualMethod FHVM;
7421 // Keep the base methods that were overriden or introduced in the subclass
7422 // by 'using' in a set. A base method not in this set is hidden.
7423 CXXRecordDecl *DC = MD->getParent();
7424 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7425 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7427 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7428 ND = shad->getTargetDecl();
7429 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7430 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7433 if (DC->lookupInBases(FHVM, Paths))
7434 OverloadedMethods = FHVM.OverloadedMethods;
7437 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7438 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7439 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7440 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7441 PartialDiagnostic PD = PDiag(
7442 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7443 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7444 Diag(overloadedMD->getLocation(), PD);
7448 /// \brief Diagnose methods which overload virtual methods in a base class
7449 /// without overriding any.
7450 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7451 if (MD->isInvalidDecl())
7454 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7457 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7458 FindHiddenVirtualMethods(MD, OverloadedMethods);
7459 if (!OverloadedMethods.empty()) {
7460 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7461 << MD << (OverloadedMethods.size() > 1);
7463 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7467 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7469 SourceLocation LBrac,
7470 SourceLocation RBrac,
7471 AttributeList *AttrList) {
7475 AdjustDeclIfTemplate(TagDecl);
7477 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7478 if (l->getKind() != AttributeList::AT_Visibility)
7481 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7485 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7486 // strict aliasing violation!
7487 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7488 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7490 CheckCompletedCXXClass(
7491 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7494 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7495 /// special functions, such as the default constructor, copy
7496 /// constructor, or destructor, to the given C++ class (C++
7497 /// [special]p1). This routine can only be executed just before the
7498 /// definition of the class is complete.
7499 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7500 if (ClassDecl->needsImplicitDefaultConstructor()) {
7501 ++ASTContext::NumImplicitDefaultConstructors;
7503 if (ClassDecl->hasInheritedConstructor())
7504 DeclareImplicitDefaultConstructor(ClassDecl);
7507 if (ClassDecl->needsImplicitCopyConstructor()) {
7508 ++ASTContext::NumImplicitCopyConstructors;
7510 // If the properties or semantics of the copy constructor couldn't be
7511 // determined while the class was being declared, force a declaration
7513 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7514 ClassDecl->hasInheritedConstructor())
7515 DeclareImplicitCopyConstructor(ClassDecl);
7516 // For the MS ABI we need to know whether the copy ctor is deleted. A
7517 // prerequisite for deleting the implicit copy ctor is that the class has a
7518 // move ctor or move assignment that is either user-declared or whose
7519 // semantics are inherited from a subobject. FIXME: We should provide a more
7520 // direct way for CodeGen to ask whether the constructor was deleted.
7521 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7522 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7523 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7524 ClassDecl->hasUserDeclaredMoveAssignment() ||
7525 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7526 DeclareImplicitCopyConstructor(ClassDecl);
7529 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7530 ++ASTContext::NumImplicitMoveConstructors;
7532 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7533 ClassDecl->hasInheritedConstructor())
7534 DeclareImplicitMoveConstructor(ClassDecl);
7537 if (ClassDecl->needsImplicitCopyAssignment()) {
7538 ++ASTContext::NumImplicitCopyAssignmentOperators;
7540 // If we have a dynamic class, then the copy assignment operator may be
7541 // virtual, so we have to declare it immediately. This ensures that, e.g.,
7542 // it shows up in the right place in the vtable and that we diagnose
7543 // problems with the implicit exception specification.
7544 if (ClassDecl->isDynamicClass() ||
7545 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7546 ClassDecl->hasInheritedAssignment())
7547 DeclareImplicitCopyAssignment(ClassDecl);
7550 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7551 ++ASTContext::NumImplicitMoveAssignmentOperators;
7553 // Likewise for the move assignment operator.
7554 if (ClassDecl->isDynamicClass() ||
7555 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7556 ClassDecl->hasInheritedAssignment())
7557 DeclareImplicitMoveAssignment(ClassDecl);
7560 if (ClassDecl->needsImplicitDestructor()) {
7561 ++ASTContext::NumImplicitDestructors;
7563 // If we have a dynamic class, then the destructor may be virtual, so we
7564 // have to declare the destructor immediately. This ensures that, e.g., it
7565 // shows up in the right place in the vtable and that we diagnose problems
7566 // with the implicit exception specification.
7567 if (ClassDecl->isDynamicClass() ||
7568 ClassDecl->needsOverloadResolutionForDestructor())
7569 DeclareImplicitDestructor(ClassDecl);
7573 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7577 // The order of template parameters is not important here. All names
7578 // get added to the same scope.
7579 SmallVector<TemplateParameterList *, 4> ParameterLists;
7581 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7582 D = TD->getTemplatedDecl();
7584 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7585 ParameterLists.push_back(PSD->getTemplateParameters());
7587 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7588 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7589 ParameterLists.push_back(DD->getTemplateParameterList(i));
7591 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7592 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7593 ParameterLists.push_back(FTD->getTemplateParameters());
7597 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7598 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7599 ParameterLists.push_back(TD->getTemplateParameterList(i));
7601 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7602 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7603 ParameterLists.push_back(CTD->getTemplateParameters());
7608 for (TemplateParameterList *Params : ParameterLists) {
7609 if (Params->size() > 0)
7610 // Ignore explicit specializations; they don't contribute to the template
7613 for (NamedDecl *Param : *Params) {
7614 if (Param->getDeclName()) {
7616 IdResolver.AddDecl(Param);
7624 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7625 if (!RecordD) return;
7626 AdjustDeclIfTemplate(RecordD);
7627 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7628 PushDeclContext(S, Record);
7631 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7632 if (!RecordD) return;
7636 /// This is used to implement the constant expression evaluation part of the
7637 /// attribute enable_if extension. There is nothing in standard C++ which would
7638 /// require reentering parameters.
7639 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7644 if (Param->getDeclName())
7645 IdResolver.AddDecl(Param);
7648 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7649 /// parsing a top-level (non-nested) C++ class, and we are now
7650 /// parsing those parts of the given Method declaration that could
7651 /// not be parsed earlier (C++ [class.mem]p2), such as default
7652 /// arguments. This action should enter the scope of the given
7653 /// Method declaration as if we had just parsed the qualified method
7654 /// name. However, it should not bring the parameters into scope;
7655 /// that will be performed by ActOnDelayedCXXMethodParameter.
7656 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7659 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7660 /// C++ method declaration. We're (re-)introducing the given
7661 /// function parameter into scope for use in parsing later parts of
7662 /// the method declaration. For example, we could see an
7663 /// ActOnParamDefaultArgument event for this parameter.
7664 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7668 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7670 // If this parameter has an unparsed default argument, clear it out
7671 // to make way for the parsed default argument.
7672 if (Param->hasUnparsedDefaultArg())
7673 Param->setDefaultArg(nullptr);
7676 if (Param->getDeclName())
7677 IdResolver.AddDecl(Param);
7680 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7681 /// processing the delayed method declaration for Method. The method
7682 /// declaration is now considered finished. There may be a separate
7683 /// ActOnStartOfFunctionDef action later (not necessarily
7684 /// immediately!) for this method, if it was also defined inside the
7686 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7690 AdjustDeclIfTemplate(MethodD);
7692 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7694 // Now that we have our default arguments, check the constructor
7695 // again. It could produce additional diagnostics or affect whether
7696 // the class has implicitly-declared destructors, among other
7698 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7699 CheckConstructor(Constructor);
7701 // Check the default arguments, which we may have added.
7702 if (!Method->isInvalidDecl())
7703 CheckCXXDefaultArguments(Method);
7706 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7707 /// the well-formedness of the constructor declarator @p D with type @p
7708 /// R. If there are any errors in the declarator, this routine will
7709 /// emit diagnostics and set the invalid bit to true. In any case, the type
7710 /// will be updated to reflect a well-formed type for the constructor and
7712 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7714 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7716 // C++ [class.ctor]p3:
7717 // A constructor shall not be virtual (10.3) or static (9.4). A
7718 // constructor can be invoked for a const, volatile or const
7719 // volatile object. A constructor shall not be declared const,
7720 // volatile, or const volatile (9.3.2).
7722 if (!D.isInvalidType())
7723 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7724 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7725 << SourceRange(D.getIdentifierLoc());
7728 if (SC == SC_Static) {
7729 if (!D.isInvalidType())
7730 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7731 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7732 << SourceRange(D.getIdentifierLoc());
7737 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7738 diagnoseIgnoredQualifiers(
7739 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7740 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7741 D.getDeclSpec().getRestrictSpecLoc(),
7742 D.getDeclSpec().getAtomicSpecLoc());
7746 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7747 if (FTI.TypeQuals != 0) {
7748 if (FTI.TypeQuals & Qualifiers::Const)
7749 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7750 << "const" << SourceRange(D.getIdentifierLoc());
7751 if (FTI.TypeQuals & Qualifiers::Volatile)
7752 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7753 << "volatile" << SourceRange(D.getIdentifierLoc());
7754 if (FTI.TypeQuals & Qualifiers::Restrict)
7755 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7756 << "restrict" << SourceRange(D.getIdentifierLoc());
7760 // C++0x [class.ctor]p4:
7761 // A constructor shall not be declared with a ref-qualifier.
7762 if (FTI.hasRefQualifier()) {
7763 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7764 << FTI.RefQualifierIsLValueRef
7765 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7769 // Rebuild the function type "R" without any type qualifiers (in
7770 // case any of the errors above fired) and with "void" as the
7771 // return type, since constructors don't have return types.
7772 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7773 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7776 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7778 EPI.RefQualifier = RQ_None;
7780 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7783 /// CheckConstructor - Checks a fully-formed constructor for
7784 /// well-formedness, issuing any diagnostics required. Returns true if
7785 /// the constructor declarator is invalid.
7786 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7787 CXXRecordDecl *ClassDecl
7788 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7790 return Constructor->setInvalidDecl();
7792 // C++ [class.copy]p3:
7793 // A declaration of a constructor for a class X is ill-formed if
7794 // its first parameter is of type (optionally cv-qualified) X and
7795 // either there are no other parameters or else all other
7796 // parameters have default arguments.
7797 if (!Constructor->isInvalidDecl() &&
7798 ((Constructor->getNumParams() == 1) ||
7799 (Constructor->getNumParams() > 1 &&
7800 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7801 Constructor->getTemplateSpecializationKind()
7802 != TSK_ImplicitInstantiation) {
7803 QualType ParamType = Constructor->getParamDecl(0)->getType();
7804 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7805 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7806 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7807 const char *ConstRef
7808 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7810 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7811 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7813 // FIXME: Rather that making the constructor invalid, we should endeavor
7815 Constructor->setInvalidDecl();
7820 /// CheckDestructor - Checks a fully-formed destructor definition for
7821 /// well-formedness, issuing any diagnostics required. Returns true
7823 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7824 CXXRecordDecl *RD = Destructor->getParent();
7826 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7829 if (!Destructor->isImplicit())
7830 Loc = Destructor->getLocation();
7832 Loc = RD->getLocation();
7834 // If we have a virtual destructor, look up the deallocation function
7835 if (FunctionDecl *OperatorDelete =
7836 FindDeallocationFunctionForDestructor(Loc, RD)) {
7837 MarkFunctionReferenced(Loc, OperatorDelete);
7838 Destructor->setOperatorDelete(OperatorDelete);
7845 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7846 /// the well-formednes of the destructor declarator @p D with type @p
7847 /// R. If there are any errors in the declarator, this routine will
7848 /// emit diagnostics and set the declarator to invalid. Even if this happens,
7849 /// will be updated to reflect a well-formed type for the destructor and
7851 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7853 // C++ [class.dtor]p1:
7854 // [...] A typedef-name that names a class is a class-name
7855 // (7.1.3); however, a typedef-name that names a class shall not
7856 // be used as the identifier in the declarator for a destructor
7858 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7859 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7860 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7861 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7862 else if (const TemplateSpecializationType *TST =
7863 DeclaratorType->getAs<TemplateSpecializationType>())
7864 if (TST->isTypeAlias())
7865 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7866 << DeclaratorType << 1;
7868 // C++ [class.dtor]p2:
7869 // A destructor is used to destroy objects of its class type. A
7870 // destructor takes no parameters, and no return type can be
7871 // specified for it (not even void). The address of a destructor
7872 // shall not be taken. A destructor shall not be static. A
7873 // destructor can be invoked for a const, volatile or const
7874 // volatile object. A destructor shall not be declared const,
7875 // volatile or const volatile (9.3.2).
7876 if (SC == SC_Static) {
7877 if (!D.isInvalidType())
7878 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7879 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7880 << SourceRange(D.getIdentifierLoc())
7881 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7885 if (!D.isInvalidType()) {
7886 // Destructors don't have return types, but the parser will
7887 // happily parse something like:
7893 // The return type will be eliminated later.
7894 if (D.getDeclSpec().hasTypeSpecifier())
7895 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
7896 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7897 << SourceRange(D.getIdentifierLoc());
7898 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7899 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
7901 D.getDeclSpec().getConstSpecLoc(),
7902 D.getDeclSpec().getVolatileSpecLoc(),
7903 D.getDeclSpec().getRestrictSpecLoc(),
7904 D.getDeclSpec().getAtomicSpecLoc());
7909 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7910 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
7911 if (FTI.TypeQuals & Qualifiers::Const)
7912 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7913 << "const" << SourceRange(D.getIdentifierLoc());
7914 if (FTI.TypeQuals & Qualifiers::Volatile)
7915 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7916 << "volatile" << SourceRange(D.getIdentifierLoc());
7917 if (FTI.TypeQuals & Qualifiers::Restrict)
7918 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
7919 << "restrict" << SourceRange(D.getIdentifierLoc());
7923 // C++0x [class.dtor]p2:
7924 // A destructor shall not be declared with a ref-qualifier.
7925 if (FTI.hasRefQualifier()) {
7926 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
7927 << FTI.RefQualifierIsLValueRef
7928 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7932 // Make sure we don't have any parameters.
7933 if (FTIHasNonVoidParameters(FTI)) {
7934 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
7936 // Delete the parameters.
7941 // Make sure the destructor isn't variadic.
7942 if (FTI.isVariadic) {
7943 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
7947 // Rebuild the function type "R" without any type qualifiers or
7948 // parameters (in case any of the errors above fired) and with
7949 // "void" as the return type, since destructors don't have return
7951 if (!D.isInvalidType())
7954 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7955 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7956 EPI.Variadic = false;
7958 EPI.RefQualifier = RQ_None;
7959 return Context.getFunctionType(Context.VoidTy, None, EPI);
7962 static void extendLeft(SourceRange &R, SourceRange Before) {
7963 if (Before.isInvalid())
7965 R.setBegin(Before.getBegin());
7966 if (R.getEnd().isInvalid())
7967 R.setEnd(Before.getEnd());
7970 static void extendRight(SourceRange &R, SourceRange After) {
7971 if (After.isInvalid())
7973 if (R.getBegin().isInvalid())
7974 R.setBegin(After.getBegin());
7975 R.setEnd(After.getEnd());
7978 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
7979 /// well-formednes of the conversion function declarator @p D with
7980 /// type @p R. If there are any errors in the declarator, this routine
7981 /// will emit diagnostics and return true. Otherwise, it will return
7982 /// false. Either way, the type @p R will be updated to reflect a
7983 /// well-formed type for the conversion operator.
7984 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
7986 // C++ [class.conv.fct]p1:
7987 // Neither parameter types nor return type can be specified. The
7988 // type of a conversion function (8.3.5) is "function taking no
7989 // parameter returning conversion-type-id."
7990 if (SC == SC_Static) {
7991 if (!D.isInvalidType())
7992 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
7993 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7994 << D.getName().getSourceRange();
7999 TypeSourceInfo *ConvTSI = nullptr;
8001 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8003 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
8004 // Conversion functions don't have return types, but the parser will
8005 // happily parse something like:
8008 // float operator bool();
8011 // The return type will be changed later anyway.
8012 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8013 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8014 << SourceRange(D.getIdentifierLoc());
8018 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8020 // Make sure we don't have any parameters.
8021 if (Proto->getNumParams() > 0) {
8022 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8024 // Delete the parameters.
8025 D.getFunctionTypeInfo().freeParams();
8027 } else if (Proto->isVariadic()) {
8028 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8032 // Diagnose "&operator bool()" and other such nonsense. This
8033 // is actually a gcc extension which we don't support.
8034 if (Proto->getReturnType() != ConvType) {
8035 bool NeedsTypedef = false;
8036 SourceRange Before, After;
8038 // Walk the chunks and extract information on them for our diagnostic.
8039 bool PastFunctionChunk = false;
8040 for (auto &Chunk : D.type_objects()) {
8041 switch (Chunk.Kind) {
8042 case DeclaratorChunk::Function:
8043 if (!PastFunctionChunk) {
8044 if (Chunk.Fun.HasTrailingReturnType) {
8045 TypeSourceInfo *TRT = nullptr;
8046 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8047 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8049 PastFunctionChunk = true;
8053 case DeclaratorChunk::Array:
8054 NeedsTypedef = true;
8055 extendRight(After, Chunk.getSourceRange());
8058 case DeclaratorChunk::Pointer:
8059 case DeclaratorChunk::BlockPointer:
8060 case DeclaratorChunk::Reference:
8061 case DeclaratorChunk::MemberPointer:
8062 case DeclaratorChunk::Pipe:
8063 extendLeft(Before, Chunk.getSourceRange());
8066 case DeclaratorChunk::Paren:
8067 extendLeft(Before, Chunk.Loc);
8068 extendRight(After, Chunk.EndLoc);
8073 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8074 After.isValid() ? After.getBegin() :
8075 D.getIdentifierLoc();
8076 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8077 DB << Before << After;
8079 if (!NeedsTypedef) {
8080 DB << /*don't need a typedef*/0;
8082 // If we can provide a correct fix-it hint, do so.
8083 if (After.isInvalid() && ConvTSI) {
8084 SourceLocation InsertLoc =
8085 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8086 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8087 << FixItHint::CreateInsertionFromRange(
8088 InsertLoc, CharSourceRange::getTokenRange(Before))
8089 << FixItHint::CreateRemoval(Before);
8091 } else if (!Proto->getReturnType()->isDependentType()) {
8092 DB << /*typedef*/1 << Proto->getReturnType();
8093 } else if (getLangOpts().CPlusPlus11) {
8094 DB << /*alias template*/2 << Proto->getReturnType();
8096 DB << /*might not be fixable*/3;
8099 // Recover by incorporating the other type chunks into the result type.
8100 // Note, this does *not* change the name of the function. This is compatible
8101 // with the GCC extension:
8102 // struct S { &operator int(); } s;
8103 // int &r = s.operator int(); // ok in GCC
8104 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8105 ConvType = Proto->getReturnType();
8108 // C++ [class.conv.fct]p4:
8109 // The conversion-type-id shall not represent a function type nor
8111 if (ConvType->isArrayType()) {
8112 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8113 ConvType = Context.getPointerType(ConvType);
8115 } else if (ConvType->isFunctionType()) {
8116 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8117 ConvType = Context.getPointerType(ConvType);
8121 // Rebuild the function type "R" without any parameters (in case any
8122 // of the errors above fired) and with the conversion type as the
8124 if (D.isInvalidType())
8125 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8127 // C++0x explicit conversion operators.
8128 if (D.getDeclSpec().isExplicitSpecified())
8129 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8130 getLangOpts().CPlusPlus11 ?
8131 diag::warn_cxx98_compat_explicit_conversion_functions :
8132 diag::ext_explicit_conversion_functions)
8133 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8136 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8137 /// the declaration of the given C++ conversion function. This routine
8138 /// is responsible for recording the conversion function in the C++
8139 /// class, if possible.
8140 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8141 assert(Conversion && "Expected to receive a conversion function declaration");
8143 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8145 // Make sure we aren't redeclaring the conversion function.
8146 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8148 // C++ [class.conv.fct]p1:
8149 // [...] A conversion function is never used to convert a
8150 // (possibly cv-qualified) object to the (possibly cv-qualified)
8151 // same object type (or a reference to it), to a (possibly
8152 // cv-qualified) base class of that type (or a reference to it),
8153 // or to (possibly cv-qualified) void.
8154 // FIXME: Suppress this warning if the conversion function ends up being a
8155 // virtual function that overrides a virtual function in a base class.
8157 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8158 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8159 ConvType = ConvTypeRef->getPointeeType();
8160 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8161 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8162 /* Suppress diagnostics for instantiations. */;
8163 else if (ConvType->isRecordType()) {
8164 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8165 if (ConvType == ClassType)
8166 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8168 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8169 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8170 << ClassType << ConvType;
8171 } else if (ConvType->isVoidType()) {
8172 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8173 << ClassType << ConvType;
8176 if (FunctionTemplateDecl *ConversionTemplate
8177 = Conversion->getDescribedFunctionTemplate())
8178 return ConversionTemplate;
8184 /// Utility class to accumulate and print a diagnostic listing the invalid
8185 /// specifier(s) on a declaration.
8186 struct BadSpecifierDiagnoser {
8187 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8188 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8189 ~BadSpecifierDiagnoser() {
8190 Diagnostic << Specifiers;
8193 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8194 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8196 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8197 return check(SpecLoc,
8198 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8200 void check(SourceLocation SpecLoc, const char *Spec) {
8201 if (SpecLoc.isInvalid()) return;
8202 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8203 if (!Specifiers.empty()) Specifiers += " ";
8208 Sema::SemaDiagnosticBuilder Diagnostic;
8209 std::string Specifiers;
8213 /// Check the validity of a declarator that we parsed for a deduction-guide.
8214 /// These aren't actually declarators in the grammar, so we need to check that
8215 /// the user didn't specify any pieces that are not part of the deduction-guide
8217 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8219 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8220 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8221 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8223 // C++ [temp.deduct.guide]p3:
8224 // A deduction-gide shall be declared in the same scope as the
8225 // corresponding class template.
8226 if (!CurContext->getRedeclContext()->Equals(
8227 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8228 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8229 << GuidedTemplateDecl;
8230 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8233 auto &DS = D.getMutableDeclSpec();
8234 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8235 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8236 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8237 DS.isNoreturnSpecified() || DS.isConstexprSpecified() ||
8238 DS.isConceptSpecified()) {
8239 BadSpecifierDiagnoser Diagnoser(
8240 *this, D.getIdentifierLoc(),
8241 diag::err_deduction_guide_invalid_specifier);
8243 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8244 DS.ClearStorageClassSpecs();
8247 // 'explicit' is permitted.
8248 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8249 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8250 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8251 Diagnoser.check(DS.getConceptSpecLoc(), "concept");
8252 DS.ClearConstexprSpec();
8253 DS.ClearConceptSpec();
8255 Diagnoser.check(DS.getConstSpecLoc(), "const");
8256 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8257 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8258 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8259 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8260 DS.ClearTypeQualifiers();
8262 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8263 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8264 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8265 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8266 DS.ClearTypeSpecType();
8269 if (D.isInvalidType())
8272 // Check the declarator is simple enough.
8273 bool FoundFunction = false;
8274 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8275 if (Chunk.Kind == DeclaratorChunk::Paren)
8277 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8278 Diag(D.getDeclSpec().getLocStart(),
8279 diag::err_deduction_guide_with_complex_decl)
8280 << D.getSourceRange();
8283 if (!Chunk.Fun.hasTrailingReturnType()) {
8284 Diag(D.getName().getLocStart(),
8285 diag::err_deduction_guide_no_trailing_return_type);
8289 // Check that the return type is written as a specialization of
8290 // the template specified as the deduction-guide's name.
8291 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8292 TypeSourceInfo *TSI = nullptr;
8293 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8294 assert(TSI && "deduction guide has valid type but invalid return type?");
8295 bool AcceptableReturnType = false;
8296 bool MightInstantiateToSpecialization = false;
8298 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8299 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8300 bool TemplateMatches =
8301 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8302 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8303 AcceptableReturnType = true;
8305 // This could still instantiate to the right type, unless we know it
8306 // names the wrong class template.
8307 auto *TD = SpecifiedName.getAsTemplateDecl();
8308 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8311 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8312 MightInstantiateToSpecialization = true;
8315 if (!AcceptableReturnType) {
8316 Diag(TSI->getTypeLoc().getLocStart(),
8317 diag::err_deduction_guide_bad_trailing_return_type)
8318 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8319 << TSI->getTypeLoc().getSourceRange();
8322 // Keep going to check that we don't have any inner declarator pieces (we
8323 // could still have a function returning a pointer to a function).
8324 FoundFunction = true;
8327 if (D.isFunctionDefinition())
8328 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8331 //===----------------------------------------------------------------------===//
8332 // Namespace Handling
8333 //===----------------------------------------------------------------------===//
8335 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8337 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8339 IdentifierInfo *II, bool *IsInline,
8340 NamespaceDecl *PrevNS) {
8341 assert(*IsInline != PrevNS->isInline());
8343 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8344 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8345 // inline namespaces, with the intention of bringing names into namespace std.
8347 // We support this just well enough to get that case working; this is not
8348 // sufficient to support reopening namespaces as inline in general.
8349 if (*IsInline && II && II->getName().startswith("__atomic") &&
8350 S.getSourceManager().isInSystemHeader(Loc)) {
8351 // Mark all prior declarations of the namespace as inline.
8352 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8353 NS = NS->getPreviousDecl())
8354 NS->setInline(*IsInline);
8355 // Patch up the lookup table for the containing namespace. This isn't really
8356 // correct, but it's good enough for this particular case.
8357 for (auto *I : PrevNS->decls())
8358 if (auto *ND = dyn_cast<NamedDecl>(I))
8359 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8363 if (PrevNS->isInline())
8364 // The user probably just forgot the 'inline', so suggest that it
8366 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8367 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8369 S.Diag(Loc, diag::err_inline_namespace_mismatch);
8371 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8372 *IsInline = PrevNS->isInline();
8375 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8377 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8378 SourceLocation InlineLoc,
8379 SourceLocation NamespaceLoc,
8380 SourceLocation IdentLoc,
8382 SourceLocation LBrace,
8383 AttributeList *AttrList,
8384 UsingDirectiveDecl *&UD) {
8385 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8386 // For anonymous namespace, take the location of the left brace.
8387 SourceLocation Loc = II ? IdentLoc : LBrace;
8388 bool IsInline = InlineLoc.isValid();
8389 bool IsInvalid = false;
8391 bool AddToKnown = false;
8392 Scope *DeclRegionScope = NamespcScope->getParent();
8394 NamespaceDecl *PrevNS = nullptr;
8396 // C++ [namespace.def]p2:
8397 // The identifier in an original-namespace-definition shall not
8398 // have been previously defined in the declarative region in
8399 // which the original-namespace-definition appears. The
8400 // identifier in an original-namespace-definition is the name of
8401 // the namespace. Subsequently in that declarative region, it is
8402 // treated as an original-namespace-name.
8404 // Since namespace names are unique in their scope, and we don't
8405 // look through using directives, just look for any ordinary names
8406 // as if by qualified name lookup.
8407 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, ForRedeclaration);
8408 LookupQualifiedName(R, CurContext->getRedeclContext());
8409 NamedDecl *PrevDecl =
8410 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8411 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8414 // This is an extended namespace definition.
8415 if (IsInline != PrevNS->isInline())
8416 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8418 } else if (PrevDecl) {
8419 // This is an invalid name redefinition.
8420 Diag(Loc, diag::err_redefinition_different_kind)
8422 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8424 // Continue on to push Namespc as current DeclContext and return it.
8425 } else if (II->isStr("std") &&
8426 CurContext->getRedeclContext()->isTranslationUnit()) {
8427 // This is the first "real" definition of the namespace "std", so update
8428 // our cache of the "std" namespace to point at this definition.
8429 PrevNS = getStdNamespace();
8431 AddToKnown = !IsInline;
8433 // We've seen this namespace for the first time.
8434 AddToKnown = !IsInline;
8437 // Anonymous namespaces.
8439 // Determine whether the parent already has an anonymous namespace.
8440 DeclContext *Parent = CurContext->getRedeclContext();
8441 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8442 PrevNS = TU->getAnonymousNamespace();
8444 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8445 PrevNS = ND->getAnonymousNamespace();
8448 if (PrevNS && IsInline != PrevNS->isInline())
8449 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8453 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8454 StartLoc, Loc, II, PrevNS);
8456 Namespc->setInvalidDecl();
8458 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8459 AddPragmaAttributes(DeclRegionScope, Namespc);
8461 // FIXME: Should we be merging attributes?
8462 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8463 PushNamespaceVisibilityAttr(Attr, Loc);
8466 StdNamespace = Namespc;
8468 KnownNamespaces[Namespc] = false;
8471 PushOnScopeChains(Namespc, DeclRegionScope);
8473 // Link the anonymous namespace into its parent.
8474 DeclContext *Parent = CurContext->getRedeclContext();
8475 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8476 TU->setAnonymousNamespace(Namespc);
8478 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8481 CurContext->addDecl(Namespc);
8483 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8484 // behaves as if it were replaced by
8485 // namespace unique { /* empty body */ }
8486 // using namespace unique;
8487 // namespace unique { namespace-body }
8488 // where all occurrences of 'unique' in a translation unit are
8489 // replaced by the same identifier and this identifier differs
8490 // from all other identifiers in the entire program.
8492 // We just create the namespace with an empty name and then add an
8493 // implicit using declaration, just like the standard suggests.
8495 // CodeGen enforces the "universally unique" aspect by giving all
8496 // declarations semantically contained within an anonymous
8497 // namespace internal linkage.
8500 UD = UsingDirectiveDecl::Create(Context, Parent,
8501 /* 'using' */ LBrace,
8502 /* 'namespace' */ SourceLocation(),
8503 /* qualifier */ NestedNameSpecifierLoc(),
8504 /* identifier */ SourceLocation(),
8506 /* Ancestor */ Parent);
8508 Parent->addDecl(UD);
8512 ActOnDocumentableDecl(Namespc);
8514 // Although we could have an invalid decl (i.e. the namespace name is a
8515 // redefinition), push it as current DeclContext and try to continue parsing.
8516 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8517 // for the namespace has the declarations that showed up in that particular
8518 // namespace definition.
8519 PushDeclContext(NamespcScope, Namespc);
8523 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8524 /// is a namespace alias, returns the namespace it points to.
8525 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8526 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8527 return AD->getNamespace();
8528 return dyn_cast_or_null<NamespaceDecl>(D);
8531 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8532 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8533 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8534 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8535 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8536 Namespc->setRBraceLoc(RBrace);
8538 if (Namespc->hasAttr<VisibilityAttr>())
8539 PopPragmaVisibility(true, RBrace);
8542 CXXRecordDecl *Sema::getStdBadAlloc() const {
8543 return cast_or_null<CXXRecordDecl>(
8544 StdBadAlloc.get(Context.getExternalSource()));
8547 EnumDecl *Sema::getStdAlignValT() const {
8548 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8551 NamespaceDecl *Sema::getStdNamespace() const {
8552 return cast_or_null<NamespaceDecl>(
8553 StdNamespace.get(Context.getExternalSource()));
8556 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8557 if (!StdExperimentalNamespaceCache) {
8558 if (auto Std = getStdNamespace()) {
8559 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8560 SourceLocation(), LookupNamespaceName);
8561 if (!LookupQualifiedName(Result, Std) ||
8562 !(StdExperimentalNamespaceCache =
8563 Result.getAsSingle<NamespaceDecl>()))
8564 Result.suppressDiagnostics();
8567 return StdExperimentalNamespaceCache;
8570 /// \brief Retrieve the special "std" namespace, which may require us to
8571 /// implicitly define the namespace.
8572 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8573 if (!StdNamespace) {
8574 // The "std" namespace has not yet been defined, so build one implicitly.
8575 StdNamespace = NamespaceDecl::Create(Context,
8576 Context.getTranslationUnitDecl(),
8578 SourceLocation(), SourceLocation(),
8579 &PP.getIdentifierTable().get("std"),
8580 /*PrevDecl=*/nullptr);
8581 getStdNamespace()->setImplicit(true);
8584 return getStdNamespace();
8587 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8588 assert(getLangOpts().CPlusPlus &&
8589 "Looking for std::initializer_list outside of C++.");
8591 // We're looking for implicit instantiations of
8592 // template <typename E> class std::initializer_list.
8594 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8597 ClassTemplateDecl *Template = nullptr;
8598 const TemplateArgument *Arguments = nullptr;
8600 if (const RecordType *RT = Ty->getAs<RecordType>()) {
8602 ClassTemplateSpecializationDecl *Specialization =
8603 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8604 if (!Specialization)
8607 Template = Specialization->getSpecializedTemplate();
8608 Arguments = Specialization->getTemplateArgs().data();
8609 } else if (const TemplateSpecializationType *TST =
8610 Ty->getAs<TemplateSpecializationType>()) {
8611 Template = dyn_cast_or_null<ClassTemplateDecl>(
8612 TST->getTemplateName().getAsTemplateDecl());
8613 Arguments = TST->getArgs();
8618 if (!StdInitializerList) {
8619 // Haven't recognized std::initializer_list yet, maybe this is it.
8620 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8621 if (TemplateClass->getIdentifier() !=
8622 &PP.getIdentifierTable().get("initializer_list") ||
8623 !getStdNamespace()->InEnclosingNamespaceSetOf(
8624 TemplateClass->getDeclContext()))
8626 // This is a template called std::initializer_list, but is it the right
8628 TemplateParameterList *Params = Template->getTemplateParameters();
8629 if (Params->getMinRequiredArguments() != 1)
8631 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8634 // It's the right template.
8635 StdInitializerList = Template;
8638 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8641 // This is an instance of std::initializer_list. Find the argument type.
8643 *Element = Arguments[0].getAsType();
8647 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8648 NamespaceDecl *Std = S.getStdNamespace();
8650 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8654 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8655 Loc, Sema::LookupOrdinaryName);
8656 if (!S.LookupQualifiedName(Result, Std)) {
8657 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8660 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8662 Result.suppressDiagnostics();
8663 // We found something weird. Complain about the first thing we found.
8664 NamedDecl *Found = *Result.begin();
8665 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8669 // We found some template called std::initializer_list. Now verify that it's
8671 TemplateParameterList *Params = Template->getTemplateParameters();
8672 if (Params->getMinRequiredArguments() != 1 ||
8673 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8674 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8681 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8682 if (!StdInitializerList) {
8683 StdInitializerList = LookupStdInitializerList(*this, Loc);
8684 if (!StdInitializerList)
8688 TemplateArgumentListInfo Args(Loc, Loc);
8689 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8690 Context.getTrivialTypeSourceInfo(Element,
8692 return Context.getCanonicalType(
8693 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8696 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
8697 // C++ [dcl.init.list]p2:
8698 // A constructor is an initializer-list constructor if its first parameter
8699 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8700 // std::initializer_list<E> for some type E, and either there are no other
8701 // parameters or else all other parameters have default arguments.
8702 if (Ctor->getNumParams() < 1 ||
8703 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8706 QualType ArgType = Ctor->getParamDecl(0)->getType();
8707 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8708 ArgType = RT->getPointeeType().getUnqualifiedType();
8710 return isStdInitializerList(ArgType, nullptr);
8713 /// \brief Determine whether a using statement is in a context where it will be
8714 /// apply in all contexts.
8715 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8716 switch (CurContext->getDeclKind()) {
8717 case Decl::TranslationUnit:
8719 case Decl::LinkageSpec:
8720 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8728 // Callback to only accept typo corrections that are namespaces.
8729 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8731 bool ValidateCandidate(const TypoCorrection &candidate) override {
8732 if (NamedDecl *ND = candidate.getCorrectionDecl())
8733 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8740 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8742 SourceLocation IdentLoc,
8743 IdentifierInfo *Ident) {
8745 if (TypoCorrection Corrected =
8746 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8747 llvm::make_unique<NamespaceValidatorCCC>(),
8748 Sema::CTK_ErrorRecovery)) {
8749 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8750 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8751 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8752 Ident->getName().equals(CorrectedStr);
8753 S.diagnoseTypo(Corrected,
8754 S.PDiag(diag::err_using_directive_member_suggest)
8755 << Ident << DC << DroppedSpecifier << SS.getRange(),
8756 S.PDiag(diag::note_namespace_defined_here));
8758 S.diagnoseTypo(Corrected,
8759 S.PDiag(diag::err_using_directive_suggest) << Ident,
8760 S.PDiag(diag::note_namespace_defined_here));
8762 R.addDecl(Corrected.getFoundDecl());
8768 Decl *Sema::ActOnUsingDirective(Scope *S,
8769 SourceLocation UsingLoc,
8770 SourceLocation NamespcLoc,
8772 SourceLocation IdentLoc,
8773 IdentifierInfo *NamespcName,
8774 AttributeList *AttrList) {
8775 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8776 assert(NamespcName && "Invalid NamespcName.");
8777 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8779 // This can only happen along a recovery path.
8780 while (S->isTemplateParamScope())
8782 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8784 UsingDirectiveDecl *UDir = nullptr;
8785 NestedNameSpecifier *Qualifier = nullptr;
8787 Qualifier = SS.getScopeRep();
8789 // Lookup namespace name.
8790 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8791 LookupParsedName(R, S, &SS);
8792 if (R.isAmbiguous())
8797 // Allow "using namespace std;" or "using namespace ::std;" even if
8798 // "std" hasn't been defined yet, for GCC compatibility.
8799 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8800 NamespcName->isStr("std")) {
8801 Diag(IdentLoc, diag::ext_using_undefined_std);
8802 R.addDecl(getOrCreateStdNamespace());
8805 // Otherwise, attempt typo correction.
8806 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8810 NamedDecl *Named = R.getRepresentativeDecl();
8811 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8812 assert(NS && "expected namespace decl");
8814 // The use of a nested name specifier may trigger deprecation warnings.
8815 DiagnoseUseOfDecl(Named, IdentLoc);
8817 // C++ [namespace.udir]p1:
8818 // A using-directive specifies that the names in the nominated
8819 // namespace can be used in the scope in which the
8820 // using-directive appears after the using-directive. During
8821 // unqualified name lookup (3.4.1), the names appear as if they
8822 // were declared in the nearest enclosing namespace which
8823 // contains both the using-directive and the nominated
8824 // namespace. [Note: in this context, "contains" means "contains
8825 // directly or indirectly". ]
8827 // Find enclosing context containing both using-directive and
8828 // nominated namespace.
8829 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8830 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8831 CommonAncestor = CommonAncestor->getParent();
8833 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8834 SS.getWithLocInContext(Context),
8835 IdentLoc, Named, CommonAncestor);
8837 if (IsUsingDirectiveInToplevelContext(CurContext) &&
8838 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8839 Diag(IdentLoc, diag::warn_using_directive_in_header);
8842 PushUsingDirective(S, UDir);
8844 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8848 ProcessDeclAttributeList(S, UDir, AttrList);
8853 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8854 // If the scope has an associated entity and the using directive is at
8855 // namespace or translation unit scope, add the UsingDirectiveDecl into
8856 // its lookup structure so qualified name lookup can find it.
8857 DeclContext *Ctx = S->getEntity();
8858 if (Ctx && !Ctx->isFunctionOrMethod())
8861 // Otherwise, it is at block scope. The using-directives will affect lookup
8862 // only to the end of the scope.
8863 S->PushUsingDirective(UDir);
8867 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8869 SourceLocation UsingLoc,
8870 SourceLocation TypenameLoc,
8872 UnqualifiedId &Name,
8873 SourceLocation EllipsisLoc,
8874 AttributeList *AttrList) {
8875 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8878 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8882 switch (Name.getKind()) {
8883 case UnqualifiedId::IK_ImplicitSelfParam:
8884 case UnqualifiedId::IK_Identifier:
8885 case UnqualifiedId::IK_OperatorFunctionId:
8886 case UnqualifiedId::IK_LiteralOperatorId:
8887 case UnqualifiedId::IK_ConversionFunctionId:
8890 case UnqualifiedId::IK_ConstructorName:
8891 case UnqualifiedId::IK_ConstructorTemplateId:
8892 // C++11 inheriting constructors.
8893 Diag(Name.getLocStart(),
8894 getLangOpts().CPlusPlus11 ?
8895 diag::warn_cxx98_compat_using_decl_constructor :
8896 diag::err_using_decl_constructor)
8899 if (getLangOpts().CPlusPlus11) break;
8903 case UnqualifiedId::IK_DestructorName:
8904 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
8908 case UnqualifiedId::IK_TemplateId:
8909 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
8910 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
8913 case UnqualifiedId::IK_DeductionGuideName:
8914 llvm_unreachable("cannot parse qualified deduction guide name");
8917 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8918 DeclarationName TargetName = TargetNameInfo.getName();
8922 // Warn about access declarations.
8923 if (UsingLoc.isInvalid()) {
8924 Diag(Name.getLocStart(),
8925 getLangOpts().CPlusPlus11 ? diag::err_access_decl
8926 : diag::warn_access_decl_deprecated)
8927 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
8930 if (EllipsisLoc.isInvalid()) {
8931 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
8932 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
8935 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
8936 !TargetNameInfo.containsUnexpandedParameterPack()) {
8937 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
8938 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
8939 EllipsisLoc = SourceLocation();
8944 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
8945 SS, TargetNameInfo, EllipsisLoc, AttrList,
8946 /*IsInstantiation*/false);
8948 PushOnScopeChains(UD, S, /*AddToContext*/ false);
8953 /// \brief Determine whether a using declaration considers the given
8954 /// declarations as "equivalent", e.g., if they are redeclarations of
8955 /// the same entity or are both typedefs of the same type.
8957 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
8958 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
8961 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
8962 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
8963 return Context.hasSameType(TD1->getUnderlyingType(),
8964 TD2->getUnderlyingType());
8970 /// Determines whether to create a using shadow decl for a particular
8971 /// decl, given the set of decls existing prior to this using lookup.
8972 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
8973 const LookupResult &Previous,
8974 UsingShadowDecl *&PrevShadow) {
8975 // Diagnose finding a decl which is not from a base class of the
8976 // current class. We do this now because there are cases where this
8977 // function will silently decide not to build a shadow decl, which
8978 // will pre-empt further diagnostics.
8980 // We don't need to do this in C++11 because we do the check once on
8983 // FIXME: diagnose the following if we care enough:
8984 // struct A { int foo; };
8985 // struct B : A { using A::foo; };
8986 // template <class T> struct C : A {};
8987 // template <class T> struct D : C<T> { using B::foo; } // <---
8988 // This is invalid (during instantiation) in C++03 because B::foo
8989 // resolves to the using decl in B, which is not a base class of D<T>.
8990 // We can't diagnose it immediately because C<T> is an unknown
8991 // specialization. The UsingShadowDecl in D<T> then points directly
8992 // to A::foo, which will look well-formed when we instantiate.
8993 // The right solution is to not collapse the shadow-decl chain.
8994 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
8995 DeclContext *OrigDC = Orig->getDeclContext();
8997 // Handle enums and anonymous structs.
8998 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
8999 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9000 while (OrigRec->isAnonymousStructOrUnion())
9001 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9003 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9004 if (OrigDC == CurContext) {
9005 Diag(Using->getLocation(),
9006 diag::err_using_decl_nested_name_specifier_is_current_class)
9007 << Using->getQualifierLoc().getSourceRange();
9008 Diag(Orig->getLocation(), diag::note_using_decl_target);
9009 Using->setInvalidDecl();
9013 Diag(Using->getQualifierLoc().getBeginLoc(),
9014 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9015 << Using->getQualifier()
9016 << cast<CXXRecordDecl>(CurContext)
9017 << Using->getQualifierLoc().getSourceRange();
9018 Diag(Orig->getLocation(), diag::note_using_decl_target);
9019 Using->setInvalidDecl();
9024 if (Previous.empty()) return false;
9026 NamedDecl *Target = Orig;
9027 if (isa<UsingShadowDecl>(Target))
9028 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9030 // If the target happens to be one of the previous declarations, we
9031 // don't have a conflict.
9033 // FIXME: but we might be increasing its access, in which case we
9034 // should redeclare it.
9035 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9036 bool FoundEquivalentDecl = false;
9037 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9039 NamedDecl *D = (*I)->getUnderlyingDecl();
9040 // We can have UsingDecls in our Previous results because we use the same
9041 // LookupResult for checking whether the UsingDecl itself is a valid
9043 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9046 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9047 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9048 PrevShadow = Shadow;
9049 FoundEquivalentDecl = true;
9050 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9051 // We don't conflict with an existing using shadow decl of an equivalent
9052 // declaration, but we're not a redeclaration of it.
9053 FoundEquivalentDecl = true;
9057 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9060 if (FoundEquivalentDecl)
9063 if (FunctionDecl *FD = Target->getAsFunction()) {
9064 NamedDecl *OldDecl = nullptr;
9065 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9066 /*IsForUsingDecl*/ true)) {
9070 case Ovl_NonFunction:
9071 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9074 // We found a decl with the exact signature.
9076 // If we're in a record, we want to hide the target, so we
9077 // return true (without a diagnostic) to tell the caller not to
9078 // build a shadow decl.
9079 if (CurContext->isRecord())
9082 // If we're not in a record, this is an error.
9083 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9087 Diag(Target->getLocation(), diag::note_using_decl_target);
9088 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9089 Using->setInvalidDecl();
9093 // Target is not a function.
9095 if (isa<TagDecl>(Target)) {
9096 // No conflict between a tag and a non-tag.
9097 if (!Tag) return false;
9099 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9100 Diag(Target->getLocation(), diag::note_using_decl_target);
9101 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9102 Using->setInvalidDecl();
9106 // No conflict between a tag and a non-tag.
9107 if (!NonTag) return false;
9109 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9110 Diag(Target->getLocation(), diag::note_using_decl_target);
9111 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9112 Using->setInvalidDecl();
9116 /// Determine whether a direct base class is a virtual base class.
9117 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9118 if (!Derived->getNumVBases())
9120 for (auto &B : Derived->bases())
9121 if (B.getType()->getAsCXXRecordDecl() == Base)
9122 return B.isVirtual();
9123 llvm_unreachable("not a direct base class");
9126 /// Builds a shadow declaration corresponding to a 'using' declaration.
9127 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9130 UsingShadowDecl *PrevDecl) {
9131 // If we resolved to another shadow declaration, just coalesce them.
9132 NamedDecl *Target = Orig;
9133 if (isa<UsingShadowDecl>(Target)) {
9134 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9135 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9138 NamedDecl *NonTemplateTarget = Target;
9139 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9140 NonTemplateTarget = TargetTD->getTemplatedDecl();
9142 UsingShadowDecl *Shadow;
9143 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9144 bool IsVirtualBase =
9145 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9146 UD->getQualifier()->getAsRecordDecl());
9147 Shadow = ConstructorUsingShadowDecl::Create(
9148 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9150 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9153 UD->addShadowDecl(Shadow);
9155 Shadow->setAccess(UD->getAccess());
9156 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9157 Shadow->setInvalidDecl();
9159 Shadow->setPreviousDecl(PrevDecl);
9162 PushOnScopeChains(Shadow, S);
9164 CurContext->addDecl(Shadow);
9170 /// Hides a using shadow declaration. This is required by the current
9171 /// using-decl implementation when a resolvable using declaration in a
9172 /// class is followed by a declaration which would hide or override
9173 /// one or more of the using decl's targets; for example:
9175 /// struct Base { void foo(int); };
9176 /// struct Derived : Base {
9177 /// using Base::foo;
9181 /// The governing language is C++03 [namespace.udecl]p12:
9183 /// When a using-declaration brings names from a base class into a
9184 /// derived class scope, member functions in the derived class
9185 /// override and/or hide member functions with the same name and
9186 /// parameter types in a base class (rather than conflicting).
9188 /// There are two ways to implement this:
9189 /// (1) optimistically create shadow decls when they're not hidden
9190 /// by existing declarations, or
9191 /// (2) don't create any shadow decls (or at least don't make them
9192 /// visible) until we've fully parsed/instantiated the class.
9193 /// The problem with (1) is that we might have to retroactively remove
9194 /// a shadow decl, which requires several O(n) operations because the
9195 /// decl structures are (very reasonably) not designed for removal.
9196 /// (2) avoids this but is very fiddly and phase-dependent.
9197 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9198 if (Shadow->getDeclName().getNameKind() ==
9199 DeclarationName::CXXConversionFunctionName)
9200 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9202 // Remove it from the DeclContext...
9203 Shadow->getDeclContext()->removeDecl(Shadow);
9205 // ...and the scope, if applicable...
9207 S->RemoveDecl(Shadow);
9208 IdResolver.RemoveDecl(Shadow);
9211 // ...and the using decl.
9212 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9214 // TODO: complain somehow if Shadow was used. It shouldn't
9215 // be possible for this to happen, because...?
9218 /// Find the base specifier for a base class with the given type.
9219 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9220 QualType DesiredBase,
9221 bool &AnyDependentBases) {
9222 // Check whether the named type is a direct base class.
9223 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9224 for (auto &Base : Derived->bases()) {
9225 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9226 if (CanonicalDesiredBase == BaseType)
9228 if (BaseType->isDependentType())
9229 AnyDependentBases = true;
9235 class UsingValidatorCCC : public CorrectionCandidateCallback {
9237 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9238 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9239 : HasTypenameKeyword(HasTypenameKeyword),
9240 IsInstantiation(IsInstantiation), OldNNS(NNS),
9241 RequireMemberOf(RequireMemberOf) {}
9243 bool ValidateCandidate(const TypoCorrection &Candidate) override {
9244 NamedDecl *ND = Candidate.getCorrectionDecl();
9246 // Keywords are not valid here.
9247 if (!ND || isa<NamespaceDecl>(ND))
9250 // Completely unqualified names are invalid for a 'using' declaration.
9251 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9254 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9257 if (RequireMemberOf) {
9258 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9259 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9260 // No-one ever wants a using-declaration to name an injected-class-name
9261 // of a base class, unless they're declaring an inheriting constructor.
9262 ASTContext &Ctx = ND->getASTContext();
9263 if (!Ctx.getLangOpts().CPlusPlus11)
9265 QualType FoundType = Ctx.getRecordType(FoundRecord);
9267 // Check that the injected-class-name is named as a member of its own
9268 // type; we don't want to suggest 'using Derived::Base;', since that
9269 // means something else.
9270 NestedNameSpecifier *Specifier =
9271 Candidate.WillReplaceSpecifier()
9272 ? Candidate.getCorrectionSpecifier()
9274 if (!Specifier->getAsType() ||
9275 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9278 // Check that this inheriting constructor declaration actually names a
9279 // direct base class of the current class.
9280 bool AnyDependentBases = false;
9281 if (!findDirectBaseWithType(RequireMemberOf,
9282 Ctx.getRecordType(FoundRecord),
9283 AnyDependentBases) &&
9287 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9288 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9291 // FIXME: Check that the base class member is accessible?
9294 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9295 if (FoundRecord && FoundRecord->isInjectedClassName())
9299 if (isa<TypeDecl>(ND))
9300 return HasTypenameKeyword || !IsInstantiation;
9302 return !HasTypenameKeyword;
9306 bool HasTypenameKeyword;
9307 bool IsInstantiation;
9308 NestedNameSpecifier *OldNNS;
9309 CXXRecordDecl *RequireMemberOf;
9311 } // end anonymous namespace
9313 /// Builds a using declaration.
9315 /// \param IsInstantiation - Whether this call arises from an
9316 /// instantiation of an unresolved using declaration. We treat
9317 /// the lookup differently for these declarations.
9318 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9319 SourceLocation UsingLoc,
9320 bool HasTypenameKeyword,
9321 SourceLocation TypenameLoc,
9323 DeclarationNameInfo NameInfo,
9324 SourceLocation EllipsisLoc,
9325 AttributeList *AttrList,
9326 bool IsInstantiation) {
9327 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9328 SourceLocation IdentLoc = NameInfo.getLoc();
9329 assert(IdentLoc.isValid() && "Invalid TargetName location.");
9331 // FIXME: We ignore attributes for now.
9333 // For an inheriting constructor declaration, the name of the using
9334 // declaration is the name of a constructor in this class, not in the
9336 DeclarationNameInfo UsingName = NameInfo;
9337 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9338 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9339 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9340 Context.getCanonicalType(Context.getRecordType(RD))));
9342 // Do the redeclaration lookup in the current scope.
9343 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9345 Previous.setHideTags(false);
9347 LookupName(Previous, S);
9349 // It is really dumb that we have to do this.
9350 LookupResult::Filter F = Previous.makeFilter();
9351 while (F.hasNext()) {
9352 NamedDecl *D = F.next();
9353 if (!isDeclInScope(D, CurContext, S))
9355 // If we found a local extern declaration that's not ordinarily visible,
9356 // and this declaration is being added to a non-block scope, ignore it.
9357 // We're only checking for scope conflicts here, not also for violations
9358 // of the linkage rules.
9359 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9360 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9365 assert(IsInstantiation && "no scope in non-instantiation");
9366 if (CurContext->isRecord())
9367 LookupQualifiedName(Previous, CurContext);
9369 // No redeclaration check is needed here; in non-member contexts we
9370 // diagnosed all possible conflicts with other using-declarations when
9371 // building the template:
9373 // For a dependent non-type using declaration, the only valid case is
9374 // if we instantiate to a single enumerator. We check for conflicts
9375 // between shadow declarations we introduce, and we check in the template
9376 // definition for conflicts between a non-type using declaration and any
9377 // other declaration, which together covers all cases.
9379 // A dependent typename using declaration will never successfully
9380 // instantiate, since it will always name a class member, so we reject
9381 // that in the template definition.
9385 // Check for invalid redeclarations.
9386 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9387 SS, IdentLoc, Previous))
9390 // Check for bad qualifiers.
9391 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9395 DeclContext *LookupContext = computeDeclContext(SS);
9397 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9398 if (!LookupContext || EllipsisLoc.isValid()) {
9399 if (HasTypenameKeyword) {
9400 // FIXME: not all declaration name kinds are legal here
9401 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9402 UsingLoc, TypenameLoc,
9404 IdentLoc, NameInfo.getName(),
9407 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9408 QualifierLoc, NameInfo, EllipsisLoc);
9411 CurContext->addDecl(D);
9415 auto Build = [&](bool Invalid) {
9417 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9418 UsingName, HasTypenameKeyword);
9420 CurContext->addDecl(UD);
9421 UD->setInvalidDecl(Invalid);
9424 auto BuildInvalid = [&]{ return Build(true); };
9425 auto BuildValid = [&]{ return Build(false); };
9427 if (RequireCompleteDeclContext(SS, LookupContext))
9428 return BuildInvalid();
9430 // Look up the target name.
9431 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9433 // Unlike most lookups, we don't always want to hide tag
9434 // declarations: tag names are visible through the using declaration
9435 // even if hidden by ordinary names, *except* in a dependent context
9436 // where it's important for the sanity of two-phase lookup.
9437 if (!IsInstantiation)
9438 R.setHideTags(false);
9440 // For the purposes of this lookup, we have a base object type
9441 // equal to that of the current context.
9442 if (CurContext->isRecord()) {
9443 R.setBaseObjectType(
9444 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9447 LookupQualifiedName(R, LookupContext);
9449 // Try to correct typos if possible. If constructor name lookup finds no
9450 // results, that means the named class has no explicit constructors, and we
9451 // suppressed declaring implicit ones (probably because it's dependent or
9454 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9455 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9456 // it will believe that glibc provides a ::gets in cases where it does not,
9457 // and will try to pull it into namespace std with a using-declaration.
9458 // Just ignore the using-declaration in that case.
9459 auto *II = NameInfo.getName().getAsIdentifierInfo();
9460 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9461 CurContext->isStdNamespace() &&
9462 isa<TranslationUnitDecl>(LookupContext) &&
9463 getSourceManager().isInSystemHeader(UsingLoc))
9465 if (TypoCorrection Corrected = CorrectTypo(
9466 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9467 llvm::make_unique<UsingValidatorCCC>(
9468 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9469 dyn_cast<CXXRecordDecl>(CurContext)),
9470 CTK_ErrorRecovery)) {
9471 // We reject candidates where DroppedSpecifier == true, hence the
9472 // literal '0' below.
9473 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9474 << NameInfo.getName() << LookupContext << 0
9477 // If we picked a correction with no attached Decl we can't do anything
9478 // useful with it, bail out.
9479 NamedDecl *ND = Corrected.getCorrectionDecl();
9481 return BuildInvalid();
9483 // If we corrected to an inheriting constructor, handle it as one.
9484 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9485 if (RD && RD->isInjectedClassName()) {
9486 // The parent of the injected class name is the class itself.
9487 RD = cast<CXXRecordDecl>(RD->getParent());
9489 // Fix up the information we'll use to build the using declaration.
9490 if (Corrected.WillReplaceSpecifier()) {
9491 NestedNameSpecifierLocBuilder Builder;
9492 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9493 QualifierLoc.getSourceRange());
9494 QualifierLoc = Builder.getWithLocInContext(Context);
9497 // In this case, the name we introduce is the name of a derived class
9499 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9500 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9501 Context.getCanonicalType(Context.getRecordType(CurClass))));
9502 UsingName.setNamedTypeInfo(nullptr);
9503 for (auto *Ctor : LookupConstructors(RD))
9507 // FIXME: Pick up all the declarations if we found an overloaded
9509 UsingName.setName(ND->getDeclName());
9513 Diag(IdentLoc, diag::err_no_member)
9514 << NameInfo.getName() << LookupContext << SS.getRange();
9515 return BuildInvalid();
9519 if (R.isAmbiguous())
9520 return BuildInvalid();
9522 if (HasTypenameKeyword) {
9523 // If we asked for a typename and got a non-type decl, error out.
9524 if (!R.getAsSingle<TypeDecl>()) {
9525 Diag(IdentLoc, diag::err_using_typename_non_type);
9526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9527 Diag((*I)->getUnderlyingDecl()->getLocation(),
9528 diag::note_using_decl_target);
9529 return BuildInvalid();
9532 // If we asked for a non-typename and we got a type, error out,
9533 // but only if this is an instantiation of an unresolved using
9534 // decl. Otherwise just silently find the type name.
9535 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9536 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9537 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9538 return BuildInvalid();
9542 // C++14 [namespace.udecl]p6:
9543 // A using-declaration shall not name a namespace.
9544 if (R.getAsSingle<NamespaceDecl>()) {
9545 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9547 return BuildInvalid();
9550 // C++14 [namespace.udecl]p7:
9551 // A using-declaration shall not name a scoped enumerator.
9552 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9553 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9554 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9556 return BuildInvalid();
9560 UsingDecl *UD = BuildValid();
9562 // Some additional rules apply to inheriting constructors.
9563 if (UsingName.getName().getNameKind() ==
9564 DeclarationName::CXXConstructorName) {
9565 // Suppress access diagnostics; the access check is instead performed at the
9566 // point of use for an inheriting constructor.
9567 R.suppressDiagnostics();
9568 if (CheckInheritingConstructorUsingDecl(UD))
9572 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9573 UsingShadowDecl *PrevDecl = nullptr;
9574 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9575 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9581 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9582 ArrayRef<NamedDecl *> Expansions) {
9583 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9584 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9585 isa<UsingPackDecl>(InstantiatedFrom));
9588 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9589 UPD->setAccess(InstantiatedFrom->getAccess());
9590 CurContext->addDecl(UPD);
9594 /// Additional checks for a using declaration referring to a constructor name.
9595 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9596 assert(!UD->hasTypename() && "expecting a constructor name");
9598 const Type *SourceType = UD->getQualifier()->getAsType();
9599 assert(SourceType &&
9600 "Using decl naming constructor doesn't have type in scope spec.");
9601 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9603 // Check whether the named type is a direct base class.
9604 bool AnyDependentBases = false;
9605 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9607 if (!Base && !AnyDependentBases) {
9608 Diag(UD->getUsingLoc(),
9609 diag::err_using_decl_constructor_not_in_direct_base)
9610 << UD->getNameInfo().getSourceRange()
9611 << QualType(SourceType, 0) << TargetClass;
9612 UD->setInvalidDecl();
9617 Base->setInheritConstructors();
9622 /// Checks that the given using declaration is not an invalid
9623 /// redeclaration. Note that this is checking only for the using decl
9624 /// itself, not for any ill-formedness among the UsingShadowDecls.
9625 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9626 bool HasTypenameKeyword,
9627 const CXXScopeSpec &SS,
9628 SourceLocation NameLoc,
9629 const LookupResult &Prev) {
9630 NestedNameSpecifier *Qual = SS.getScopeRep();
9632 // C++03 [namespace.udecl]p8:
9633 // C++0x [namespace.udecl]p10:
9634 // A using-declaration is a declaration and can therefore be used
9635 // repeatedly where (and only where) multiple declarations are
9638 // That's in non-member contexts.
9639 if (!CurContext->getRedeclContext()->isRecord()) {
9640 // A dependent qualifier outside a class can only ever resolve to an
9641 // enumeration type. Therefore it conflicts with any other non-type
9642 // declaration in the same scope.
9643 // FIXME: How should we check for dependent type-type conflicts at block
9645 if (Qual->isDependent() && !HasTypenameKeyword) {
9646 for (auto *D : Prev) {
9647 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9648 bool OldCouldBeEnumerator =
9649 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9651 OldCouldBeEnumerator ? diag::err_redefinition
9652 : diag::err_redefinition_different_kind)
9653 << Prev.getLookupName();
9654 Diag(D->getLocation(), diag::note_previous_definition);
9662 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9666 NestedNameSpecifier *DQual;
9667 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9668 DTypename = UD->hasTypename();
9669 DQual = UD->getQualifier();
9670 } else if (UnresolvedUsingValueDecl *UD
9671 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9673 DQual = UD->getQualifier();
9674 } else if (UnresolvedUsingTypenameDecl *UD
9675 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9677 DQual = UD->getQualifier();
9680 // using decls differ if one says 'typename' and the other doesn't.
9681 // FIXME: non-dependent using decls?
9682 if (HasTypenameKeyword != DTypename) continue;
9684 // using decls differ if they name different scopes (but note that
9685 // template instantiation can cause this check to trigger when it
9686 // didn't before instantiation).
9687 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9688 Context.getCanonicalNestedNameSpecifier(DQual))
9691 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9692 Diag(D->getLocation(), diag::note_using_decl) << 1;
9700 /// Checks that the given nested-name qualifier used in a using decl
9701 /// in the current context is appropriately related to the current
9702 /// scope. If an error is found, diagnoses it and returns true.
9703 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9705 const CXXScopeSpec &SS,
9706 const DeclarationNameInfo &NameInfo,
9707 SourceLocation NameLoc) {
9708 DeclContext *NamedContext = computeDeclContext(SS);
9710 if (!CurContext->isRecord()) {
9711 // C++03 [namespace.udecl]p3:
9712 // C++0x [namespace.udecl]p8:
9713 // A using-declaration for a class member shall be a member-declaration.
9715 // If we weren't able to compute a valid scope, it might validly be a
9716 // dependent class scope or a dependent enumeration unscoped scope. If
9717 // we have a 'typename' keyword, the scope must resolve to a class type.
9718 if ((HasTypename && !NamedContext) ||
9719 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9720 auto *RD = NamedContext
9721 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9723 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9726 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9729 // If we have a complete, non-dependent source type, try to suggest a
9730 // way to get the same effect.
9734 // Find what this using-declaration was referring to.
9735 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9736 R.setHideTags(false);
9737 R.suppressDiagnostics();
9738 LookupQualifiedName(R, RD);
9740 if (R.getAsSingle<TypeDecl>()) {
9741 if (getLangOpts().CPlusPlus11) {
9742 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9743 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9744 << 0 // alias declaration
9745 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9746 NameInfo.getName().getAsString() +
9749 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9750 SourceLocation InsertLoc =
9751 getLocForEndOfToken(NameInfo.getLocEnd());
9752 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9753 << 1 // typedef declaration
9754 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9755 << FixItHint::CreateInsertion(
9756 InsertLoc, " " + NameInfo.getName().getAsString());
9758 } else if (R.getAsSingle<VarDecl>()) {
9759 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9760 // repeating the type of the static data member here.
9762 if (getLangOpts().CPlusPlus11) {
9763 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9764 FixIt = FixItHint::CreateReplacement(
9765 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9768 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9769 << 2 // reference declaration
9771 } else if (R.getAsSingle<EnumConstantDecl>()) {
9772 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9773 // repeating the type of the enumeration here, and we can't do so if
9774 // the type is anonymous.
9776 if (getLangOpts().CPlusPlus11) {
9777 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9778 FixIt = FixItHint::CreateReplacement(
9780 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9783 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9784 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9790 // Otherwise, this might be valid.
9794 // The current scope is a record.
9796 // If the named context is dependent, we can't decide much.
9797 if (!NamedContext) {
9798 // FIXME: in C++0x, we can diagnose if we can prove that the
9799 // nested-name-specifier does not refer to a base class, which is
9800 // still possible in some cases.
9802 // Otherwise we have to conservatively report that things might be
9807 if (!NamedContext->isRecord()) {
9808 // Ideally this would point at the last name in the specifier,
9809 // but we don't have that level of source info.
9810 Diag(SS.getRange().getBegin(),
9811 diag::err_using_decl_nested_name_specifier_is_not_class)
9812 << SS.getScopeRep() << SS.getRange();
9816 if (!NamedContext->isDependentContext() &&
9817 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9820 if (getLangOpts().CPlusPlus11) {
9821 // C++11 [namespace.udecl]p3:
9822 // In a using-declaration used as a member-declaration, the
9823 // nested-name-specifier shall name a base class of the class
9826 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9827 cast<CXXRecordDecl>(NamedContext))) {
9828 if (CurContext == NamedContext) {
9830 diag::err_using_decl_nested_name_specifier_is_current_class)
9835 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9836 Diag(SS.getRange().getBegin(),
9837 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9839 << cast<CXXRecordDecl>(CurContext)
9848 // C++03 [namespace.udecl]p4:
9849 // A using-declaration used as a member-declaration shall refer
9850 // to a member of a base class of the class being defined [etc.].
9852 // Salient point: SS doesn't have to name a base class as long as
9853 // lookup only finds members from base classes. Therefore we can
9854 // diagnose here only if we can prove that that can't happen,
9855 // i.e. if the class hierarchies provably don't intersect.
9857 // TODO: it would be nice if "definitely valid" results were cached
9858 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9859 // need to be repeated.
9861 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9862 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9867 // Collect all bases. Return false if we find a dependent base.
9868 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9871 // Returns true if the base is dependent or is one of the accumulated base
9873 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9874 return !Bases.count(Base);
9877 // Return false if the class has a dependent base or if it or one
9878 // of its bases is present in the base set of the current context.
9879 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9880 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9883 Diag(SS.getRange().getBegin(),
9884 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9886 << cast<CXXRecordDecl>(CurContext)
9892 Decl *Sema::ActOnAliasDeclaration(Scope *S,
9894 MultiTemplateParamsArg TemplateParamLists,
9895 SourceLocation UsingLoc,
9896 UnqualifiedId &Name,
9897 AttributeList *AttrList,
9899 Decl *DeclFromDeclSpec) {
9900 // Skip up to the relevant declaration scope.
9901 while (S->isTemplateParamScope())
9903 assert((S->getFlags() & Scope::DeclScope) &&
9904 "got alias-declaration outside of declaration scope");
9906 if (Type.isInvalid())
9909 bool Invalid = false;
9910 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
9911 TypeSourceInfo *TInfo = nullptr;
9912 GetTypeFromParser(Type.get(), &TInfo);
9914 if (DiagnoseClassNameShadow(CurContext, NameInfo))
9917 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
9918 UPPC_DeclarationType)) {
9920 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9921 TInfo->getTypeLoc().getBeginLoc());
9924 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
9925 LookupName(Previous, S);
9927 // Warn about shadowing the name of a template parameter.
9928 if (Previous.isSingleResult() &&
9929 Previous.getFoundDecl()->isTemplateParameter()) {
9930 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
9934 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
9935 "name in alias declaration must be an identifier");
9936 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
9938 Name.Identifier, TInfo);
9940 NewTD->setAccess(AS);
9943 NewTD->setInvalidDecl();
9945 ProcessDeclAttributeList(S, NewTD, AttrList);
9946 AddPragmaAttributes(S, NewTD);
9948 CheckTypedefForVariablyModifiedType(S, NewTD);
9949 Invalid |= NewTD->isInvalidDecl();
9951 bool Redeclaration = false;
9954 if (TemplateParamLists.size()) {
9955 TypeAliasTemplateDecl *OldDecl = nullptr;
9956 TemplateParameterList *OldTemplateParams = nullptr;
9958 if (TemplateParamLists.size() != 1) {
9959 Diag(UsingLoc, diag::err_alias_template_extra_headers)
9960 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
9961 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
9963 TemplateParameterList *TemplateParams = TemplateParamLists[0];
9965 // Check that we can declare a template here.
9966 if (CheckTemplateDeclScope(S, TemplateParams))
9969 // Only consider previous declarations in the same scope.
9970 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
9971 /*ExplicitInstantiationOrSpecialization*/false);
9972 if (!Previous.empty()) {
9973 Redeclaration = true;
9975 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
9976 if (!OldDecl && !Invalid) {
9977 Diag(UsingLoc, diag::err_redefinition_different_kind)
9980 NamedDecl *OldD = Previous.getRepresentativeDecl();
9981 if (OldD->getLocation().isValid())
9982 Diag(OldD->getLocation(), diag::note_previous_definition);
9987 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
9988 if (TemplateParameterListsAreEqual(TemplateParams,
9989 OldDecl->getTemplateParameters(),
9992 OldTemplateParams = OldDecl->getTemplateParameters();
9996 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
9998 !Context.hasSameType(OldTD->getUnderlyingType(),
9999 NewTD->getUnderlyingType())) {
10000 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10001 // but we can't reasonably accept it.
10002 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10003 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10004 if (OldTD->getLocation().isValid())
10005 Diag(OldTD->getLocation(), diag::note_previous_definition);
10011 // Merge any previous default template arguments into our parameters,
10012 // and check the parameter list.
10013 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10014 TPC_TypeAliasTemplate))
10017 TypeAliasTemplateDecl *NewDecl =
10018 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10019 Name.Identifier, TemplateParams,
10021 NewTD->setDescribedAliasTemplate(NewDecl);
10023 NewDecl->setAccess(AS);
10026 NewDecl->setInvalidDecl();
10028 NewDecl->setPreviousDecl(OldDecl);
10032 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10033 setTagNameForLinkagePurposes(TD, NewTD);
10034 handleTagNumbering(TD, S);
10036 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10040 PushOnScopeChains(NewND, S);
10041 ActOnDocumentableDecl(NewND);
10045 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10046 SourceLocation AliasLoc,
10047 IdentifierInfo *Alias, CXXScopeSpec &SS,
10048 SourceLocation IdentLoc,
10049 IdentifierInfo *Ident) {
10051 // Lookup the namespace name.
10052 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10053 LookupParsedName(R, S, &SS);
10055 if (R.isAmbiguous())
10059 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10060 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10064 assert(!R.isAmbiguous() && !R.empty());
10065 NamedDecl *ND = R.getRepresentativeDecl();
10067 // Check if we have a previous declaration with the same name.
10068 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10070 LookupName(PrevR, S);
10072 // Check we're not shadowing a template parameter.
10073 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10074 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10078 // Filter out any other lookup result from an enclosing scope.
10079 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10080 /*AllowInlineNamespace*/false);
10082 // Find the previous declaration and check that we can redeclare it.
10083 NamespaceAliasDecl *Prev = nullptr;
10084 if (PrevR.isSingleResult()) {
10085 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10086 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10087 // We already have an alias with the same name that points to the same
10088 // namespace; check that it matches.
10089 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10091 } else if (isVisible(PrevDecl)) {
10092 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10094 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10095 << AD->getNamespace();
10098 } else if (isVisible(PrevDecl)) {
10099 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10100 ? diag::err_redefinition
10101 : diag::err_redefinition_different_kind;
10102 Diag(AliasLoc, DiagID) << Alias;
10103 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10108 // The use of a nested name specifier may trigger deprecation warnings.
10109 DiagnoseUseOfDecl(ND, IdentLoc);
10111 NamespaceAliasDecl *AliasDecl =
10112 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10113 Alias, SS.getWithLocInContext(Context),
10116 AliasDecl->setPreviousDecl(Prev);
10118 PushOnScopeChains(AliasDecl, S);
10123 struct SpecialMemberExceptionSpecInfo
10124 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10125 SourceLocation Loc;
10126 Sema::ImplicitExceptionSpecification ExceptSpec;
10128 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10129 Sema::CXXSpecialMember CSM,
10130 Sema::InheritedConstructorInfo *ICI,
10131 SourceLocation Loc)
10132 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10134 bool visitBase(CXXBaseSpecifier *Base);
10135 bool visitField(FieldDecl *FD);
10137 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10140 void visitSubobjectCall(Subobject Subobj,
10141 Sema::SpecialMemberOverloadResult SMOR);
10145 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10146 auto *RT = Base->getType()->getAs<RecordType>();
10150 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10151 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10152 if (auto *BaseCtor = SMOR.getMethod()) {
10153 visitSubobjectCall(Base, BaseCtor);
10157 visitClassSubobject(BaseClass, Base, 0);
10161 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10162 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10163 Expr *E = FD->getInClassInitializer();
10165 // FIXME: It's a little wasteful to build and throw away a
10166 // CXXDefaultInitExpr here.
10167 // FIXME: We should have a single context note pointing at Loc, and
10168 // this location should be MD->getLocation() instead, since that's
10169 // the location where we actually use the default init expression.
10170 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10172 ExceptSpec.CalledExpr(E);
10173 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10174 ->getAs<RecordType>()) {
10175 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10176 FD->getType().getCVRQualifiers());
10181 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10184 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10185 bool IsMutable = Field && Field->isMutable();
10186 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10189 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10190 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10191 // Note, if lookup fails, it doesn't matter what exception specification we
10192 // choose because the special member will be deleted.
10193 if (CXXMethodDecl *MD = SMOR.getMethod())
10194 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10197 static Sema::ImplicitExceptionSpecification
10198 ComputeDefaultedSpecialMemberExceptionSpec(
10199 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10200 Sema::InheritedConstructorInfo *ICI) {
10201 CXXRecordDecl *ClassDecl = MD->getParent();
10203 // C++ [except.spec]p14:
10204 // An implicitly declared special member function (Clause 12) shall have an
10205 // exception-specification. [...]
10206 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10207 if (ClassDecl->isInvalidDecl())
10208 return Info.ExceptSpec;
10210 // C++1z [except.spec]p7:
10211 // [Look for exceptions thrown by] a constructor selected [...] to
10212 // initialize a potentially constructed subobject,
10213 // C++1z [except.spec]p8:
10214 // The exception specification for an implicitly-declared destructor, or a
10215 // destructor without a noexcept-specifier, is potentially-throwing if and
10216 // only if any of the destructors for any of its potentially constructed
10217 // subojects is potentially throwing.
10218 // FIXME: We respect the first rule but ignore the "potentially constructed"
10219 // in the second rule to resolve a core issue (no number yet) that would have
10221 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10222 // struct B : A {};
10223 // struct C : B { void f(); };
10224 // ... due to giving B::~B() a non-throwing exception specification.
10225 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10226 : Info.VisitAllBases);
10228 return Info.ExceptSpec;
10232 /// RAII object to register a special member as being currently declared.
10233 struct DeclaringSpecialMember {
10235 Sema::SpecialMemberDecl D;
10236 Sema::ContextRAII SavedContext;
10237 bool WasAlreadyBeingDeclared;
10239 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10240 : S(S), D(RD, CSM), SavedContext(S, RD) {
10241 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10242 if (WasAlreadyBeingDeclared)
10243 // This almost never happens, but if it does, ensure that our cache
10244 // doesn't contain a stale result.
10245 S.SpecialMemberCache.clear();
10247 // Register a note to be produced if we encounter an error while
10248 // declaring the special member.
10249 Sema::CodeSynthesisContext Ctx;
10250 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10251 // FIXME: We don't have a location to use here. Using the class's
10252 // location maintains the fiction that we declare all special members
10253 // with the class, but (1) it's not clear that lying about that helps our
10254 // users understand what's going on, and (2) there may be outer contexts
10255 // on the stack (some of which are relevant) and printing them exposes
10257 Ctx.PointOfInstantiation = RD->getLocation();
10259 Ctx.SpecialMember = CSM;
10260 S.pushCodeSynthesisContext(Ctx);
10263 ~DeclaringSpecialMember() {
10264 if (!WasAlreadyBeingDeclared) {
10265 S.SpecialMembersBeingDeclared.erase(D);
10266 S.popCodeSynthesisContext();
10270 /// \brief Are we already trying to declare this special member?
10271 bool isAlreadyBeingDeclared() const {
10272 return WasAlreadyBeingDeclared;
10277 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10278 // Look up any existing declarations, but don't trigger declaration of all
10279 // implicit special members with this name.
10280 DeclarationName Name = FD->getDeclName();
10281 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10283 for (auto *D : FD->getParent()->lookup(Name))
10284 if (auto *Acceptable = R.getAcceptableDecl(D))
10285 R.addDecl(Acceptable);
10287 R.suppressDiagnostics();
10289 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10292 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10293 CXXRecordDecl *ClassDecl) {
10294 // C++ [class.ctor]p5:
10295 // A default constructor for a class X is a constructor of class X
10296 // that can be called without an argument. If there is no
10297 // user-declared constructor for class X, a default constructor is
10298 // implicitly declared. An implicitly-declared default constructor
10299 // is an inline public member of its class.
10300 assert(ClassDecl->needsImplicitDefaultConstructor() &&
10301 "Should not build implicit default constructor!");
10303 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10304 if (DSM.isAlreadyBeingDeclared())
10307 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10308 CXXDefaultConstructor,
10311 // Create the actual constructor declaration.
10312 CanQualType ClassType
10313 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10314 SourceLocation ClassLoc = ClassDecl->getLocation();
10315 DeclarationName Name
10316 = Context.DeclarationNames.getCXXConstructorName(ClassType);
10317 DeclarationNameInfo NameInfo(Name, ClassLoc);
10318 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10319 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10320 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10321 /*isImplicitlyDeclared=*/true, Constexpr);
10322 DefaultCon->setAccess(AS_public);
10323 DefaultCon->setDefaulted();
10325 if (getLangOpts().CUDA) {
10326 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10328 /* ConstRHS */ false,
10329 /* Diagnose */ false);
10332 // Build an exception specification pointing back at this constructor.
10333 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10334 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10336 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10337 // constructors is easy to compute.
10338 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10340 // Note that we have declared this constructor.
10341 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10343 Scope *S = getScopeForContext(ClassDecl);
10344 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10346 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10347 SetDeclDeleted(DefaultCon, ClassLoc);
10350 PushOnScopeChains(DefaultCon, S, false);
10351 ClassDecl->addDecl(DefaultCon);
10356 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10357 CXXConstructorDecl *Constructor) {
10358 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10359 !Constructor->doesThisDeclarationHaveABody() &&
10360 !Constructor->isDeleted()) &&
10361 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10362 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10365 CXXRecordDecl *ClassDecl = Constructor->getParent();
10366 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10368 SynthesizedFunctionScope Scope(*this, Constructor);
10370 // The exception specification is needed because we are defining the
10372 ResolveExceptionSpec(CurrentLocation,
10373 Constructor->getType()->castAs<FunctionProtoType>());
10374 MarkVTableUsed(CurrentLocation, ClassDecl);
10376 // Add a context note for diagnostics produced after this point.
10377 Scope.addContextNote(CurrentLocation);
10379 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10380 Constructor->setInvalidDecl();
10384 SourceLocation Loc = Constructor->getLocEnd().isValid()
10385 ? Constructor->getLocEnd()
10386 : Constructor->getLocation();
10387 Constructor->setBody(new (Context) CompoundStmt(Loc));
10388 Constructor->markUsed(Context);
10390 if (ASTMutationListener *L = getASTMutationListener()) {
10391 L->CompletedImplicitDefinition(Constructor);
10394 DiagnoseUninitializedFields(*this, Constructor);
10397 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10398 // Perform any delayed checks on exception specifications.
10399 CheckDelayedMemberExceptionSpecs();
10402 /// Find or create the fake constructor we synthesize to model constructing an
10403 /// object of a derived class via a constructor of a base class.
10404 CXXConstructorDecl *
10405 Sema::findInheritingConstructor(SourceLocation Loc,
10406 CXXConstructorDecl *BaseCtor,
10407 ConstructorUsingShadowDecl *Shadow) {
10408 CXXRecordDecl *Derived = Shadow->getParent();
10409 SourceLocation UsingLoc = Shadow->getLocation();
10411 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10412 // For now we use the name of the base class constructor as a member of the
10413 // derived class to indicate a (fake) inherited constructor name.
10414 DeclarationName Name = BaseCtor->getDeclName();
10416 // Check to see if we already have a fake constructor for this inherited
10417 // constructor call.
10418 for (NamedDecl *Ctor : Derived->lookup(Name))
10419 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10420 ->getInheritedConstructor()
10423 return cast<CXXConstructorDecl>(Ctor);
10425 DeclarationNameInfo NameInfo(Name, UsingLoc);
10426 TypeSourceInfo *TInfo =
10427 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10428 FunctionProtoTypeLoc ProtoLoc =
10429 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10431 // Check the inherited constructor is valid and find the list of base classes
10432 // from which it was inherited.
10433 InheritedConstructorInfo ICI(*this, Loc, Shadow);
10436 BaseCtor->isConstexpr() &&
10437 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10438 false, BaseCtor, &ICI);
10440 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10441 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10442 BaseCtor->isExplicit(), /*Inline=*/true,
10443 /*ImplicitlyDeclared=*/true, Constexpr,
10444 InheritedConstructor(Shadow, BaseCtor));
10445 if (Shadow->isInvalidDecl())
10446 DerivedCtor->setInvalidDecl();
10448 // Build an unevaluated exception specification for this fake constructor.
10449 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10450 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10451 EPI.ExceptionSpec.Type = EST_Unevaluated;
10452 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10453 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10454 FPT->getParamTypes(), EPI));
10456 // Build the parameter declarations.
10457 SmallVector<ParmVarDecl *, 16> ParamDecls;
10458 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10459 TypeSourceInfo *TInfo =
10460 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10461 ParmVarDecl *PD = ParmVarDecl::Create(
10462 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10463 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10464 PD->setScopeInfo(0, I);
10466 // Ensure attributes are propagated onto parameters (this matters for
10467 // format, pass_object_size, ...).
10468 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10469 ParamDecls.push_back(PD);
10470 ProtoLoc.setParam(I, PD);
10473 // Set up the new constructor.
10474 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10475 DerivedCtor->setAccess(BaseCtor->getAccess());
10476 DerivedCtor->setParams(ParamDecls);
10477 Derived->addDecl(DerivedCtor);
10479 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10480 SetDeclDeleted(DerivedCtor, UsingLoc);
10482 return DerivedCtor;
10485 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10486 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10487 Ctor->getInheritedConstructor().getShadowDecl());
10488 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10492 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10493 CXXConstructorDecl *Constructor) {
10494 CXXRecordDecl *ClassDecl = Constructor->getParent();
10495 assert(Constructor->getInheritedConstructor() &&
10496 !Constructor->doesThisDeclarationHaveABody() &&
10497 !Constructor->isDeleted());
10498 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10501 // Initializations are performed "as if by a defaulted default constructor",
10502 // so enter the appropriate scope.
10503 SynthesizedFunctionScope Scope(*this, Constructor);
10505 // The exception specification is needed because we are defining the
10507 ResolveExceptionSpec(CurrentLocation,
10508 Constructor->getType()->castAs<FunctionProtoType>());
10509 MarkVTableUsed(CurrentLocation, ClassDecl);
10511 // Add a context note for diagnostics produced after this point.
10512 Scope.addContextNote(CurrentLocation);
10514 ConstructorUsingShadowDecl *Shadow =
10515 Constructor->getInheritedConstructor().getShadowDecl();
10516 CXXConstructorDecl *InheritedCtor =
10517 Constructor->getInheritedConstructor().getConstructor();
10519 // [class.inhctor.init]p1:
10520 // initialization proceeds as if a defaulted default constructor is used to
10521 // initialize the D object and each base class subobject from which the
10522 // constructor was inherited
10524 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10525 CXXRecordDecl *RD = Shadow->getParent();
10526 SourceLocation InitLoc = Shadow->getLocation();
10528 // Build explicit initializers for all base classes from which the
10529 // constructor was inherited.
10530 SmallVector<CXXCtorInitializer*, 8> Inits;
10531 for (bool VBase : {false, true}) {
10532 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10533 if (B.isVirtual() != VBase)
10536 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10540 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10541 if (!BaseCtor.first)
10544 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10545 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10546 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10548 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10549 Inits.push_back(new (Context) CXXCtorInitializer(
10550 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10551 SourceLocation()));
10555 // We now proceed as if for a defaulted default constructor, with the relevant
10556 // initializers replaced.
10558 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
10559 Constructor->setInvalidDecl();
10563 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10564 Constructor->markUsed(Context);
10566 if (ASTMutationListener *L = getASTMutationListener()) {
10567 L->CompletedImplicitDefinition(Constructor);
10570 DiagnoseUninitializedFields(*this, Constructor);
10573 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10574 // C++ [class.dtor]p2:
10575 // If a class has no user-declared destructor, a destructor is
10576 // declared implicitly. An implicitly-declared destructor is an
10577 // inline public member of its class.
10578 assert(ClassDecl->needsImplicitDestructor());
10580 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10581 if (DSM.isAlreadyBeingDeclared())
10584 // Create the actual destructor declaration.
10585 CanQualType ClassType
10586 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10587 SourceLocation ClassLoc = ClassDecl->getLocation();
10588 DeclarationName Name
10589 = Context.DeclarationNames.getCXXDestructorName(ClassType);
10590 DeclarationNameInfo NameInfo(Name, ClassLoc);
10591 CXXDestructorDecl *Destructor
10592 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10593 QualType(), nullptr, /*isInline=*/true,
10594 /*isImplicitlyDeclared=*/true);
10595 Destructor->setAccess(AS_public);
10596 Destructor->setDefaulted();
10598 if (getLangOpts().CUDA) {
10599 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10601 /* ConstRHS */ false,
10602 /* Diagnose */ false);
10605 // Build an exception specification pointing back at this destructor.
10606 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10607 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10609 // We don't need to use SpecialMemberIsTrivial here; triviality for
10610 // destructors is easy to compute.
10611 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10613 // Note that we have declared this destructor.
10614 ++ASTContext::NumImplicitDestructorsDeclared;
10616 Scope *S = getScopeForContext(ClassDecl);
10617 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10619 // We can't check whether an implicit destructor is deleted before we complete
10620 // the definition of the class, because its validity depends on the alignment
10621 // of the class. We'll check this from ActOnFields once the class is complete.
10622 if (ClassDecl->isCompleteDefinition() &&
10623 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10624 SetDeclDeleted(Destructor, ClassLoc);
10626 // Introduce this destructor into its scope.
10628 PushOnScopeChains(Destructor, S, false);
10629 ClassDecl->addDecl(Destructor);
10634 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10635 CXXDestructorDecl *Destructor) {
10636 assert((Destructor->isDefaulted() &&
10637 !Destructor->doesThisDeclarationHaveABody() &&
10638 !Destructor->isDeleted()) &&
10639 "DefineImplicitDestructor - call it for implicit default dtor");
10640 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
10643 CXXRecordDecl *ClassDecl = Destructor->getParent();
10644 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10646 SynthesizedFunctionScope Scope(*this, Destructor);
10648 // The exception specification is needed because we are defining the
10650 ResolveExceptionSpec(CurrentLocation,
10651 Destructor->getType()->castAs<FunctionProtoType>());
10652 MarkVTableUsed(CurrentLocation, ClassDecl);
10654 // Add a context note for diagnostics produced after this point.
10655 Scope.addContextNote(CurrentLocation);
10657 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10658 Destructor->getParent());
10660 if (CheckDestructor(Destructor)) {
10661 Destructor->setInvalidDecl();
10665 SourceLocation Loc = Destructor->getLocEnd().isValid()
10666 ? Destructor->getLocEnd()
10667 : Destructor->getLocation();
10668 Destructor->setBody(new (Context) CompoundStmt(Loc));
10669 Destructor->markUsed(Context);
10671 if (ASTMutationListener *L = getASTMutationListener()) {
10672 L->CompletedImplicitDefinition(Destructor);
10676 /// \brief Perform any semantic analysis which needs to be delayed until all
10677 /// pending class member declarations have been parsed.
10678 void Sema::ActOnFinishCXXMemberDecls() {
10679 // If the context is an invalid C++ class, just suppress these checks.
10680 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10681 if (Record->isInvalidDecl()) {
10682 DelayedDefaultedMemberExceptionSpecs.clear();
10683 DelayedExceptionSpecChecks.clear();
10686 checkForMultipleExportedDefaultConstructors(*this, Record);
10690 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10691 referenceDLLExportedClassMethods();
10694 void Sema::referenceDLLExportedClassMethods() {
10695 if (!DelayedDllExportClasses.empty()) {
10696 // Calling ReferenceDllExportedMethods might cause the current function to
10697 // be called again, so use a local copy of DelayedDllExportClasses.
10698 SmallVector<CXXRecordDecl *, 4> WorkList;
10699 std::swap(DelayedDllExportClasses, WorkList);
10700 for (CXXRecordDecl *Class : WorkList)
10701 ReferenceDllExportedMethods(*this, Class);
10705 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10706 CXXDestructorDecl *Destructor) {
10707 assert(getLangOpts().CPlusPlus11 &&
10708 "adjusting dtor exception specs was introduced in c++11");
10710 // C++11 [class.dtor]p3:
10711 // A declaration of a destructor that does not have an exception-
10712 // specification is implicitly considered to have the same exception-
10713 // specification as an implicit declaration.
10714 const FunctionProtoType *DtorType = Destructor->getType()->
10715 getAs<FunctionProtoType>();
10716 if (DtorType->hasExceptionSpec())
10719 // Replace the destructor's type, building off the existing one. Fortunately,
10720 // the only thing of interest in the destructor type is its extended info.
10721 // The return and arguments are fixed.
10722 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10723 EPI.ExceptionSpec.Type = EST_Unevaluated;
10724 EPI.ExceptionSpec.SourceDecl = Destructor;
10725 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10727 // FIXME: If the destructor has a body that could throw, and the newly created
10728 // spec doesn't allow exceptions, we should emit a warning, because this
10729 // change in behavior can break conforming C++03 programs at runtime.
10730 // However, we don't have a body or an exception specification yet, so it
10731 // needs to be done somewhere else.
10735 /// \brief An abstract base class for all helper classes used in building the
10736 // copy/move operators. These classes serve as factory functions and help us
10737 // avoid using the same Expr* in the AST twice.
10738 class ExprBuilder {
10739 ExprBuilder(const ExprBuilder&) = delete;
10740 ExprBuilder &operator=(const ExprBuilder&) = delete;
10743 static Expr *assertNotNull(Expr *E) {
10744 assert(E && "Expression construction must not fail.");
10750 virtual ~ExprBuilder() {}
10752 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10755 class RefBuilder: public ExprBuilder {
10760 Expr *build(Sema &S, SourceLocation Loc) const override {
10761 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10764 RefBuilder(VarDecl *Var, QualType VarType)
10765 : Var(Var), VarType(VarType) {}
10768 class ThisBuilder: public ExprBuilder {
10770 Expr *build(Sema &S, SourceLocation Loc) const override {
10771 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10775 class CastBuilder: public ExprBuilder {
10776 const ExprBuilder &Builder;
10778 ExprValueKind Kind;
10779 const CXXCastPath &Path;
10782 Expr *build(Sema &S, SourceLocation Loc) const override {
10783 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10784 CK_UncheckedDerivedToBase, Kind,
10788 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10789 const CXXCastPath &Path)
10790 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10793 class DerefBuilder: public ExprBuilder {
10794 const ExprBuilder &Builder;
10797 Expr *build(Sema &S, SourceLocation Loc) const override {
10798 return assertNotNull(
10799 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10802 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10805 class MemberBuilder: public ExprBuilder {
10806 const ExprBuilder &Builder;
10810 LookupResult &MemberLookup;
10813 Expr *build(Sema &S, SourceLocation Loc) const override {
10814 return assertNotNull(S.BuildMemberReferenceExpr(
10815 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10816 nullptr, MemberLookup, nullptr, nullptr).get());
10819 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10820 LookupResult &MemberLookup)
10821 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10822 MemberLookup(MemberLookup) {}
10825 class MoveCastBuilder: public ExprBuilder {
10826 const ExprBuilder &Builder;
10829 Expr *build(Sema &S, SourceLocation Loc) const override {
10830 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10833 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10836 class LvalueConvBuilder: public ExprBuilder {
10837 const ExprBuilder &Builder;
10840 Expr *build(Sema &S, SourceLocation Loc) const override {
10841 return assertNotNull(
10842 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10845 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10848 class SubscriptBuilder: public ExprBuilder {
10849 const ExprBuilder &Base;
10850 const ExprBuilder &Index;
10853 Expr *build(Sema &S, SourceLocation Loc) const override {
10854 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10855 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10858 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10859 : Base(Base), Index(Index) {}
10862 } // end anonymous namespace
10864 /// When generating a defaulted copy or move assignment operator, if a field
10865 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10866 /// do so. This optimization only applies for arrays of scalars, and for arrays
10867 /// of class type where the selected copy/move-assignment operator is trivial.
10869 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10870 const ExprBuilder &ToB, const ExprBuilder &FromB) {
10871 // Compute the size of the memory buffer to be copied.
10872 QualType SizeType = S.Context.getSizeType();
10873 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10874 S.Context.getTypeSizeInChars(T).getQuantity());
10876 // Take the address of the field references for "from" and "to". We
10877 // directly construct UnaryOperators here because semantic analysis
10878 // does not permit us to take the address of an xvalue.
10879 Expr *From = FromB.build(S, Loc);
10880 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10881 S.Context.getPointerType(From->getType()),
10882 VK_RValue, OK_Ordinary, Loc);
10883 Expr *To = ToB.build(S, Loc);
10884 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10885 S.Context.getPointerType(To->getType()),
10886 VK_RValue, OK_Ordinary, Loc);
10888 const Type *E = T->getBaseElementTypeUnsafe();
10889 bool NeedsCollectableMemCpy =
10890 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
10892 // Create a reference to the __builtin_objc_memmove_collectable function
10893 StringRef MemCpyName = NeedsCollectableMemCpy ?
10894 "__builtin_objc_memmove_collectable" :
10895 "__builtin_memcpy";
10896 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
10897 Sema::LookupOrdinaryName);
10898 S.LookupName(R, S.TUScope, true);
10900 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
10902 // Something went horribly wrong earlier, and we will have complained
10904 return StmtError();
10906 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
10907 VK_RValue, Loc, nullptr);
10908 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
10910 Expr *CallArgs[] = {
10911 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
10913 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
10914 Loc, CallArgs, Loc);
10916 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
10917 return Call.getAs<Stmt>();
10920 /// \brief Builds a statement that copies/moves the given entity from \p From to
10923 /// This routine is used to copy/move the members of a class with an
10924 /// implicitly-declared copy/move assignment operator. When the entities being
10925 /// copied are arrays, this routine builds for loops to copy them.
10927 /// \param S The Sema object used for type-checking.
10929 /// \param Loc The location where the implicit copy/move is being generated.
10931 /// \param T The type of the expressions being copied/moved. Both expressions
10932 /// must have this type.
10934 /// \param To The expression we are copying/moving to.
10936 /// \param From The expression we are copying/moving from.
10938 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
10939 /// Otherwise, it's a non-static member subobject.
10941 /// \param Copying Whether we're copying or moving.
10943 /// \param Depth Internal parameter recording the depth of the recursion.
10945 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
10946 /// if a memcpy should be used instead.
10948 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
10949 const ExprBuilder &To, const ExprBuilder &From,
10950 bool CopyingBaseSubobject, bool Copying,
10951 unsigned Depth = 0) {
10952 // C++11 [class.copy]p28:
10953 // Each subobject is assigned in the manner appropriate to its type:
10955 // - if the subobject is of class type, as if by a call to operator= with
10956 // the subobject as the object expression and the corresponding
10957 // subobject of x as a single function argument (as if by explicit
10958 // qualification; that is, ignoring any possible virtual overriding
10959 // functions in more derived classes);
10961 // C++03 [class.copy]p13:
10962 // - if the subobject is of class type, the copy assignment operator for
10963 // the class is used (as if by explicit qualification; that is,
10964 // ignoring any possible virtual overriding functions in more derived
10966 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
10967 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
10969 // Look for operator=.
10970 DeclarationName Name
10971 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
10972 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
10973 S.LookupQualifiedName(OpLookup, ClassDecl, false);
10975 // Prior to C++11, filter out any result that isn't a copy/move-assignment
10977 if (!S.getLangOpts().CPlusPlus11) {
10978 LookupResult::Filter F = OpLookup.makeFilter();
10979 while (F.hasNext()) {
10980 NamedDecl *D = F.next();
10981 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
10982 if (Method->isCopyAssignmentOperator() ||
10983 (!Copying && Method->isMoveAssignmentOperator()))
10991 // Suppress the protected check (C++ [class.protected]) for each of the
10992 // assignment operators we found. This strange dance is required when
10993 // we're assigning via a base classes's copy-assignment operator. To
10994 // ensure that we're getting the right base class subobject (without
10995 // ambiguities), we need to cast "this" to that subobject type; to
10996 // ensure that we don't go through the virtual call mechanism, we need
10997 // to qualify the operator= name with the base class (see below). However,
10998 // this means that if the base class has a protected copy assignment
10999 // operator, the protected member access check will fail. So, we
11000 // rewrite "protected" access to "public" access in this case, since we
11001 // know by construction that we're calling from a derived class.
11002 if (CopyingBaseSubobject) {
11003 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11005 if (L.getAccess() == AS_protected)
11006 L.setAccess(AS_public);
11010 // Create the nested-name-specifier that will be used to qualify the
11011 // reference to operator=; this is required to suppress the virtual
11014 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11015 SS.MakeTrivial(S.Context,
11016 NestedNameSpecifier::Create(S.Context, nullptr, false,
11020 // Create the reference to operator=.
11021 ExprResult OpEqualRef
11022 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11023 SS, /*TemplateKWLoc=*/SourceLocation(),
11024 /*FirstQualifierInScope=*/nullptr,
11026 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11027 /*SuppressQualifierCheck=*/true);
11028 if (OpEqualRef.isInvalid())
11029 return StmtError();
11031 // Build the call to the assignment operator.
11033 Expr *FromInst = From.build(S, Loc);
11034 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11035 OpEqualRef.getAs<Expr>(),
11036 Loc, FromInst, Loc);
11037 if (Call.isInvalid())
11038 return StmtError();
11040 // If we built a call to a trivial 'operator=' while copying an array,
11041 // bail out. We'll replace the whole shebang with a memcpy.
11042 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11043 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11044 return StmtResult((Stmt*)nullptr);
11046 // Convert to an expression-statement, and clean up any produced
11048 return S.ActOnExprStmt(Call);
11051 // - if the subobject is of scalar type, the built-in assignment
11052 // operator is used.
11053 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11055 ExprResult Assignment = S.CreateBuiltinBinOp(
11056 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11057 if (Assignment.isInvalid())
11058 return StmtError();
11059 return S.ActOnExprStmt(Assignment);
11062 // - if the subobject is an array, each element is assigned, in the
11063 // manner appropriate to the element type;
11065 // Construct a loop over the array bounds, e.g.,
11067 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11069 // that will copy each of the array elements.
11070 QualType SizeType = S.Context.getSizeType();
11072 // Create the iteration variable.
11073 IdentifierInfo *IterationVarName = nullptr;
11075 SmallString<8> Str;
11076 llvm::raw_svector_ostream OS(Str);
11077 OS << "__i" << Depth;
11078 IterationVarName = &S.Context.Idents.get(OS.str());
11080 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11081 IterationVarName, SizeType,
11082 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11085 // Initialize the iteration variable to zero.
11086 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11087 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11089 // Creates a reference to the iteration variable.
11090 RefBuilder IterationVarRef(IterationVar, SizeType);
11091 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11093 // Create the DeclStmt that holds the iteration variable.
11094 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11096 // Subscript the "from" and "to" expressions with the iteration variable.
11097 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11098 MoveCastBuilder FromIndexMove(FromIndexCopy);
11099 const ExprBuilder *FromIndex;
11101 FromIndex = &FromIndexCopy;
11103 FromIndex = &FromIndexMove;
11105 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11107 // Build the copy/move for an individual element of the array.
11109 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11110 ToIndex, *FromIndex, CopyingBaseSubobject,
11111 Copying, Depth + 1);
11112 // Bail out if copying fails or if we determined that we should use memcpy.
11113 if (Copy.isInvalid() || !Copy.get())
11116 // Create the comparison against the array bound.
11118 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11120 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11121 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11122 BO_NE, S.Context.BoolTy,
11123 VK_RValue, OK_Ordinary, Loc, FPOptions());
11125 // Create the pre-increment of the iteration variable.
11127 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11128 SizeType, VK_LValue, OK_Ordinary, Loc);
11130 // Construct the loop that copies all elements of this array.
11131 return S.ActOnForStmt(
11132 Loc, Loc, InitStmt,
11133 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11134 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11138 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11139 const ExprBuilder &To, const ExprBuilder &From,
11140 bool CopyingBaseSubobject, bool Copying) {
11141 // Maybe we should use a memcpy?
11142 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11143 T.isTriviallyCopyableType(S.Context))
11144 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11146 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11147 CopyingBaseSubobject,
11150 // If we ended up picking a trivial assignment operator for an array of a
11151 // non-trivially-copyable class type, just emit a memcpy.
11152 if (!Result.isInvalid() && !Result.get())
11153 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11158 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11159 // Note: The following rules are largely analoguous to the copy
11160 // constructor rules. Note that virtual bases are not taken into account
11161 // for determining the argument type of the operator. Note also that
11162 // operators taking an object instead of a reference are allowed.
11163 assert(ClassDecl->needsImplicitCopyAssignment());
11165 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11166 if (DSM.isAlreadyBeingDeclared())
11169 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11170 QualType RetType = Context.getLValueReferenceType(ArgType);
11171 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11173 ArgType = ArgType.withConst();
11174 ArgType = Context.getLValueReferenceType(ArgType);
11176 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11180 // An implicitly-declared copy assignment operator is an inline public
11181 // member of its class.
11182 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11183 SourceLocation ClassLoc = ClassDecl->getLocation();
11184 DeclarationNameInfo NameInfo(Name, ClassLoc);
11185 CXXMethodDecl *CopyAssignment =
11186 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11187 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11188 /*isInline=*/true, Constexpr, SourceLocation());
11189 CopyAssignment->setAccess(AS_public);
11190 CopyAssignment->setDefaulted();
11191 CopyAssignment->setImplicit();
11193 if (getLangOpts().CUDA) {
11194 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11196 /* ConstRHS */ Const,
11197 /* Diagnose */ false);
11200 // Build an exception specification pointing back at this member.
11201 FunctionProtoType::ExtProtoInfo EPI =
11202 getImplicitMethodEPI(*this, CopyAssignment);
11203 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11205 // Add the parameter to the operator.
11206 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11207 ClassLoc, ClassLoc,
11208 /*Id=*/nullptr, ArgType,
11209 /*TInfo=*/nullptr, SC_None,
11211 CopyAssignment->setParams(FromParam);
11213 CopyAssignment->setTrivial(
11214 ClassDecl->needsOverloadResolutionForCopyAssignment()
11215 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11216 : ClassDecl->hasTrivialCopyAssignment());
11218 // Note that we have added this copy-assignment operator.
11219 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11221 Scope *S = getScopeForContext(ClassDecl);
11222 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11224 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11225 SetDeclDeleted(CopyAssignment, ClassLoc);
11228 PushOnScopeChains(CopyAssignment, S, false);
11229 ClassDecl->addDecl(CopyAssignment);
11231 return CopyAssignment;
11234 /// Diagnose an implicit copy operation for a class which is odr-used, but
11235 /// which is deprecated because the class has a user-declared copy constructor,
11236 /// copy assignment operator, or destructor.
11237 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11238 assert(CopyOp->isImplicit());
11240 CXXRecordDecl *RD = CopyOp->getParent();
11241 CXXMethodDecl *UserDeclaredOperation = nullptr;
11243 // In Microsoft mode, assignment operations don't affect constructors and
11245 if (RD->hasUserDeclaredDestructor()) {
11246 UserDeclaredOperation = RD->getDestructor();
11247 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11248 RD->hasUserDeclaredCopyConstructor() &&
11249 !S.getLangOpts().MSVCCompat) {
11250 // Find any user-declared copy constructor.
11251 for (auto *I : RD->ctors()) {
11252 if (I->isCopyConstructor()) {
11253 UserDeclaredOperation = I;
11257 assert(UserDeclaredOperation);
11258 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11259 RD->hasUserDeclaredCopyAssignment() &&
11260 !S.getLangOpts().MSVCCompat) {
11261 // Find any user-declared move assignment operator.
11262 for (auto *I : RD->methods()) {
11263 if (I->isCopyAssignmentOperator()) {
11264 UserDeclaredOperation = I;
11268 assert(UserDeclaredOperation);
11271 if (UserDeclaredOperation) {
11272 S.Diag(UserDeclaredOperation->getLocation(),
11273 diag::warn_deprecated_copy_operation)
11274 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11275 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11279 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11280 CXXMethodDecl *CopyAssignOperator) {
11281 assert((CopyAssignOperator->isDefaulted() &&
11282 CopyAssignOperator->isOverloadedOperator() &&
11283 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11284 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11285 !CopyAssignOperator->isDeleted()) &&
11286 "DefineImplicitCopyAssignment called for wrong function");
11287 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11290 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11291 if (ClassDecl->isInvalidDecl()) {
11292 CopyAssignOperator->setInvalidDecl();
11296 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11298 // The exception specification is needed because we are defining the
11300 ResolveExceptionSpec(CurrentLocation,
11301 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11303 // Add a context note for diagnostics produced after this point.
11304 Scope.addContextNote(CurrentLocation);
11306 // C++11 [class.copy]p18:
11307 // The [definition of an implicitly declared copy assignment operator] is
11308 // deprecated if the class has a user-declared copy constructor or a
11309 // user-declared destructor.
11310 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11311 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11313 // C++0x [class.copy]p30:
11314 // The implicitly-defined or explicitly-defaulted copy assignment operator
11315 // for a non-union class X performs memberwise copy assignment of its
11316 // subobjects. The direct base classes of X are assigned first, in the
11317 // order of their declaration in the base-specifier-list, and then the
11318 // immediate non-static data members of X are assigned, in the order in
11319 // which they were declared in the class definition.
11321 // The statements that form the synthesized function body.
11322 SmallVector<Stmt*, 8> Statements;
11324 // The parameter for the "other" object, which we are copying from.
11325 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11326 Qualifiers OtherQuals = Other->getType().getQualifiers();
11327 QualType OtherRefType = Other->getType();
11328 if (const LValueReferenceType *OtherRef
11329 = OtherRefType->getAs<LValueReferenceType>()) {
11330 OtherRefType = OtherRef->getPointeeType();
11331 OtherQuals = OtherRefType.getQualifiers();
11334 // Our location for everything implicitly-generated.
11335 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11336 ? CopyAssignOperator->getLocEnd()
11337 : CopyAssignOperator->getLocation();
11339 // Builds a DeclRefExpr for the "other" object.
11340 RefBuilder OtherRef(Other, OtherRefType);
11342 // Builds the "this" pointer.
11345 // Assign base classes.
11346 bool Invalid = false;
11347 for (auto &Base : ClassDecl->bases()) {
11348 // Form the assignment:
11349 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11350 QualType BaseType = Base.getType().getUnqualifiedType();
11351 if (!BaseType->isRecordType()) {
11356 CXXCastPath BasePath;
11357 BasePath.push_back(&Base);
11359 // Construct the "from" expression, which is an implicit cast to the
11360 // appropriately-qualified base type.
11361 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11362 VK_LValue, BasePath);
11364 // Dereference "this".
11365 DerefBuilder DerefThis(This);
11366 CastBuilder To(DerefThis,
11367 Context.getCVRQualifiedType(
11368 BaseType, CopyAssignOperator->getTypeQualifiers()),
11369 VK_LValue, BasePath);
11372 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11374 /*CopyingBaseSubobject=*/true,
11376 if (Copy.isInvalid()) {
11377 CopyAssignOperator->setInvalidDecl();
11381 // Success! Record the copy.
11382 Statements.push_back(Copy.getAs<Expr>());
11385 // Assign non-static members.
11386 for (auto *Field : ClassDecl->fields()) {
11387 // FIXME: We should form some kind of AST representation for the implied
11388 // memcpy in a union copy operation.
11389 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11392 if (Field->isInvalidDecl()) {
11397 // Check for members of reference type; we can't copy those.
11398 if (Field->getType()->isReferenceType()) {
11399 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11400 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11401 Diag(Field->getLocation(), diag::note_declared_at);
11406 // Check for members of const-qualified, non-class type.
11407 QualType BaseType = Context.getBaseElementType(Field->getType());
11408 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11409 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11410 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11411 Diag(Field->getLocation(), diag::note_declared_at);
11416 // Suppress assigning zero-width bitfields.
11417 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11420 QualType FieldType = Field->getType().getNonReferenceType();
11421 if (FieldType->isIncompleteArrayType()) {
11422 assert(ClassDecl->hasFlexibleArrayMember() &&
11423 "Incomplete array type is not valid");
11427 // Build references to the field in the object we're copying from and to.
11428 CXXScopeSpec SS; // Intentionally empty
11429 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11431 MemberLookup.addDecl(Field);
11432 MemberLookup.resolveKind();
11434 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11436 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11438 // Build the copy of this field.
11439 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11441 /*CopyingBaseSubobject=*/false,
11443 if (Copy.isInvalid()) {
11444 CopyAssignOperator->setInvalidDecl();
11448 // Success! Record the copy.
11449 Statements.push_back(Copy.getAs<Stmt>());
11453 // Add a "return *this;"
11454 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11456 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11457 if (Return.isInvalid())
11460 Statements.push_back(Return.getAs<Stmt>());
11464 CopyAssignOperator->setInvalidDecl();
11470 CompoundScopeRAII CompoundScope(*this);
11471 Body = ActOnCompoundStmt(Loc, Loc, Statements,
11472 /*isStmtExpr=*/false);
11473 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11475 CopyAssignOperator->setBody(Body.getAs<Stmt>());
11476 CopyAssignOperator->markUsed(Context);
11478 if (ASTMutationListener *L = getASTMutationListener()) {
11479 L->CompletedImplicitDefinition(CopyAssignOperator);
11483 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11484 assert(ClassDecl->needsImplicitMoveAssignment());
11486 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11487 if (DSM.isAlreadyBeingDeclared())
11490 // Note: The following rules are largely analoguous to the move
11491 // constructor rules.
11493 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11494 QualType RetType = Context.getLValueReferenceType(ArgType);
11495 ArgType = Context.getRValueReferenceType(ArgType);
11497 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11501 // An implicitly-declared move assignment operator is an inline public
11502 // member of its class.
11503 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11504 SourceLocation ClassLoc = ClassDecl->getLocation();
11505 DeclarationNameInfo NameInfo(Name, ClassLoc);
11506 CXXMethodDecl *MoveAssignment =
11507 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11508 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11509 /*isInline=*/true, Constexpr, SourceLocation());
11510 MoveAssignment->setAccess(AS_public);
11511 MoveAssignment->setDefaulted();
11512 MoveAssignment->setImplicit();
11514 if (getLangOpts().CUDA) {
11515 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11517 /* ConstRHS */ false,
11518 /* Diagnose */ false);
11521 // Build an exception specification pointing back at this member.
11522 FunctionProtoType::ExtProtoInfo EPI =
11523 getImplicitMethodEPI(*this, MoveAssignment);
11524 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11526 // Add the parameter to the operator.
11527 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11528 ClassLoc, ClassLoc,
11529 /*Id=*/nullptr, ArgType,
11530 /*TInfo=*/nullptr, SC_None,
11532 MoveAssignment->setParams(FromParam);
11534 MoveAssignment->setTrivial(
11535 ClassDecl->needsOverloadResolutionForMoveAssignment()
11536 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11537 : ClassDecl->hasTrivialMoveAssignment());
11539 // Note that we have added this copy-assignment operator.
11540 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11542 Scope *S = getScopeForContext(ClassDecl);
11543 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11545 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11546 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11547 SetDeclDeleted(MoveAssignment, ClassLoc);
11551 PushOnScopeChains(MoveAssignment, S, false);
11552 ClassDecl->addDecl(MoveAssignment);
11554 return MoveAssignment;
11557 /// Check if we're implicitly defining a move assignment operator for a class
11558 /// with virtual bases. Such a move assignment might move-assign the virtual
11559 /// base multiple times.
11560 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11561 SourceLocation CurrentLocation) {
11562 assert(!Class->isDependentContext() && "should not define dependent move");
11564 // Only a virtual base could get implicitly move-assigned multiple times.
11565 // Only a non-trivial move assignment can observe this. We only want to
11566 // diagnose if we implicitly define an assignment operator that assigns
11567 // two base classes, both of which move-assign the same virtual base.
11568 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11569 Class->getNumBases() < 2)
11572 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11573 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11576 for (auto &BI : Class->bases()) {
11577 Worklist.push_back(&BI);
11578 while (!Worklist.empty()) {
11579 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11580 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11582 // If the base has no non-trivial move assignment operators,
11583 // we don't care about moves from it.
11584 if (!Base->hasNonTrivialMoveAssignment())
11587 // If there's nothing virtual here, skip it.
11588 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11591 // If we're not actually going to call a move assignment for this base,
11592 // or the selected move assignment is trivial, skip it.
11593 Sema::SpecialMemberOverloadResult SMOR =
11594 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11595 /*ConstArg*/false, /*VolatileArg*/false,
11596 /*RValueThis*/true, /*ConstThis*/false,
11597 /*VolatileThis*/false);
11598 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11599 !SMOR.getMethod()->isMoveAssignmentOperator())
11602 if (BaseSpec->isVirtual()) {
11603 // We're going to move-assign this virtual base, and its move
11604 // assignment operator is not trivial. If this can happen for
11605 // multiple distinct direct bases of Class, diagnose it. (If it
11606 // only happens in one base, we'll diagnose it when synthesizing
11607 // that base class's move assignment operator.)
11608 CXXBaseSpecifier *&Existing =
11609 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11611 if (Existing && Existing != &BI) {
11612 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11614 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11615 << (Base->getCanonicalDecl() ==
11616 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11617 << Base << Existing->getType() << Existing->getSourceRange();
11618 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11619 << (Base->getCanonicalDecl() ==
11620 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11621 << Base << BI.getType() << BaseSpec->getSourceRange();
11623 // Only diagnose each vbase once.
11624 Existing = nullptr;
11627 // Only walk over bases that have defaulted move assignment operators.
11628 // We assume that any user-provided move assignment operator handles
11629 // the multiple-moves-of-vbase case itself somehow.
11630 if (!SMOR.getMethod()->isDefaulted())
11633 // We're going to move the base classes of Base. Add them to the list.
11634 for (auto &BI : Base->bases())
11635 Worklist.push_back(&BI);
11641 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11642 CXXMethodDecl *MoveAssignOperator) {
11643 assert((MoveAssignOperator->isDefaulted() &&
11644 MoveAssignOperator->isOverloadedOperator() &&
11645 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11646 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11647 !MoveAssignOperator->isDeleted()) &&
11648 "DefineImplicitMoveAssignment called for wrong function");
11649 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
11652 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11653 if (ClassDecl->isInvalidDecl()) {
11654 MoveAssignOperator->setInvalidDecl();
11658 // C++0x [class.copy]p28:
11659 // The implicitly-defined or move assignment operator for a non-union class
11660 // X performs memberwise move assignment of its subobjects. The direct base
11661 // classes of X are assigned first, in the order of their declaration in the
11662 // base-specifier-list, and then the immediate non-static data members of X
11663 // are assigned, in the order in which they were declared in the class
11666 // Issue a warning if our implicit move assignment operator will move
11667 // from a virtual base more than once.
11668 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11670 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11672 // The exception specification is needed because we are defining the
11674 ResolveExceptionSpec(CurrentLocation,
11675 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11677 // Add a context note for diagnostics produced after this point.
11678 Scope.addContextNote(CurrentLocation);
11680 // The statements that form the synthesized function body.
11681 SmallVector<Stmt*, 8> Statements;
11683 // The parameter for the "other" object, which we are move from.
11684 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11685 QualType OtherRefType = Other->getType()->
11686 getAs<RValueReferenceType>()->getPointeeType();
11687 assert(!OtherRefType.getQualifiers() &&
11688 "Bad argument type of defaulted move assignment");
11690 // Our location for everything implicitly-generated.
11691 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11692 ? MoveAssignOperator->getLocEnd()
11693 : MoveAssignOperator->getLocation();
11695 // Builds a reference to the "other" object.
11696 RefBuilder OtherRef(Other, OtherRefType);
11698 MoveCastBuilder MoveOther(OtherRef);
11700 // Builds the "this" pointer.
11703 // Assign base classes.
11704 bool Invalid = false;
11705 for (auto &Base : ClassDecl->bases()) {
11706 // C++11 [class.copy]p28:
11707 // It is unspecified whether subobjects representing virtual base classes
11708 // are assigned more than once by the implicitly-defined copy assignment
11710 // FIXME: Do not assign to a vbase that will be assigned by some other base
11711 // class. For a move-assignment, this can result in the vbase being moved
11714 // Form the assignment:
11715 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11716 QualType BaseType = Base.getType().getUnqualifiedType();
11717 if (!BaseType->isRecordType()) {
11722 CXXCastPath BasePath;
11723 BasePath.push_back(&Base);
11725 // Construct the "from" expression, which is an implicit cast to the
11726 // appropriately-qualified base type.
11727 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11729 // Dereference "this".
11730 DerefBuilder DerefThis(This);
11732 // Implicitly cast "this" to the appropriately-qualified base type.
11733 CastBuilder To(DerefThis,
11734 Context.getCVRQualifiedType(
11735 BaseType, MoveAssignOperator->getTypeQualifiers()),
11736 VK_LValue, BasePath);
11739 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11741 /*CopyingBaseSubobject=*/true,
11742 /*Copying=*/false);
11743 if (Move.isInvalid()) {
11744 MoveAssignOperator->setInvalidDecl();
11748 // Success! Record the move.
11749 Statements.push_back(Move.getAs<Expr>());
11752 // Assign non-static members.
11753 for (auto *Field : ClassDecl->fields()) {
11754 // FIXME: We should form some kind of AST representation for the implied
11755 // memcpy in a union copy operation.
11756 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11759 if (Field->isInvalidDecl()) {
11764 // Check for members of reference type; we can't move those.
11765 if (Field->getType()->isReferenceType()) {
11766 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11767 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11768 Diag(Field->getLocation(), diag::note_declared_at);
11773 // Check for members of const-qualified, non-class type.
11774 QualType BaseType = Context.getBaseElementType(Field->getType());
11775 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11776 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11777 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11778 Diag(Field->getLocation(), diag::note_declared_at);
11783 // Suppress assigning zero-width bitfields.
11784 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11787 QualType FieldType = Field->getType().getNonReferenceType();
11788 if (FieldType->isIncompleteArrayType()) {
11789 assert(ClassDecl->hasFlexibleArrayMember() &&
11790 "Incomplete array type is not valid");
11794 // Build references to the field in the object we're copying from and to.
11795 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11797 MemberLookup.addDecl(Field);
11798 MemberLookup.resolveKind();
11799 MemberBuilder From(MoveOther, OtherRefType,
11800 /*IsArrow=*/false, MemberLookup);
11801 MemberBuilder To(This, getCurrentThisType(),
11802 /*IsArrow=*/true, MemberLookup);
11804 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11805 "Member reference with rvalue base must be rvalue except for reference "
11806 "members, which aren't allowed for move assignment.");
11808 // Build the move of this field.
11809 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11811 /*CopyingBaseSubobject=*/false,
11812 /*Copying=*/false);
11813 if (Move.isInvalid()) {
11814 MoveAssignOperator->setInvalidDecl();
11818 // Success! Record the copy.
11819 Statements.push_back(Move.getAs<Stmt>());
11823 // Add a "return *this;"
11824 ExprResult ThisObj =
11825 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11827 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11828 if (Return.isInvalid())
11831 Statements.push_back(Return.getAs<Stmt>());
11835 MoveAssignOperator->setInvalidDecl();
11841 CompoundScopeRAII CompoundScope(*this);
11842 Body = ActOnCompoundStmt(Loc, Loc, Statements,
11843 /*isStmtExpr=*/false);
11844 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11846 MoveAssignOperator->setBody(Body.getAs<Stmt>());
11847 MoveAssignOperator->markUsed(Context);
11849 if (ASTMutationListener *L = getASTMutationListener()) {
11850 L->CompletedImplicitDefinition(MoveAssignOperator);
11854 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11855 CXXRecordDecl *ClassDecl) {
11856 // C++ [class.copy]p4:
11857 // If the class definition does not explicitly declare a copy
11858 // constructor, one is declared implicitly.
11859 assert(ClassDecl->needsImplicitCopyConstructor());
11861 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11862 if (DSM.isAlreadyBeingDeclared())
11865 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11866 QualType ArgType = ClassType;
11867 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11869 ArgType = ArgType.withConst();
11870 ArgType = Context.getLValueReferenceType(ArgType);
11872 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11873 CXXCopyConstructor,
11876 DeclarationName Name
11877 = Context.DeclarationNames.getCXXConstructorName(
11878 Context.getCanonicalType(ClassType));
11879 SourceLocation ClassLoc = ClassDecl->getLocation();
11880 DeclarationNameInfo NameInfo(Name, ClassLoc);
11882 // An implicitly-declared copy constructor is an inline public
11883 // member of its class.
11884 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11885 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11886 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11888 CopyConstructor->setAccess(AS_public);
11889 CopyConstructor->setDefaulted();
11891 if (getLangOpts().CUDA) {
11892 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
11894 /* ConstRHS */ Const,
11895 /* Diagnose */ false);
11898 // Build an exception specification pointing back at this member.
11899 FunctionProtoType::ExtProtoInfo EPI =
11900 getImplicitMethodEPI(*this, CopyConstructor);
11901 CopyConstructor->setType(
11902 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
11904 // Add the parameter to the constructor.
11905 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
11906 ClassLoc, ClassLoc,
11907 /*IdentifierInfo=*/nullptr,
11908 ArgType, /*TInfo=*/nullptr,
11910 CopyConstructor->setParams(FromParam);
11912 CopyConstructor->setTrivial(
11913 ClassDecl->needsOverloadResolutionForCopyConstructor()
11914 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
11915 : ClassDecl->hasTrivialCopyConstructor());
11917 // Note that we have declared this constructor.
11918 ++ASTContext::NumImplicitCopyConstructorsDeclared;
11920 Scope *S = getScopeForContext(ClassDecl);
11921 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
11923 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
11924 SetDeclDeleted(CopyConstructor, ClassLoc);
11927 PushOnScopeChains(CopyConstructor, S, false);
11928 ClassDecl->addDecl(CopyConstructor);
11930 return CopyConstructor;
11933 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
11934 CXXConstructorDecl *CopyConstructor) {
11935 assert((CopyConstructor->isDefaulted() &&
11936 CopyConstructor->isCopyConstructor() &&
11937 !CopyConstructor->doesThisDeclarationHaveABody() &&
11938 !CopyConstructor->isDeleted()) &&
11939 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
11940 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
11943 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
11944 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
11946 SynthesizedFunctionScope Scope(*this, CopyConstructor);
11948 // The exception specification is needed because we are defining the
11950 ResolveExceptionSpec(CurrentLocation,
11951 CopyConstructor->getType()->castAs<FunctionProtoType>());
11952 MarkVTableUsed(CurrentLocation, ClassDecl);
11954 // Add a context note for diagnostics produced after this point.
11955 Scope.addContextNote(CurrentLocation);
11957 // C++11 [class.copy]p7:
11958 // The [definition of an implicitly declared copy constructor] is
11959 // deprecated if the class has a user-declared copy assignment operator
11960 // or a user-declared destructor.
11961 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
11962 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
11964 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
11965 CopyConstructor->setInvalidDecl();
11967 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
11968 ? CopyConstructor->getLocEnd()
11969 : CopyConstructor->getLocation();
11970 Sema::CompoundScopeRAII CompoundScope(*this);
11971 CopyConstructor->setBody(
11972 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
11973 CopyConstructor->markUsed(Context);
11976 if (ASTMutationListener *L = getASTMutationListener()) {
11977 L->CompletedImplicitDefinition(CopyConstructor);
11981 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
11982 CXXRecordDecl *ClassDecl) {
11983 assert(ClassDecl->needsImplicitMoveConstructor());
11985 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
11986 if (DSM.isAlreadyBeingDeclared())
11989 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11990 QualType ArgType = Context.getRValueReferenceType(ClassType);
11992 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11993 CXXMoveConstructor,
11996 DeclarationName Name
11997 = Context.DeclarationNames.getCXXConstructorName(
11998 Context.getCanonicalType(ClassType));
11999 SourceLocation ClassLoc = ClassDecl->getLocation();
12000 DeclarationNameInfo NameInfo(Name, ClassLoc);
12002 // C++11 [class.copy]p11:
12003 // An implicitly-declared copy/move constructor is an inline public
12004 // member of its class.
12005 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12006 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12007 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12009 MoveConstructor->setAccess(AS_public);
12010 MoveConstructor->setDefaulted();
12012 if (getLangOpts().CUDA) {
12013 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12015 /* ConstRHS */ false,
12016 /* Diagnose */ false);
12019 // Build an exception specification pointing back at this member.
12020 FunctionProtoType::ExtProtoInfo EPI =
12021 getImplicitMethodEPI(*this, MoveConstructor);
12022 MoveConstructor->setType(
12023 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12025 // Add the parameter to the constructor.
12026 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12027 ClassLoc, ClassLoc,
12028 /*IdentifierInfo=*/nullptr,
12029 ArgType, /*TInfo=*/nullptr,
12031 MoveConstructor->setParams(FromParam);
12033 MoveConstructor->setTrivial(
12034 ClassDecl->needsOverloadResolutionForMoveConstructor()
12035 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12036 : ClassDecl->hasTrivialMoveConstructor());
12038 // Note that we have declared this constructor.
12039 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12041 Scope *S = getScopeForContext(ClassDecl);
12042 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12044 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12045 ClassDecl->setImplicitMoveConstructorIsDeleted();
12046 SetDeclDeleted(MoveConstructor, ClassLoc);
12050 PushOnScopeChains(MoveConstructor, S, false);
12051 ClassDecl->addDecl(MoveConstructor);
12053 return MoveConstructor;
12056 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12057 CXXConstructorDecl *MoveConstructor) {
12058 assert((MoveConstructor->isDefaulted() &&
12059 MoveConstructor->isMoveConstructor() &&
12060 !MoveConstructor->doesThisDeclarationHaveABody() &&
12061 !MoveConstructor->isDeleted()) &&
12062 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12063 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12066 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12067 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12069 SynthesizedFunctionScope Scope(*this, MoveConstructor);
12071 // The exception specification is needed because we are defining the
12073 ResolveExceptionSpec(CurrentLocation,
12074 MoveConstructor->getType()->castAs<FunctionProtoType>());
12075 MarkVTableUsed(CurrentLocation, ClassDecl);
12077 // Add a context note for diagnostics produced after this point.
12078 Scope.addContextNote(CurrentLocation);
12080 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12081 MoveConstructor->setInvalidDecl();
12083 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12084 ? MoveConstructor->getLocEnd()
12085 : MoveConstructor->getLocation();
12086 Sema::CompoundScopeRAII CompoundScope(*this);
12087 MoveConstructor->setBody(ActOnCompoundStmt(
12088 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12089 MoveConstructor->markUsed(Context);
12092 if (ASTMutationListener *L = getASTMutationListener()) {
12093 L->CompletedImplicitDefinition(MoveConstructor);
12097 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12098 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12101 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12102 SourceLocation CurrentLocation,
12103 CXXConversionDecl *Conv) {
12104 SynthesizedFunctionScope Scope(*this, Conv);
12106 CXXRecordDecl *Lambda = Conv->getParent();
12107 CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
12108 // If we are defining a specialization of a conversion to function-ptr
12109 // cache the deduced template arguments for this specialization
12110 // so that we can use them to retrieve the corresponding call-operator
12111 // and static-invoker.
12112 const TemplateArgumentList *DeducedTemplateArgs = nullptr;
12114 // Retrieve the corresponding call-operator specialization.
12115 if (Lambda->isGenericLambda()) {
12116 assert(Conv->isFunctionTemplateSpecialization());
12117 FunctionTemplateDecl *CallOpTemplate =
12118 CallOp->getDescribedFunctionTemplate();
12119 DeducedTemplateArgs = Conv->getTemplateSpecializationArgs();
12120 void *InsertPos = nullptr;
12121 FunctionDecl *CallOpSpec = CallOpTemplate->findSpecialization(
12122 DeducedTemplateArgs->asArray(),
12124 assert(CallOpSpec &&
12125 "Conversion operator must have a corresponding call operator");
12126 CallOp = cast<CXXMethodDecl>(CallOpSpec);
12129 // Mark the call operator referenced (and add to pending instantiations
12131 // For both the conversion and static-invoker template specializations
12132 // we construct their body's in this function, so no need to add them
12133 // to the PendingInstantiations.
12134 MarkFunctionReferenced(CurrentLocation, CallOp);
12136 // Retrieve the static invoker...
12137 CXXMethodDecl *Invoker = Lambda->getLambdaStaticInvoker();
12138 // ... and get the corresponding specialization for a generic lambda.
12139 if (Lambda->isGenericLambda()) {
12140 assert(DeducedTemplateArgs &&
12141 "Must have deduced template arguments from Conversion Operator");
12142 FunctionTemplateDecl *InvokeTemplate =
12143 Invoker->getDescribedFunctionTemplate();
12144 void *InsertPos = nullptr;
12145 FunctionDecl *InvokeSpec = InvokeTemplate->findSpecialization(
12146 DeducedTemplateArgs->asArray(),
12148 assert(InvokeSpec &&
12149 "Must have a corresponding static invoker specialization");
12150 Invoker = cast<CXXMethodDecl>(InvokeSpec);
12152 // Construct the body of the conversion function { return __invoke; }.
12153 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12154 VK_LValue, Conv->getLocation()).get();
12155 assert(FunctionRef && "Can't refer to __invoke function?");
12156 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12157 Conv->setBody(new (Context) CompoundStmt(Context, Return,
12158 Conv->getLocation(),
12159 Conv->getLocation()));
12161 Conv->markUsed(Context);
12162 Conv->setReferenced();
12164 // Fill in the __invoke function with a dummy implementation. IR generation
12165 // will fill in the actual details.
12166 Invoker->markUsed(Context);
12167 Invoker->setReferenced();
12168 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12170 if (ASTMutationListener *L = getASTMutationListener()) {
12171 L->CompletedImplicitDefinition(Conv);
12172 L->CompletedImplicitDefinition(Invoker);
12178 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12179 SourceLocation CurrentLocation,
12180 CXXConversionDecl *Conv)
12182 assert(!Conv->getParent()->isGenericLambda());
12184 SynthesizedFunctionScope Scope(*this, Conv);
12186 // Copy-initialize the lambda object as needed to capture it.
12187 Expr *This = ActOnCXXThis(CurrentLocation).get();
12188 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12190 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12191 Conv->getLocation(),
12194 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12195 // behavior. Note that only the general conversion function does this
12196 // (since it's unusable otherwise); in the case where we inline the
12197 // block literal, it has block literal lifetime semantics.
12198 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12199 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12200 CK_CopyAndAutoreleaseBlockObject,
12201 BuildBlock.get(), nullptr, VK_RValue);
12203 if (BuildBlock.isInvalid()) {
12204 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12205 Conv->setInvalidDecl();
12209 // Create the return statement that returns the block from the conversion
12211 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12212 if (Return.isInvalid()) {
12213 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12214 Conv->setInvalidDecl();
12218 // Set the body of the conversion function.
12219 Stmt *ReturnS = Return.get();
12220 Conv->setBody(new (Context) CompoundStmt(Context, ReturnS,
12221 Conv->getLocation(),
12222 Conv->getLocation()));
12223 Conv->markUsed(Context);
12225 // We're done; notify the mutation listener, if any.
12226 if (ASTMutationListener *L = getASTMutationListener()) {
12227 L->CompletedImplicitDefinition(Conv);
12231 /// \brief Determine whether the given list arguments contains exactly one
12232 /// "real" (non-default) argument.
12233 static bool hasOneRealArgument(MultiExprArg Args) {
12234 switch (Args.size()) {
12239 if (!Args[1]->isDefaultArgument())
12244 return !Args[0]->isDefaultArgument();
12251 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12252 NamedDecl *FoundDecl,
12253 CXXConstructorDecl *Constructor,
12254 MultiExprArg ExprArgs,
12255 bool HadMultipleCandidates,
12256 bool IsListInitialization,
12257 bool IsStdInitListInitialization,
12258 bool RequiresZeroInit,
12259 unsigned ConstructKind,
12260 SourceRange ParenRange) {
12261 bool Elidable = false;
12263 // C++0x [class.copy]p34:
12264 // When certain criteria are met, an implementation is allowed to
12265 // omit the copy/move construction of a class object, even if the
12266 // copy/move constructor and/or destructor for the object have
12267 // side effects. [...]
12268 // - when a temporary class object that has not been bound to a
12269 // reference (12.2) would be copied/moved to a class object
12270 // with the same cv-unqualified type, the copy/move operation
12271 // can be omitted by constructing the temporary object
12272 // directly into the target of the omitted copy/move
12273 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12274 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12275 Expr *SubExpr = ExprArgs[0];
12276 Elidable = SubExpr->isTemporaryObject(
12277 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12280 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12281 FoundDecl, Constructor,
12282 Elidable, ExprArgs, HadMultipleCandidates,
12283 IsListInitialization,
12284 IsStdInitListInitialization, RequiresZeroInit,
12285 ConstructKind, ParenRange);
12289 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12290 NamedDecl *FoundDecl,
12291 CXXConstructorDecl *Constructor,
12293 MultiExprArg ExprArgs,
12294 bool HadMultipleCandidates,
12295 bool IsListInitialization,
12296 bool IsStdInitListInitialization,
12297 bool RequiresZeroInit,
12298 unsigned ConstructKind,
12299 SourceRange ParenRange) {
12300 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12301 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12302 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12303 return ExprError();
12306 return BuildCXXConstructExpr(
12307 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12308 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12309 RequiresZeroInit, ConstructKind, ParenRange);
12312 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12313 /// including handling of its default argument expressions.
12315 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12316 CXXConstructorDecl *Constructor,
12318 MultiExprArg ExprArgs,
12319 bool HadMultipleCandidates,
12320 bool IsListInitialization,
12321 bool IsStdInitListInitialization,
12322 bool RequiresZeroInit,
12323 unsigned ConstructKind,
12324 SourceRange ParenRange) {
12325 assert(declaresSameEntity(
12326 Constructor->getParent(),
12327 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12328 "given constructor for wrong type");
12329 MarkFunctionReferenced(ConstructLoc, Constructor);
12330 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12331 return ExprError();
12333 return CXXConstructExpr::Create(
12334 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12335 ExprArgs, HadMultipleCandidates, IsListInitialization,
12336 IsStdInitListInitialization, RequiresZeroInit,
12337 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12341 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12342 assert(Field->hasInClassInitializer());
12344 // If we already have the in-class initializer nothing needs to be done.
12345 if (Field->getInClassInitializer())
12346 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12348 // If we might have already tried and failed to instantiate, don't try again.
12349 if (Field->isInvalidDecl())
12350 return ExprError();
12352 // Maybe we haven't instantiated the in-class initializer. Go check the
12353 // pattern FieldDecl to see if it has one.
12354 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12356 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12357 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12358 DeclContext::lookup_result Lookup =
12359 ClassPattern->lookup(Field->getDeclName());
12361 // Lookup can return at most two results: the pattern for the field, or the
12362 // injected class name of the parent record. No other member can have the
12363 // same name as the field.
12364 // In modules mode, lookup can return multiple results (coming from
12365 // different modules).
12366 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12367 "more than two lookup results for field name");
12368 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12370 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12371 "cannot have other non-field member with same name");
12372 for (auto L : Lookup)
12373 if (isa<FieldDecl>(L)) {
12374 Pattern = cast<FieldDecl>(L);
12377 assert(Pattern && "We must have set the Pattern!");
12380 if (InstantiateInClassInitializer(Loc, Field, Pattern,
12381 getTemplateInstantiationArgs(Field))) {
12382 // Don't diagnose this again.
12383 Field->setInvalidDecl();
12384 return ExprError();
12386 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12390 // If the brace-or-equal-initializer of a non-static data member
12391 // invokes a defaulted default constructor of its class or of an
12392 // enclosing class in a potentially evaluated subexpression, the
12393 // program is ill-formed.
12395 // This resolution is unworkable: the exception specification of the
12396 // default constructor can be needed in an unevaluated context, in
12397 // particular, in the operand of a noexcept-expression, and we can be
12398 // unable to compute an exception specification for an enclosed class.
12400 // Any attempt to resolve the exception specification of a defaulted default
12401 // constructor before the initializer is lexically complete will ultimately
12402 // come here at which point we can diagnose it.
12403 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12404 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12405 << OutermostClass << Field;
12406 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12407 // Recover by marking the field invalid, unless we're in a SFINAE context.
12408 if (!isSFINAEContext())
12409 Field->setInvalidDecl();
12410 return ExprError();
12413 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12414 if (VD->isInvalidDecl()) return;
12416 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12417 if (ClassDecl->isInvalidDecl()) return;
12418 if (ClassDecl->hasIrrelevantDestructor()) return;
12419 if (ClassDecl->isDependentContext()) return;
12421 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12422 MarkFunctionReferenced(VD->getLocation(), Destructor);
12423 CheckDestructorAccess(VD->getLocation(), Destructor,
12424 PDiag(diag::err_access_dtor_var)
12425 << VD->getDeclName()
12427 DiagnoseUseOfDecl(Destructor, VD->getLocation());
12429 if (Destructor->isTrivial()) return;
12430 if (!VD->hasGlobalStorage()) return;
12432 // Emit warning for non-trivial dtor in global scope (a real global,
12433 // class-static, function-static).
12434 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12436 // TODO: this should be re-enabled for static locals by !CXAAtExit
12437 if (!VD->isStaticLocal())
12438 Diag(VD->getLocation(), diag::warn_global_destructor);
12441 /// \brief Given a constructor and the set of arguments provided for the
12442 /// constructor, convert the arguments and add any required default arguments
12443 /// to form a proper call to this constructor.
12445 /// \returns true if an error occurred, false otherwise.
12447 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12448 MultiExprArg ArgsPtr,
12449 SourceLocation Loc,
12450 SmallVectorImpl<Expr*> &ConvertedArgs,
12451 bool AllowExplicit,
12452 bool IsListInitialization) {
12453 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12454 unsigned NumArgs = ArgsPtr.size();
12455 Expr **Args = ArgsPtr.data();
12457 const FunctionProtoType *Proto
12458 = Constructor->getType()->getAs<FunctionProtoType>();
12459 assert(Proto && "Constructor without a prototype?");
12460 unsigned NumParams = Proto->getNumParams();
12462 // If too few arguments are available, we'll fill in the rest with defaults.
12463 if (NumArgs < NumParams)
12464 ConvertedArgs.reserve(NumParams);
12466 ConvertedArgs.reserve(NumArgs);
12468 VariadicCallType CallType =
12469 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12470 SmallVector<Expr *, 8> AllArgs;
12471 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12473 llvm::makeArrayRef(Args, NumArgs),
12475 CallType, AllowExplicit,
12476 IsListInitialization);
12477 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12479 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12481 CheckConstructorCall(Constructor,
12482 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12489 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12490 const FunctionDecl *FnDecl) {
12491 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12492 if (isa<NamespaceDecl>(DC)) {
12493 return SemaRef.Diag(FnDecl->getLocation(),
12494 diag::err_operator_new_delete_declared_in_namespace)
12495 << FnDecl->getDeclName();
12498 if (isa<TranslationUnitDecl>(DC) &&
12499 FnDecl->getStorageClass() == SC_Static) {
12500 return SemaRef.Diag(FnDecl->getLocation(),
12501 diag::err_operator_new_delete_declared_static)
12502 << FnDecl->getDeclName();
12509 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12510 CanQualType ExpectedResultType,
12511 CanQualType ExpectedFirstParamType,
12512 unsigned DependentParamTypeDiag,
12513 unsigned InvalidParamTypeDiag) {
12514 QualType ResultType =
12515 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12517 // Check that the result type is not dependent.
12518 if (ResultType->isDependentType())
12519 return SemaRef.Diag(FnDecl->getLocation(),
12520 diag::err_operator_new_delete_dependent_result_type)
12521 << FnDecl->getDeclName() << ExpectedResultType;
12523 // Check that the result type is what we expect.
12524 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12525 return SemaRef.Diag(FnDecl->getLocation(),
12526 diag::err_operator_new_delete_invalid_result_type)
12527 << FnDecl->getDeclName() << ExpectedResultType;
12529 // A function template must have at least 2 parameters.
12530 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12531 return SemaRef.Diag(FnDecl->getLocation(),
12532 diag::err_operator_new_delete_template_too_few_parameters)
12533 << FnDecl->getDeclName();
12535 // The function decl must have at least 1 parameter.
12536 if (FnDecl->getNumParams() == 0)
12537 return SemaRef.Diag(FnDecl->getLocation(),
12538 diag::err_operator_new_delete_too_few_parameters)
12539 << FnDecl->getDeclName();
12541 // Check the first parameter type is not dependent.
12542 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12543 if (FirstParamType->isDependentType())
12544 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12545 << FnDecl->getDeclName() << ExpectedFirstParamType;
12547 // Check that the first parameter type is what we expect.
12548 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12549 ExpectedFirstParamType)
12550 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12551 << FnDecl->getDeclName() << ExpectedFirstParamType;
12557 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12558 // C++ [basic.stc.dynamic.allocation]p1:
12559 // A program is ill-formed if an allocation function is declared in a
12560 // namespace scope other than global scope or declared static in global
12562 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12565 CanQualType SizeTy =
12566 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12568 // C++ [basic.stc.dynamic.allocation]p1:
12569 // The return type shall be void*. The first parameter shall have type
12571 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12573 diag::err_operator_new_dependent_param_type,
12574 diag::err_operator_new_param_type))
12577 // C++ [basic.stc.dynamic.allocation]p1:
12578 // The first parameter shall not have an associated default argument.
12579 if (FnDecl->getParamDecl(0)->hasDefaultArg())
12580 return SemaRef.Diag(FnDecl->getLocation(),
12581 diag::err_operator_new_default_arg)
12582 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12588 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12589 // C++ [basic.stc.dynamic.deallocation]p1:
12590 // A program is ill-formed if deallocation functions are declared in a
12591 // namespace scope other than global scope or declared static in global
12593 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12596 // C++ [basic.stc.dynamic.deallocation]p2:
12597 // Each deallocation function shall return void and its first parameter
12599 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
12600 SemaRef.Context.VoidPtrTy,
12601 diag::err_operator_delete_dependent_param_type,
12602 diag::err_operator_delete_param_type))
12608 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12609 /// of this overloaded operator is well-formed. If so, returns false;
12610 /// otherwise, emits appropriate diagnostics and returns true.
12611 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12612 assert(FnDecl && FnDecl->isOverloadedOperator() &&
12613 "Expected an overloaded operator declaration");
12615 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12617 // C++ [over.oper]p5:
12618 // The allocation and deallocation functions, operator new,
12619 // operator new[], operator delete and operator delete[], are
12620 // described completely in 3.7.3. The attributes and restrictions
12621 // found in the rest of this subclause do not apply to them unless
12622 // explicitly stated in 3.7.3.
12623 if (Op == OO_Delete || Op == OO_Array_Delete)
12624 return CheckOperatorDeleteDeclaration(*this, FnDecl);
12626 if (Op == OO_New || Op == OO_Array_New)
12627 return CheckOperatorNewDeclaration(*this, FnDecl);
12629 // C++ [over.oper]p6:
12630 // An operator function shall either be a non-static member
12631 // function or be a non-member function and have at least one
12632 // parameter whose type is a class, a reference to a class, an
12633 // enumeration, or a reference to an enumeration.
12634 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12635 if (MethodDecl->isStatic())
12636 return Diag(FnDecl->getLocation(),
12637 diag::err_operator_overload_static) << FnDecl->getDeclName();
12639 bool ClassOrEnumParam = false;
12640 for (auto Param : FnDecl->parameters()) {
12641 QualType ParamType = Param->getType().getNonReferenceType();
12642 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12643 ParamType->isEnumeralType()) {
12644 ClassOrEnumParam = true;
12649 if (!ClassOrEnumParam)
12650 return Diag(FnDecl->getLocation(),
12651 diag::err_operator_overload_needs_class_or_enum)
12652 << FnDecl->getDeclName();
12655 // C++ [over.oper]p8:
12656 // An operator function cannot have default arguments (8.3.6),
12657 // except where explicitly stated below.
12659 // Only the function-call operator allows default arguments
12660 // (C++ [over.call]p1).
12661 if (Op != OO_Call) {
12662 for (auto Param : FnDecl->parameters()) {
12663 if (Param->hasDefaultArg())
12664 return Diag(Param->getLocation(),
12665 diag::err_operator_overload_default_arg)
12666 << FnDecl->getDeclName() << Param->getDefaultArgRange();
12670 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12671 { false, false, false }
12672 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12673 , { Unary, Binary, MemberOnly }
12674 #include "clang/Basic/OperatorKinds.def"
12677 bool CanBeUnaryOperator = OperatorUses[Op][0];
12678 bool CanBeBinaryOperator = OperatorUses[Op][1];
12679 bool MustBeMemberOperator = OperatorUses[Op][2];
12681 // C++ [over.oper]p8:
12682 // [...] Operator functions cannot have more or fewer parameters
12683 // than the number required for the corresponding operator, as
12684 // described in the rest of this subclause.
12685 unsigned NumParams = FnDecl->getNumParams()
12686 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12687 if (Op != OO_Call &&
12688 ((NumParams == 1 && !CanBeUnaryOperator) ||
12689 (NumParams == 2 && !CanBeBinaryOperator) ||
12690 (NumParams < 1) || (NumParams > 2))) {
12691 // We have the wrong number of parameters.
12692 unsigned ErrorKind;
12693 if (CanBeUnaryOperator && CanBeBinaryOperator) {
12694 ErrorKind = 2; // 2 -> unary or binary.
12695 } else if (CanBeUnaryOperator) {
12696 ErrorKind = 0; // 0 -> unary
12698 assert(CanBeBinaryOperator &&
12699 "All non-call overloaded operators are unary or binary!");
12700 ErrorKind = 1; // 1 -> binary
12703 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12704 << FnDecl->getDeclName() << NumParams << ErrorKind;
12707 // Overloaded operators other than operator() cannot be variadic.
12708 if (Op != OO_Call &&
12709 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12710 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12711 << FnDecl->getDeclName();
12714 // Some operators must be non-static member functions.
12715 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12716 return Diag(FnDecl->getLocation(),
12717 diag::err_operator_overload_must_be_member)
12718 << FnDecl->getDeclName();
12721 // C++ [over.inc]p1:
12722 // The user-defined function called operator++ implements the
12723 // prefix and postfix ++ operator. If this function is a member
12724 // function with no parameters, or a non-member function with one
12725 // parameter of class or enumeration type, it defines the prefix
12726 // increment operator ++ for objects of that type. If the function
12727 // is a member function with one parameter (which shall be of type
12728 // int) or a non-member function with two parameters (the second
12729 // of which shall be of type int), it defines the postfix
12730 // increment operator ++ for objects of that type.
12731 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12732 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12733 QualType ParamType = LastParam->getType();
12735 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12736 !ParamType->isDependentType())
12737 return Diag(LastParam->getLocation(),
12738 diag::err_operator_overload_post_incdec_must_be_int)
12739 << LastParam->getType() << (Op == OO_MinusMinus);
12746 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12747 FunctionTemplateDecl *TpDecl) {
12748 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12750 // Must have one or two template parameters.
12751 if (TemplateParams->size() == 1) {
12752 NonTypeTemplateParmDecl *PmDecl =
12753 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12755 // The template parameter must be a char parameter pack.
12756 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12757 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12760 } else if (TemplateParams->size() == 2) {
12761 TemplateTypeParmDecl *PmType =
12762 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12763 NonTypeTemplateParmDecl *PmArgs =
12764 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12766 // The second template parameter must be a parameter pack with the
12767 // first template parameter as its type.
12768 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12769 PmArgs->isTemplateParameterPack()) {
12770 const TemplateTypeParmType *TArgs =
12771 PmArgs->getType()->getAs<TemplateTypeParmType>();
12772 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12773 TArgs->getIndex() == PmType->getIndex()) {
12774 if (!SemaRef.inTemplateInstantiation())
12775 SemaRef.Diag(TpDecl->getLocation(),
12776 diag::ext_string_literal_operator_template);
12782 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12783 diag::err_literal_operator_template)
12784 << TpDecl->getTemplateParameters()->getSourceRange();
12788 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12789 /// of this literal operator function is well-formed. If so, returns
12790 /// false; otherwise, emits appropriate diagnostics and returns true.
12791 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12792 if (isa<CXXMethodDecl>(FnDecl)) {
12793 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12794 << FnDecl->getDeclName();
12798 if (FnDecl->isExternC()) {
12799 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12800 if (const LinkageSpecDecl *LSD =
12801 FnDecl->getDeclContext()->getExternCContext())
12802 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
12806 // This might be the definition of a literal operator template.
12807 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12809 // This might be a specialization of a literal operator template.
12811 TpDecl = FnDecl->getPrimaryTemplate();
12813 // template <char...> type operator "" name() and
12814 // template <class T, T...> type operator "" name() are the only valid
12815 // template signatures, and the only valid signatures with no parameters.
12817 if (FnDecl->param_size() != 0) {
12818 Diag(FnDecl->getLocation(),
12819 diag::err_literal_operator_template_with_params);
12823 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12826 } else if (FnDecl->param_size() == 1) {
12827 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12829 QualType ParamType = Param->getType().getUnqualifiedType();
12831 // Only unsigned long long int, long double, any character type, and const
12832 // char * are allowed as the only parameters.
12833 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12834 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12835 Context.hasSameType(ParamType, Context.CharTy) ||
12836 Context.hasSameType(ParamType, Context.WideCharTy) ||
12837 Context.hasSameType(ParamType, Context.Char16Ty) ||
12838 Context.hasSameType(ParamType, Context.Char32Ty)) {
12839 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12840 QualType InnerType = Ptr->getPointeeType();
12842 // Pointer parameter must be a const char *.
12843 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12845 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12846 Diag(Param->getSourceRange().getBegin(),
12847 diag::err_literal_operator_param)
12848 << ParamType << "'const char *'" << Param->getSourceRange();
12852 } else if (ParamType->isRealFloatingType()) {
12853 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12854 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12857 } else if (ParamType->isIntegerType()) {
12858 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12859 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12863 Diag(Param->getSourceRange().getBegin(),
12864 diag::err_literal_operator_invalid_param)
12865 << ParamType << Param->getSourceRange();
12869 } else if (FnDecl->param_size() == 2) {
12870 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12872 // First, verify that the first parameter is correct.
12874 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12876 // Two parameter function must have a pointer to const as a
12877 // first parameter; let's strip those qualifiers.
12878 const PointerType *PT = FirstParamType->getAs<PointerType>();
12881 Diag((*Param)->getSourceRange().getBegin(),
12882 diag::err_literal_operator_param)
12883 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12887 QualType PointeeType = PT->getPointeeType();
12888 // First parameter must be const
12889 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
12890 Diag((*Param)->getSourceRange().getBegin(),
12891 diag::err_literal_operator_param)
12892 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12896 QualType InnerType = PointeeType.getUnqualifiedType();
12897 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
12898 // are allowed as the first parameter to a two-parameter function
12899 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
12900 Context.hasSameType(InnerType, Context.WideCharTy) ||
12901 Context.hasSameType(InnerType, Context.Char16Ty) ||
12902 Context.hasSameType(InnerType, Context.Char32Ty))) {
12903 Diag((*Param)->getSourceRange().getBegin(),
12904 diag::err_literal_operator_param)
12905 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
12909 // Move on to the second and final parameter.
12912 // The second parameter must be a std::size_t.
12913 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
12914 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
12915 Diag((*Param)->getSourceRange().getBegin(),
12916 diag::err_literal_operator_param)
12917 << SecondParamType << Context.getSizeType()
12918 << (*Param)->getSourceRange();
12922 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
12926 // Parameters are good.
12928 // A parameter-declaration-clause containing a default argument is not
12929 // equivalent to any of the permitted forms.
12930 for (auto Param : FnDecl->parameters()) {
12931 if (Param->hasDefaultArg()) {
12932 Diag(Param->getDefaultArgRange().getBegin(),
12933 diag::err_literal_operator_default_argument)
12934 << Param->getDefaultArgRange();
12939 StringRef LiteralName
12940 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
12941 if (LiteralName[0] != '_') {
12942 // C++11 [usrlit.suffix]p1:
12943 // Literal suffix identifiers that do not start with an underscore
12944 // are reserved for future standardization.
12945 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
12946 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
12952 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
12953 /// linkage specification, including the language and (if present)
12954 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
12955 /// language string literal. LBraceLoc, if valid, provides the location of
12956 /// the '{' brace. Otherwise, this linkage specification does not
12957 /// have any braces.
12958 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
12960 SourceLocation LBraceLoc) {
12961 StringLiteral *Lit = cast<StringLiteral>(LangStr);
12962 if (!Lit->isAscii()) {
12963 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
12964 << LangStr->getSourceRange();
12968 StringRef Lang = Lit->getString();
12969 LinkageSpecDecl::LanguageIDs Language;
12971 Language = LinkageSpecDecl::lang_c;
12972 else if (Lang == "C++")
12973 Language = LinkageSpecDecl::lang_cxx;
12975 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
12976 << LangStr->getSourceRange();
12980 // FIXME: Add all the various semantics of linkage specifications
12982 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
12983 LangStr->getExprLoc(), Language,
12984 LBraceLoc.isValid());
12985 CurContext->addDecl(D);
12986 PushDeclContext(S, D);
12990 /// ActOnFinishLinkageSpecification - Complete the definition of
12991 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
12992 /// valid, it's the position of the closing '}' brace in a linkage
12993 /// specification that uses braces.
12994 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
12996 SourceLocation RBraceLoc) {
12997 if (RBraceLoc.isValid()) {
12998 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
12999 LSDecl->setRBraceLoc(RBraceLoc);
13002 return LinkageSpec;
13005 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13006 AttributeList *AttrList,
13007 SourceLocation SemiLoc) {
13008 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13009 // Attribute declarations appertain to empty declaration so we handle
13012 ProcessDeclAttributeList(S, ED, AttrList);
13014 CurContext->addDecl(ED);
13018 /// \brief Perform semantic analysis for the variable declaration that
13019 /// occurs within a C++ catch clause, returning the newly-created
13021 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13022 TypeSourceInfo *TInfo,
13023 SourceLocation StartLoc,
13024 SourceLocation Loc,
13025 IdentifierInfo *Name) {
13026 bool Invalid = false;
13027 QualType ExDeclType = TInfo->getType();
13029 // Arrays and functions decay.
13030 if (ExDeclType->isArrayType())
13031 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13032 else if (ExDeclType->isFunctionType())
13033 ExDeclType = Context.getPointerType(ExDeclType);
13035 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13036 // The exception-declaration shall not denote a pointer or reference to an
13037 // incomplete type, other than [cv] void*.
13038 // N2844 forbids rvalue references.
13039 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13040 Diag(Loc, diag::err_catch_rvalue_ref);
13044 if (ExDeclType->isVariablyModifiedType()) {
13045 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13049 QualType BaseType = ExDeclType;
13050 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13051 unsigned DK = diag::err_catch_incomplete;
13052 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13053 BaseType = Ptr->getPointeeType();
13055 DK = diag::err_catch_incomplete_ptr;
13056 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13057 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13058 BaseType = Ref->getPointeeType();
13060 DK = diag::err_catch_incomplete_ref;
13062 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13063 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13066 if (!Invalid && !ExDeclType->isDependentType() &&
13067 RequireNonAbstractType(Loc, ExDeclType,
13068 diag::err_abstract_type_in_decl,
13069 AbstractVariableType))
13072 // Only the non-fragile NeXT runtime currently supports C++ catches
13073 // of ObjC types, and no runtime supports catching ObjC types by value.
13074 if (!Invalid && getLangOpts().ObjC1) {
13075 QualType T = ExDeclType;
13076 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13077 T = RT->getPointeeType();
13079 if (T->isObjCObjectType()) {
13080 Diag(Loc, diag::err_objc_object_catch);
13082 } else if (T->isObjCObjectPointerType()) {
13083 // FIXME: should this be a test for macosx-fragile specifically?
13084 if (getLangOpts().ObjCRuntime.isFragile())
13085 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13089 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13090 ExDeclType, TInfo, SC_None);
13091 ExDecl->setExceptionVariable(true);
13093 // In ARC, infer 'retaining' for variables of retainable type.
13094 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13097 if (!Invalid && !ExDeclType->isDependentType()) {
13098 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13099 // Insulate this from anything else we might currently be parsing.
13100 EnterExpressionEvaluationContext scope(
13101 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13103 // C++ [except.handle]p16:
13104 // The object declared in an exception-declaration or, if the
13105 // exception-declaration does not specify a name, a temporary (12.2) is
13106 // copy-initialized (8.5) from the exception object. [...]
13107 // The object is destroyed when the handler exits, after the destruction
13108 // of any automatic objects initialized within the handler.
13110 // We just pretend to initialize the object with itself, then make sure
13111 // it can be destroyed later.
13112 QualType initType = Context.getExceptionObjectType(ExDeclType);
13114 InitializedEntity entity =
13115 InitializedEntity::InitializeVariable(ExDecl);
13116 InitializationKind initKind =
13117 InitializationKind::CreateCopy(Loc, SourceLocation());
13119 Expr *opaqueValue =
13120 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13121 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13122 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13123 if (result.isInvalid())
13126 // If the constructor used was non-trivial, set this as the
13128 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13129 if (!construct->getConstructor()->isTrivial()) {
13130 Expr *init = MaybeCreateExprWithCleanups(construct);
13131 ExDecl->setInit(init);
13134 // And make sure it's destructable.
13135 FinalizeVarWithDestructor(ExDecl, recordType);
13141 ExDecl->setInvalidDecl();
13146 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13148 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13149 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13150 bool Invalid = D.isInvalidType();
13152 // Check for unexpanded parameter packs.
13153 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13154 UPPC_ExceptionType)) {
13155 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13156 D.getIdentifierLoc());
13160 IdentifierInfo *II = D.getIdentifier();
13161 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13162 LookupOrdinaryName,
13163 ForRedeclaration)) {
13164 // The scope should be freshly made just for us. There is just no way
13165 // it contains any previous declaration, except for function parameters in
13166 // a function-try-block's catch statement.
13167 assert(!S->isDeclScope(PrevDecl));
13168 if (isDeclInScope(PrevDecl, CurContext, S)) {
13169 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13170 << D.getIdentifier();
13171 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13173 } else if (PrevDecl->isTemplateParameter())
13174 // Maybe we will complain about the shadowed template parameter.
13175 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13178 if (D.getCXXScopeSpec().isSet() && !Invalid) {
13179 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13180 << D.getCXXScopeSpec().getRange();
13184 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13186 D.getIdentifierLoc(),
13187 D.getIdentifier());
13189 ExDecl->setInvalidDecl();
13191 // Add the exception declaration into this scope.
13193 PushOnScopeChains(ExDecl, S);
13195 CurContext->addDecl(ExDecl);
13197 ProcessDeclAttributes(S, ExDecl, D);
13201 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13203 Expr *AssertMessageExpr,
13204 SourceLocation RParenLoc) {
13205 StringLiteral *AssertMessage =
13206 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13208 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13211 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13212 AssertMessage, RParenLoc, false);
13215 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13217 StringLiteral *AssertMessage,
13218 SourceLocation RParenLoc,
13220 assert(AssertExpr != nullptr && "Expected non-null condition");
13221 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13223 // In a static_assert-declaration, the constant-expression shall be a
13224 // constant expression that can be contextually converted to bool.
13225 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13226 if (Converted.isInvalid())
13230 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13231 diag::err_static_assert_expression_is_not_constant,
13232 /*AllowFold=*/false).isInvalid())
13235 if (!Failed && !Cond) {
13236 SmallString<256> MsgBuffer;
13237 llvm::raw_svector_ostream Msg(MsgBuffer);
13239 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13240 Diag(StaticAssertLoc, diag::err_static_assert_failed)
13241 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13246 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13247 /*DiscardedValue*/false,
13248 /*IsConstexpr*/true);
13249 if (FullAssertExpr.isInvalid())
13252 AssertExpr = FullAssertExpr.get();
13254 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13255 AssertExpr, AssertMessage, RParenLoc,
13258 CurContext->addDecl(Decl);
13262 /// \brief Perform semantic analysis of the given friend type declaration.
13264 /// \returns A friend declaration that.
13265 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13266 SourceLocation FriendLoc,
13267 TypeSourceInfo *TSInfo) {
13268 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13270 QualType T = TSInfo->getType();
13271 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13273 // C++03 [class.friend]p2:
13274 // An elaborated-type-specifier shall be used in a friend declaration
13277 // * The class-key of the elaborated-type-specifier is required.
13278 if (!CodeSynthesisContexts.empty()) {
13279 // Do not complain about the form of friend template types during any kind
13280 // of code synthesis. For template instantiation, we will have complained
13281 // when the template was defined.
13283 if (!T->isElaboratedTypeSpecifier()) {
13284 // If we evaluated the type to a record type, suggest putting
13286 if (const RecordType *RT = T->getAs<RecordType>()) {
13287 RecordDecl *RD = RT->getDecl();
13289 SmallString<16> InsertionText(" ");
13290 InsertionText += RD->getKindName();
13292 Diag(TypeRange.getBegin(),
13293 getLangOpts().CPlusPlus11 ?
13294 diag::warn_cxx98_compat_unelaborated_friend_type :
13295 diag::ext_unelaborated_friend_type)
13296 << (unsigned) RD->getTagKind()
13298 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13302 getLangOpts().CPlusPlus11 ?
13303 diag::warn_cxx98_compat_nonclass_type_friend :
13304 diag::ext_nonclass_type_friend)
13308 } else if (T->getAs<EnumType>()) {
13310 getLangOpts().CPlusPlus11 ?
13311 diag::warn_cxx98_compat_enum_friend :
13312 diag::ext_enum_friend)
13317 // C++11 [class.friend]p3:
13318 // A friend declaration that does not declare a function shall have one
13319 // of the following forms:
13320 // friend elaborated-type-specifier ;
13321 // friend simple-type-specifier ;
13322 // friend typename-specifier ;
13323 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13324 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13327 // If the type specifier in a friend declaration designates a (possibly
13328 // cv-qualified) class type, that class is declared as a friend; otherwise,
13329 // the friend declaration is ignored.
13330 return FriendDecl::Create(Context, CurContext,
13331 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13335 /// Handle a friend tag declaration where the scope specifier was
13337 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13338 unsigned TagSpec, SourceLocation TagLoc,
13340 IdentifierInfo *Name,
13341 SourceLocation NameLoc,
13342 AttributeList *Attr,
13343 MultiTemplateParamsArg TempParamLists) {
13344 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13346 bool IsMemberSpecialization = false;
13347 bool Invalid = false;
13349 if (TemplateParameterList *TemplateParams =
13350 MatchTemplateParametersToScopeSpecifier(
13351 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13352 IsMemberSpecialization, Invalid)) {
13353 if (TemplateParams->size() > 0) {
13354 // This is a declaration of a class template.
13358 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13359 NameLoc, Attr, TemplateParams, AS_public,
13360 /*ModulePrivateLoc=*/SourceLocation(),
13361 FriendLoc, TempParamLists.size() - 1,
13362 TempParamLists.data()).get();
13364 // The "template<>" header is extraneous.
13365 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13366 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13367 IsMemberSpecialization = true;
13371 if (Invalid) return nullptr;
13373 bool isAllExplicitSpecializations = true;
13374 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13375 if (TempParamLists[I]->size()) {
13376 isAllExplicitSpecializations = false;
13381 // FIXME: don't ignore attributes.
13383 // If it's explicit specializations all the way down, just forget
13384 // about the template header and build an appropriate non-templated
13385 // friend. TODO: for source fidelity, remember the headers.
13386 if (isAllExplicitSpecializations) {
13387 if (SS.isEmpty()) {
13388 bool Owned = false;
13389 bool IsDependent = false;
13390 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13392 /*ModulePrivateLoc=*/SourceLocation(),
13393 MultiTemplateParamsArg(), Owned, IsDependent,
13394 /*ScopedEnumKWLoc=*/SourceLocation(),
13395 /*ScopedEnumUsesClassTag=*/false,
13396 /*UnderlyingType=*/TypeResult(),
13397 /*IsTypeSpecifier=*/false);
13400 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13401 ElaboratedTypeKeyword Keyword
13402 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13403 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13408 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13409 if (isa<DependentNameType>(T)) {
13410 DependentNameTypeLoc TL =
13411 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13412 TL.setElaboratedKeywordLoc(TagLoc);
13413 TL.setQualifierLoc(QualifierLoc);
13414 TL.setNameLoc(NameLoc);
13416 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13417 TL.setElaboratedKeywordLoc(TagLoc);
13418 TL.setQualifierLoc(QualifierLoc);
13419 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13422 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13423 TSI, FriendLoc, TempParamLists);
13424 Friend->setAccess(AS_public);
13425 CurContext->addDecl(Friend);
13429 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13433 // Handle the case of a templated-scope friend class. e.g.
13434 // template <class T> class A<T>::B;
13435 // FIXME: we don't support these right now.
13436 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13437 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13438 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13439 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13440 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13441 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13442 TL.setElaboratedKeywordLoc(TagLoc);
13443 TL.setQualifierLoc(SS.getWithLocInContext(Context));
13444 TL.setNameLoc(NameLoc);
13446 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13447 TSI, FriendLoc, TempParamLists);
13448 Friend->setAccess(AS_public);
13449 Friend->setUnsupportedFriend(true);
13450 CurContext->addDecl(Friend);
13455 /// Handle a friend type declaration. This works in tandem with
13458 /// Notes on friend class templates:
13460 /// We generally treat friend class declarations as if they were
13461 /// declaring a class. So, for example, the elaborated type specifier
13462 /// in a friend declaration is required to obey the restrictions of a
13463 /// class-head (i.e. no typedefs in the scope chain), template
13464 /// parameters are required to match up with simple template-ids, &c.
13465 /// However, unlike when declaring a template specialization, it's
13466 /// okay to refer to a template specialization without an empty
13467 /// template parameter declaration, e.g.
13468 /// friend class A<T>::B<unsigned>;
13469 /// We permit this as a special case; if there are any template
13470 /// parameters present at all, require proper matching, i.e.
13471 /// template <> template \<class T> friend class A<int>::B;
13472 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13473 MultiTemplateParamsArg TempParams) {
13474 SourceLocation Loc = DS.getLocStart();
13476 assert(DS.isFriendSpecified());
13477 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13479 // Try to convert the decl specifier to a type. This works for
13480 // friend templates because ActOnTag never produces a ClassTemplateDecl
13481 // for a TUK_Friend.
13482 Declarator TheDeclarator(DS, Declarator::MemberContext);
13483 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13484 QualType T = TSI->getType();
13485 if (TheDeclarator.isInvalidType())
13488 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13491 // This is definitely an error in C++98. It's probably meant to
13492 // be forbidden in C++0x, too, but the specification is just
13495 // The problem is with declarations like the following:
13496 // template <T> friend A<T>::foo;
13497 // where deciding whether a class C is a friend or not now hinges
13498 // on whether there exists an instantiation of A that causes
13499 // 'foo' to equal C. There are restrictions on class-heads
13500 // (which we declare (by fiat) elaborated friend declarations to
13501 // be) that makes this tractable.
13503 // FIXME: handle "template <> friend class A<T>;", which
13504 // is possibly well-formed? Who even knows?
13505 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13506 Diag(Loc, diag::err_tagless_friend_type_template)
13507 << DS.getSourceRange();
13511 // C++98 [class.friend]p1: A friend of a class is a function
13512 // or class that is not a member of the class . . .
13513 // This is fixed in DR77, which just barely didn't make the C++03
13514 // deadline. It's also a very silly restriction that seriously
13515 // affects inner classes and which nobody else seems to implement;
13516 // thus we never diagnose it, not even in -pedantic.
13518 // But note that we could warn about it: it's always useless to
13519 // friend one of your own members (it's not, however, worthless to
13520 // friend a member of an arbitrary specialization of your template).
13523 if (!TempParams.empty())
13524 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13527 DS.getFriendSpecLoc());
13529 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13534 D->setAccess(AS_public);
13535 CurContext->addDecl(D);
13540 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13541 MultiTemplateParamsArg TemplateParams) {
13542 const DeclSpec &DS = D.getDeclSpec();
13544 assert(DS.isFriendSpecified());
13545 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13547 SourceLocation Loc = D.getIdentifierLoc();
13548 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13550 // C++ [class.friend]p1
13551 // A friend of a class is a function or class....
13552 // Note that this sees through typedefs, which is intended.
13553 // It *doesn't* see through dependent types, which is correct
13554 // according to [temp.arg.type]p3:
13555 // If a declaration acquires a function type through a
13556 // type dependent on a template-parameter and this causes
13557 // a declaration that does not use the syntactic form of a
13558 // function declarator to have a function type, the program
13560 if (!TInfo->getType()->isFunctionType()) {
13561 Diag(Loc, diag::err_unexpected_friend);
13563 // It might be worthwhile to try to recover by creating an
13564 // appropriate declaration.
13568 // C++ [namespace.memdef]p3
13569 // - If a friend declaration in a non-local class first declares a
13570 // class or function, the friend class or function is a member
13571 // of the innermost enclosing namespace.
13572 // - The name of the friend is not found by simple name lookup
13573 // until a matching declaration is provided in that namespace
13574 // scope (either before or after the class declaration granting
13576 // - If a friend function is called, its name may be found by the
13577 // name lookup that considers functions from namespaces and
13578 // classes associated with the types of the function arguments.
13579 // - When looking for a prior declaration of a class or a function
13580 // declared as a friend, scopes outside the innermost enclosing
13581 // namespace scope are not considered.
13583 CXXScopeSpec &SS = D.getCXXScopeSpec();
13584 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13585 DeclarationName Name = NameInfo.getName();
13588 // Check for unexpanded parameter packs.
13589 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13590 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13591 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13594 // The context we found the declaration in, or in which we should
13595 // create the declaration.
13597 Scope *DCScope = S;
13598 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13601 // There are five cases here.
13602 // - There's no scope specifier and we're in a local class. Only look
13603 // for functions declared in the immediately-enclosing block scope.
13604 // We recover from invalid scope qualifiers as if they just weren't there.
13605 FunctionDecl *FunctionContainingLocalClass = nullptr;
13606 if ((SS.isInvalid() || !SS.isSet()) &&
13607 (FunctionContainingLocalClass =
13608 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13609 // C++11 [class.friend]p11:
13610 // If a friend declaration appears in a local class and the name
13611 // specified is an unqualified name, a prior declaration is
13612 // looked up without considering scopes that are outside the
13613 // innermost enclosing non-class scope. For a friend function
13614 // declaration, if there is no prior declaration, the program is
13617 // Find the innermost enclosing non-class scope. This is the block
13618 // scope containing the local class definition (or for a nested class,
13619 // the outer local class).
13620 DCScope = S->getFnParent();
13622 // Look up the function name in the scope.
13623 Previous.clear(LookupLocalFriendName);
13624 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13626 if (!Previous.empty()) {
13627 // All possible previous declarations must have the same context:
13628 // either they were declared at block scope or they are members of
13629 // one of the enclosing local classes.
13630 DC = Previous.getRepresentativeDecl()->getDeclContext();
13632 // This is ill-formed, but provide the context that we would have
13633 // declared the function in, if we were permitted to, for error recovery.
13634 DC = FunctionContainingLocalClass;
13636 adjustContextForLocalExternDecl(DC);
13638 // C++ [class.friend]p6:
13639 // A function can be defined in a friend declaration of a class if and
13640 // only if the class is a non-local class (9.8), the function name is
13641 // unqualified, and the function has namespace scope.
13642 if (D.isFunctionDefinition()) {
13643 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13646 // - There's no scope specifier, in which case we just go to the
13647 // appropriate scope and look for a function or function template
13648 // there as appropriate.
13649 } else if (SS.isInvalid() || !SS.isSet()) {
13650 // C++11 [namespace.memdef]p3:
13651 // If the name in a friend declaration is neither qualified nor
13652 // a template-id and the declaration is a function or an
13653 // elaborated-type-specifier, the lookup to determine whether
13654 // the entity has been previously declared shall not consider
13655 // any scopes outside the innermost enclosing namespace.
13656 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
13658 // Find the appropriate context according to the above.
13661 // Skip class contexts. If someone can cite chapter and verse
13662 // for this behavior, that would be nice --- it's what GCC and
13663 // EDG do, and it seems like a reasonable intent, but the spec
13664 // really only says that checks for unqualified existing
13665 // declarations should stop at the nearest enclosing namespace,
13666 // not that they should only consider the nearest enclosing
13668 while (DC->isRecord())
13669 DC = DC->getParent();
13671 DeclContext *LookupDC = DC;
13672 while (LookupDC->isTransparentContext())
13673 LookupDC = LookupDC->getParent();
13676 LookupQualifiedName(Previous, LookupDC);
13678 if (!Previous.empty()) {
13683 if (isTemplateId) {
13684 if (isa<TranslationUnitDecl>(LookupDC)) break;
13686 if (LookupDC->isFileContext()) break;
13688 LookupDC = LookupDC->getParent();
13691 DCScope = getScopeForDeclContext(S, DC);
13693 // - There's a non-dependent scope specifier, in which case we
13694 // compute it and do a previous lookup there for a function
13695 // or function template.
13696 } else if (!SS.getScopeRep()->isDependent()) {
13697 DC = computeDeclContext(SS);
13698 if (!DC) return nullptr;
13700 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13702 LookupQualifiedName(Previous, DC);
13704 // Ignore things found implicitly in the wrong scope.
13705 // TODO: better diagnostics for this case. Suggesting the right
13706 // qualified scope would be nice...
13707 LookupResult::Filter F = Previous.makeFilter();
13708 while (F.hasNext()) {
13709 NamedDecl *D = F.next();
13710 if (!DC->InEnclosingNamespaceSetOf(
13711 D->getDeclContext()->getRedeclContext()))
13716 if (Previous.empty()) {
13717 D.setInvalidType();
13718 Diag(Loc, diag::err_qualified_friend_not_found)
13719 << Name << TInfo->getType();
13723 // C++ [class.friend]p1: A friend of a class is a function or
13724 // class that is not a member of the class . . .
13725 if (DC->Equals(CurContext))
13726 Diag(DS.getFriendSpecLoc(),
13727 getLangOpts().CPlusPlus11 ?
13728 diag::warn_cxx98_compat_friend_is_member :
13729 diag::err_friend_is_member);
13731 if (D.isFunctionDefinition()) {
13732 // C++ [class.friend]p6:
13733 // A function can be defined in a friend declaration of a class if and
13734 // only if the class is a non-local class (9.8), the function name is
13735 // unqualified, and the function has namespace scope.
13736 SemaDiagnosticBuilder DB
13737 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13739 DB << SS.getScopeRep();
13740 if (DC->isFileContext())
13741 DB << FixItHint::CreateRemoval(SS.getRange());
13745 // - There's a scope specifier that does not match any template
13746 // parameter lists, in which case we use some arbitrary context,
13747 // create a method or method template, and wait for instantiation.
13748 // - There's a scope specifier that does match some template
13749 // parameter lists, which we don't handle right now.
13751 if (D.isFunctionDefinition()) {
13752 // C++ [class.friend]p6:
13753 // A function can be defined in a friend declaration of a class if and
13754 // only if the class is a non-local class (9.8), the function name is
13755 // unqualified, and the function has namespace scope.
13756 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13757 << SS.getScopeRep();
13761 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13764 if (!DC->isRecord()) {
13766 switch (D.getName().getKind()) {
13767 case UnqualifiedId::IK_ConstructorTemplateId:
13768 case UnqualifiedId::IK_ConstructorName:
13771 case UnqualifiedId::IK_DestructorName:
13774 case UnqualifiedId::IK_ConversionFunctionId:
13777 case UnqualifiedId::IK_DeductionGuideName:
13780 case UnqualifiedId::IK_Identifier:
13781 case UnqualifiedId::IK_ImplicitSelfParam:
13782 case UnqualifiedId::IK_LiteralOperatorId:
13783 case UnqualifiedId::IK_OperatorFunctionId:
13784 case UnqualifiedId::IK_TemplateId:
13787 // This implies that it has to be an operator or function.
13788 if (DiagArg >= 0) {
13789 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13794 // FIXME: This is an egregious hack to cope with cases where the scope stack
13795 // does not contain the declaration context, i.e., in an out-of-line
13796 // definition of a class.
13797 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13799 FakeDCScope.setEntity(DC);
13800 DCScope = &FakeDCScope;
13803 bool AddToScope = true;
13804 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13805 TemplateParams, AddToScope);
13806 if (!ND) return nullptr;
13808 assert(ND->getLexicalDeclContext() == CurContext);
13810 // If we performed typo correction, we might have added a scope specifier
13811 // and changed the decl context.
13812 DC = ND->getDeclContext();
13814 // Add the function declaration to the appropriate lookup tables,
13815 // adjusting the redeclarations list as necessary. We don't
13816 // want to do this yet if the friending class is dependent.
13818 // Also update the scope-based lookup if the target context's
13819 // lookup context is in lexical scope.
13820 if (!CurContext->isDependentContext()) {
13821 DC = DC->getRedeclContext();
13822 DC->makeDeclVisibleInContext(ND);
13823 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13824 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13827 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13828 D.getIdentifierLoc(), ND,
13829 DS.getFriendSpecLoc());
13830 FrD->setAccess(AS_public);
13831 CurContext->addDecl(FrD);
13833 if (ND->isInvalidDecl()) {
13834 FrD->setInvalidDecl();
13836 if (DC->isRecord()) CheckFriendAccess(ND);
13839 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13840 FD = FTD->getTemplatedDecl();
13842 FD = cast<FunctionDecl>(ND);
13844 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13845 // default argument expression, that declaration shall be a definition
13846 // and shall be the only declaration of the function or function
13847 // template in the translation unit.
13848 if (functionDeclHasDefaultArgument(FD)) {
13849 // We can't look at FD->getPreviousDecl() because it may not have been set
13850 // if we're in a dependent context. If the function is known to be a
13851 // redeclaration, we will have narrowed Previous down to the right decl.
13852 if (D.isRedeclaration()) {
13853 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13854 Diag(Previous.getRepresentativeDecl()->getLocation(),
13855 diag::note_previous_declaration);
13856 } else if (!D.isFunctionDefinition())
13857 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13860 // Mark templated-scope function declarations as unsupported.
13861 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13862 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13863 << SS.getScopeRep() << SS.getRange()
13864 << cast<CXXRecordDecl>(CurContext);
13865 FrD->setUnsupportedFriend(true);
13872 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
13873 AdjustDeclIfTemplate(Dcl);
13875 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
13877 Diag(DelLoc, diag::err_deleted_non_function);
13881 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
13882 // Don't consider the implicit declaration we generate for explicit
13883 // specializations. FIXME: Do not generate these implicit declarations.
13884 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
13885 Prev->getPreviousDecl()) &&
13886 !Prev->isDefined()) {
13887 Diag(DelLoc, diag::err_deleted_decl_not_first);
13888 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
13889 Prev->isImplicit() ? diag::note_previous_implicit_declaration
13890 : diag::note_previous_declaration);
13892 // If the declaration wasn't the first, we delete the function anyway for
13894 Fn = Fn->getCanonicalDecl();
13897 // dllimport/dllexport cannot be deleted.
13898 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
13899 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
13900 Fn->setInvalidDecl();
13903 if (Fn->isDeleted())
13906 // See if we're deleting a function which is already known to override a
13907 // non-deleted virtual function.
13908 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
13909 bool IssuedDiagnostic = false;
13910 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
13911 E = MD->end_overridden_methods();
13913 if (!(*MD->begin_overridden_methods())->isDeleted()) {
13914 if (!IssuedDiagnostic) {
13915 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
13916 IssuedDiagnostic = true;
13918 Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
13921 // If this function was implicitly deleted because it was defaulted,
13922 // explain why it was deleted.
13923 if (IssuedDiagnostic && MD->isDefaulted())
13924 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
13928 // C++11 [basic.start.main]p3:
13929 // A program that defines main as deleted [...] is ill-formed.
13931 Diag(DelLoc, diag::err_deleted_main);
13933 // C++11 [dcl.fct.def.delete]p4:
13934 // A deleted function is implicitly inline.
13935 Fn->setImplicitlyInline();
13936 Fn->setDeletedAsWritten();
13939 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
13940 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
13943 if (MD->getParent()->isDependentType()) {
13944 MD->setDefaulted();
13945 MD->setExplicitlyDefaulted();
13949 CXXSpecialMember Member = getSpecialMember(MD);
13950 if (Member == CXXInvalid) {
13951 if (!MD->isInvalidDecl())
13952 Diag(DefaultLoc, diag::err_default_special_members);
13956 MD->setDefaulted();
13957 MD->setExplicitlyDefaulted();
13959 // Unset that we will have a body for this function. We might not,
13960 // if it turns out to be trivial, and we don't need this marking now
13961 // that we've marked it as defaulted.
13962 MD->setWillHaveBody(false);
13964 // If this definition appears within the record, do the checking when
13965 // the record is complete.
13966 const FunctionDecl *Primary = MD;
13967 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
13968 // Ask the template instantiation pattern that actually had the
13969 // '= default' on it.
13972 // If the method was defaulted on its first declaration, we will have
13973 // already performed the checking in CheckCompletedCXXClass. Such a
13974 // declaration doesn't trigger an implicit definition.
13975 if (Primary->getCanonicalDecl()->isDefaulted())
13978 CheckExplicitlyDefaultedSpecialMember(MD);
13980 if (!MD->isInvalidDecl())
13981 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
13983 Diag(DefaultLoc, diag::err_default_special_members);
13987 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
13988 for (Stmt *SubStmt : S->children()) {
13991 if (isa<ReturnStmt>(SubStmt))
13992 Self.Diag(SubStmt->getLocStart(),
13993 diag::err_return_in_constructor_handler);
13994 if (!isa<Expr>(SubStmt))
13995 SearchForReturnInStmt(Self, SubStmt);
13999 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14000 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14001 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14002 SearchForReturnInStmt(*this, Handler);
14006 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14007 const CXXMethodDecl *Old) {
14008 const FunctionType *NewFT = New->getType()->getAs<FunctionType>();
14009 const FunctionType *OldFT = Old->getType()->getAs<FunctionType>();
14011 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14013 // If the calling conventions match, everything is fine
14014 if (NewCC == OldCC)
14017 // If the calling conventions mismatch because the new function is static,
14018 // suppress the calling convention mismatch error; the error about static
14019 // function override (err_static_overrides_virtual from
14020 // Sema::CheckFunctionDeclaration) is more clear.
14021 if (New->getStorageClass() == SC_Static)
14024 Diag(New->getLocation(),
14025 diag::err_conflicting_overriding_cc_attributes)
14026 << New->getDeclName() << New->getType() << Old->getType();
14027 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14031 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14032 const CXXMethodDecl *Old) {
14033 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14034 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14036 if (Context.hasSameType(NewTy, OldTy) ||
14037 NewTy->isDependentType() || OldTy->isDependentType())
14040 // Check if the return types are covariant
14041 QualType NewClassTy, OldClassTy;
14043 /// Both types must be pointers or references to classes.
14044 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14045 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14046 NewClassTy = NewPT->getPointeeType();
14047 OldClassTy = OldPT->getPointeeType();
14049 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14050 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14051 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14052 NewClassTy = NewRT->getPointeeType();
14053 OldClassTy = OldRT->getPointeeType();
14058 // The return types aren't either both pointers or references to a class type.
14059 if (NewClassTy.isNull()) {
14060 Diag(New->getLocation(),
14061 diag::err_different_return_type_for_overriding_virtual_function)
14062 << New->getDeclName() << NewTy << OldTy
14063 << New->getReturnTypeSourceRange();
14064 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14065 << Old->getReturnTypeSourceRange();
14070 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14071 // C++14 [class.virtual]p8:
14072 // If the class type in the covariant return type of D::f differs from
14073 // that of B::f, the class type in the return type of D::f shall be
14074 // complete at the point of declaration of D::f or shall be the class
14076 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14077 if (!RT->isBeingDefined() &&
14078 RequireCompleteType(New->getLocation(), NewClassTy,
14079 diag::err_covariant_return_incomplete,
14080 New->getDeclName()))
14084 // Check if the new class derives from the old class.
14085 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14086 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14087 << New->getDeclName() << NewTy << OldTy
14088 << New->getReturnTypeSourceRange();
14089 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14090 << Old->getReturnTypeSourceRange();
14094 // Check if we the conversion from derived to base is valid.
14095 if (CheckDerivedToBaseConversion(
14096 NewClassTy, OldClassTy,
14097 diag::err_covariant_return_inaccessible_base,
14098 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14099 New->getLocation(), New->getReturnTypeSourceRange(),
14100 New->getDeclName(), nullptr)) {
14101 // FIXME: this note won't trigger for delayed access control
14102 // diagnostics, and it's impossible to get an undelayed error
14103 // here from access control during the original parse because
14104 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14105 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14106 << Old->getReturnTypeSourceRange();
14111 // The qualifiers of the return types must be the same.
14112 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14113 Diag(New->getLocation(),
14114 diag::err_covariant_return_type_different_qualifications)
14115 << New->getDeclName() << NewTy << OldTy
14116 << New->getReturnTypeSourceRange();
14117 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14118 << Old->getReturnTypeSourceRange();
14123 // The new class type must have the same or less qualifiers as the old type.
14124 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14125 Diag(New->getLocation(),
14126 diag::err_covariant_return_type_class_type_more_qualified)
14127 << New->getDeclName() << NewTy << OldTy
14128 << New->getReturnTypeSourceRange();
14129 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14130 << Old->getReturnTypeSourceRange();
14137 /// \brief Mark the given method pure.
14139 /// \param Method the method to be marked pure.
14141 /// \param InitRange the source range that covers the "0" initializer.
14142 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14143 SourceLocation EndLoc = InitRange.getEnd();
14144 if (EndLoc.isValid())
14145 Method->setRangeEnd(EndLoc);
14147 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14152 if (!Method->isInvalidDecl())
14153 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14154 << Method->getDeclName() << InitRange;
14158 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14159 if (D->getFriendObjectKind())
14160 Diag(D->getLocation(), diag::err_pure_friend);
14161 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14162 CheckPureMethod(M, ZeroLoc);
14164 Diag(D->getLocation(), diag::err_illegal_initializer);
14167 /// \brief Determine whether the given declaration is a static data member.
14168 static bool isStaticDataMember(const Decl *D) {
14169 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14170 return Var->isStaticDataMember();
14175 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
14176 /// an initializer for the out-of-line declaration 'Dcl'. The scope
14177 /// is a fresh scope pushed for just this purpose.
14179 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14180 /// static data member of class X, names should be looked up in the scope of
14182 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14183 // If there is no declaration, there was an error parsing it.
14184 if (!D || D->isInvalidDecl())
14187 // We will always have a nested name specifier here, but this declaration
14188 // might not be out of line if the specifier names the current namespace:
14191 if (D->isOutOfLine())
14192 EnterDeclaratorContext(S, D->getDeclContext());
14194 // If we are parsing the initializer for a static data member, push a
14195 // new expression evaluation context that is associated with this static
14197 if (isStaticDataMember(D))
14198 PushExpressionEvaluationContext(
14199 ExpressionEvaluationContext::PotentiallyEvaluated, D);
14202 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
14203 /// initializer for the out-of-line declaration 'D'.
14204 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14205 // If there is no declaration, there was an error parsing it.
14206 if (!D || D->isInvalidDecl())
14209 if (isStaticDataMember(D))
14210 PopExpressionEvaluationContext();
14212 if (D->isOutOfLine())
14213 ExitDeclaratorContext(S);
14216 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14217 /// C++ if/switch/while/for statement.
14218 /// e.g: "if (int x = f()) {...}"
14219 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14221 // The declarator shall not specify a function or an array.
14222 // The type-specifier-seq shall not contain typedef and shall not declare a
14223 // new class or enumeration.
14224 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14225 "Parser allowed 'typedef' as storage class of condition decl.");
14227 Decl *Dcl = ActOnDeclarator(S, D);
14231 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14232 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14233 << D.getSourceRange();
14240 void Sema::LoadExternalVTableUses() {
14241 if (!ExternalSource)
14244 SmallVector<ExternalVTableUse, 4> VTables;
14245 ExternalSource->ReadUsedVTables(VTables);
14246 SmallVector<VTableUse, 4> NewUses;
14247 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14248 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14249 = VTablesUsed.find(VTables[I].Record);
14250 // Even if a definition wasn't required before, it may be required now.
14251 if (Pos != VTablesUsed.end()) {
14252 if (!Pos->second && VTables[I].DefinitionRequired)
14253 Pos->second = true;
14257 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14258 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14261 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14264 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14265 bool DefinitionRequired) {
14266 // Ignore any vtable uses in unevaluated operands or for classes that do
14267 // not have a vtable.
14268 if (!Class->isDynamicClass() || Class->isDependentContext() ||
14269 CurContext->isDependentContext() || isUnevaluatedContext())
14272 // Try to insert this class into the map.
14273 LoadExternalVTableUses();
14274 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14275 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14276 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14278 // If we already had an entry, check to see if we are promoting this vtable
14279 // to require a definition. If so, we need to reappend to the VTableUses
14280 // list, since we may have already processed the first entry.
14281 if (DefinitionRequired && !Pos.first->second) {
14282 Pos.first->second = true;
14284 // Otherwise, we can early exit.
14288 // The Microsoft ABI requires that we perform the destructor body
14289 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14290 // the deleting destructor is emitted with the vtable, not with the
14291 // destructor definition as in the Itanium ABI.
14292 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14293 CXXDestructorDecl *DD = Class->getDestructor();
14294 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14295 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14296 // If this is an out-of-line declaration, marking it referenced will
14297 // not do anything. Manually call CheckDestructor to look up operator
14299 ContextRAII SavedContext(*this, DD);
14300 CheckDestructor(DD);
14302 MarkFunctionReferenced(Loc, Class->getDestructor());
14308 // Local classes need to have their virtual members marked
14309 // immediately. For all other classes, we mark their virtual members
14310 // at the end of the translation unit.
14311 if (Class->isLocalClass())
14312 MarkVirtualMembersReferenced(Loc, Class);
14314 VTableUses.push_back(std::make_pair(Class, Loc));
14317 bool Sema::DefineUsedVTables() {
14318 LoadExternalVTableUses();
14319 if (VTableUses.empty())
14322 // Note: The VTableUses vector could grow as a result of marking
14323 // the members of a class as "used", so we check the size each
14324 // time through the loop and prefer indices (which are stable) to
14325 // iterators (which are not).
14326 bool DefinedAnything = false;
14327 for (unsigned I = 0; I != VTableUses.size(); ++I) {
14328 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14331 TemplateSpecializationKind ClassTSK =
14332 Class->getTemplateSpecializationKind();
14334 SourceLocation Loc = VTableUses[I].second;
14336 bool DefineVTable = true;
14338 // If this class has a key function, but that key function is
14339 // defined in another translation unit, we don't need to emit the
14340 // vtable even though we're using it.
14341 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14342 if (KeyFunction && !KeyFunction->hasBody()) {
14343 // The key function is in another translation unit.
14344 DefineVTable = false;
14345 TemplateSpecializationKind TSK =
14346 KeyFunction->getTemplateSpecializationKind();
14347 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14348 TSK != TSK_ImplicitInstantiation &&
14349 "Instantiations don't have key functions");
14351 } else if (!KeyFunction) {
14352 // If we have a class with no key function that is the subject
14353 // of an explicit instantiation declaration, suppress the
14354 // vtable; it will live with the explicit instantiation
14356 bool IsExplicitInstantiationDeclaration =
14357 ClassTSK == TSK_ExplicitInstantiationDeclaration;
14358 for (auto R : Class->redecls()) {
14359 TemplateSpecializationKind TSK
14360 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14361 if (TSK == TSK_ExplicitInstantiationDeclaration)
14362 IsExplicitInstantiationDeclaration = true;
14363 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14364 IsExplicitInstantiationDeclaration = false;
14369 if (IsExplicitInstantiationDeclaration)
14370 DefineVTable = false;
14373 // The exception specifications for all virtual members may be needed even
14374 // if we are not providing an authoritative form of the vtable in this TU.
14375 // We may choose to emit it available_externally anyway.
14376 if (!DefineVTable) {
14377 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14381 // Mark all of the virtual members of this class as referenced, so
14382 // that we can build a vtable. Then, tell the AST consumer that a
14383 // vtable for this class is required.
14384 DefinedAnything = true;
14385 MarkVirtualMembersReferenced(Loc, Class);
14386 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14387 if (VTablesUsed[Canonical])
14388 Consumer.HandleVTable(Class);
14390 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14391 // no key function or the key function is inlined. Don't warn in C++ ABIs
14392 // that lack key functions, since the user won't be able to make one.
14393 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14394 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14395 const FunctionDecl *KeyFunctionDef = nullptr;
14396 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14397 KeyFunctionDef->isInlined())) {
14398 Diag(Class->getLocation(),
14399 ClassTSK == TSK_ExplicitInstantiationDefinition
14400 ? diag::warn_weak_template_vtable
14401 : diag::warn_weak_vtable)
14406 VTableUses.clear();
14408 return DefinedAnything;
14411 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14412 const CXXRecordDecl *RD) {
14413 for (const auto *I : RD->methods())
14414 if (I->isVirtual() && !I->isPure())
14415 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14418 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14419 const CXXRecordDecl *RD) {
14420 // Mark all functions which will appear in RD's vtable as used.
14421 CXXFinalOverriderMap FinalOverriders;
14422 RD->getFinalOverriders(FinalOverriders);
14423 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14424 E = FinalOverriders.end();
14426 for (OverridingMethods::const_iterator OI = I->second.begin(),
14427 OE = I->second.end();
14429 assert(OI->second.size() > 0 && "no final overrider");
14430 CXXMethodDecl *Overrider = OI->second.front().Method;
14432 // C++ [basic.def.odr]p2:
14433 // [...] A virtual member function is used if it is not pure. [...]
14434 if (!Overrider->isPure())
14435 MarkFunctionReferenced(Loc, Overrider);
14439 // Only classes that have virtual bases need a VTT.
14440 if (RD->getNumVBases() == 0)
14443 for (const auto &I : RD->bases()) {
14444 const CXXRecordDecl *Base =
14445 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14446 if (Base->getNumVBases() == 0)
14448 MarkVirtualMembersReferenced(Loc, Base);
14452 /// SetIvarInitializers - This routine builds initialization ASTs for the
14453 /// Objective-C implementation whose ivars need be initialized.
14454 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14455 if (!getLangOpts().CPlusPlus)
14457 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14458 SmallVector<ObjCIvarDecl*, 8> ivars;
14459 CollectIvarsToConstructOrDestruct(OID, ivars);
14462 SmallVector<CXXCtorInitializer*, 32> AllToInit;
14463 for (unsigned i = 0; i < ivars.size(); i++) {
14464 FieldDecl *Field = ivars[i];
14465 if (Field->isInvalidDecl())
14468 CXXCtorInitializer *Member;
14469 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14470 InitializationKind InitKind =
14471 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14473 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14474 ExprResult MemberInit =
14475 InitSeq.Perform(*this, InitEntity, InitKind, None);
14476 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14477 // Note, MemberInit could actually come back empty if no initialization
14478 // is required (e.g., because it would call a trivial default constructor)
14479 if (!MemberInit.get() || MemberInit.isInvalid())
14483 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14485 MemberInit.getAs<Expr>(),
14487 AllToInit.push_back(Member);
14489 // Be sure that the destructor is accessible and is marked as referenced.
14490 if (const RecordType *RecordTy =
14491 Context.getBaseElementType(Field->getType())
14492 ->getAs<RecordType>()) {
14493 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14494 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14495 MarkFunctionReferenced(Field->getLocation(), Destructor);
14496 CheckDestructorAccess(Field->getLocation(), Destructor,
14497 PDiag(diag::err_access_dtor_ivar)
14498 << Context.getBaseElementType(Field->getType()));
14502 ObjCImplementation->setIvarInitializers(Context,
14503 AllToInit.data(), AllToInit.size());
14508 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14509 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14510 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14511 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14513 if (Ctor->isInvalidDecl())
14516 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14518 // Target may not be determinable yet, for instance if this is a dependent
14519 // call in an uninstantiated template.
14521 const FunctionDecl *FNTarget = nullptr;
14522 (void)Target->hasBody(FNTarget);
14523 Target = const_cast<CXXConstructorDecl*>(
14524 cast_or_null<CXXConstructorDecl>(FNTarget));
14527 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14528 // Avoid dereferencing a null pointer here.
14529 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14531 if (!Current.insert(Canonical).second)
14534 // We know that beyond here, we aren't chaining into a cycle.
14535 if (!Target || !Target->isDelegatingConstructor() ||
14536 Target->isInvalidDecl() || Valid.count(TCanonical)) {
14537 Valid.insert(Current.begin(), Current.end());
14539 // We've hit a cycle.
14540 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14541 Current.count(TCanonical)) {
14542 // If we haven't diagnosed this cycle yet, do so now.
14543 if (!Invalid.count(TCanonical)) {
14544 S.Diag((*Ctor->init_begin())->getSourceLocation(),
14545 diag::warn_delegating_ctor_cycle)
14548 // Don't add a note for a function delegating directly to itself.
14549 if (TCanonical != Canonical)
14550 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14552 CXXConstructorDecl *C = Target;
14553 while (C->getCanonicalDecl() != Canonical) {
14554 const FunctionDecl *FNTarget = nullptr;
14555 (void)C->getTargetConstructor()->hasBody(FNTarget);
14556 assert(FNTarget && "Ctor cycle through bodiless function");
14558 C = const_cast<CXXConstructorDecl*>(
14559 cast<CXXConstructorDecl>(FNTarget));
14560 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14564 Invalid.insert(Current.begin(), Current.end());
14567 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14572 void Sema::CheckDelegatingCtorCycles() {
14573 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14575 for (DelegatingCtorDeclsType::iterator
14576 I = DelegatingCtorDecls.begin(ExternalSource),
14577 E = DelegatingCtorDecls.end();
14579 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14581 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14582 CE = Invalid.end();
14584 (*CI)->setInvalidDecl();
14588 /// \brief AST visitor that finds references to the 'this' expression.
14589 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14593 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14595 bool VisitCXXThisExpr(CXXThisExpr *E) {
14596 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14597 << E->isImplicit();
14603 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14604 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14608 TypeLoc TL = TSInfo->getTypeLoc();
14609 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14613 // C++11 [expr.prim.general]p3:
14614 // [The expression this] shall not appear before the optional
14615 // cv-qualifier-seq and it shall not appear within the declaration of a
14616 // static member function (although its type and value category are defined
14617 // within a static member function as they are within a non-static member
14618 // function). [ Note: this is because declaration matching does not occur
14619 // until the complete declarator is known. - end note ]
14620 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14621 FindCXXThisExpr Finder(*this);
14623 // If the return type came after the cv-qualifier-seq, check it now.
14624 if (Proto->hasTrailingReturn() &&
14625 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14628 // Check the exception specification.
14629 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14632 return checkThisInStaticMemberFunctionAttributes(Method);
14635 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14636 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14640 TypeLoc TL = TSInfo->getTypeLoc();
14641 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14645 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14646 FindCXXThisExpr Finder(*this);
14648 switch (Proto->getExceptionSpecType()) {
14650 case EST_Uninstantiated:
14651 case EST_Unevaluated:
14652 case EST_BasicNoexcept:
14653 case EST_DynamicNone:
14658 case EST_ComputedNoexcept:
14659 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14664 for (const auto &E : Proto->exceptions()) {
14665 if (!Finder.TraverseType(E))
14674 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14675 FindCXXThisExpr Finder(*this);
14677 // Check attributes.
14678 for (const auto *A : Method->attrs()) {
14679 // FIXME: This should be emitted by tblgen.
14680 Expr *Arg = nullptr;
14681 ArrayRef<Expr *> Args;
14682 if (const auto *G = dyn_cast<GuardedByAttr>(A))
14684 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14686 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14687 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14688 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14689 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14690 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14691 Arg = ETLF->getSuccessValue();
14692 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14693 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14694 Arg = STLF->getSuccessValue();
14695 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14696 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14697 Arg = LR->getArg();
14698 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14699 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14700 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14701 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14702 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14703 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14704 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14705 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14706 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14707 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14709 if (Arg && !Finder.TraverseStmt(Arg))
14712 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14713 if (!Finder.TraverseStmt(Args[I]))
14721 void Sema::checkExceptionSpecification(
14722 bool IsTopLevel, ExceptionSpecificationType EST,
14723 ArrayRef<ParsedType> DynamicExceptions,
14724 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14725 SmallVectorImpl<QualType> &Exceptions,
14726 FunctionProtoType::ExceptionSpecInfo &ESI) {
14727 Exceptions.clear();
14729 if (EST == EST_Dynamic) {
14730 Exceptions.reserve(DynamicExceptions.size());
14731 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14732 // FIXME: Preserve type source info.
14733 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14736 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14737 collectUnexpandedParameterPacks(ET, Unexpanded);
14738 if (!Unexpanded.empty()) {
14739 DiagnoseUnexpandedParameterPacks(
14740 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14746 // Check that the type is valid for an exception spec, and
14748 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14749 Exceptions.push_back(ET);
14751 ESI.Exceptions = Exceptions;
14755 if (EST == EST_ComputedNoexcept) {
14756 // If an error occurred, there's no expression here.
14757 if (NoexceptExpr) {
14758 assert((NoexceptExpr->isTypeDependent() ||
14759 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14761 "Parser should have made sure that the expression is boolean");
14762 if (IsTopLevel && NoexceptExpr &&
14763 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14764 ESI.Type = EST_BasicNoexcept;
14768 if (!NoexceptExpr->isValueDependent())
14769 NoexceptExpr = VerifyIntegerConstantExpression(NoexceptExpr, nullptr,
14770 diag::err_noexcept_needs_constant_expression,
14771 /*AllowFold*/ false).get();
14772 ESI.NoexceptExpr = NoexceptExpr;
14778 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14779 ExceptionSpecificationType EST,
14780 SourceRange SpecificationRange,
14781 ArrayRef<ParsedType> DynamicExceptions,
14782 ArrayRef<SourceRange> DynamicExceptionRanges,
14783 Expr *NoexceptExpr) {
14787 // Dig out the method we're referring to.
14788 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14789 MethodD = FunTmpl->getTemplatedDecl();
14791 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14795 // Check the exception specification.
14796 llvm::SmallVector<QualType, 4> Exceptions;
14797 FunctionProtoType::ExceptionSpecInfo ESI;
14798 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14799 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14802 // Update the exception specification on the function type.
14803 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14805 if (Method->isStatic())
14806 checkThisInStaticMemberFunctionExceptionSpec(Method);
14808 if (Method->isVirtual()) {
14809 // Check overrides, which we previously had to delay.
14810 for (CXXMethodDecl::method_iterator O = Method->begin_overridden_methods(),
14811 OEnd = Method->end_overridden_methods();
14813 CheckOverridingFunctionExceptionSpec(Method, *O);
14817 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14819 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14820 SourceLocation DeclStart,
14821 Declarator &D, Expr *BitWidth,
14822 InClassInitStyle InitStyle,
14823 AccessSpecifier AS,
14824 AttributeList *MSPropertyAttr) {
14825 IdentifierInfo *II = D.getIdentifier();
14827 Diag(DeclStart, diag::err_anonymous_property);
14830 SourceLocation Loc = D.getIdentifierLoc();
14832 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14833 QualType T = TInfo->getType();
14834 if (getLangOpts().CPlusPlus) {
14835 CheckExtraCXXDefaultArguments(D);
14837 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14838 UPPC_DataMemberType)) {
14839 D.setInvalidType();
14841 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14845 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14847 if (D.getDeclSpec().isInlineSpecified())
14848 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14849 << getLangOpts().CPlusPlus1z;
14850 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14851 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14852 diag::err_invalid_thread)
14853 << DeclSpec::getSpecifierName(TSCS);
14855 // Check to see if this name was declared as a member previously
14856 NamedDecl *PrevDecl = nullptr;
14857 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14858 LookupName(Previous, S);
14859 switch (Previous.getResultKind()) {
14860 case LookupResult::Found:
14861 case LookupResult::FoundUnresolvedValue:
14862 PrevDecl = Previous.getAsSingle<NamedDecl>();
14865 case LookupResult::FoundOverloaded:
14866 PrevDecl = Previous.getRepresentativeDecl();
14869 case LookupResult::NotFound:
14870 case LookupResult::NotFoundInCurrentInstantiation:
14871 case LookupResult::Ambiguous:
14875 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14876 // Maybe we will complain about the shadowed template parameter.
14877 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14878 // Just pretend that we didn't see the previous declaration.
14879 PrevDecl = nullptr;
14882 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14883 PrevDecl = nullptr;
14885 SourceLocation TSSL = D.getLocStart();
14886 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
14887 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
14888 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
14889 ProcessDeclAttributes(TUScope, NewPD, D);
14890 NewPD->setAccess(AS);
14892 if (NewPD->isInvalidDecl())
14893 Record->setInvalidDecl();
14895 if (D.getDeclSpec().isModulePrivateSpecified())
14896 NewPD->setModulePrivate();
14898 if (NewPD->isInvalidDecl() && PrevDecl) {
14899 // Don't introduce NewFD into scope; there's already something
14900 // with the same name in the same scope.
14902 PushOnScopeChains(NewPD, S);
14904 Record->addDecl(NewPD);